text:
package qiniu.predem.android.probe;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.regex.Matcher;

import javax.net.ssl.HttpsURLConnection;

import qiniu.predem.android.bean.LogBean;
import qiniu.predem.android.config.Configuration;
import qiniu.predem.android.http.MySSLSocketFactory;
import qiniu.predem.android.http.ProbeInputStream;
import qiniu.predem.android.util.LogUtils;
import qiniu.predem.android.util.MatcherUtil;

/**
 * Created by Misty on 5/18/17.
 */
@Aspect
public final class HttpURLConnProbe {
    protected static final HashMap<Object, LogBean> reportMap = new HashMap<>();
    private static final String TAG = "HttpURLConnProbe";

    @Around("call(* java.net.URL+.openConnection(..))")
    public Object onHttpURLOpenConnect(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!Configuration.httpMonitorEnable || joinPoint.getArgs().length != 0) {
            return joinPoint.proceed();
        }

        try {
            if (!joinPoint.getTarget().toString().startsWith("http://") && !joinPoint.getTarget().toString().startsWith("https://")) {
                return joinPoint.proceed();
            }

            URL url = (URL) joinPoint.getTarget();

            //判断是否需要收集url信息
            if (GlobalConfig.isExcludeHost(url.getHost()) || ProbeWebClient.isExcludeIPs(url.getHost())) {
                return joinPoint.proceed();
            }

            HttpURLConnection conn;

            LogBean bean = LogBean.obtain();
            bean.setStartTimestamp(System.currentTimeMillis());
            conn = (HttpURLConnection) joinPoint.proceed();
            // 判断host是否是IP
            Matcher matcher = MatcherUtil.IP_Pattern.matcher(url.getHost());
            if (matcher.find()) {
                bean.setHostIP(url.getHost());
                bean.setDnsTime(0);
                bean.setDomain(url.getHost());
                bean.setPath(url.getPath());
            } else {
                String hostIp = null;
                if (Configuration.dnsEnable) {
                    long stime = System.currentTimeMillis();
                    try {
                        bean.setHostIP(InetAddress.getByName(url.getHost()).getHostAddress());
                    } catch (UnknownHostException e) {
                        throw e;
                    }
                    bean.setDnsTime(System.currentTimeMillis() - stime);
                    bean.setDomain(url.getHost());
                    bean.setPath(url.getPath());

                    //302跳转
                    conn.setInstanceFollowRedirects(false);
                    //https请求
                    if (url.toString().startsWith("https://")) {
                        ((HttpsURLConnection) conn).setSSLSocketFactory(new MySSLSocketFactory(hostIp));
                    }
                } else {
                    return joinPoint.proceed();
                }
                synchronized (reportMap) {
                    reportMap.put(conn.hashCode(), bean);
                }
            }
            return conn;
        } catch (Exception e) {
            LogUtils.e(TAG, "-----" + e.toString());
            return joinPoint.proceed();
        }
    }

    @Around("call(* java.net.URLConnection+.getInputStream(..))")
    public Object onHttpURLConnectInput(ProceedingJoinPoint joinPoint) throws Throwable {
        if (!Configuration.httpMonitorEnable) {
            return joinPoint.proceed();
        }
        try {
            URLConnection conn = (URLConnection) joinPoint.getTarget();

            URL url;
            if (conn instanceof HttpURLConnection) {
                url = ((HttpURLConnection) joinPoint.getTarget()).getURL();
            } else {
                return joinPoint.proceed();
            }

            if (GlobalConfig.isExcludeHost(url.getHost()) || ProbeWebClient.isExcludeIPs(url.getHost())) {
                return joinPoint.proceed();
            }

            try {
                synchronized (reportMap) {
                    int key = conn.hashCode();
                    if (reportMap.containsKey(key)) {
                        LogBean urlTraceRecord = reportMap.get(key);
                        reportMap.remove(key);
                        if (GlobalConfig.isExcludeHost(urlTraceRecord.getDomain()) || ProbeWebClient.isExcludeIPs(urlTraceRecord.getDomain())) {
                            return joinPoint.proceed();
                        }

                        urlTraceRecord.setResponseTimestamp(System.currentTimeMillis());
                        urlTraceRecord.setStatusCode(((HttpURLConnection) conn).getResponseCode());
                        return ProbeInputStream.obtain((InputStream) joinPoint.proceed(), urlTraceRecord);
                    } else {
                        LogBean urlTraceRecord = LogBean.obtain();
                        urlTraceRecord.setDomain(url.getHost());
                        urlTraceRecord.setPath(url.getPath());
                        urlTraceRecord.setMethod(((HttpURLConnection) conn).getRequestMethod());
                        urlTraceRecord.setDnsTime(0);
                        urlTraceRecord.setResponseTimestamp(System.currentTimeMillis());
                        urlTraceRecord.setHostIP("-");
                        urlTraceRecord.setStatusCode(((HttpURLConnection) conn).getResponseCode());
                        return ProbeInputStream.obtain((InputStream) joinPoint.proceed(), urlTraceRecord);
                    }
                }
            } catch (Exception e) {
                LogUtils.e(TAG, e.toString());
                return joinPoint.proceed();
            }
        } catch (Exception e) {
            LogUtils.e(TAG, e.toString());
            return joinPoint.proceed();
        }
    }
}


text:
package libsvm;
public class Model implements java.io.Serializable
{
	public Parameter param;	// parameter
	public int nr_class;		// number of classes, = 2 in regression/one class svm
	public int l;			// total #SV
	public Node[][] SV;	// SVs (SV[l])
	public double[][] sv_coef;	// coefficients for SVs in decision functions (sv_coef[k-1][l])
	public double[] rho;		// constants in decision functions (rho[k*(k-1)/2])
  public double[] w_2;   // hyperplane squared norms for each binary SVM (PCL, taken from Gabor Melis)
	public double[] probA;         // pariwise probability information
	public double[] probB;
	public int[] sv_indices;       // sv_indices[0,...,nSV-1] are values in [1,...,num_traning_data] to indicate SVs in the training set

	// for classification only

	public int[] label;		// label of each class (label[k])
	public int[] nSV;		// number of SVs for each class (nSV[k])
				// nSV[0] + nSV[1] + ... + nSV[k-1] = l
};

redpajama_set_name: RedPajamaGithub


text:
"""Brazilian Portuguese Word-of-the-Day from transparent.com"""

import logging
import xml.etree.ElementTree as ET
from asyncio import create_task, sleep
from datetime import timedelta

import httpx

REFRESH_INTERVAL = timedelta(hours=8)

_logger = logging.getLogger(__name__)
_state = {}

def start_plugin(context):
    task = create_task(_refresh(context), name="word_ptbr.refresh")
    _state["task"] = task

def stop_plugin(context):  # pylint: disable=unused-argument
    task = _state.get("task")
    if task:
        task.cancel()

async def _refresh(context):
    """Get the word of the day."""
    url = "https://wotd.transparent.com/rss/pt-widget.xml"
    while True:
        try:
            transport = httpx.AsyncHTTPTransport(retries=3)
            async with httpx.AsyncClient(transport=transport, timeout=10) as client:
                response = await client.get(url)
            response.raise_for_status()
            data = _parse(response.text)
            await context.post_event("refresh", data)
            context.vote_connected()
        except httpx.TransportError as ex:
            # https://www.python-httpx.org/exceptions/
            context.vote_disconnected(ex)
            _logger.exception("Network error getting word-of-the-day data.")
        except Exception:  # pylint: disable=broad-except
            _logger.exception("Error getting word-of-the-day data.")

        await sleep(REFRESH_INTERVAL.total_seconds())

def _parse(xml):
    root = ET.fromstring(xml)
    return {
        "word": root.find("./words/word").text,
        "translation": root.find("./words/translation").text,
        "part_of_speech": root.find("./words/wordtype").text,
        "sentence": root.find("./words/fnphrase").text,
        "sentence_translation": root.find("./words/enphrase").text,
    }


text:
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import PageHeader from 'components/PageHeader'
import { connect } from 'react-redux'
import { createGif } from 'state/gifs/actions'
import { push } from 'redux-json-router'

class PageAdd extends PureComponent {

  state = {
    name: '',
    description: ''
  }

  handleSubmit = (e) => {
    const { createGif, push } = this.props
    const { title, url } = e.target

    e.preventDefault()

    return createGif({ name: title.value, url: url.value })
      .then(data => push('/'))
  }

  render () {
    return (

        <PageHeader title='Add Gif' />
        <form onSubmit={ this.handleSubmit }>

          Title
          <input
            type='text'
            id='title'
            name='title' />

          Url:
          <input
            type='text'
            id='url'
            name='url' />

          <button type='submit' >Save</button>
        </form>

    )
  }

}

PageAdd.propTypes = {
  createGif: PropTypes.func.isRequired,
  push: PropTypes.func.isRequired
}

export default connect(null, { createGif, push })(PageAdd)


text:
/**
 * Used as the maximum length of an array-like value.
 * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
 * for more details.
 */
var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;

/**
 * Checks if `value` is a valid array-like length.
 *
 * **Note:** This function is based on ES `ToLength`. See the
 * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)
 * for more details.
 *
 * @private
 * @param {*} value The value to check.
 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
 */
function isLength(value) {
  return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}

module.exports = isLength;


text:
import { JointBase } from "./JointBase";
import { Sprite } from "../../display/Sprite"
import { Point } from "../../maths/Point"
import { Physics } from "../Physics"
import { RigidBody } from "../RigidBody"
import { ClassUtils } from "../../utils/ClassUtils";

