text:
<?php

abstract class Gwilym_Plugins implements Gwilym_Plugins_Interface
{
	/** @var Gwilym_KeyStore_Interface */
	private static $_staticKeyStore;

	private static function _staticKeyStore ()
	{
		if (self::$_staticKeyStore === null)
		{
			// note: make sure this uses the same keystore configuration as __construct (except the prefix)
			self::$_staticKeyStore = Gwilym_KeyStore::factory();
		}
		return self::$_staticKeyStore;
	}

	public static function classNameToPluginId ($className)
	{
		return preg_replace('#^Gwilym_Plugins_(.*?)_Plugin$#', '$1', $className);
	}

	/**
	* Discover and return a list of all available plugins based on available files. This assumes that plugins are all located under /Gwilym/Plugins and have corresponding classes named Gwilym_Plugins_{id}_Plugin
	*
	* @return Traversable list of all file-wise available plugins or false if file scanning failed
	*/
	public static function plugins ($instanciate = false)
	{
		$plugins = Gwilym_Autoloader::findClasses('Gwilym_Plugins_*_Plugin');
		if (!$instanciate) {
			return $plugins;
		}
		return new Gwilym_Iterator_Instantiator($plugins);
	}

	/** @return array<string> list of currently active plugins */
	public static function activePlugins ()
	{
		// note: make sure this uses the same keystore configuration as __construct
		$keystore = Gwilym_KeyStore::factory();

		return $keystore->multiGet('gwilym,plugin,active,*');
	}

	/** @var Gwilym_keyStore_Interface */
	protected $_keystore;

	protected $_id;

	public function __construct ()
	{
		// note: make sure this uses the same keystore configuration as _staticKeyStore (except the prefix)
		$this->_keystore = Gwilym_KeyStore::factory();
		$this->_keystore->prefix('gwilym,plugin,' . $this->id() . ',');
		$this->_keystore->lockPrefix();
	}

	public function id ()
	{
		if ($this->_id === null) {
			$this->_id = self::classNameToPluginId(get_class($this));
		}
		return $this->_id;
	}

	public function active ()
	{
		return (bool)self::_staticKeyStore()->get('gwilym,plugin,active,' . $this->id());
	}

	public function activate ()
	{
		if ($this->active()) {
			return true;
		}
		return (bool)self::_staticKeyStore()->set('gwilym,plugin,active,' . $this->id(), $this->id());
	}

	public function deactivate ()
	{
		if (!$this->active()) {
			return true;
		}
		return (bool)self::_staticKeyStore()->delete('gwilym,plugin,active,' . $this->id());
	}
}


text:
class CreateSavedAnimes < ActiveRecord::Migration
  def change
    create_table :saved_animes do |t|
      t.integer :user_id
      t.integer :anime_id

      t.timestamps null: false
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
var Base = require('arale-base')
var $ = require('jquery')
var DAParser = require('./daparser')
var AutoRender = require('./auto-render')

var DELEGATE_EVENT_NS = '.delegate-events-'
var ON_RENDER = '_onRender'
var DATA_WIDGET_CID = 'data-widget-cid'

// 所有初始化过的 Widget 实例
var cachedInstances = {}

var Widget = Base.extend({

  // config 中的这些键值会直接添加到实例上,转换成 properties
  propsInAttrs: ['initElement', 'element', 'events'],

  // 与 widget 关联的 DOM 元素
  element: null,

  // 事件代理,格式为:
  //   {
  //     'mousedown .title': 'edit',
  //     'click {{attrs.saveButton}}': 'save'
  //     'click .open': function(ev) { ... }
  //   }
  events: null,

  // 属性列表
  attrs: {
    // 基本属性
    id: null,
    className: null,
    style: null,

    // 默认模板
    template: '

',

    // 默认数据模型
    model: null,

    // 组件的默认父节点
    parentNode: document.body
  },

  // 初始化方法,确定组件创建时的基本流程:
  // 初始化 attrs --》 初始化 props --》 初始化 events --》 子类的初始化
  initialize: function(config) {
    this.cid = uniqueCid()

    // 初始化 attrs
    var dataAttrsConfig = this._parseDataAttrsConfig(config)
    Widget.superclass.initialize.call(this, config ? $.extend(dataAttrsConfig, config) : dataAttrsConfig)

    // 初始化 props
    this.parseElement()
    this.initProps()

    // 初始化 events
    this.delegateEvents()

    // 子类自定义的初始化
    this.setup()

    // 保存实例信息
    this._stamp()

    // 是否由 template 初始化
    this._isTemplate = !(config && config.element)
  },

  // 解析通过 data-attr 设置的 api
  _parseDataAttrsConfig: function(config) {
    var element, dataAttrsConfig
    if (config) {
      element = config.initElement ? $(config.initElement) : $(config.element)
    }

    // 解析 data-api 时,只考虑用户传入的 element,不考虑来自继承或从模板构建的
    if (element && element[0] && !AutoRender.isDataApiOff(element)) {
      dataAttrsConfig = DAParser.parseElement(element)
    }

    return dataAttrsConfig
  },

  // 构建 this.element
  parseElement: function() {
    var element = this.element

    if (element) {
      this.element = $(element)
    }
    // 未传入 element 时,从 template 构建
    else if (this.get('template')) {
      this.parseElementFromTemplate()
    }

    // 如果对应的 DOM 元素不存在,则报错
    if (!this.element || !this.element[0]) {
      throw new Error('element is invalid')
    }
  },

  // 从模板中构建 this.element
  parseElementFromTemplate: function() {
    this.element = $(this.get('template'))
  },

  // 负责 properties 的初始化,提供给子类覆盖
  initProps: function() {
  },

  // 注册事件代理
  delegateEvents: function(element, events, handler) {
    var argus = trimRightUndefine(Array.prototype.slice.call(arguments));
    // widget.delegateEvents()
    if (argus.length === 0) {
      events = getEvents(this)
      element = this.element
    }

    // widget.delegateEvents({
    //   'click p': 'fn1',
    //   'click li': 'fn2'
    // })
    else if (argus.length === 1) {
      events = element
      element = this.element
    }

    // widget.delegateEvents('click p', function(ev) { ... })
    else if (argus.length === 2) {
      handler = events
      events = element
      element = this.element
    }

    // widget.delegateEvents(element, 'click p', function(ev) { ... })
    else {
      element || (element = this.element)
      this._delegateElements || (this._delegateElements = [])
      this._delegateElements.push($(element))
    }

    // 'click p' => {'click p': handler}
    if (isString(events) && isFunction(handler)) {
      var o = {}
      o[events] = handler
      events = o
    }

    // key 为 'event selector'
    for (var key in events) {
      if (!events.hasOwnProperty(key)) continue

      var args = parseEventKey(key, this)
      var eventType = args.type
      var selector = args.selector

      ;(function(handler, widget) {

        var callback = function(ev) {
          if (isFunction(handler)) {
            handler.call(widget, ev)
          } else {
            widget[handler](ev)
          }
        }

        // delegate
        if (selector) {
          $(element).on(eventType, selector, callback)
        }
        // normal bind
        // 分开写是为了兼容 zepto,zepto 的判断不如 jquery 强劲有力
        else {
          $(element).on(eventType, callback)
        }

      })(events[key], this)
    }

    return this
  },

  // 卸载事件代理
  undelegateEvents: function(element, eventKey) {
    var argus = trimRightUndefine(Array.prototype.slice.call(arguments));

    if (!eventKey) {
      eventKey = element
      element = null
    }

    // 卸载所有
    // .undelegateEvents()
    if (argus.length === 0) {
      var type = DELEGATE_EVENT_NS + this.cid

      this.element && this.element.off(type)

      // 卸载所有外部传入的 element
      if (this._delegateElements) {
        for (var de in this._delegateElements) {
          if (!this._delegateElements.hasOwnProperty(de)) continue
          this._delegateElements[de].off(type)
        }
      }

    } else {
      var args = parseEventKey(eventKey, this)

      // 卸载 this.element
      // .undelegateEvents(events)
      if (!element) {
        this.element && this.element.off(args.type, args.selector)
      }

      // 卸载外部 element
      // .undelegateEvents(element, events)
      else {
        $(element).off(args.type, args.selector)
      }
    }
    return this
  },

  // 提供给子类覆盖的初始化方法
  setup: function() {
  },

  // 将 widget 渲染到页面上
  // 渲染不仅仅包括插入到 DOM 树中,还包括样式渲染等
  // 约定:子类覆盖时,需保持 `return this`
  render: function() {

    // 让渲染相关属性的初始值生效,并绑定到 change 事件
    if (!this.rendered) {
      this._renderAndBindAttrs()
      this.rendered = true
    }

    // 插入到文档流中
    var parentNode = this.get('parentNode')
    if (parentNode && !isInDocument(this.element[0])) {
      // 隔离样式,添加统一的命名空间
      // https://github.com/aliceui/aliceui.org/issues/9
      var outerBoxClass = this.constructor.outerBoxClass
      if (outerBoxClass) {
        var outerBox = this._outerBox = $('

').addClass(outerBoxClass)
        outerBox.append(this.element).appendTo(parentNode)
      } else {
        this.element.appendTo(parentNode)
      }
    }

    return this
  },

  // 让属性的初始值生效,并绑定到 change:attr 事件上
  _renderAndBindAttrs: function() {
    var widget = this
    var attrs = widget.attrs

    for (var attr in attrs) {
      if (!attrs.hasOwnProperty(attr)) continue
      var m = ON_RENDER + ucfirst(attr)

      if (this[m]) {
        var val = this.get(attr)

        // 让属性的初始值生效。注:默认空值不触发
        if (!isEmptyAttrValue(val)) {
          this[m](val, undefined, attr)
        }

        // 将 _onRenderXx 自动绑定到 change:xx 事件上
        (function(m) {
          widget.on('change:' + attr, function(val, prev, key) {
            widget[m](val, prev, key)
          })
        })(m)
      }
    }
  },

  _onRenderId: function(val) {
    this.element.attr('id', val)
  },

  _onRenderClassName: function(val) {
    this.element.addClass(val)
  },

  _onRenderStyle: function(val) {
    this.element.css(val)
  },

  // 让 element 与 Widget 实例建立关联
  _stamp: function() {
    var cid = this.cid;

    (this.initElement || this.element).attr(DATA_WIDGET_CID, cid)
    cachedInstances[cid] = this
  },

  // 在 this.element 内寻找匹配节点
  $: function(selector) {
    return this.element.find(selector)
  },

  destroy: function() {
    this.undelegateEvents()
    delete cachedInstances[this.cid]

    // For memory leak
    if (this.element && this._isTemplate) {
      this.element.off()
      // 如果是 widget 生成的 element 则去除
      if (this._outerBox) {
        this._outerBox.remove()
      } else {
        this.element.remove()
      }
    }
    this.element = null

    Widget.superclass.destroy.call(this)
  }
})

// For memory leak
$(window).unload(function() {
  for(var cid in cachedInstances) {
    cachedInstances[cid].destroy()
  }
})

// 查询与 selector 匹配的第一个 DOM 节点,得到与该 DOM 节点相关联的 Widget 实例
Widget.query = function(selector) {
  var element = $(selector).eq(0)
  var cid

  element && (cid = element.attr(DATA_WIDGET_CID))
  return cachedInstances[cid]
}

Widget.autoRender = AutoRender.autoRender
Widget.autoRenderAll = AutoRender.autoRenderAll
Widget.StaticsWhiteList = ['autoRender']

module.exports = Widget

// Helpers
// ------

var toString = Object.prototype.toString
var cidCounter = 0

function uniqueCid() {
  return 'widget-' + cidCounter++
}

function isString(val) {
  return toString.call(val) === '[object String]'
}

function isFunction(val) {
  return toString.call(val) === '[object Function]'
}

// Zepto 上没有 contains 方法
var contains = $.contains || function(a, b) {
  //noinspection JSBitwiseOperatorUsage
  return !!(a.compareDocumentPosition(b) & 16)
}

function isInDocument(element) {
  return contains(document.documentElement, element)
}

function ucfirst(str) {
  return str.charAt(0).toUpperCase() + str.substring(1)
}

var EVENT_KEY_SPLITTER = /^(\S+)\s*(.*)$/
var EXPRESSION_FLAG = /{{([^}]+)}}/g
var INVALID_SELECTOR = 'INVALID_SELECTOR'

function getEvents(widget) {
  if (isFunction(widget.events)) {
    widget.events = widget.events()
  }
  return widget.events
}

function parseEventKey(eventKey, widget) {
  var match = eventKey.match(EVENT_KEY_SPLITTER)
  var eventType = match[1] + DELEGATE_EVENT_NS + widget.cid

  // 当没有 selector 时,需要设置为 undefined,以使得 zepto 能正确转换为 bind
  var selector = match[2] || undefined

  if (selector && selector.indexOf('{{') > -1) {
    selector = parseExpressionInEventKey(selector, widget)
  }

  return {
    type: eventType,
    selector: selector
  }
}

// 解析 eventKey 中的 {{xx}}, {{yy}}
function parseExpressionInEventKey(selector, widget) {

  return selector.replace(EXPRESSION_FLAG, function(m, name) {
    var parts = name.split('.')
    var point = widget, part

    while (part = parts.shift()) {
      if (point === widget.attrs) {
        point = widget.get(part)
      } else {
        point = point[part]
      }
    }

    // 已经是 className,比如来自 dataset 的
    if (isString(point)) {
      return point
    }

    // 不能识别的,返回无效标识
    return INVALID_SELECTOR
  })
}

// 对于 attrs 的 value 来说,以下值都认为是空值: null, undefined
function isEmptyAttrValue(o) {
  return o == null || o === undefined
}

function trimRightUndefine(argus) {
  for (var i = argus.length - 1; i >= 0; i--) {
    if (argus[i] === undefined) {
      argus.pop();
    } else {
      break;
    }
  }
  return argus;
}