/**
 * 轮子关节:围绕节点旋转,包含弹性属性,使得刚体在节点位置发生弹性偏移
 */
export class WheelJoint extends JointBase {
    /**@private */
    private static _temp: any;
    /**[首次设置有效]关节的自身刚体*/
    selfBody: RigidBody;
    /**[首次设置有效]关节的连接刚体*/
    otherBody: RigidBody;
    /**[首次设置有效]关节的链接点,是相对于自身刚体的左上角位置偏移*/
    anchor: any[] = [0, 0];
    /**[首次设置有效]两个刚体是否可以发生碰撞,默认为false*/
    collideConnected: boolean = false;
    /**[首次设置有效]一个向量值,描述运动方向,比如1,0是沿X轴向右*/
    axis: any[] = [1, 0];

    /**弹簧系统的震动频率,可以视为弹簧的弹性系数,通常频率应该小于时间步长频率的一半*/
    private _frequency: number = 5;
    /**刚体在回归到节点过程中受到的阻尼比,建议取值0~1*/
    private _dampingRatio: number = 0.7;

    /**是否开启马达,开启马达可使目标刚体运动*/
    private _enableMotor: boolean = false;
    /**启用马达后,可以达到的最大旋转速度*/
    private _motorSpeed: number = 0;
    /**启用马达后,可以施加的最大扭距,如果最大扭矩太小,会导致不旋转*/
    private _maxMotorTorque: number = 10000;

     /**是否对刚体的移动范围加以约束*/
     private _enableLimit: boolean = true;
     /**启用约束后,刚体移动范围的下限,是距离anchor的偏移量*/
     private _lowerTranslation: number = 0;
     /**启用约束后,刚体移动范围的上限,是距离anchor的偏移量*/
     private _upperTranslation: number = 0;

    /**
     * @override
     */
    protected _createJoint(): void {
        if (!this._joint) {
            if (!this.otherBody) throw "otherBody can not be empty";
            this.selfBody = this.selfBody || this.owner.getComponent(RigidBody);
            if (!this.selfBody) throw "selfBody can not be empty";

            var box2d: any = (<any>window).box2d;
            var def: any = WheelJoint._temp || (WheelJoint._temp = new box2d.b2WheelJointDef());
            var anchorPos: Point = (<Sprite>this.selfBody.owner).localToGlobal(Point.TEMP.setTo(this.anchor[0], this.anchor[1]), false, Physics.I.worldRoot);
            var anchorVec: any = new box2d.b2Vec2(anchorPos.x / Physics.PIXEL_RATIO, anchorPos.y / Physics.PIXEL_RATIO);
            def.Initialize(this.otherBody.getBody(), this.selfBody.getBody(), anchorVec, new box2d.b2Vec2(this.axis[0], this.axis[1]));
            def.enableMotor = this._enableMotor;
            def.motorSpeed = this._motorSpeed;
            def.maxMotorTorque = this._maxMotorTorque;
            box2d.b2LinearStiffness(def, this._frequency, this._dampingRatio, def.bodyA, def.bodyB);
            // def.stiffness = this._stiffness;
            // def.damping = this._damping;
            def.collideConnected = this.collideConnected;
            def.enableLimit = this._enableLimit;
            def.lowerTranslation = this._lowerTranslation / Physics.PIXEL_RATIO;
            def.upperTranslation = this._upperTranslation / Physics.PIXEL_RATIO;

            this._joint = Physics.I._createJoint(def);
        }
    }

    /**弹簧系统的震动频率,可以视为弹簧的弹性系数,通常频率应该小于时间步长频率的一半*/
    get frequency(): number {
        return this._frequency;
    }

    set frequency(value: number) {
        this._frequency = value;
        if (this._joint) {
            let out: any = {};
            let box2d: any = (<any>window).box2d;
            let bodyA = this.otherBody ? this.otherBody.getBody() : Physics.I._emptyBody;
            let bodyB = this.selfBody.getBody();
            box2d.b2LinearStiffness(out, this._frequency, this._dampingRatio, bodyA, bodyB);

            this._joint.SetStiffness(out.stiffness);
            this._joint.SetDamping(out.damping);
        }
    }

    /**刚体在回归到节点过程中受到的阻尼比,建议取值0~1*/
    get damping(): number {
        return this._dampingRatio;
    }

    set damping(value: number) {
        this._dampingRatio = value;
        if (this._joint) {
            let out: any = {};
            let box2d: any = (<any>window).box2d;
            let bodyA = this.otherBody ? this.otherBody.getBody() : Physics.I._emptyBody;
            let bodyB = this.selfBody.getBody();
            box2d.b2LinearStiffness(out, this._frequency, this._dampingRatio, bodyA, bodyB);

            // this._joint.SetStiffness(out.stiffness); // 修改 dampingRatio 最终只影响 damping
            this._joint.SetDamping(out.damping);
        }
    }

    /**是否开启马达,开启马达可使目标刚体运动*/
    get enableMotor(): boolean {
        return this._enableMotor;
    }

    set enableMotor(value: boolean) {
        this._enableMotor = value;
        if (this._joint) this._joint.EnableMotor(value);
    }

    /**启用马达后,可以达到的最大旋转速度*/
    get motorSpeed(): number {
        return this._motorSpeed;
    }

    set motorSpeed(value: number) {
        this._motorSpeed = value;
        if (this._joint) this._joint.SetMotorSpeed(value);
    }

    /**启用马达后,可以施加的最大扭距,如果最大扭矩太小,会导致不旋转*/
    get maxMotorTorque(): number {
        return this._maxMotorTorque;
    }

    set maxMotorTorque(value: number) {
        this._maxMotorTorque = value;
        if (this._joint) this._joint.SetMaxMotorTorque(value);
    }

    /**是否对刚体的移动范围加以约束*/
    get enableLimit(): boolean {
        return this._enableLimit;
    }

    set enableLimit(value: boolean) {
        this._enableLimit = value;
        if (this._joint) this._joint.EnableLimit(value);
    }

    /**启用约束后,刚体移动范围的下限,是距离anchor的偏移量*/
    get lowerTranslation(): number {
        return this._lowerTranslation;
    }

    set lowerTranslation(value: number) {
        this._lowerTranslation = value;
        if (this._joint) this._joint.SetLimits(value, this._upperTranslation);
    }

    /**启用约束后,刚体移动范围的上限,是距离anchor的偏移量*/
    get upperTranslation(): number {
        return this._upperTranslation;
    }

    set upperTranslation(value: number) {
        this._upperTranslation = value;
        if (this._joint) this._joint.SetLimits(this._lowerTranslation, value);
    }
}

ClassUtils.regClass("laya.physics.joint.WheelJoint", WheelJoint);
ClassUtils.regClass("Laya.WheelJoint", WheelJoint);


text:
#include "lullaby/systems/render/fpl/material.h"

#include <utility>

#include "lullaby/util/logging.h"

namespace lull {

Material::Material(
    const ShaderPtr& shader,
    const std::vector<Uniform::Description>& uniform_descriptions) {
  SetShader(shader);
  for (const auto& it : uniform_descriptions) {
    AddUniform(it);
  }
}

void Material::SetShader(const ShaderPtr& shader) {
  shader_ = shader;
  for (auto& uniform : uniforms_) {
    uniform.GetDescription().binding = -1;
  }
}
const ShaderPtr& Material::GetShader() const { return shader_; }

void Material::SetTexture(int index, const TexturePtr& texture) {
  // Texture unit is an int, but must be positive and below the number of
  // samplers. Currently we aren't checking how many samplers are available,
  // therefore we at best ensure the value is below 256.
  DCHECK_GE(index, 0);
  DCHECK_LE(index, 255);

  if (texture == nullptr) {
    textures_.erase(index);
  } else {
    textures_[index] = texture;
  }
}
TexturePtr Material::GetTexture(int index) const {
  const auto it = textures_.find(index);
  if (it == textures_.end()) {
    return nullptr;
  } else {
    return it->second;
  }
}

Material::UniformIndex Material::AddUniform(
    const Uniform::Description& description) {
  const UniformIndex index = uniforms_.size();

  uniforms_.emplace_back(description);
  name_to_uniform_index_[Hash(description.name)] = index;

  return index;
}

Material::UniformIndex Material::AddUniform(Uniform uniform) {
  const UniformIndex index = static_cast<UniformIndex>(uniforms_.size());
  Uniform::Description& desc = uniform.GetDescription();
  desc.binding = -1;

  name_to_uniform_index_[Hash(desc.name)] = index;
  uniforms_.emplace_back(std::move(uniform));

  return index;
}

void Material::ClearUniforms() {
  name_to_uniform_index_.clear();
  uniforms_.clear();
}

Uniform* Material::GetUniformByName(string_view name) {
  return GetUniformByHash(Hash(name));
}

const Uniform* Material::GetUniformByName(string_view name) const {
  return GetUniformByHash(Hash(name));
}

Uniform* Material::GetUniformByIndex(UniformIndex index) {
  if (index < uniforms_.size()) {
    return &uniforms_[index];
  }

  return nullptr;
}

const Uniform* Material::GetUniformByIndex(UniformIndex index) const {
  if (index < uniforms_.size()) {
    return &uniforms_[index];
  }

  return nullptr;
}

Uniform* Material::GetUniformByHash(HashValue hash) {
  const auto it = name_to_uniform_index_.find(hash);
  if (it == name_to_uniform_index_.end()) {
    return nullptr;
  }

  return GetUniformByIndex(it->second);
}

const Uniform* Material::GetUniformByHash(HashValue hash) const {
  const auto it = name_to_uniform_index_.find(hash);
  if (it == name_to_uniform_index_.end()) {
    return nullptr;
  }

  return GetUniformByIndex(it->second);
}

void Material::SetUniform(Uniform uniform) {
  const HashValue name_hash = Hash(uniform.GetDescription().name);
  auto iter = name_to_uniform_index_.find(name_hash);
  if (iter != name_to_uniform_index_.end()) {
    uniforms_[iter->second] = std::move(uniform);
  } else {
    name_to_uniform_index_[name_hash] = uniforms_.size();
    uniforms_.emplace_back(std::move(uniform));
  }
}

const std::vector<Uniform>& Material::GetUniforms() const { return uniforms_; }
std::vector<Uniform>& Material::GetUniforms() { return uniforms_; }
const std::unordered_map<int, TexturePtr>& Material::GetTextures() const {
  return textures_;
}

void Material::SetBlendState(const fplbase::BlendState* blend_state) {
  if (blend_state) {
    blend_state_ = *blend_state;
  } else {
    blend_state_.reset();
  }
}

void Material::SetCullState(const fplbase::CullState* cull_state) {
  if (cull_state) {
    cull_state_ = *cull_state;
  } else {
    cull_state_.reset();
  }
}

void Material::SetDepthState(const fplbase::DepthState* depth_state) {
  if (depth_state) {
    depth_state_ = *depth_state;
  } else {
    depth_state_.reset();
  }
}

void Material::SetPointState(const fplbase::PointState* point_state) {
  if (point_state) {
    point_state_ = *point_state;
  } else {
    point_state_.reset();
  }
}

void Material::SetStencilState(const fplbase::StencilState* stencil_state) {
  if (stencil_state) {
    stencil_state_ = *stencil_state;
  } else {
    stencil_state_.reset();
  }
}

const fplbase::BlendState* Material::GetBlendState() const {
  return blend_state_.get();
}

const fplbase::CullState* Material::GetCullState() const {
  return cull_state_.get();
}

const fplbase::DepthState* Material::GetDepthState() const {
  return depth_state_.get();
}

const fplbase::PointState* Material::GetPointState() const {
  return point_state_.get();
}

const fplbase::StencilState* Material::GetStencilState() const {
  return stencil_state_.get();
}

}  // namespace lull