text:
package com.teamup.mihaylov.teamup.DrawerNavMain;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.UserInfo;
import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.mikepenz.materialdrawer.util.AbstractDrawerImageLoader;
import com.mikepenz.materialdrawer.util.DrawerImageLoader;
import com.mikepenz.materialdrawer.util.DrawerUIUtils;
import com.teamup.mihaylov.teamup.Events.CreateEvent.CreateEventActivity;
import com.teamup.mihaylov.teamup.Events.ListEvents.ListAllEvents.ListEventsActivity;
import com.teamup.mihaylov.teamup.Home.HomeFragment;
import com.teamup.mihaylov.teamup.SignUp.SignUpActivity;
import com.teamup.mihaylov.teamup.UserProfile.UserProfileActivity;
import com.teamup.mihaylov.teamup.R;
import com.teamup.mihaylov.teamup.SignIn.SignInActivity;
import com.teamup.mihaylov.teamup.base.authentication.AuthenticationProvider;
import com.teamup.mihaylov.teamup.base.BaseActivity;
import com.teamup.mihaylov.teamup.base.data.LocalUsersData;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class DrawerNavMainActivity extends BaseActivity {

    private static final int CAMERA_REQUEST = 1;
    private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 2;
    private Fragment mFragment;

    private Toolbar mToolbar;
    private Drawer mDrawer;
    private Uri mImageUri;
    private AccountHeader mDrawerHeader;
    private DrawerBuilder mDrawerBuilder;
    private PrimaryDrawerItem mHomeDrawerItem;
    private PrimaryDrawerItem mSignInDrawerItem;
    private PrimaryDrawerItem mSignUpDrawerItem;
    private PrimaryDrawerItem mSignOutDrawerItem;
    private PrimaryDrawerItem mProfileDrawerItem;
    private PrimaryDrawerItem mCreateEventDrawerItem;
    private PrimaryDrawerItem mListEventsDrawerItem;
    private SectionDrawerItem mEventsSectionDrawerItem;

    @Inject
    public AuthenticationProvider authProvider;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.content_container, new HomeFragment())
                .commit();
    }

    protected void onStart() {
        setupDrawerHeaderProfileImage();
        setupDrawerItems();
        setupDrawer();

        super.onStart();
    }

    protected void onStop() {
        super.onStop();
    }

    private boolean checkAndRequestPermissions() {
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
                    REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
                    openCamera();
                } else {
                    Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            switch (resultCode) {
                case Activity.RESULT_OK: {
                    Toast.makeText(getApplicationContext(), "saved", Toast.LENGTH_LONG).show();
                    break;
                }
                case Activity.RESULT_CANCELED: {
                    Toast.makeText(getApplicationContext(), "not saved", Toast.LENGTH_LONG).show();
                    break;
                }
            }
        }
    }

    private void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        String uid = authProvider.getUserId();
        String imageFileName = uid + ".jpg";
        File path = getExternalFilesDir("Pictures");

        try {
            if (!path.exists()) {
                path.mkdirs();
            }

            File imageFile = new File(path, imageFileName);

            mImageUri = FileProvider.getUriForFile(getApplicationContext(), "com.TeamUpApplication.android.fileprovider", imageFile);

            takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
            startActivityForResult(takePictureIntent, CAMERA_REQUEST);
        } catch (Exception e) {
            Log.w("ExternalStorage", "Error writing ", e);
        }
    }

    private Uri getProfileImageUri() {
        String uid = authProvider.getUserId();
        String imageFileName = uid + ".jpg";
        File path = getExternalFilesDir("Pictures");

        File imageFile = new File(path, imageFileName);

        Uri uri;

        if (!imageFile.exists()) {
            return null;
        } else {
            uri = FileProvider.getUriForFile(getApplicationContext(),
                    "com.TeamUpApplication.android.fileprovider", imageFile);
        }

        return uri;
    }

    public void setupDrawerHeaderProfileImage() {
        DrawerImageLoader.init(new AbstractDrawerImageLoader() {
            @Override
            public void set(final ImageView imageView,
                            final Uri uri,
                            final Drawable placeholder,
                            final String tag) {
                Glide.with(imageView.getContext()).load(uri).placeholder(placeholder).into(imageView);
            }

            @Override
            public void cancel(ImageView imageView) {
                Glide.clear(imageView);
            }

            @Override
            public Drawable placeholder(final Context ctx, final String tag) {
                if (DrawerImageLoader.Tags.PROFILE.name().equals(tag)) {
                    return DrawerUIUtils.getPlaceHolder(ctx);
                } else if (DrawerImageLoader.Tags.ACCOUNT_HEADER.name().equals(tag)) {
                    return new IconicsDrawable(ctx)
                            .iconText(" ")
                            .backgroundColorRes(com.mikepenz.materialdrawer.R.color.primary)
                            .sizeDp(56);
                }

                return super.placeholder(ctx, tag);
            }
        });
    }

    public void setupDrawerHeader(final FirebaseUser user) {
        final ProfileDrawerItem userProfile = new ProfileDrawerItem();

        if (user != null) {
            String userEmail = user.getEmail();
            String userName = user.getDisplayName();

            if (user.getPhotoUrl() != null) {
                boolean isTrue = user.getPhotoUrl() != null;
                Log.v("Profile image", Boolean.toString(isTrue));
                userProfile
                        .withName(userEmail).withTextColor(Color.BLACK)
                        .withEmail(userName).withTextColor(Color.BLACK)
                        .withIcon(user.getPhotoUrl().toString());
            } else if (getProfileImageUri() != null) {
                Log.v("PROFILE_PICTURE", getProfileImageUri().toString());
                userProfile
                        .withName(userEmail).withTextColor(Color.BLACK)
                        .withEmail(userName).withTextColor(Color.BLACK)
                        .withIcon(getProfileImageUri().toString());
            } else {
                userProfile
                        .withName(userEmail).withTextColor(Color.BLACK)
                        .withEmail(userName).withTextColor(Color.BLACK);
            }
        } else {
            userProfile
                    .withName("Not signed in").withTextColor(Color.BLACK)
                    .withEmail("Anonymous").withTextColor(Color.BLACK);
        }

        mDrawerHeader = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.drawer_profile_background)
                .addProfiles(userProfile)
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                        for (UserInfo user : authProvider.getFirebaseInstance().getCurrentUser().getProviderData()) {
                            if (user.getProviderId().equals("password")) {
                                if (checkAndRequestPermissions()) {
                                    openCamera();
                                }
                            }
                        }

                        if (mImageUri != null) {
                            mDrawerHeader.updateProfile(userProfile.withIcon(mImageUri));
                        }

                        return false;
                    }
                })
                .build();
    }

    public void setupDrawerItems() {

        mHomeDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_home)
                        .withIdentifier(1)
                        .withIcon(GoogleMaterial.Icon.gmd_home)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mProfileDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_profile)
                        .withIdentifier(2)
                        .withIcon(GoogleMaterial.Icon.gmd_person)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mSignInDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_sign_in)
                        .withIdentifier(3)
                        .withIcon(FontAwesome.Icon.faw_sign_in)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mSignUpDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_sign_up)
                        .withIdentifier(4)
                        .withIcon(FontAwesome.Icon.faw_user_plus)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mSignOutDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_sign_out)
                        .withIdentifier(5)
                        .withIcon(FontAwesome.Icon.faw_sign_out)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mListEventsDrawerItem =
                new PrimaryDrawerItem()
                        .withName(R.string.drawer_list_events)
                        .withIdentifier(6)
                        .withIcon(FontAwesome.Icon.faw_list)
                        .withIconColor(ContextCompat.getColor(getApplicationContext(),
                                R.color.colorPrimaryDark));

        mCreateEventDrawerItem = new PrimaryDrawerItem().withName(R.string.drawer_create_event).withIdentifier(7)
                .withIcon(GoogleMaterial.Icon.gmd_create)
                .withIconColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimaryDark));

        mEventsSectionDrawerItem = new SectionDrawerItem().withName(R.string.drawer_events_section);
    }

    public void setupDrawer() {

        FirebaseUser user = authProvider.getUser();

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        setupDrawerHeader(user);

        long selectedDrawerItem = getIntent().getLongExtra("SELECTED_DRAWER_ITEM", 1);

        mDrawerBuilder = new DrawerBuilder()
                .withSelectedItem(selectedDrawerItem)
                .withActivity(this)
                .withToolbar(mToolbar)
                .withActionBarDrawerToggle(true)
                .withActionBarDrawerToggleAnimated(true)
                .withAccountHeader(mDrawerHeader)
                .withRootView(R.id.drawer_layout);

        if (user == null) {
            mDrawer = mDrawerBuilder.addDrawerItems(
                    mHomeDrawerItem,
                    mSignInDrawerItem,
                    mSignUpDrawerItem,
                    mEventsSectionDrawerItem,
                    mListEventsDrawerItem)
                    .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {

                        private Intent intent;

                        @Override
                        public boolean onItemClick(final View view, final int position, final IDrawerItem drawerItem) {
                            switch ((int) drawerItem.getIdentifier()) {
                                case 1:
                                    mFragment = new HomeFragment();
                                    break;
                                case 3:
                                    intent = new Intent(getApplicationContext(),
                                            SignInActivity.class);
                                    break;
                                case 4:
                                    intent = new Intent(getApplicationContext(),
                                            SignUpActivity.class);
                                    break;
                                case 6:
                                    Toast.makeText(getApplicationContext(), "Clicked list", Toast.LENGTH_SHORT).show();
                                    intent = new Intent(getApplicationContext(),
                                            ListEventsActivity.class);
                                    break;
                            }

                            if (mFragment != null) {
                                getSupportFragmentManager()
                                        .beginTransaction()
                                        .replace(R.id.content_container, mFragment)
                                        .commit();
                            }

                            if (intent != null) {
                                intent.putExtra("SELECTED_DRAWER_ITEM",
                                        drawerItem.getIdentifier());

                                startActivity(intent);
                            }

                            return false;
                        }
                    })
                    .build();
        } else {
            mDrawer = mDrawerBuilder.addDrawerItems(
                    mHomeDrawerItem,
                    mProfileDrawerItem,
                    mSignOutDrawerItem,
                    mEventsSectionDrawerItem,
                    mListEventsDrawerItem,
                    mCreateEventDrawerItem)
                    .withOnDrawerItemClickListener(
                            new Drawer.OnDrawerItemClickListener() {

                                private Intent intent;

                                @Override
                                public boolean onItemClick(final View view,
                                                           final int position,
                                                           final IDrawerItem drawerItem) {

                                    switch ((int) drawerItem.getIdentifier()) {
                                        case 1:
                                            mFragment = new HomeFragment();
                                            break;
                                        case 2:
                                            intent = new Intent(getApplicationContext(),
                                                    UserProfileActivity.class);
                                            break;
                                        case 5:
                                            authProvider.signOut();
                                            intent = new Intent(getApplicationContext(),
                                                    DrawerNavMainActivity.class);
                                            break;
                                        case 6:
                                            intent = new Intent(getApplicationContext(),
                                                    ListEventsActivity.class);
                                            break;
                                        case 7:
                                            intent = new Intent(getApplicationContext(),
                                                    CreateEventActivity.class);
                                            break;
                                        default:
                                    }

                                    if (mFragment != null) {
                                        getSupportFragmentManager()
                                                .beginTransaction()
                                                .replace(R.id.content_container,
                                                        mFragment)
                                                .commit();
                                    }

                                    if (intent != null) {
                                        intent.putExtra("SELECTED_DRAWER_ITEM",
                                                drawerItem.getIdentifier());
                                        startActivity(intent);
                                    }

                                    return false;
                                }
                            })
                    .build();
        }
    }

    public void updateDrawer() {
        mDrawer.removeHeader();
        setupDrawer();
    }
}