text:
package com.rappidjs.ide.idea.js.requirejs;

import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.util.IncorrectOperationException;
import com.rappidjs.ide.idea.RappidProject;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * User: tony
 * Date: 26.08.14
 * Time: 11:01
 */
public class RequirejsReference implements PsiReference {

    protected PsiElement element;
    protected TextRange textRange;
    protected RappidProject rappidProject;

    public RequirejsReference(PsiElement element, TextRange textRange, RappidProject rappidProject) {
        this.element = element;
        this.textRange = textRange;
        this.rappidProject = rappidProject;
    }

    @Override
    public PsiElement getElement() {
        return this.element;
    }

    @Nullable
    @Override
    public PsiElement resolve() {
        return rappidProject.getRequirejsConfig().requireResolve(element);
    }

    @Override
    public String toString() {
        return getCanonicalText();
    }

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

    @NotNull
    @Override
    public Object[] getVariants() {
        ArrayList<LookupElement> completionResultSet = new ArrayList<LookupElement>();

        return completionResultSet.toArray();
//
//        List<String> files = element
//                .getProject()
//                .getComponent(RequirejsProjectComponent.class)
//                .getCompletion(element);
//
//        for (String file : files) {
//            completionResultSet.add(
//                    LookupElementBuilder
//                            .create(element, file)
//                            .withInsertHandler(
//                                    RequirejsInsertHandler.getInstance()
//                            )
//            );
//        }
//
//        return completionResultSet.toArray();
    }

    @Override
    public boolean isReferenceTo(PsiElement psiElement) {
        return false;
    }

    @Override
    public PsiElement bindToElement(@NotNull PsiElement psiElement) throws IncorrectOperationException {
        throw new IncorrectOperationException();
    }

    @Override
    public PsiElement handleElementRename(String s) throws IncorrectOperationException {
        throw new IncorrectOperationException();
    }

    @Override
    public TextRange getRangeInElement() {
        return textRange;
    }

    @NotNull
    @Override
    public String getCanonicalText() {
        return element.getText();
    }
}


text:
// Camera
// * Use person and face detection to know when people are around, or cats
//

var cameraSource = (function(global) {

  var id = 'source-camera',
      title = 'Camera',
      videoElement = null;

  function start(opts) {
    videoElement = opts.videoElement;
    showCameraPreview(opts.callback);
  }

  function showCameraPreview(cb) {
    navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {

      var vidURL = window.URL.createObjectURL(stream);

      videoElement.src = vidURL;
      videoElement.play();

      if (cb) {
        cb();
      }

      /*
      setInterval(function() {
        console.log('intval')

        videoSnapshot(function(canvas) {
          //track.stop();

          //addSnapshotToPage(canvas);

          // upload photo
          canvas.toBlob(function(blob) {
            uploadPhoto(blob, function() {
              console.log('uploaded!')
            });
          });

        });
      }, 2000);
      */

    });
  }

  // the whole deal
  // * videoSnapshot() writes snapshot from video preview to a canvas
  // * get the binary data from the snapshot
  // * upload the binary data to the server
  function snapshot() {
    videoSnapshot(function(canvas) {
      // upload photo
      canvas.toBlob(function(blob) {
        uploadPhoto(blob, function() {
          console.log('uploaded!')
        });
      });
    });
  }

  function snapshotToCanvas(cb) {
    videoSnapshot(cb);
  }

  function videoSnapshot(cb) {
    var vid = document.querySelector('#vid'),
        width = 320,
        height = vid.videoHeight / (vid.videoWidth/width),
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

    canvas.width = width;
    canvas.height = height;

    context.drawImage(vid, 0, 0, width, height);

    cb(canvas);
  }

  function addSnapshotToPage(canvas) {
    var img = document.createElement('img')
    img.src = canvas.toDataURL()
    document.body.appendChild(img)
  }

  function uploadPhoto(fileBlob, callback) {
    // Create object for form data
    var fd = new FormData();
    // 'upl' is the arbitrary string that multer expects to match
    // its config on the server end.
    fd.append('upl', fileBlob, 'file-' + Date.now() + '.jpg');

    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://' + window.location.hostname + ':3000/upload');
    xhr.onload = function() {
      console.log('photo uploadeddddd')
      try {
        var data = JSON.parse(xhr.responseText).data;
      } catch(ex) {
      }
    }

    xhr.send(fd);
    console.log('upload: sent');
  }

  // public
  return {
    id: id,
    title: title,
    start: start,
    snapshot: snapshot,
    snapshotToCanvas: snapshotToCanvas
  };

})(this);


text:
package com.alkisum.android.cloudrun.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.NumberPicker;

import com.alkisum.android.cloudrun.R;

import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;

/**
 * Dialog to set the duration.
 *
 * @author Alkisum
 * @version 4.1
 * @since 2.0
 */

public class DurationDialog extends DialogFragment {

    /**
     * Fragment tag for FragmentManager.
     */
    public static final String FRAGMENT_TAG = "duration_dialog";

    /**
     * Argument for default hour.
     */
    private static final String ARG_HOUR = "arg_hour";

    /**
     * Argument for default minute.
     */
    private static final String ARG_MINUTE = "arg_minute";

    /**
     * Argument for default second.
     */
    private static final String ARG_SECOND = "arg_second";

    /**
     * Listener for the dialog.
     */
    private DurationDialogListener callback;

    /**
     * Create a new instance of DurationDialog.
     *
     * @param hour   Default hour
     * @param minute Default minute
     * @param second Default second
     * @return New instance of DurationDialog
     */
    public static DurationDialog newInstance(final int hour, final int minute,
                                             final int second) {
        DurationDialog durationDialog = new DurationDialog();
        Bundle args = new Bundle();
        args.putInt(ARG_HOUR, hour);
        args.putInt(ARG_MINUTE, minute);
        args.putInt(ARG_SECOND, second);
        durationDialog.setArguments(args);
        return durationDialog;
    }

    @Override
    public final void onAttach(@NonNull final Context context) {
        super.onAttach(context);
        try {
            callback = (DurationDialogListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.getClass().getSimpleName()
                    + " must implement DurationDialogListener");
        }
    }

    @NonNull
    @Override
    public final Dialog onCreateDialog(final Bundle savedInstanceState) {
        int hour = 0;
        int minute = 0;
        int second = 0;
        if (getArguments() != null) {
            hour = getArguments().getInt(ARG_HOUR);
            minute = getArguments().getInt(ARG_MINUTE);
            second = getArguments().getInt(ARG_SECOND);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        View view = View.inflate(getActivity(), R.layout.dialog_duration, null);

        final NumberPicker nbHour = view.findViewById(R.id.duration_nb_hour);
        nbHour.setMinValue(0);
        nbHour.setMaxValue(23);
        nbHour.setValue(hour);
        final NumberPicker nbMinute = view.findViewById(
                R.id.duration_nb_minute);
        nbMinute.setMinValue(0);
        nbMinute.setMaxValue(59);
        nbMinute.setValue(minute);
        final NumberPicker nbSecond = view.findViewById(
                R.id.duration_nb_second);
        nbSecond.setMinValue(0);
        nbSecond.setMaxValue(59);
        nbSecond.setValue(second);

        builder.setView(view)
                .setTitle(R.string.duration_title)
                .setPositiveButton(android.R.string.ok,
                        (dialog, id) -> callback.onDurationSubmit(
                                nbHour.getValue(),
                                nbMinute.getValue(),
                                nbSecond.getValue()))
                .setNegativeButton(android.R.string.cancel,
                        (dialog, id) -> Objects.requireNonNull(
                                DurationDialog.this.getDialog()).cancel());
        return builder.create();
    }

    /**
     * Listener for the dialog.
     */
    public interface DurationDialogListener {

        /**
         * Called when the user submit the dialog.
         *
         * @param hour   Hour set
         * @param minute Minute set
         * @param second Second set
         */
        void onDurationSubmit(int hour, int minute, int second);
    }
}


text:
package vgrechka.phizdetsidea.phizdets.suggestionList;

import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.JBPopupListener;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

/**
 * List of suggestions to be displayed.
 * Suggestions may be separated into groups: Group1[suggestion1, suggestion2, suggestion3].
 * Each suggestion may also be marked as strong (see {@link vgrechka.phizdetsidea.phizdets.suggestionList.Suggestion}
 *
 * @author Ilya.Kazakevich
 */
public class SuggestionList {
  /**
   * Listens popup close event
   */
  @Nullable
  private final JBPopupListener myListener;
  /**
   * Popup itself
   */
  @Nullable
  private JBPopup myListPopUp;
  /**
   * Model of suggestion list
   */
  private final DefaultListModel myListModel = new DefaultListModel();
  /**
   * Suggestion list
   */
  private final JList myList = new JList(myListModel);

  public SuggestionList() {
    myListener = null;
  }

  /**
   * @param listener popup listener (will be called back when popup closed)
   */
  public SuggestionList(@SuppressWarnings("NullableProblems") @NotNull final JBPopupListener listener) {
    myListener = listener;
  }

  /**
   * @param values          suggestions wrapped into suggestion builder.
   *                        Prefered usage pattern.
   * @param displayPoint    point on screen to display suggestions
   * @param elementToSelect element in list to be selected (if any)
   * @see vgrechka.phizdetsidea.phizdets.suggestionList.SuggestionsBuilder
   */
  public void showSuggestions(@NotNull final SuggestionsBuilder values,
                              @NotNull final RelativePoint displayPoint,
                              @Nullable final String elementToSelect) {
    showSuggestions(values.getList(), displayPoint, elementToSelect);
  }

  /**
   * @param values          suggestions in format [group1[suggestions]]. See class doc for info about groups.
   *                        We recommend you not to use this method.
   *                        Use {@link #showSuggestions(SuggestionsBuilder, com.intellij.ui.awt.RelativePoint, String)} instead.
   *                        {@link vgrechka.phizdetsidea.phizdets.suggestionList.SuggestionsBuilder} is easier to use
   * @param displayPoint    point on screen to display suggestions
   * @param elementToSelect element in list to be selected (if any)
   */
  public void showSuggestions(@NotNull final List<List<Suggestion>> values,
                              @NotNull final RelativePoint displayPoint,
                              @Nullable final String elementToSelect) {
    close();
    myList.setCellRenderer(new MyCellRenderer());
    myListModel.clear();
    if (values.isEmpty()) {
      return;
    }
    // Fill and select

    int record = 0; // Record to select
    // Iterate through groups adding suggestions. Odd groups should be marked differently.
    for (int groupId = 0; groupId < values.size(); groupId++) {
      final List<Suggestion> suggestions = values.get(groupId);
      for (int suggestionId = 0; suggestionId < suggestions.size(); suggestionId++) {
        final Suggestion suggestion = suggestions.get(suggestionId);
        myListModel.addElement(new SuggestionListElement((groupId % 2) == 0, suggestion));
        if (suggestion.getText().equals(elementToSelect)) {
          myList.setSelectedIndex(record);
        }
        record++;
      }
    }
    if ((myList.getSelectedIndex() ==-1) && (!myListModel.isEmpty())) {
      myList.setSelectedIndex(0); // Select first element
    }

    // Use scroll bars
    final JScrollPane content = new JScrollPane(myList, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    myListPopUp =
      JBPopupFactory.getInstance().createComponentPopupBuilder(content, null)
        .createPopup();
    if (myListener != null) {
      myListPopUp.addListener(myListener);
    }
    myListPopUp.show(displayPoint);
    myList.ensureIndexIsVisible(myList.getSelectedIndex()); // Scrolls to selected
  }

  /**
   * Close suggestion list
   */
  public void close() {
    if (myListPopUp != null) {
      myListPopUp.cancel();
    }
  }

  /**
   * Move selection
   *
   * @param directionUp up if true. Down otherwise
   */
  public void moveSelection(final boolean directionUp) {
    if (myListModel.isEmpty()) {
      return;
    }
    // Handle separation
    int newIndex = myList.getSelectedIndex() + (directionUp ? -1 : 1);
    if (newIndex < 0) {
      newIndex = 0;
    }
    if (newIndex >= myListModel.size()) {
      newIndex = myListModel.size() - 1;
    }
    myList.setSelectedIndex(newIndex);
    myList.scrollRectToVisible(myList.getCellBounds(newIndex, newIndex));
  }

  /**
   * @return currently selected value (null if nothing is selected)
   */
  @Nullable
  public String getValue() {
    if (myListPopUp == null || !myListPopUp.isVisible()) {
      return null; // Nothing is selected if list is invisible
    }
    final Object value = myList.getSelectedValue();
    return ((value == null) ? null : getElement(value).mySuggestion.getText());
  }

  /**
   * @return true if no suggestion list is displayed now.
   */
  public final synchronized boolean isClosed() {
    return myListPopUp == null || myListPopUp.isDisposed();
  }

  /**
   * Element that represents suggestion
   */
  private static final class SuggestionListElement {
    /**
     * is part of odd group
     */
    private final boolean myOddGroup;
    /**
     * suggestion itself
     */
    @NotNull
    private final Suggestion mySuggestion;

    private SuggestionListElement(final boolean oddGroup,
                                  @NotNull final Suggestion suggestion) {
      myOddGroup = oddGroup;
      mySuggestion = suggestion;
    }
  }

  /**
   * Cell renderer for suggestion
   */
  private static class MyCellRenderer extends DefaultListCellRenderer {
    @NotNull
    private static final Color ODD_GROUP_SELECTED_BACKGROUND_COLOR =
      EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.SELECTED_TEARLINE_COLOR);
    @NotNull
    private static final Color ODD_GROUP_BACKGROUND_COLOR =
      EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.TEARLINE_COLOR);

    @Override
    public Component getListCellRendererComponent(final JList list,
                                                  final Object value,
                                                  final int index,
                                                  final boolean isSelected,
                                                  final boolean cellHasFocus) {
      final SuggestionListElement element = getElement(value);
      // Out parent always uses label
      final Component component = super.getListCellRendererComponent(list, element.mySuggestion.getText(), index, isSelected,
                                                                     cellHasFocus);

      if (element.myOddGroup) {
        component.setBackground(isSelected ? ODD_GROUP_SELECTED_BACKGROUND_COLOR : ODD_GROUP_BACKGROUND_COLOR);
        final Font oldFont = component.getFont();
        component.setFont(new Font(oldFont.getName(), Font.ITALIC, oldFont.getSize()));
      }

      if (!(component instanceof JLabel)) {
        return component; // We can't change any property here
      }

      final JLabel label = (JLabel)component;
      if (element.mySuggestion.isStrong()) {
        // We use icons to display "strong" element
        label.setIcon(PlatformIcons.FOLDER_ICON);
      }

      return component;
    }
  }

  /**
   * Converts argument to {@link SuggestionListElement} which always should be.
   *
   * @param value argument to convert
   * @return converted argument
   */
  @NotNull
  private static SuggestionListElement getElement(final Object value) {
    assert value instanceof SuggestionListElement : "Value is not valid element: " + value;
    return (SuggestionListElement)value;
  }
}