text:
package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class RadioButtonCreate extends JFrame {
    public RadioButtonCreate() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1, 2));

        JPanel leftPanel = new JPanel();
        JLabel label = new JLabel("Employees: ");
        leftPanel.add(label);

        JPanel rightPanel = new JPanel(new GridLayout(4, 1));

        // Create a JRadioButton by calling the JRadioButton constructors and
        // passing a string for radio button text. We can also pass a boolean
        // value to select or unselect the radio button.
        JRadioButton radio1 = new JRadioButton("1 - 10");
        JRadioButton radio2 = new JRadioButton("11 - 50", true);
        JRadioButton radio3 = new JRadioButton("51 - 100");
        JRadioButton radio4 = new JRadioButton("101 - 1000", false);

        rightPanel.add(radio1);
        rightPanel.add(radio2);
        rightPanel.add(radio3);
        rightPanel.add(radio4);

        getContentPane().add(leftPanel);
        getContentPane().add(rightPanel);

        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new RadioButtonCreate().setVisible(true);
            }
        });
    }
}


text:
layout: page
title: Sharon Silva's 53rd Birthday
date: 2016-05-24
author: Pamela Kennedy
tags: weekly links, java
status: published
summary: Etiam quis cursus purus. Sed magna nisl, ultrices ac.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/13/2017
  endDate: 04/16/2017
  ctyhocn: GEGVYHX
  groupCode: SS5B
published: true
---
Aliquam ornare, eros et ornare molestie, magna leo viverra tortor, sed pulvinar augue nunc sit amet diam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc accumsan eu dolor scelerisque suscipit. Vestibulum in purus placerat, faucibus mi id, dictum justo. Integer porttitor arcu at nibh facilisis, sed semper enim blandit. Praesent eleifend enim eu mauris sollicitudin, vel pellentesque dolor mollis. Proin nulla neque, dictum quis lacus ut, imperdiet pulvinar ipsum.

* Nulla sit amet libero sed arcu tincidunt tristique quis et urna
* Donec aliquet ante ac justo maximus, at congue orci rhoncus.

Phasellus sodales nisl nulla, a sollicitudin erat tempor facilisis. Nulla sit amet varius turpis, a venenatis enim. Nunc feugiat tristique risus eget bibendum. Quisque dapibus pellentesque ultrices. Integer justo diam, convallis congue laoreet eu, eleifend non eros. In bibendum tellus et quam ultricies sagittis. Suspendisse potenti. Nam tristique rutrum justo, nec venenatis ante. Ut sit amet turpis quis ex rhoncus pellentesque in sit amet tortor.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Soporte;

import Acciones.PropiedadAction;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;

/**
 *
 * @author angelo
 */
public class Archivo {

    /**
     * Renombra una carpeta o un archivo.
     *
     * @param rutaOriginal Nombre original.
     * @param rutaNueva Nuevo nombre.
     */
    public static void renombrarCarpeta(String rutaOriginal, String rutaNueva) {
        // File (or directory) with old name
        File file = new File(rutaOriginal);
        // File (or directory) with new name
        File file2 = new File(rutaNueva);
        // Rename file (or directory)
        file.renameTo(file2);
    }