text:
Chef Sugar
==========
[![Gem Version](http://img.shields.io/gem/v/chef-sugar.svg?style=flat-square)][gem]
[![Build Status](http://img.shields.io/travis/sethvargo/chef-sugar.svg?style=flat-square)][travis]

[gem]: https://rubygems.org/gems/chef-sugar
[travis]: http://travis-ci.org/sethvargo/chef-sugar

Chef Sugar is a Gem & Chef Recipe that includes series of helpful sugar of the Chef core and other resources to make a cleaner, more lean recipe DSL, enforce DRY principles, and make writing Chef recipes an awesome experience!

Installation
------------
If you want to develop/hack on chef-sugar, please see the Contributing.md.

If you are using Berkshelf, add `chef-sugar` to your `Berksfile`:

```ruby
cookbook 'chef-sugar'
```

Otherwise, you can use `knife` or download the tarball directly from the community site:

```ruby
knife cookbook site install chef-sugar
```

Usage
-----
In order to use Chef Sugar in your Chef Recipes, you'll first need to include it:

```ruby
include_recipe 'chef-sugar::default'
```

Alternatively you can put it in a base role or recipe and it will be included subsequently.

Requiring the Chef Sugar Gem will automatically extend the Recipe DSL, `Chef::Resource`, and `Chef::Provider` with helpful convenience methods.

### Module Method
If you are working outside of the Recipe DSL, you can use the module methods instead of the Recipe DSL. In general, the module methods have the same name as their Recipe-DSL counterparts, but require the node object as a parameter. For example:

In a Recipe:

```ruby
# cookbook/recipes/default.rb
do_something if windows?
```

In a Library as a singleton:

```ruby
# cookbook/libraries/default.rb
def only_on_windows(&block)
  yield if Chef::Sugar::PlatformFamily.windows?(@node)
end
```

In a Library as a Mixin:

```ruby
# cookbook/libraries/default.rb
include Chef::Sugar::PlatformFamily

def only_on_windows(&block)
  yield if windows?(@node)
end
```

API
---
**Note:** For the most extensive API documentation, please see the YARD documentation.

### Architecture
**Note:** Some of the architecture commands begin with an underscore (`_`) because Ruby does not permit methods to start with a numeric.

- `_64_bit?`
- `_32_bit?`
- `intel?`
- `sparc?`
- `ppc64?`
- `ppc64le?`
- `powerpc?`

#### Examples
```ruby
execute 'build[my binary]' do
  command '...'
  not_if  { _64_bit? }
end
```

### Cloud
- `azure?`
- `cloud?`
- `digitalocean?`
- `ec2?`
- `eucalyptus?`
- `gce?`
- `linode?`
- `openstack?`
- `cloudstack?`
- `rackspace?`

#### Examples
```ruby
template '/tmp/config' do
  variables(
    # See also: best_ip_for
    ipaddress: cloud? ? node['local_ipv4'] : node['public_ipv4']
  )
end
```

### Core Extensions
**Note:** Core extensions are **not** included by default. You must require the `chef/sugar/core_extensions` module manually to gain access to these APIs:

```ruby
require 'chef/sugar/core_extensions'
```

- `String#satisfies?`
- `String#satisfied_by?`
- `Array#satisfied_by?`
- `Object#blank?`

#### Examples
```ruby
# Checking version constraints
'1.0.0'.satisfies?('~> 1.0') #=> true
'~> 1.0'.satisfied_by?('1.0') #=> true
```

```ruby
# Check for an object's presence
''.blank? #=> true
['hello'].blank? #=> false
```

### Data Bag
- `encrypted_data_bag_item` - a handy DSL method for loading encrypted data bag items the same way you load a regular data bag item; this requires `Chef::Config[:encrypted_data_bag_secret]` is set!
- `encrypted_data_bag_item_for_environment` - find the encrypted data bag entry for the current node's Chef environment.
- `data_bag_item_for_environment` - find the data bag entry for the current node's Chef environment.

#### Examples
```ruby
encrypted_data_bag_item('accounts', 'hipchat')
```

```ruby
encrypted_data_bag_item_for_environment('accounts', 'github')
```

```ruby
data_bag_item_for_environment('accounts', 'github')
```

### Docker
Chef Sugar looks for hints to see if the node being converged is a Docker container. When [Ohai supports checking other nodes](https://github.com/opscode/ohai/pull/428), Chef Sugar will automatically pick up the information.

- `docker?`

#### Examples
```ruby
template '/runme' do
  only_if { docker?(node) }
end
```

### Attributes
Chef Sugar adds more Chef-like DSL to attribute definitions. Instead of using the Ruby hash syntax, you can define attributes using nested namespaces. This DSL may be more friendly to non-Ruby developers. It can safely be mixed-and-matched with the standard syntax.

```ruby
# This is functionally the same as default['apache2']['config']['root'] = '/var/www'
namespace 'apache2' do
  namespace 'config' do
    root '/var/www'
  end
end
```

```ruby
# Specify multiple keys instead of nesting namespaces
namespace 'apache2', 'config' do
  root '/var/www'
end
```

```ruby
# Specify different nested precedence levels
namespace 'apache2', precedence: normal do
  namespace 'config', precedence: override do
    root '/var/www' #=> override['apache2']['config']['root'] = '/var/www'
  end
end
```

### Constraints
- `constraints` - create a new constraint (or requirement) that can be used to test version validations.
- `chef_version` - (DSL only) a wrapper for `version(Chef::VERSION)`
- `version` - create a new version that can be used to test constraint validation.

#### Examples
```ruby
# Check if a version is satisfied by a constraint
version('1.2.3').satisfies?('~> 1.2.0')
```

```ruby
# Check if a constraint is satisfied by a version
constraint('~> 1.2.0').satisfied_by?('1.2.3')
```

```ruby
# Support multiple constraints
version('1.2.3').satisfies?('> 1.2', '< 2.0')
constraint('> 1.2', '< 2.0').satisfied_by?('1.2.3')
```

```ruby
# Only perform an operation if Chef is at a certain version
package 'apache2' do
  not_if { chef_version.satisfies?('~> 11.0') } # Ignore Chef 11
end
```

### Kernel
- `require_chef_gem` - "safely" require a gem. Loading a gem with Chef is sometimes difficult and confusing. The errors that Chef produces are also sometimes not very intuitive. In the event you require a gem to exist on the system, you can use `require_chef_gem`, which will attempt to require the gem and then produce helpful output if the gem is not installed:

        Chef could not load the gem `#{name}'! You may need to install the gem
        manually with `gem install #{name}', or include a recipe before you can
        use this resource. Please consult the documentation for this cookbook
        for proper usage.

#### Examples
```ruby
# LWRP
require_chef_gem 'pry'
```

```ruby
class Chef
  class Provider
    class MyProvider > Provider
      require_chef_gem 'pry'
    end
  end
end
```

### Init
- `systemd?` - detect if init system is systemd
- `upstart?` - detect if init system is upstart
- `runit?` - detect if init system is runit

#### Examples
```ruby
systemd_service 'my-service' do
  description 'My Service'
  install do
    wanted_by 'multi-user.target'
  end
  service do
    exec_start '/usr/bin/myserviced'
  end
  action [:create, :enable, :start]
  only_if { systemd? }
end

cookbook_file '/etc/init/my-service.conf' do
  source 'my-service.conf'
  only_if { upstart? }
end
```

### IP
- `best_ip_for` - determine the best IP address for the given "other" node, preferring local IP addresses over public ones.

#### Examples
```ruby
redis = search('node', 'role:redis').first

template '/tmp/config' do
  variables(
    ipaddress: best_ip_for(redis)
  )
end
```

### Node

Additional methods for the `node` object

- `deep_fetch` - safely fetch a nested attribute.
- `deep_fetch!` - fetch a nested attribute, raising a more semantic error if the key does not exist.
- `in?` - determine if the node is in the given Chef environment.

#### Examples
```ruby
credentials = if node.in?('production')
                Chef::EncryptedDataBag.new('...')
              else
                data_bag('...')
              end
```

```ruby
node.deep_fetch('apache2', 'config', 'root') => node['apache2']['config']['root']
```

### Platform
- `amazon_linux?`
- `centos?`
- `linux_mint?`
- `oracle_linux?`
- `redhat_enterprise_linux?`
- `scientific_linux?`
- `ubuntu?`
- `solaris2?`
- `aix?`
- `smartos?`
- `omnios?`
- `raspbian?`
- `nexus?`
- `ios_xr?`

There are also a series of dynamically defined matchers that map named operating system release versions and comparison operators in the form "#{platform}\_#{operator}\_#{name}?". For example:

- `debian_after_squeeze?`
- `linuxmint_after_or_at_olivia?`
- `mac_os_x_lion?`
- `ubuntu_before_lucid?`
- `ubuntu_before_or_at_maverick?`
- `solaris_10?`
- `solaris_11?`

To get a full list, run the following in IRB:

```ruby
require 'chef/sugar'
puts Chef::Sugar::Platform.instance_methods
```

#### Examples
```ruby
if ubuntu?
  execute 'apt-get update'
end
```

### Platform Family
- `arch_linux?`
- `debian?`
- `fedora?`
- `freebsd?`
- `gentoo?`
- `linux?`
- `mac_os_x?`
- `openbsd?`
- `rhel?`
- `slackware?`
- `suse?`
- `windows?`
- `wrlinux?`

#### Examples
```ruby
node['attribute'] = if windows?
                      'C:\Foo\BarDrive'
                    else
                      '/foo/bar_drive'
                    end
```

### Ruby
**Note:** The applies to the Ruby found at `node['languages']['ruby']`.

- `ruby_20?`
- `ruby_19?`

#### Examples
```ruby
log 'This has been known to fail on Ruby 2.0' if ruby_20?
```

### Run Context
- `includes_recipe?` - determines if the current run context includes the recipe

```ruby
if includes_recipe?('apache2::default')
  apache_module 'my_module' do
    # ...
  end
end
```

### Shell
- `which`
- `dev_null`
- `installed?`
- `installed_at_version?`
- `version_for`

#### Examples
```ruby
log "Using `mongo` at `#{which('mongo')}`"

if installed?('apt')
  execute 'apt-get update'
end

execute 'install[thing]' do
  command "... 2>&1 #{dev_null}"
  not_if  { installed_at_version?('thing', node['thing']['version']) }
end

log "Skipping git install, version is at #{version_for('mongo', '-v')}"
```

### Vagrant
- `vagrant?`

#### Examples
```ruby
http_request 'http://...' do
  not_if { vagrant? }
end
```

### Virtualization
- `kvm?`
- `lxc?`
- `virtualbox?`
- `vmware?`
- `openvz?`

#### Examples
```ruby
service 'ntpd' do
  action [:enable, :start]
  not_if { lxc? }
end
```

### Filters
- `at_compile_time` - accepts a block of resources to run at compile time
- `before` - insert resource in the collection before the given resource
- `after` - insert resource in the collection after the given resource

#### Examples
```ruby
at_compile_time do
  package 'apache2'
end

# This is equivalent to
package 'apache2' do
  action :nothing
end.run_action(:install)
```

```ruby
before 'service[apache2]' do
  log 'I am before the apache 2 service fires!'
end
```

```ruby
after 'service[apache2]' do
  log 'I am after the apache 2 service fires!'
end
```

License & Authors
-----------------
- Author: Seth Vargo (sethvargo@gmail.com)

```text
Copyright 2013-2015 Seth Vargo

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.
```


text:
@interface WeatherPickerViewController : UIViewController <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) Entry *entry;
@property (nonatomic, readwrite) BOOL inCreationFlow;
@end


text:
package x.bench.test.mixed;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

/* this code is from http://wpcertification.blogspot.de/2014/08/java-client-for-publishing-and.html
 * Download 2016-06-17 02:31:48
 */
/**
 *
 * Created by user on 8/4/14.
 */
public class HelloKafkaProducer {
    final static String TOPIC = "javatest";

    public static void main(String[] argv){
        Properties properties = new Properties();
        properties.put("metadata.broker.list","localhost:9092");
        properties.put("serializer.class","kafka.serializer.StringEncoder");
        ProducerConfig producesrConfig = new ProducerConfig(properties);
        kafka.javaapi.producer.Producer<String,String> producer = new kafka.javaapi.producer.Producer<String, String>(producesrConfig);
        SimpleDateFormat sdf = new SimpleDateFormat();
        KeyedMessage<String, String> message =new KeyedMessage<String, String>(TOPIC,"Test message from java program " + sdf.format(new Date()));
        producer.send(message);
        producer.close();
    }
}


text:
module("ScaleLine");

test("ScaleLineTest_constructor", function() {
    expect(10);
    var scaleLine = new SuperMap.Control.ScaleLine();
    equals(scaleLine.CLASS_NAME, "SuperMap.Control.ScaleLine", "scaleLine_constructor");
    equals(scaleLine.maxWidth, 100, "scaleLine_constructor");
    equals(scaleLine.isImperialUnits, true, "scaleLine_constructor");
    equals(scaleLine.topOutUnits, "km", "scaleLine_constructor");
    equals(scaleLine.topInUnits, "m", "scaleLine_constructor");
    equals(scaleLine.bottomOutUnits, "mi", "scaleLine_constructor");
    equals(scaleLine.bottomInUnits, "ft", "scaleLine_constructor");
    equals(scaleLine.eTop, null, "scaleLine_constructor");
    equals(scaleLine.eBottom, null, "scaleLine_constructor");
    equals(scaleLine.geodesic, false, "scaleLine_constructor");
});

test("ScaleLineTest_draw", function() {
    expect(9);
    var map = new SuperMap.Map("map");
    var scaleLine = new SuperMap.Control.ScaleLine();
    map.addControl(scaleLine);
    var div = scaleLine.draw();
    equals(scaleLine.eTop.className, "smControlScaleLineTop", "scaleLine_draw");
    equals(scaleLine.eTop.style.visibility, "visible", "scaleLine_draw");
    equals(scaleLine.eBottom.className, "smControlScaleLineBottom", "scaleLine_draw");
    equals(scaleLine.eBottom.style.visibility, "visible", "scaleLine_draw");
    equals(div.tagName, "DIV", "scaleLine_draw");
    equals(div.id.split("_")[0], "SuperMap.Control.ScaleLine", "scaleLine_draw");
    equals(div.className, "smControlScaleLine smControlNoSelect", "scaleLine_draw");

    scaleLine.topOutUnits = "";
    scaleLine.topInUnits = "";
    scaleLine.eTop = null;
    scaleLine.draw();
    equals(scaleLine.eTop.style.visibility, "hidden", "scaleLine_draw");

    scaleLine.bottomOutUnits = "";
    scaleLine.bottomInUnits = "";
    scaleLine.isImperialUnits = true;
    scaleLine.eTop = null;
    scaleLine.draw();
    equals(scaleLine.eBottom.style.visibility, "hidden", "scaleLine_draw");
});

test("ScaleLineTest_getBarLen", function() {
    var scaleLine = new SuperMap.Control.ScaleLine();
    var maxLen = 0.5;
    var len = scaleLine.getBarLen(maxLen);
    equals(len, 1, "scaleLine_getBarLen");
});

test("ScaleLineTest_update", function() {
    expect(16);
    var map = new SuperMap.Map("map");
    var scaleLine = new SuperMap.Control.ScaleLine();
    map.addControl(scaleLine);
    var options = {numZoomLevels: 12,useCanvas:false};
    var bounds= new SuperMap.Bounds(-180, -90, 180, 90);
    var layer = new SuperMap.Layer.Image(
        'World_Day',
        'images/Day.jpg',
        bounds ,
        options
    );
    map.addLayer(layer);
    map.zoomToMaxExtent();
    scaleLine.update();
    equals(scaleLine.eBottom.style.width, "51px", "scaleLine_update");
    equals(scaleLine.eBottom.innerHTML, "5000 英里", "scaleLine_update");
    equals(scaleLine.eTop.style.width, "64px", "scaleLine_update");
    equals(scaleLine.eTop.innerHTML, "10000 公里", "scaleLine_update");

    scaleLine.geodesic = true;
    scaleLine.update();
    equals(scaleLine.eBottom.style.width, "51px", "scaleLine_update");
    equals(scaleLine.eBottom.innerHTML, "5000 英里", "scaleLine_update");
    equals(scaleLine.eTop.style.width, "64px", "scaleLine_update");
    equals(scaleLine.eTop.innerHTML, "10000 公里", "scaleLine_update");

    scaleLine.eBottom.style.visibility = "hidden";
    scaleLine.eTop.style.visibility = "hidden";
    scaleLine.update();
    equals(scaleLine.eBottom.style.width, "51px", "scaleLine_update");
    equals(scaleLine.eBottom.innerHTML, "5000 英里", "scaleLine_update");
    equals(scaleLine.eTop.style.width, "64px", "scaleLine_update");
    equals(scaleLine.eTop.innerHTML, "10000 公里", "scaleLine_update");

    scaleLine.geodesic = false;
    scaleLine.update();
    equals(scaleLine.eBottom.style.width, "51px", "scaleLine_update");
    equals(scaleLine.eBottom.innerHTML, "5000 英里", "scaleLine_update");
    equals(scaleLine.eTop.style.width, "64px", "scaleLine_update");
    equals(scaleLine.eTop.innerHTML, "10000 公里", "scaleLine_update");
});


text:
namespace System.Web.Mvc.Html {
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web.Mvc.Resources;
    using System.Web.Routing;

    public static class TextAreaExtensions {
        // These values are similar to the defaults used by WebForms
        // when using <asp:TextBox TextMode="MultiLine"> without specifying
        // the Rows and Columns attributes.
        private const int TextAreaRows = 2;
        private const int TextAreaColumns = 20;

        public static string TextArea(this HtmlHelper htmlHelper, string name) {
            return TextArea(htmlHelper, name, (object)null /* htmlAttributes */);
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, object htmlAttributes) {
            return TextArea(htmlHelper, name, new RouteValueDictionary(htmlAttributes));
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) {
            // Add implicit parameters
            Dictionary<string, object> implicitAttributes = new Dictionary<string, object>();
            implicitAttributes.Add("rows", TextAreaRows.ToString(CultureInfo.InvariantCulture));
            implicitAttributes.Add("cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture));
            return TextAreaHelper(htmlHelper, name, true /* useViewData */, null /* value */, implicitAttributes, null /* explicitParameters */, htmlAttributes);
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, string value) {
            return TextArea(htmlHelper, name, value, (object) null /* htmlAttributes */);
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes) {
            return TextArea(htmlHelper, name, value, new RouteValueDictionary(htmlAttributes));
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, string value, IDictionary<string, object> htmlAttributes) {
            // Add implicit parameters
            Dictionary<string, object> implicitAttributes = new Dictionary<string, object>();
            implicitAttributes.Add("rows", TextAreaRows.ToString(CultureInfo.InvariantCulture));
            implicitAttributes.Add("cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture));
            return TextAreaHelper(htmlHelper, name, (value == null) /* useViewData */, value, implicitAttributes, null /* explicitParameters */, htmlAttributes);
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, object htmlAttributes) {
            return TextArea(htmlHelper, name, value, rows, columns, new RouteValueDictionary(htmlAttributes));
        }

        public static string TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, IDictionary<string, object> htmlAttributes) {
            if (rows <= 0) {
                throw new ArgumentOutOfRangeException("rows", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);
            }
            if (columns <= 0) {
                throw new ArgumentOutOfRangeException("columns", MvcResources.HtmlHelper_TextAreaParameterOutOfRange);
            }

            Dictionary<string, object> explicitParameters = new Dictionary<string, object>();
            explicitParameters.Add("rows", rows.ToString(CultureInfo.InvariantCulture));
            explicitParameters.Add("cols", columns.ToString(CultureInfo.InvariantCulture));
            return TextAreaHelper(htmlHelper, name, (value == null) /* useViewData */, value, null /* implictAttributes */, explicitParameters, htmlAttributes);
        }

        private static string TextAreaHelper(this HtmlHelper htmlHelper, string name, bool useViewData, string value, IDictionary<string, object> implicitAttributes, IDictionary<string, object> explicitParameters, IDictionary<string, object> htmlAttributes) {
            if (String.IsNullOrEmpty(name)) {
                throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name");
            }

            TagBuilder tagBuilder = new TagBuilder("textarea");
            // Add implicit attributes.
            tagBuilder.MergeAttributes(implicitAttributes);
            tagBuilder.GenerateId(name);
            // Merge htmlAttributes.
            tagBuilder.MergeAttributes(htmlAttributes, true);
            // Override all the attributes with explicit parameters.
            tagBuilder.MergeAttributes(explicitParameters, true);
            tagBuilder.MergeAttribute("name", name, true);

            // If there are any errors for a named field, we add the css attribute.
            ModelState modelState;
            if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) {
                if (modelState.Errors.Count > 0) {
                    tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                }
            }

            // The first newline is always trimmed when a TextArea is rendered, so we add an extra one
            // in case the value being rendered is something like "\r\nHello".
            // The attempted value receives precedence over the explicitly supplied value parameter.
            string attemptedValue = (string)htmlHelper.GetModelStateValue(name, typeof(string));
            tagBuilder.SetInnerText(Environment.NewLine + (attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(name) : value)));
            return tagBuilder.ToString(TagRenderMode.Normal);
        }
    }
}


text:
layout: post
title:  "CSP1150 Lecture 3"
date:   2014-08-10 11:33:00
categories:
- lecture
- CSP1150
---

# Java Introduction Continued

## `String` Methods

### `.length();`

``` java
String name = "Marty"
int stringSize = name.length();
```

`stringSize = 5`

Returns a `String`'s length as an `int`.

### `.charAt(index);`

``` java
String name = "Marty";
char letter = name.charAt(2)
```

`letter = "r"`

Returns `char` at that particular index of a `String`. Index begins at zero.

<!--more-->

### `.toLowerCase();`

``` java
String bigName = "MARTY";
String littleName = bigName.toLowerCase();
```

`littleName = "marty"`

Returns a new string that is the lower case equivalent of the caller.

### `.toUpperCase();`

``` java
String littleName = "marty";
String bigName = littleName.toUpperCase();
```

`bigName = "MARTY"`

Returns a new string that is the upper case equivalent of the caller.

## Scope

- Refers to the part of a program that has access to a `variable`'s contents
- Variables declared inside a method, like `main()` are called *local variables*
- Local variables' scope begins at its declaration, and ends at the end of the method where it was declared
- Order of declaration is important
	- Do not use a variable before it is declared, it will produce error

``` java
// This program can't find its variable

public class Scope {
	public static void main(String[] args) {
		System.out.println(value); // error
		int value = 100;
	}
}
```

- Local variables cannot have two with the same name inside the same scope
	- It will not change the value of the variable
	- It will create another one and produce error

``` java
public static void main(String[] args) {
	// number is declared first time
	int number = 7;
	System.out.println(number);
	// number declared again
	int number = 100; // error
	System.out.println(number); // error
}
```

## `Scanner` Class

- Must be imported from `java.util`
- Imports happen before the `Class` is declared

``` java
// importing here
import java.util.Scanner;

public class UserInput {
	public static void main(String[] args) {
		// creating new Scanner object
		Scanner sc = new Scanner(System.in);
		// returns user input as string
		System.out.print("What's your name?");
		String name = sc.nextLine();
		// returns user input as int
		System.out.print("How many hours did you work this week?");
		int hours = sc.nextInt();
		// returns user input as double
		System.out.print("What is your hourly rate?");
		double payRate = sc.nextDouble();
	}
}
```

### `Scanner` methods

``` java
sc.nextByte(); 		// returns input as byte
sc.nextDouble(); 	// returns input as double
sc.nextFloat();		// returns input as float
sc.nextInt();		// returns input as int
sc.nextLine();		// returns input as String
sc.nextLong();		// returns input as long
sc.nextShort();		// returns input as short
sc.close();			// closes Scanner object
```

### Reading a Single Character

``` java
System.out.print("Are you sure you want to delete file? (Y = yes, N = no)");
String input = sc.nextLine();
// gets the first char
char answer = input.charAt(0);
```

### Mixing Calls to `.nextLine()` with Calls to Other `Scanner` Methods

`.nextline()` method behaves differently to other `Scanner` methods. If mixing with other methods, do the following:

``` java
import java.util.Scanner;

public class CorrectedInputProblem {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		// get users age
		System.out.print("What is your age?");
		int age = sc.nextInt();

		// get users income
		System.out.print("What is your annual income?");
		double income = sc.nextDouble();

		// consumes remaining newline
		sc.nextLine();

		// get users name
		System.out.print("What is your name?");
		String name = sc.nextLine();
	}
}
```

Use an extra instance of `.nextLine()` between a different `Scanner` method and the actual `.nextLine()` to use up the extra `newLine` character that is created by the previous method. If not, the proper `.nextLine()` input will be ignored.

## Dialog Boxes

`JOptionPane` class can quickly display dialog boxes. This section shows two different types:

- Message dialog
	- Displays message
	- OK button
- Input dialog
	- Prompts user for input
	- Has text field where input is typed
	- OK button
	- Cancel button

Things to note:

- Must be imported
- Input is stored as `String` but can be converted to other types

### Import statement

``` java
import javax.swing.JOptionPane;
```

### Displaying Message Dialogs

``` java
JOptionPane.showMessageDialog(null, "Hello World");
```

`null` argument is important if the program displays other graphical windows. More on that later.

### Displaying Input Dialogs

``` java
String name = JOptionPane.showInputDialog("Enter your name:");
```

The argument passed into the method is the message that we want to display in the dialog box.

### Dialog Example

``` java
import javax.swing.JOptionPane;

public class NamesDialog {
	public static void main(String[] args) {
		// get user first name
		String firstName = JOptionPane.showInputDialog("What is your first name?");

		// get user middle name
		String middleName = JOptionPane.showInputDialog("What is your middle name?");

		// get user last name
		String lastName = JOptionPane.showInputDialog("What is your last name?");

		// display greeting
		JOptionPane.showMessageDialog(null, "Hello " + firstName + " " + middleName + " " + lastName);

		// close JOptionPane
		System.exit(0);
	}
}
```

`System.exit(0);` must be used to close `JOptionPane`, otherwise it's thread will continue to run in the background even after `main()` has finished. This is because `JOptionPane` causes an additional thread to run in the `JVM`.

## Parsing `String` as Numbers

`JOptionPane` does not have different methods to read input values as different data types. `showInputDialog()` always returns user input as `String`, even if numbers are entered. This will be an issue if we need to perform math operations with user input. In these cases, we need to convert user input to a numeric value, and can use the following methods.

``` java
Byte.parseByte(str);		// converts to byte
Double.parseDouble(str);	// converts to double
Float.parseFloat(str);		// converts to float
Integer.parseInt(str);		// converts to int
Long.parseLong(str);		// converts to long
Short.parseShort(str);		// converts to short
```

### Parse Example

``` java
String str = JOptionPane.showInputDialog("Enter a number:");
int number = Integer.parseInt(str);

String priceInput = JOptionPane.showInputDialog("Enter the price:");
double price = Double.parseDouble(priceInput);
```

## Common Errors to Avoid

- Mismatched braces, quotation marks or parenthesis
- Misspelling key words
- Using capitals in key words
- Using key word as a variable name
- Using inconsistent spelling of variable names
- Using inconsistent casing of variable names
- Inserting spaces in variable names
- Forgetting the semi-colon at the end of a statement
- Assigning `double` literal to a `float` variable
- Using commas or other currency symbols in numeric literals
- Unintentionally performing integer division
	- When both operands of a division statement are integers, the returning result will be an integer
	- Remainders will be discarded
- Forgetting to group parts of mathematical expressions
- Inserting a space in a combined assignment operator
	- A space cannot appear between the two operators that make a combined assignment operator
	- `++` right
	- `+ +` wrong
- Using a variable to receive the result of a calculation when the variable's data type is incompatible with the data type of the result
- Incorrectly terminating a multi-line comment or documentation comment
- Forgetting to use the correct `import` statement in a program
- Not converting the `showInputDialog()` value to a number when using an input dialog to read numeric input


text:
void zmqError(const char *str) { LOG(ZMQ, "zmq: Error: %s, errno=%s\n", str, zmq_strerror(errno)); }
CZMQNotificationInterface::CZMQNotificationInterface() : pcontext(nullptr) {}
CZMQNotificationInterface::~CZMQNotificationInterface()
{
    Shutdown();

    for (std::list<CZMQAbstractNotifier *>::iterator i = notifiers.begin(); i != notifiers.end(); ++i)
    {
        delete *i;
    }
}

CZMQNotificationInterface *CZMQNotificationInterface::CreateWithArguments(
    const std::map<std::string, std::string> &args)
{
    CZMQNotificationInterface *notificationInterface = nullptr;
    std::map<std::string, CZMQNotifierFactory> factories;
    std::list<CZMQAbstractNotifier *> notifiers;

    factories["pubhashblock"] = CZMQAbstractNotifier::Create<CZMQPublishHashBlockNotifier>;
    factories["pubhashtx"] = CZMQAbstractNotifier::Create<CZMQPublishHashTransactionNotifier>;
    factories["pubrawblock"] = CZMQAbstractNotifier::Create<CZMQPublishRawBlockNotifier>;
    factories["pubrawtx"] = CZMQAbstractNotifier::Create<CZMQPublishRawTransactionNotifier>;

    for (std::map<std::string, CZMQNotifierFactory>::const_iterator i = factories.begin(); i != factories.end(); ++i)
    {
        std::map<std::string, std::string>::const_iterator j = args.find("-zmq" + i->first);
        if (j != args.end())
        {
            CZMQNotifierFactory factory = i->second;
            std::string address = j->second;
            CZMQAbstractNotifier *notifier = factory();
            notifier->SetType(i->first);
            notifier->SetAddress(address);
            notifiers.push_back(notifier);
        }
    }

    if (!notifiers.empty())
    {
        notificationInterface = new CZMQNotificationInterface();
        notificationInterface->notifiers = notifiers;

        if (!notificationInterface->Initialize())
        {
            delete notificationInterface;
            notificationInterface = nullptr;
        }
    }

    return notificationInterface;
}

// Called at startup to conditionally set up ZMQ socket(s)
bool CZMQNotificationInterface::Initialize()
{
    LOG(ZMQ, "zmq: Initialize notification interface\n");
    assert(!pcontext);

    pcontext = zmq_init(1);

    if (!pcontext)
    {
        zmqError("Unable to initialize context");
        return false;
    }

    std::list<CZMQAbstractNotifier *>::iterator i = notifiers.begin();
    for (; i != notifiers.end(); ++i)
    {
        CZMQAbstractNotifier *notifier = *i;
        if (notifier->Initialize(pcontext))
        {
            LOG(ZMQ, "  Notifier %s ready (address = %s)\n", notifier->GetType(), notifier->GetAddress());
        }
        else
        {
            LOG(ZMQ, "  Notifier %s failed (address = %s)\n", notifier->GetType(), notifier->GetAddress());
            break;
        }
    }

    if (i != notifiers.end())
    {
        Shutdown();
        return false;
    }

    return true;
}

// Called during shutdown sequence
void CZMQNotificationInterface::Shutdown()
{
    LOG(ZMQ, "zmq: Shutdown notification interface\n");
    if (pcontext)
    {
        for (std::list<CZMQAbstractNotifier *>::iterator i = notifiers.begin(); i != notifiers.end(); ++i)
        {
            CZMQAbstractNotifier *notifier = *i;
            LOG(ZMQ, "   Shutdown notifier %s at %s\n", notifier->GetType(), notifier->GetAddress());
            notifier->Shutdown();
        }
        zmq_ctx_destroy(pcontext);

        pcontext = 0;
    }
}

void CZMQNotificationInterface::UpdatedBlockTip(const CBlockIndex *pindex)
{
    for (std::list<CZMQAbstractNotifier *>::iterator i = notifiers.begin(); i != notifiers.end();)
    {
        CZMQAbstractNotifier *notifier = *i;
        if (notifier->NotifyBlock(pindex))
        {
            i++;
        }
        else
        {
            notifier->Shutdown();
            i = notifiers.erase(i);
        }
    }
}

void CZMQNotificationInterface::SyncTransaction(const CTransactionRef &ptx, const CBlock *pblock, int txIndex)
{
    for (std::list<CZMQAbstractNotifier *>::iterator i = notifiers.begin(); i != notifiers.end();)
    {
        CZMQAbstractNotifier *notifier = *i;
        if (notifier->NotifyTransaction(ptx))
        {
            i++;
        }
        else
        {
            notifier->Shutdown();
            i = notifiers.erase(i);
        }
    }
}


text:
class ComponentReverb :	public Component
{
public:
	ComponentReverb(GameObject*);
	~ComponentReverb();

	void Update(float real_dt, float game_dt);
	void OnEditor();
	bool CheckCollision(float3 p) const;

	std::string target_bus = "";
	float value = 0.0;

	uint PrepareToSave() const;
	void Save(char *& cursor) const;

private:
	math::OBB box;

};


text:
package com.intellij.openapi.vcs.changes.committed;

import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.changes.ui.SimpleChangesBrowser;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Set;

public class CommittedChangesBrowser extends SimpleChangesBrowser {
  private CommittedChangesBrowserUseCase myUseCase;

  public CommittedChangesBrowser(@NotNull Project project) {
    super(project, false, false);
  }

  @NotNull
  @Override
  protected List<AnAction> createToolbarActions() {
    return ContainerUtil.append(
      super.createToolbarActions(),
      ActionManager.getInstance().getAction("Vcs.RepositoryChangesBrowserToolbar")
    );
  }

  @NotNull
  @Override
  protected List<AnAction> createPopupMenuActions() {
    return ContainerUtil.append(
      super.createPopupMenuActions(),
      ActionManager.getInstance().getAction("Vcs.RepositoryChangesBrowserMenu")
    );
  }

  public void setUseCase(final CommittedChangesBrowserUseCase useCase) {
    myUseCase = useCase;
  }

  @Override
  public Object getData(@NotNull @NonNls final String dataId) {
    if (CommittedChangesBrowserUseCase.DATA_KEY.is(dataId)) {
      return myUseCase;
    }
    else if (VcsDataKeys.VCS.is(dataId)) {
      Set<AbstractVcs> abstractVcs = ChangesUtil.getAffectedVcses(getSelectedChanges(), myProject);
      if (abstractVcs.size() == 1) return ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(abstractVcs)).getKeyInstanceMethod();
      return null;
    }
    return super.getData(dataId);
  }
}


text:
 $(document).ready(function() {

    $('.sign-up').hide(); //Initially form wil be hidden.

     $('#sign_in').click(function() {
     $('.sign-up').fadeIn(1000);//Form shows on button click
     $('#sign_in').hide();
     $('.sign-in').hide();
   });
 });


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  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 Egret 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 EGRET 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 EGRET AND 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 egret.gui {

	/**
	 * @class egret.gui.ILayoutManagerClient
	 * @interface
	 * @classdesc
	 * 使用布局管理器的组件接口
	 * @extends egret.IEventDispatcher
	 */
	export interface ILayoutManagerClient extends IEventDispatcher{
		/**
		 * 验证组件的属性
		 * @method egret.gui.ILayoutManagerClient#validateProperties
		 */
		validateProperties():void;
		/**
		 * 验证组件的尺寸
		 * @method egret.gui.ILayoutManagerClient#validateSize
		 * @param recursive? {boolean}
		 */
		validateSize(recursive?:boolean):void;
		/**
		 * 验证子项的位置和大小,并绘制其他可视内容
		 * @method egret.gui.ILayoutManagerClient#validateDisplayList
		 */
		validateDisplayList():void;
		/**
		 * 在显示列表的嵌套深度
		 * @member egret.gui.ILayoutManagerClient#nestLevel
		 */
		nestLevel:number;
		/**
		 * 是否完成初始化。此标志只能由 LayoutManager 修改。
		 * @member egret.gui.ILayoutManagerClient#initialized
		 */
		initialized:boolean;
		/**
		 * 一个标志,用于确定某个对象是否正在等待分派其updateComplete事件。此标志只能由 LayoutManager 修改。
		 * @member egret.gui.ILayoutManagerClient#updateCompletePendingFlag
		 */
		updateCompletePendingFlag:boolean;
		/**
		 * 父级显示对象
		 * @member egret.gui.ILayoutManagerClient#parent
		 */
		parent:DisplayObjectContainer;
	}
}


text:
package jp.ijufumi.demo.spring.boot.jpa.domain;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {}


text:
import json
from collections import Counter

import click

@click.command()
@click.argument("input-file", type=click.Path(exists=True, dir_okay=False))
@click.argument("output-file", type=click.Path(exists=False, dir_okay=False))
@click.option("--char-dict/--no-char-dict", default=False)
def get_dict(input_file, output_file, char_dict):

    with open(input_file) as f:
        text = f.read()

    counts = Counter(list(text) if char_dict else text.split())

    dct = {w[0]: i for i, w in enumerate(counts.most_common(), 2)}
    dct["UNK"] = 1
    dct["eos"] = 0

    with open(output_file, "w") as f:
        json.dump(dct, f, indent=4)  # FIXME: encoding error

if __name__ == "__main__":
    get_dict()


text:
/*
 * This file is part of the swblocks-baselib library.
 *
 * 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.
 */

#ifndef __BL_REACTIVE_OBSERVERBASE_H_
#define __BL_REACTIVE_OBSERVERBASE_H_

#include <baselib/reactive/Observer.h>

#include <baselib/core/ObjModel.h>
#include <baselib/core/BaseIncludes.h>

namespace bl
{
    namespace reactive
    {
        /**
         * @brief class ObserverBase
         */
        template
        <
            typename E = void
        >
        class ObserverBaseT : public Observer
        {
            BL_CTR_DEFAULT( ObserverBaseT, protected )
            BL_DECLARE_OBJECT_IMPL_ONEIFACE( ObserverBaseT, Observer )

        public:

            virtual void onCompleted() OVERRIDE
            {
                BL_LOG(
                    Logging::debug(),
                    BL_MSG()
                        << "ObserverBase::onCompleted()"
                    );
            }

            virtual void onError( SAA_in const std::exception_ptr& eptr ) OVERRIDE
            {
                utils::tryCatchLog(
                    "ObserverBase:onError() was called with the following exception",
                    [ & ]() -> void
                    {
                        cpp::safeRethrowException( eptr );
                    },
                    cpp::void_callback_t(),
                    utils::LogFlags::DEBUG_ONLY
                    );
            }
        };

        typedef ObserverBaseT<> ObserverBase;

    } // reactive

} // bl

#endif /* __BL_REACTIVE_OBSERVERBASE_H_ */


text:
namespace Zone.UmbracoPersonalisationGroups.Criteria.Session
{
    public enum SessionSettingMatch
    {
        Exists,
        DoesNotExist,
        MatchesValue,
        ContainsValue,
        GreaterThanValue,
        GreaterThanOrEqualToValue,
        LessThanValue,
        LessThanOrEqualToValue,
    }

    public class SessionSetting
    {
        public string Key { get; set; }

        public SessionSettingMatch Match { get; set; }

        public string Value { get; set; }
    }
}