    /**
     * Crea un archivo en el disco del sistema, y devuelve la ruta del archivo
     * para poder ser guardaro en la base de datos.
     *
     * @param ruta La ruta del archivo donde sera creado.
     * @param upload EL archivo.
     * @param uploadFileName El nombre del archivo.
     * @return La ruta para la BD.
     */
    public static String crearImagen(String ruta, File upload, String uploadFileName) {
        File directorio = new File(ruta);
        String rutaBD = ruta + "/" + uploadFileName;
        if (!directorio.exists()) {
            directorio.mkdirs();
        }
        try {
            FileUtils.copyFile(upload, new File(directorio, uploadFileName));
        } catch (IOException ex) {
            Logger.getLogger(PropiedadAction.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rutaBD;
    }

    /**
     * Elimina todos los archivos que contenga una carpeta, o el archivo en si.
     *
     * @param ruta La ruta de una carpeta o un archivo.
     */
    public static void delete(String ruta) {
        try {
            File f = new File(ruta);
            delete(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Elimina todos los archivos que contenga una carpeta, o el archivo en si.
     *
     * @param file Una carpeta o un archivo.
     */
    public static void delete(File file) {
        try {
            if (file.exists()) {
                if (file.isDirectory()) {

                    //directory is empty, then delete it
                    if (file.list().length == 0) {
                        file.delete();
                    } else {

                        //list all the directory contents
                        String files[] = file.list();

                        for (String temp : files) {
                            //construct the file structure
                            File fileDelete = new File(file, temp);

                            //recursive delete
                            delete(fileDelete);
                        }

                        //check the directory again, if empty then delete it
                        if (file.list().length == 0) {
                            file.delete();
                        }
                    }

                } else {
                    //if file, then delete it
                    file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}


text:
/**
 * SETUP
 **/
  var app = app || {};

/**
 * MODELS
 **/
  app.Contact = Backbone.Model.extend({
    idAttribute: "_id",
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      name: {}
    },
    url: function() {
      return '/admin/administrators/'+ this.id +'/';
    },
    initialize: function(data) {
      this.set(data);
    },
    update: function() {
      this.save(undefined, {});
    }
  });

  app.Login = Backbone.Model.extend({
    idAttribute: "_id",
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      user: {},
      newUsername: ''
    },
    url: function() {
      return '/admin/administrators/'+ this.id +'/';
    },
    initialize: function(data) {
      this.set(data);
    },
    userLink: function() {
      this.save(undefined, {
        url: this.url() +'user/'
      });
    },
    userUnlink: function() {
      this.destroy({
        url: this.url() +'user/',
        success: function(model, response, options) {
          model.set(response);
        }
      });
    }
  });

  app.Groups = Backbone.Model.extend({
    idAttribute: "_id",
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      groups: [],
      groupList: [],
      newMembership: ''
    },
    url: function() {
      return '/admin/administrators/'+ this.id +'/groups/';
    },
    initialize: function(data) {
      this.set(data);
    },
    saveGroups: function() {
      var newGroups = _.map(this.get('groups'), function(group) { return group._id; });
      this.save({newGroups: newGroups}, {});
    }
  });

  app.Permissions = Backbone.Model.extend({
    idAttribute: "_id",
    defaults: {
      success: false,
      errors: [],
      errfor: {},
      permissions: [],
      newPermission: ''
    },
    url: function() {
      return '/admin/administrators/'+ this.id +'/permissions/';
    },
    initialize: function(data) {
      this.set(data);
    },
    savePermissions: function() {
      this.save(undefined, {});
    }
  });

  app.Delete = Backbone.Model.extend({
    idAttribute: "_id",
    defaults: {
      success: false,
      errors: [],
      errfor: {}
    },
    url: function() {
      return '/admin/administrators/'+ this.id +'/';
    },
    initialize: function(data) {
      this.set(data);
    },
    delete: function() {
      this.destroy({
        success: function(model, response, options) {
          model.set(response);
        }
      });
    }
  });

/**
 * VIEWS
 **/
  app.HeaderView = Backbone.View.extend({
    el: '#header',
    template: _.template( $('#tmpl-header').html() ),
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      this.$el.html(this.template( this.model.toJSON() ));
    }
  });

  app.ContactView = Backbone.View.extend({
    el: '#contact',
    template: _.template( $('#tmpl-contact').html() ),
    events: {
      'click .btn-update': 'update'
    },
    update: function() {
      this.model.set({
        name: {
          first: this.$el.find('[name="name.first"]').val(),
          middle: this.$el.find('[name="name.middle"]').val(),
          last: this.$el.find('[name="name.last"]').val(),
          full: this.$el.find('[name="name.first"]').val() +' '+ this.$el.find('[name="name.last"]').val()
        }
      }, {silent: true});

      this.model.update();
    },
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      var modelData = this.model.toJSON();

      //render
      this.$el.html(this.template( modelData ));

      //set input values
      for(var key in modelData) {
        this.$el.find('[name="'+ key +'"]').val(modelData[key]);
      }
    }
  });

  app.LoginView = Backbone.View.extend({
    el: '#login',
    template: _.template( $('#tmpl-login').html() ),
    events: {
      'click .btn-user-open': 'userOpen',
      'click .btn-user-link': 'userLink',
      'click .btn-user-unlink': 'userUnlink'
    },
    userOpen: function() {
      location.href = '/admin/users/'+ this.model.get('user')._id +'/';
    },
    userLink: function() {
      this.model.set({ newUsername: $('[name="newUsername"]').val() }, {silent: true});
      this.model.userLink();
    },
    userUnlink: function() {
      if (confirm('Are you sure?')) {
        this.model.userUnlink();
      }
    },
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      var modelData = this.model.toJSON();

      //render
      this.$el.html(this.template( modelData ));

      //set input values
      for(var key in modelData) {
        this.$el.find('[name="'+ key +'"]').val(modelData[key]);
      }
    }
  });

  app.GroupsView = Backbone.View.extend({
    el: '#groups',
    template: _.template( $('#tmpl-groups').html() ),
    events: {
      'click .btn-add': 'add',
      'click .btn-delete': 'delete',
      'click .btn-save': 'saveGroups'
    },
    add: function(event) {
      //validate
      var newMembership = this.$el.find('[name="newMembership"]').val();
      var newMembershipName = this.$el.find('[name="newMembership"] option:selected').text();
      if (!newMembership) {
        alert('Please select a group.');
        return;
      }
      else {
        var alreadyAdded = false;
        _.each(this.model.get('groups'), function(group) {
          if (newMembership == group._id) {
            alreadyAdded = true;
          }
        });
        if (alreadyAdded) {
          alert('That group already exists.');
          return;
        }
      }

      //add item
      this.model.get('groups').push({_id: newMembership, name: newMembershipName});

      //sort
      var sorted = this.model.get('groups');
      sorted.sort(function(a, b) {
        return a.name.toLowerCase() > b.name.toLowerCase();
      });
      this.model.set('groups', sorted);

      //re-render
      this.render();
    },
    delete: function(event) {
      if (confirm('Are you sure?')) {
        var idx = this.$el.find('.btn-delete').index(event.currentTarget);
        this.model.get('groups').splice(idx, 1);
        this.render();
      }
    },
    saveGroups: function() {
      if (confirm('Are you sure?')) {
        this.model.saveGroups();
      }
    },
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      var modelData = this.model.toJSON();

      //render
      this.$el.html(this.template( modelData ));

      //set input values
      for(var key in modelData) {
        this.$el.find('[name="'+ key +'"]').val(modelData[key]);
      }
    }
  });

  app.PermissionsView = Backbone.View.extend({
    el: '#permissions',
    template: _.template( $('#tmpl-permissions').html() ),
    events: {
      'click .btn-add': 'add',
      'click .btn-allow': 'allow',
      'click .btn-deny': 'deny',
      'click .btn-delete': 'delete',
      'click .btn-set': 'savePermissions'
    },
    add: function(event) {
      //validate
      var newPermission = this.$el.find('[name="newPermission"]').val().trim();
      if (!newPermission) {
        alert('Please enter a name.');
        return;
      }
      else {
        var alreadyAdded = false;
        _.each(this.model.get('permissions'), function(permission) {
          if (newPermission == permission.name) {
            alreadyAdded = true;
          }
        });
        if (alreadyAdded) {
          alert('That name already exists.');
          return;
        }
      }

      //add item
      this.model.get('permissions').push({name: newPermission, permit: true});

      //sort
      var sorted = this.model.get('permissions');
      sorted.sort(function(a, b) {
        return a.name.toLowerCase() > b.name.toLowerCase();
      });
      this.model.set('permissions', sorted);

      //re-render
      this.render();
    },
    allow: function(event) {
      var idx = this.$el.find('.btn-allow').index(event.currentTarget);
      this.model.get('permissions')[idx].permit = true;
      this.render();
    },
    deny: function(event) {
      var idx = this.$el.find('.btn-deny').index(event.currentTarget);
      this.model.get('permissions')[idx].permit = false;
      this.render();
    },
    delete: function(event) {
      if (confirm('Are you sure?')) {
        var idx = this.$el.find('.btn-delete').index(event.currentTarget);
        this.model.get('permissions').splice(idx, 1);
        this.render();
      }
    },
    savePermissions: function() {
      if (confirm('Are you sure?')) {
        this.model.savePermissions();
      }
    },
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      var modelData = this.model.toJSON();

      //render
      this.$el.html(this.template( modelData ));

      //set input values
      for(var key in modelData) {
        this.$el.find('[name="'+ key +'"]').val(modelData[key]);
      }
    }
  });

  app.DeleteView = Backbone.View.extend({
    el: '#delete',
    template: _.template( $('#tmpl-delete').html() ),
    events: {
      'click .btn-delete': 'delete',
    },
    delete: function() {
      if (confirm('Are you sure?')) {
        this.model.delete();
      }
    },
    initialize: function() {
      this.model.on('change', this.render, this);
      this.render();
    },
    render: function() {
      if (this.model.get('success')) {
        location.href = '/admin/administrators/';
      }

      //render
      this.$el.html(this.template( this.model.toJSON() ));
    }
  });

  app.MainView = Backbone.View.extend({
    el: '.page .container',
    initialize: function() {
      var groupList = JSON.parse($('#data-group-list').html());
      var initData = JSON.parse($('#data-record').html());
      this.model = new app.Contact({
        _id: initData._id,
        name: {
          first: initData.name.first,
          middle: initData.name.middle,
          last: initData.name.last,
          full: initData.name.full
        }
      });

      app.headerView = new app.HeaderView({ model: this.model });
      app.contactView = new app.ContactView({ model: this.model });
      app.loginView = new app.LoginView({ model: new app.Login({ _id: initData._id, user: initData.user }) });
      app.groupsView = new app.GroupsView({ model: new app.Groups({ _id: initData._id, groups: initData.groups, groupList: groupList }) });
      app.permissionsView = new app.PermissionsView({ model: new app.Permissions({ _id: initData._id, permissions: initData.permissions }) });
      app.deleteView = new app.DeleteView({ model: new app.Delete({ _id: initData._id }) });
    }
  });

/**
 * BOOTUP
 **/
  $(document).ready(function() {
    app.mainView = new app.MainView();
  });


text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}

--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
--     * Redistributions of source code must retain the above copyright notice,
--       this list of conditions and the following disclaimer.
--     * Redistributions in binary form must reproduce the above copyright
--       notice, this list of conditions and the following disclaimer in the
--       documentation and/or other materials provided with the distribution.
--     * Neither the name of the ERICSSON AB nor the names of its contributors
--       may be used to endorse or promote products derived from this software
--       without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--

module Feldspar.Core.Frontend.Integral
where

import qualified Prelude as P

import Data.Int
import Data.Word

import Language.Syntactic

import Feldspar.Range
import Feldspar.Core.Types
import Feldspar.Core.Constructs
import Feldspar.Core.Constructs.Integral

import Feldspar.Core.Frontend.Condition
import Feldspar.Core.Frontend.Eq
import Feldspar.Core.Frontend.Logic
import Feldspar.Core.Frontend.Num
import Feldspar.Core.Frontend.Ord

class (Ord a, Numeric a, BoundedInt a, P.Integral a, Size a ~ Range a) => Integral a
  where
    quot :: Data a -> Data a -> Data a
    quot = sugarSymF Quot
    rem  :: Data a -> Data a -> Data a
    rem  = sugarSymF Rem
    div  :: Data a -> Data a -> Data a
    div  = sugarSymF Div
    mod  :: Data a -> Data a -> Data a
    mod  = sugarSymF Mod
    (^)  :: Data a -> Data a -> Data a
    (^)  = sugarSymF Exp

divSem :: (Integral a)
       => Data a -> Data a -> Data a
divSem x y = (x > 0 && y < 0 || x < 0 && y > 0) && rem x y /= 0 ?   quot x y P.- 1
                                                                P.$ quot x y

instance Integral Word8
instance Integral Word16
instance Integral Word32
instance Integral Word64
instance Integral WordN
instance Integral Int8
instance Integral Int16
instance Integral Int32
instance Integral Int64
instance Integral IntN


text:
import { Component, ElementRef, forwardRef, Inject, Injector, OnInit, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';

import { Util } from '../../../util/util';
import { OBarMenuComponent } from '../o-bar-menu.component';
import { DEFAULT_INPUTS_O_BASE_MENU_ITEM, OBaseMenuItemClass } from '../o-base-menu-item.class';

export const DEFAULT_INPUTS_O_BAR_MENU_ITEM = [
  ...DEFAULT_INPUTS_O_BASE_MENU_ITEM,
  // route [string]: name of the state to navigate. Default: no value.
  'route',

  // action [function]: function to execute. Default: no value.
  'action'
];

@Component({
  selector: 'o-bar-menu-item',
  templateUrl: './o-bar-menu-item.component.html',
  styleUrls: ['./o-bar-menu-item.component.scss'],
  inputs: DEFAULT_INPUTS_O_BAR_MENU_ITEM,
  encapsulation: ViewEncapsulation.None,
  host: {
    '[class.o-bar-menu-item]': 'true',
    '[attr.disabled]': 'disabled'
  }
})
export class OBarMenuItemComponent extends OBaseMenuItemClass implements OnInit {

  protected router: Router;
  route: string;
  action: () => void;

  constructor(
    @Inject(forwardRef(() => OBarMenuComponent)) protected menu: OBarMenuComponent,
    protected elRef: ElementRef,
    protected injector: Injector
  ) {
    super(menu, elRef, injector);
    this.router = this.injector.get(Router);
  }

  ngOnInit() {
    // if (typeof (this.route) === 'string') {
    //   // TODO, permisos por route?
    // } else {
    //   this.restricted = false;
    // }
    super.ngOnInit();
  }

  collapseMenu(evt: Event) {
    if (this.menu) {
      this.menu.collapseAll();
    }
  }

  onClick() {
    if (this.disabled) {
      return;
    }
    if (Util.isDefined(this.route)) {
      this.router.navigate([this.route]);
    } else if (Util.isDefined(this.action)) {
      this.action();
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Media.Animation;
using System.Timers;
using BookApplication.XAML;

namespace BookApplication
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    ///
    public partial class MainWindow : Window
    {
        public TreeViewDataMV treeviewMV = new TreeViewDataMV();
        public AdvertisementMV advertisementMV = new AdvertisementMV();
        //create new object for database operation
        public DBOperation dbOperation = new DBOperation();
        //generate object out of model view class
        public MVVM objMVVM = new MVVM();

        public MainWindow()
        {
            InitializeComponent();

            //load tool bar
            InitializeToolBar();

            //connect database
            dbOperation.ConnectDB();

            //Read first level tree node from database
            List<TreeNode> firstLevelNode = null;
            dbOperation.ReadTreeViewData("select * from TreeView where ParentID = 0", out firstLevelNode);
            treeviewMV.FirstLevelNode = firstLevelNode;

            //Read second level tree node from database
            for(int i=0; i<firstLevelNode.Count; i++)
            {
                //read second level tree nodes of a particular first tree node
                List<TreeNode> secondLevelNode = null;
                int parentID = firstLevelNode[i].NodeID;
                dbOperation.ReadTreeViewData(string.Format("select * from TreeView where ParentID = {0:d}", parentID), out secondLevelNode);
                //each first level tree node corresponds to a number of second level tree nodes, so use Dictionary to persist
                treeviewMV.secondLevelNode.Add(parentID, secondLevelNode);
            }

            //the initial display of GridView should be LocalShelf table from database
            List<Book> bookList = null;
            dbOperation.ReadGridViewData("select * from LocalShelf", out bookList);
            for (int i = 0; i < bookList.Count; i++)
            {
                //for book description module, each book has a corresponding HTML page
                string url = string.Format("file:///D:/ProjectC%23/BookApplication/BookApplication/HTML/book{0}.html", i + 1);
                //calculate reading progress
                int progress = 15 + i * 4;
                objMVVM.BookCollection.Books.Add(new Book(bookList[i].BookID, bookList[i].BookName, bookList[i].BookType, bookList[i].OrderID, bookList[i].Price, bookList[i].Size, bookList[i].Status, bookList[i].Icon, url, progress));
            };

            //Read advertisement from database
            List<string> Adcontent = null;
            dbOperation.ReadAdvertisement("select Content from Advertisement", out Adcontent);
            for (int i = 0; i < Adcontent.Count; i++)
            {
                objMVVM.AdervertiseCollection.Adervertises.Add(new AdvertisementMV(Adcontent[i]));
            }
            advertisementMV.Advertisement = Adcontent;
            if (advertisementMV.Advertisement.Count > 0)
                advertisementMV.CurrentAdvertisement = advertisementMV.Advertisement[0];

            //initialize treeview data
            treeviewMV.InitializeTreeViewData();

            //change advertisement every 30 seconds
            aTimer = new System.Timers.Timer(30000);
            //OnTimedEvent is the function of timer
            aTimer.Elapsed += OnTimedEvent;
            aTimer.Enabled = true;

            //bind treeview model object and booklist view object with main window's DataContext
            //so the user interface would update as soon as the data change
            DataContext = new
            {
                treeviewMV.DigitalResources,
                treeviewMV.ShoppingMall,
                objMVVM.BookCollection,
                objMVVM.AdervertiseCollection
            };

            //bind advertisement model object with control TextBlock's DataContext
            advertise.DataContext = advertisementMV;
        }

        //initialize tool bar on main window
        private void InitializeToolBar()
        {
            //bind a ToolBarInterface object with each button, Name attribute is not used
            Import.Content = new ToolBarInterface { Name = "Import", ImagePath = "../pictures/import.png" };
            Delete.Content = new ToolBarInterface { Name = "Delete", ImagePath = "../pictures/delete.png" };
            MultiSelect.Content = new ToolBarInterface { Name = "MultiSelect", ImagePath = "../pictures/multichoice.png" };
            button4.Content = new ToolBarInterface { Name = "USA", ImagePath = "../pictures/USA.bmp" };
            ListStyle.Content = new ToolBarInterface { Name = "ListStyle", ImagePath = "../pictures/list.png" };
            BookDescription.Content = new ToolBarInterface { Name = "BookDescription", ImagePath = "../pictures/detail.png" };
            button7.Content = new ToolBarInterface { Name = "paste", ImagePath = "../Images/paste.png" };
        }

        private void OnConnectDB(object sender, ExecutedRoutedEventArgs e)
        {
            //dbOperation.ConnectDB();
            //dbOperation.ExecuteReader("select * from TreeView");
        }

        private void OnAboutDlg(object sender, ExecutedRoutedEventArgs e)
        {
            About dlg = new About();
            dlg.Show();
        }

        private void timer_callback(object state)
        {
            /*
            advertisementMV.CurrentAdvertisement = advertisementMV.Advertisement[advertisementMV.Count];
            advertisementMV.Count++;
            if (advertisementMV.Count == advertisementMV.Advertisement.Count)
                advertisementMV.Count = 0;
            */
        }

        //realize the rolling advertisement on the bottom
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //Display advertisement on status bar
            //Timer time = new Timer(timer_callback, null, 1000, 100000);
            DoubleAnimation doubleAnimation = new DoubleAnimation();
            doubleAnimation.From = -advertise.ActualWidth; //start from left
            doubleAnimation.To = canMain.ActualWidth; //move to the right
            doubleAnimation.RepeatBehavior = RepeatBehavior.Forever; //endless rolling from left to right
            doubleAnimation.Duration = new Duration(TimeSpan.Parse("0:0:24")); //rolling time, the shorter time, the faster rolling speed
            advertise.BeginAnimation(Canvas.LeftProperty, doubleAnimation); //start animation
        }

        //My Digital Resources tree view selection change
        private void TreeViewItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //clear bookCollection container, then the GridView would be cleared as well
            objMVVM.BookCollection.Books.Clear();

            //identify the corresponding table name of selected tree node
            TreeNode dd = (TreeNode)TreeViewData.SelectedItem;
            string tablename = dd.TableName;

            //read GridView data from database
            List<Book> bookList = null;
            dbOperation.ReadGridViewData("select * from " + tablename, out bookList);

            //update bookCollection container
            for (int i = 0; i < bookList.Count; i++)
            {
                //URL point to a HTML page(BookApplication\HTML) which displayed in book description function
                string url = string.Format("file:///D:/ProjectC%23/BookApplication/BookApplication/HTML/book{0}.html", i + 1);
                //calculate reading progress
                int progress = 15 + i * 4;
                //add all the book objects to book list in MVVM object
                objMVVM.BookCollection.Books.Add(new Book(bookList[i].BookID, bookList[i].BookName, bookList[i].BookType, bookList[i].OrderID, bookList[i].Price, bookList[i].Size, bookList[i].Status, bookList[i].Icon, url, progress));
            };
        }

        //Online Shopping Mall tree view selection change
        private void TreeViewItem_MouseLeftButtonUp1(object sender, MouseButtonEventArgs e)
        {
            TreeNode node = (TreeNode)TreeViewData.SelectedItem;
            if(node.NodeName == "JD Website")
            {
                JDwebsite pwnd = new JDwebsite();
                pwnd.Show();
            }
        }

        //double click book list GridView, open the reading window
        private void GridViewData_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            Book book = (Book)GridViewData.SelectedItem;
            Content pwnd = new Content(book.BookID);
            pwnd.Show();
        }

        private void MultiSelect_Click(object sender, RoutedEventArgs e)
        {
            if (30 == selcolumn.Width)
                selcolumn.Width = 0;
            else
                selcolumn.Width = 30;
        }

        //delete the selected books from both database and model
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < GridViewData.Items.Count; i++)
            {
                Book book = (Book)GridViewData.Items[i];
                if(book.Check)
                {
                    string sql = string.Format("delete from LocalShelf where BookID={0}", book.BookID);
                    dbOperation.DeleteBook(sql);
                    objMVVM.BookCollection.Books.RemoveAt(i);
                    i--;
                }
            }
        }

        private void GridViewData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Book book = (Book)GridViewData.SelectedItem;
        }

        private void ListStyle_Click(object sender, RoutedEventArgs e)
        {
            ListData.Width = this.Width;
            DetailView.Width = 0;
            TabView.Width = 0;
        }

        //detailed book list selection change
        private void DetailedBookView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //get the selected book object
            Book book = (Book)DetailedBookView.SelectedItem;
            //get url from book object
            Uri source = new Uri(book.Url, UriKind.Absolute);
            //display HTML file
            BookPage.Source = source;
        }

        //when click description tool bar, show the detailed book list which is hidden initially
        private void BookDescription_Click(object sender, RoutedEventArgs e)
        {
            //show the detailed book list by setting width, the original width is 0
            DetailView.Width = 250;
            //TabView is a frame which is used to display HTML page
            TabView.Width = 900;
            //set the original book list GridView's width to 0 to hide it
            ListData.Width = 0;
        }

        public System.Timers.Timer aTimer { get; set; }
        //loop the advertisement list, start from beginning as soon as reaching the end
        private void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            //change current advertisement periodically
            advertisementMV.CurrentAdvertisement = advertisementMV.Advertisement[advertisementMV.Count];
            advertisementMV.Count++;
            //if get to the last advertisement, then restart from the first advertisement
            if (advertisementMV.Count == advertisementMV.Advertisement.Count)
                advertisementMV.Count = 0;
        }

        private void ListStyle_MouseMove(object sender, MouseEventArgs e)
        {
            ListStyle.Content = new ToolBarInterface { Name = "ListStyle", ImagePath = "../pictures/list1.png" };
        }

        private void ListStyle_MouseLeave(object sender, MouseEventArgs e)
        {
            ListStyle.Content = new ToolBarInterface { Name = "ListStyle", ImagePath = "../pictures/list.png" };
        }

        private void Delete_MouseMove(object sender, MouseEventArgs e)
        {
            Delete.Content = new ToolBarInterface { Name = "Delete", ImagePath = "../pictures/delete1.png" };
        }

        private void Delete_MouseLeave(object sender, MouseEventArgs e)
        {
            Delete.Content = new ToolBarInterface { Name = "Delete", ImagePath = "../pictures/delete.png" };
        }

        //Import tool bar's mouse over picture
        private void Import_MouseMove(object sender, MouseEventArgs e)
        {
            Import.Content = new ToolBarInterface { Name = "Import", ImagePath = "../pictures/import1.png" };
        }

        //Import tool bar's mouse leave picture
        private void Import_MouseLeave(object sender, MouseEventArgs e)
        {
            Import.Content = new ToolBarInterface { Name = "Import", ImagePath = "../pictures/import.png" };
        }

        //"start" button on book list GridView
        private void StartRead_Click(object sender, RoutedEventArgs e)
        {
            Book book = (Book)GridViewData.SelectedItem;
            Content pwnd = new Content(book.BookID);
            pwnd.Show();
        }

        //function of menu "Exit"
        private void OnExit(object sender, ExecutedRoutedEventArgs e)
        {
            this.Close();
        }

        private void MultiSelect_MouseMove(object sender, MouseEventArgs e)
        {
            MultiSelect.Content = new ToolBarInterface { Name = "MultiSelect", ImagePath = "../pictures/multichoice1.png" };
        }

        private void MultiSelect_MouseLeave(object sender, MouseEventArgs e)
        {
            MultiSelect.Content = new ToolBarInterface { Name = "MultiSelect", ImagePath = "../pictures/multichoice.png" };
        }

        private void BookDescription_MouseMove(object sender, MouseEventArgs e)
        {
            BookDescription.Content = new ToolBarInterface { Name = "BookDescription", ImagePath = "../pictures/detail1.png" };
        }

        private void BookDescription_MouseLeave(object sender, MouseEventArgs e)
        {
            BookDescription.Content = new ToolBarInterface { Name = "BookDescription", ImagePath = "../pictures/detail.png" };
        }
    }
}


text:
package org.apache.flink.runtime.executiongraph.failover.flip1;

/**
 * Restart strategy which does not restart tasks when tasks fail.
 */
public enum  NoRestartBackoffTimeStrategy implements RestartBackoffTimeStrategy {
	INSTANCE;

	@Override
	public boolean canRestart() {
		return false;
	}

	@Override
	public long getBackoffTime() {
		return 0L;
	}

	@Override
	public void notifyFailure(final Throwable cause) {
		// nothing to do
	}

	@Override
	public String toString() {
		return "NoRestartBackoffTimeStrategy";
	}

	/**
	 * The factory for creating {@link NoRestartBackoffTimeStrategy}.
	 */
	public enum NoRestartBackoffTimeStrategyFactory implements Factory {
		INSTANCE;

		@Override
		public RestartBackoffTimeStrategy create() {
			return NoRestartBackoffTimeStrategy.INSTANCE;
		}

		@Override
		public String toString() {
			return "NoRestartBackoffTimeStrategyFactory";
		}
	}
}


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Sets the default storage account
#>
function Set-CurrentStorageAccountName
{
    param([string] $storageAccountName)
    $currentSubscription = Get-AzureSubscription -Current

    Set-AzureSubscription -SubscriptionId $currentSubscription.SubscriptionId -CurrentStorageAccountName $storageAccountName
}

<#
.SYNOPSIS
Gets the default location
#>
function Get-DefaultLocation
{
    return (Get-AzureLocation)[0].Name
}

<#
.SYNOPSIS
Gets the default image
#>
function Get-DefaultImage
{
    param([string] $loc)
    return (Get-AzureVMImage | where {$_.OS -eq "Windows"} | where {$_.Location.Contains($loc)})[0].ImageName
}

<#
.SYNOPSIS
Gets valid and available cloud service name.
#>
function Get-CloudServiceName
{
    return getAssetName
}

<#
.SYNOPSIS
Cleanup cloud service
#>
function Cleanup-CloudService
{
    param([string] $name)
    try
    {
         Remove-AzureService -ServiceName $name -Force
    }
    catch
    {
         Write-Warning "Cannot Remove the Cloud Service"
    }
}

<#
.SYNOPSIS
Cleanup storage
#>
function Cleanup-Storage
{
    param([string] $name)
    Remove-AzureStorageAccount -StorageAccountName $name
    try
    {
         Remove-AzureStorageAccount -StorageAccountName $name
    }
    catch
    {
         Write-Warning "Cannot Remove the Storage Account"
    }
}

<#
.SYNOPSIS
Gets test mode - 'Record' or 'Playback'
#>
function Get-ComputeTestMode
{
    $oldErrorActionPreferenceValue = $ErrorActionPreference;
    $ErrorActionPreference = "SilentlyContinue";

    try
    {
        $testMode = [Microsoft.Azure.Test.HttpRecorder.HttpMockServer]::Mode;
        $testMode = $testMode.ToString();
    }
    catch
    {
        if (($Error.Count -gt 0) -and ($Error[0].Exception.Message -like '*Unable to find type*'))
        {
            $testMode = 'Record';
        }
        else
        {
            throw;
        }
    }
    finally
    {
        $ErrorActionPreference = $oldErrorActionPreferenceValue;
    }

    return $testMode;
}


text:
package com.intellij.openapi.ui;

import org.jetbrains.annotations.NotNull;

public interface TestDialog {
  TestDialog DEFAULT = message -> {
    throw new RuntimeException(message);
  };
  TestDialog YES = __ -> Messages.YES;
  TestDialog OK = __ -> Messages.OK;
  TestDialog NO = __ -> Messages.NO;

  int show(@NotNull String message);
}


text:
import os
import posixpath
import re
import shutil
import sys

from distutils import sysconfig
import setuptools
from setuptools.command import build_ext

here = os.path.dirname(os.path.abspath(__file__))

IS_WINDOWS = sys.platform.startswith('win')

def _get_version():
  """Parse the version string from __init__.py."""
  with open(os.path.join(here, 'bindings', 'python', 'benchmark', '__init__.py')) as f:
    try:
      version_line = next(
          line for line in f if line.startswith('__version__'))
    except StopIteration:
      raise ValueError('__version__ not defined in __init__.py')
    else:
      ns = {}
      exec(version_line, ns)  # pylint: disable=exec-used
      return ns['__version__']

def _parse_requirements(path):
  with open(os.path.join(here, path)) as f:
    return [
        line.rstrip() for line in f
        if not (line.isspace() or line.startswith('#'))
    ]

class BazelExtension(setuptools.Extension):
  """A C/C++ extension that is defined as a Bazel BUILD target."""

  def __init__(self, name, bazel_target):
    self.bazel_target = bazel_target
    self.relpath, self.target_name = (
        posixpath.relpath(bazel_target, '//').split(':'))
    setuptools.Extension.__init__(self, name, sources=[])

class BuildBazelExtension(build_ext.build_ext):
  """A command that runs Bazel to build a C/C++ extension."""

  def run(self):
    for ext in self.extensions:
      self.bazel_build(ext)
    build_ext.build_ext.run(self)

  def bazel_build(self, ext):
    with open('WORKSPACE', 'r') as f:
      workspace_contents = f.read()

    with open('WORKSPACE', 'w') as f:
      f.write(re.sub(
          r'(?<=path = ").*(?=",  # May be overwritten by setup\.py\.)',
          sysconfig.get_python_inc().replace(os.path.sep, posixpath.sep),
          workspace_contents))

    if not os.path.exists(self.build_temp):
      os.makedirs(self.build_temp)

    bazel_argv = [
        'bazel',
        'build',
        ext.bazel_target,
        '--symlink_prefix=' + os.path.join(self.build_temp, 'bazel-'),
        '--compilation_mode=' + ('dbg' if self.debug else 'opt'),
    ]

    if IS_WINDOWS:
      # Link with python*.lib.
      for library_dir in self.library_dirs:
        bazel_argv.append('--linkopt=/LIBPATH:' + library_dir)

    self.spawn(bazel_argv)

    shared_lib_suffix = '.dll' if IS_WINDOWS else '.so'
    ext_bazel_bin_path = os.path.join(
        self.build_temp, 'bazel-bin',
        ext.relpath, ext.target_name + shared_lib_suffix)
    ext_dest_path = self.get_ext_fullpath(ext.name)
    ext_dest_dir = os.path.dirname(ext_dest_path)
    if not os.path.exists(ext_dest_dir):
      os.makedirs(ext_dest_dir)
    shutil.copyfile(ext_bazel_bin_path, ext_dest_path)

setuptools.setup(
    name='google-benchmark',
    version=_get_version(),
    url='https://github.com/google/benchmark',
    description='A library to benchmark code snippets.',
    author='Google',
    author_email='benchmark-py@google.com',
    # Contained modules and scripts.
    package_dir={'': 'bindings/python'},
    packages=setuptools.find_packages('bindings/python'),
    install_requires=_parse_requirements('bindings/python/requirements.txt'),
    cmdclass=dict(build_ext=BuildBazelExtension),
    ext_modules=[BazelExtension('benchmark._benchmark', '//bindings/python/benchmark:_benchmark')],
    zip_safe=False,
    # PyPI package information.
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Topic :: Software Development :: Testing',
        'Topic :: System :: Benchmark',
    ],
    license='Apache 2.0',
    keywords='benchmark',
)