text:
'''
Create virtualenv environments.

.. versionadded:: 0.17.0
'''
from __future__ import absolute_import

# Import python libs
import glob
import shutil
import logging
import os
import os.path

# Import salt libs
import salt.utils
import salt.exceptions
from salt.ext.six import string_types

KNOWN_BINARY_NAMES = frozenset(
    ['virtualenv',
     'virtualenv2',
     'virtualenv-2.6',
     'virtualenv-2.7'
     ]
)

log = logging.getLogger(__name__)

__opts__ = {
    'venv_bin': salt.utils.which_bin(KNOWN_BINARY_NAMES) or 'virtualenv'
}

__pillar__ = {}

# Define the module's virtual name
__virtualname__ = 'virtualenv'

def __virtual__():
    return __virtualname__

def create(path,
           venv_bin=None,
           system_site_packages=False,
           distribute=False,
           clear=False,
           python=None,
           extra_search_dir=None,
           never_download=None,
           prompt=None,
           pip=False,
           symlinks=None,
           upgrade=None,
           user=None,
           use_vt=False,
           saltenv='base'):
    '''
    Create a virtualenv

    path
        The path to create the virtualenv
    venv_bin : None (default 'virtualenv')
        The name (and optionally path) of the virtualenv command. This can also
        be set globally in the minion config file as ``virtualenv.venv_bin``.
    system_site_packages : False
        Passthrough argument given to virtualenv or pyvenv
    distribute : False
        Passthrough argument given to virtualenv
    pip : False
        Install pip after creating a virtual environment,
        implies distribute=True
    clear : False
        Passthrough argument given to virtualenv or pyvenv
    python : None (default)
        Passthrough argument given to virtualenv
    extra_search_dir : None (default)
        Passthrough argument given to virtualenv
    never_download : None (default)
        Passthrough argument given to virtualenv if True
    prompt : None (default)
        Passthrough argument given to virtualenv if not None
    symlinks : None
        Passthrough argument given to pyvenv if True
    upgrade : None
        Passthrough argument given to pyvenv if True
    user : None
        Set ownership for the virtualenv
    runas : None
        Set ownership for the virtualenv

    use_vt : False
        Use VT terminal emulation (see ouptut while installing)

        .. versionadded:: 2015.5.0

    saltenv : 'base'
        Specify a different environment. The default environment is ``base``.

        .. versionadded:: 2014.1.0

    .. note::
        The ``runas`` argument is deprecated as of 2014.1.0. ``user`` should be
        used instead.

    CLI Example:

    .. code-block:: bash

        salt '*' virtualenv.create /path/to/new/virtualenv
    '''
    if venv_bin is None:
        venv_bin = __opts__.get('venv_bin') or __pillar__.get('venv_bin')
    # raise CommandNotFoundError if venv_bin is missing
    salt.utils.check_or_die(venv_bin)

    cmd = [venv_bin]

    if 'pyvenv' not in venv_bin:
        # ----- Stop the user if pyvenv only options are used --------------->
        # If any of the following values are not None, it means that the user
        # is actually passing a True or False value. Stop Him!
        if upgrade is not None:
            raise salt.exceptions.CommandExecutionError(
                'The `upgrade`(`--upgrade`) option is not supported '
                'by {0!r}'.format(venv_bin)
            )
        elif symlinks is not None:
            raise salt.exceptions.CommandExecutionError(
                'The `symlinks`(`--symlinks`) option is not supported '
                'by {0!r}'.format(venv_bin)
            )
        # <---- Stop the user if pyvenv only options are used ----------------

        # Virtualenv package
        try:
            import virtualenv
            version = getattr(virtualenv, '__version__',
                              virtualenv.virtualenv_version)
            virtualenv_version_info = tuple(
                [int(i) for i in version.split('rc')[0].split('.')]
            )
        except ImportError:
            # Unable to import?? Let's parse the version from the console
            version_cmd = '{0} --version'.format(venv_bin)
            ret = __salt__['cmd.run_all'](
                    version_cmd, runas=user, python_shell=False
                )
            if ret['retcode'] > 0 or not ret['stdout'].strip():
                raise salt.exceptions.CommandExecutionError(
                    'Unable to get the virtualenv version output using {0!r}. '
                    'Returned data: {1!r}'.format(version_cmd, ret)
                )
            virtualenv_version_info = tuple(
                [int(i) for i in
                 ret['stdout'].strip().split('rc')[0].split('.')]
            )

        if distribute:
            if virtualenv_version_info >= (1, 10):
                log.info(
                    'The virtualenv \'--distribute\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'distribute\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.'
                )
            else:
                cmd.append('--distribute')

        if python is not None and python.strip() != '':
            if not salt.utils.which(python):
                raise salt.exceptions.CommandExecutionError(
                    'Cannot find requested python ({0}).'.format(python)
                )
            cmd.append('--python={0}'.format(python))
        if extra_search_dir is not None:
            if isinstance(extra_search_dir, string_types) and \
                    extra_search_dir.strip() != '':
                extra_search_dir = [
                    e.strip() for e in extra_search_dir.split(',')
                ]
            for entry in extra_search_dir:
                cmd.append('--extra-search-dir={0}'.format(entry))
        if never_download is True:
            if virtualenv_version_info >= (1, 10):
                log.info(
                    'The virtualenv \'--never-download\' option has been '
                    'deprecated in virtualenv(>=1.10), as such, the '
                    '\'never_download\' option to `virtualenv.create()` has '
                    'also been deprecated and it\'s not necessary anymore.'
                )
            else:
                cmd.append('--never-download')
        if prompt is not None and prompt.strip() != '':
            cmd.append('--prompt={0!r}'.format(prompt))
    else:
        # venv module from the Python >= 3.3 standard library

        # ----- Stop the user if virtualenv only options are being used ----->
        # If any of the following values are not None, it means that the user
        # is actually passing a True or False value. Stop Him!
        if python is not None and python.strip() != '':
            raise salt.exceptions.CommandExecutionError(
                'The `python`(`--python`) option is not supported '
                'by {0!r}'.format(venv_bin)
            )
        elif extra_search_dir is not None and extra_search_dir.strip() != '':
            raise salt.exceptions.CommandExecutionError(
                'The `extra_search_dir`(`--extra-search-dir`) option is not '
                'supported by {0!r}'.format(venv_bin)
            )
        elif never_download is not None:
            raise salt.exceptions.CommandExecutionError(
                'The `never_download`(`--never-download`) option is not '
                'supported by {0!r}'.format(venv_bin)
            )
        elif prompt is not None and prompt.strip() != '':
            raise salt.exceptions.CommandExecutionError(
                'The `prompt`(`--prompt`) option is not supported '
                'by {0!r}'.format(venv_bin)
            )
        # <---- Stop the user if virtualenv only options are being used ------

        if upgrade is True:
            cmd.append('--upgrade')
        if symlinks is True:
            cmd.append('--symlinks')

    # Common options to virtualenv and pyvenv
    if clear is True:
        cmd.append('--clear')
    if system_site_packages is True:
        cmd.append('--system-site-packages')

    # Finally the virtualenv path
    cmd.append(path)

    # Let's create the virtualenv
    ret = __salt__['cmd.run_all'](cmd, runas=user, python_shell=False)
    if ret['retcode'] != 0:
        # Something went wrong. Let's bail out now!
        return ret

    # Check if distribute and pip are already installed
    if salt.utils.is_windows():
        venv_python = os.path.join(path, 'Scripts', 'python.exe')
        venv_pip = os.path.join(path, 'Scripts', 'pip.exe')
        venv_setuptools = os.path.join(path, 'Scripts', 'easy_install.exe')
    else:
        venv_python = os.path.join(path, 'bin', 'python')
        venv_pip = os.path.join(path, 'bin', 'pip')
        venv_setuptools = os.path.join(path, 'bin', 'easy_install')

    # Install setuptools
    if (pip or distribute) and not os.path.exists(venv_setuptools):
        _install_script(
            'https://bitbucket.org/pypa/setuptools/raw/default/ez_setup.py',
            path, venv_python, user, saltenv=saltenv, use_vt=use_vt
        )

        # clear up the distribute archive which gets downloaded
        for fpath in glob.glob(os.path.join(path, 'distribute-*.tar.gz*')):
            os.unlink(fpath)

    if ret['retcode'] != 0:
        # Something went wrong. Let's bail out now!
        return ret

    # Install pip
    if pip and not os.path.exists(venv_pip):
        _ret = _install_script(
            'https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py',
            path, venv_python, user, saltenv=saltenv, use_vt=use_vt
        )
        # Let's update the return dictionary with the details from the pip
        # installation
        ret.update(
            retcode=_ret['retcode'],
            stdout='{0}\n{1}'.format(ret['stdout'], _ret['stdout']).strip(),
            stderr='{0}\n{1}'.format(ret['stderr'], _ret['stderr']).strip(),
        )

    return ret

def get_site_packages(venv):
    '''
    Returns the path to the site-packages directory inside a virtualenv

    venv
        Path to the virtualenv.

    CLI Example:

    .. code-block:: bash

        salt '*' virtualenv.get_site_packages /path/to/my/venv
    '''
    bin_path = os.path.join(venv, 'bin/python')

    if not os.path.exists(bin_path):
        raise salt.exceptions.CommandExecutionError(
            "Path does not appear to be a virtualenv: '{0}'".format(bin_path))

    ret = __salt__['cmd.exec_code_all'](bin_path, 'from distutils import sysconfig; print sysconfig.get_python_lib()')

    if ret['retcode'] != 0:
        raise salt.exceptions.CommandExecutionError('{stdout}\n{stderr}'.format(**ret))

    return ret['stdout']

def get_resource_path(venv, package_or_requirement, resource_name):
    '''
    Returns the path to a resource of a package or a distribution inside a virtualenv

    .. versionadded:: 2015.5.0

    venv
        Path to the virtualenv.
    package_or_requirement
        Name of the package where the resource resides in.
    resource_name
        Name of the resource of which the path is to be returned.

    CLI Example:

    .. code-block:: bash

        salt '*' virtualenv.get_resource_path /path/to/my/venv my_package my/resource.xml
    '''
    if not salt.utils.verify.safe_py_code(package_or_requirement):
        raise salt.exceptions.CommandExecutionError
    if not salt.utils.verify.safe_py_code(resource_name):
        raise salt.exceptions.CommandExecutionError
    bin_path = os.path.join(venv, 'bin/python')

    if not os.path.exists(bin_path):
        raise salt.exceptions.CommandExecutionError("Path does not appear to be a virtualenv: '{0}'".format(bin_path))

    ret = __salt__['cmd.exec_code_all'](bin_path, "import pkg_resources; print pkg_resources.resource_filename('{0}', '{1}')".format(package_or_requirement, resource_name))

    if ret['retcode'] != 0:
        raise salt.exceptions.CommandExecutionError('{stdout}\n{stderr}'.format(**ret))

    return ret['stdout']

def get_resource_content(venv, package_or_requirement, resource_name):
    '''
    Returns the content of a resource of a package or a distribution inside a virtualenv

    .. versionadded:: 2015.5.0

    venv
        Path to the virtualenv.
    package_or_requirement
        Name of the package where the resource resides in.
    resource_name
        Name of the resource of which the content is to be returned.

    CLI Example:

    .. code-block:: bash

        salt '*' virtualenv.get_resource_content /path/to/my/venv my_package my/resource.xml
    '''
    if not salt.utils.verify.safe_py_code(package_or_requirement):
        raise salt.exceptions.CommandExecutionError
    if not salt.utils.verify.safe_py_code(resource_name):
        raise salt.exceptions.CommandExecutionError
    bin_path = os.path.join(venv, 'bin/python')

    if not os.path.exists(bin_path):
        raise salt.exceptions.CommandExecutionError("Path does not appear to be a virtualenv: '{0}'".format(bin_path))

    ret = __salt__['cmd.exec_code_all'](bin_path, "import pkg_resources; print pkg_resources.resource_string('{0}', '{1}')".format(package_or_requirement, resource_name))

    if ret['retcode'] != 0:
        raise salt.exceptions.CommandExecutionError('{stdout}\n{stderr}'.format(**ret))

    return ret['stdout']

def _install_script(source, cwd, python, user, saltenv='base', use_vt=False):
    if not salt.utils.is_windows():
        tmppath = salt.utils.mkstemp(dir=cwd)
    else:
        tmppath = __salt__['cp.cache_file'](source, saltenv)

    if not salt.utils.is_windows():
        fn_ = __salt__['cp.cache_file'](source, saltenv)
        shutil.copyfile(fn_, tmppath)
        os.chmod(tmppath, 0o500)
        os.chown(tmppath, __salt__['file.user_to_uid'](user), -1)
    try:
        return __salt__['cmd.run_all'](
            '{0} {1}'.format(python, tmppath),
            runas=user,
            cwd=cwd,
            env={'VIRTUAL_ENV': cwd},
            use_vt=use_vt,
            python_shell=False,
        )
    finally:
        os.remove(tmppath)


text:
package uk.co.thinkofdeath.thinkcraft.bukkit.textures;

import uk.co.thinkofdeath.thinkcraft.resources.Texture;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

public class BufferedTexture implements Texture {

    private final BufferedImage image;

    public BufferedTexture(InputStream inputStream) {
        try {
            image = ImageIO.read(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public BufferedTexture(int w, int h) {
        image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    }

    @Override
    public int getWidth() {
        return image.getWidth();
    }

    @Override
    public int getHeight() {
        return image.getHeight();
    }

    @Override
    public int[] getPixels(int x, int y, int w, int h) {
        return image.getRGB(x, y, w, h, null, 0, w);
    }

    @Override
    public void setPixels(int[] data, int x, int y, int w, int h) {
        image.setRGB(x, y, w, h, data, 0, w);
    }

    public BufferedImage getImage() {
        return image;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>../modules/Bizs.MultiSelectTree/0.1/MultiSelectTree.js - open jquery components library</title>
    <link rel="stylesheet" href="../assets/css/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="stylesheet" href="../assets/css/widget.css">
    <link rel="stylesheet" href="../assets/css/tabview.css">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 0.2

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

JC.AjaxTree

JC.AjaxUpload

JC.alert

JC.AutoChecked

JC.AutoComplete

JC.AutoFixed

JC.AutoSelect

JC.BaseMVC

JC.BaseMVC.Model

JC.Calendar

JC.common

JC.confirm

JC.Cover

JC.DCalendar

JC.Dialog

JC.Dialog.alert

JC.Dialog.confirm

JC.Dialog.mask

JC.Dialog.msgbox

JC.Drag

JC.DragSelect

JC.f

JC.FChart

JC.Fixed

JC.FlowChart

JC.FormFillUrl

JC.FrameUtil

JC.hideAllPanel

JC.hideAllPopup

JC.ImageCutter

JC.LunarCalendar

JC.LunarCalendar.Model

JC.LunarCalendar.View

JC.msgbox

JC.NSlider

JC.NumericStepper

JC.Paginator

JC.Panel

JC.Panel.Model

JC.Panel.View

JC.Placeholder

JC.PopTips

JC.Rate

JC.Scrollbar

JC.ServerSort

JC.Slider

JC.Slider.Model

JC.StepControl

JC.Suggest

JC.Tab

JC.Tab.Model

JC.Tab.View

JC.TableFreeze

JC.Tips

JC.Tips.Model

JC.Tips.View

JC.Tree

JC.Tree.Model

JC.Valid

window.Bizs.ActionLogic

window.Bizs.AutoSelectComplete

window.Bizs.ChangeLogic

window.Bizs.CommonModify

window.Bizs.CRMSchedule

window.Bizs.CustomColumn

window.Bizs.DisableLogic

window.Bizs.DMultiDate

window.Bizs.DropdownTree

window.Bizs.FormLogic

window.Bizs.InputSelect

window.Bizs.KillISPCache

window.Bizs.MoneyTips

window.Bizs.MultiAutoComplete

window.Bizs.MultiChangeLogic

window.Bizs.MultiDate

window.Bizs.MultiSelect

window.Bizs.MultiselectPanel

window.Bizs.MultiSelectTree

window.Bizs.MultiUpload

window.Bizs.TaskViewer

window.jQuery

window.jQuery.mousewheel

window.JSON

window.Raphael

window.requirejs

window.swfobject

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: ../modules/Bizs.MultiSelectTree/0.1/MultiSelectTree.js

;(function(define, _win) { 'use strict'; define( 'Bizs.MultiSelectTree', [ 'JC.common', 'JC.Tree' ], function(){
/**
 * MultiSelect<br />
 * 多选树<br/>
 * 基于JC.Tree的扩展<br />
 *
 *  <p><b>require</b>:
 *      <a href='JC.common.html'>JC.common</a>
 *      , <a href='JC.Tree.html'>JC.Tree</a>
 *  </p>
 *
 *  <p><a href='https://github.com/openjavascript/jquerycomps' target='_blank'>JC Project Site</a>
 *      | <a href='http://jc2.openjavascript.org/docs_api/classes/Bizs.MultiSelectTree.html' target='_blank'>API docs</a>
 *      | <a href='../../modules/Bizs.MultiSelectTree/0.1/_demo' target='_blank'>demo link</a></p>
 *
 * @namespace   window.Bizs
 * @class       MultiSelectTree
 * @constructor
 * @param   {selector|string}   _selector
 * @version dev 0.1 2014-06-19
 * @author  sunlei <sunlei@360.cn> | 75 Team
 */
    JC.use && !JC.Tree && JC.use( 'JC.Tree' );
    Bizs.MultiSelectTree = MultiSelectTree

	function MultiSelectTree( _treeEle, _treeData, _cb, _renderTpl ){
		// init tree and callback
		this._tree = new JC.Tree( _treeEle, _treeData );
		this._getSelected = _cb;
        this._renderTpl = _renderTpl;
	}
	MultiSelectTree.prototype = {
        /**
         * explain~
         * @method expandChild
         * @param   {event} _evt
         */
		"expandChild" : function(_evt){
			var target = $(_evt.target);
			var dataid = target.attr('dataid');
			if(this._tree._model.hasChild(dataid)){
				this._tree._view.open(dataid);
				var children = this._tree._model.child(dataid);
				for(var i=0;i<children.length;i++){
					this.expandChild(children[i][0]);
				}
			}
		},
		"foldChild" : function(_evt){
			var target = $(_evt.target);
			var dataid = target.attr('dataid');
			this._tree._view.close(dataid);
		},
		"autoCheck" : function(target){
			if(target.attr("dataid") == this._tree._model.root()[0]){
				return;
			}
			var parent_ul = JC.f.getJqParent(target,"ul");
			var notCheckedCount = parent_ul.find('input.js_checkbox:not(:checked)').length;
			var parent_sel = parent_ul.prev().find('input.js_checkbox').eq(0);
			if(notCheckedCount === 0){
				parent_sel[0].checked = true;
				this.autoCheck(parent_sel);
			}
			else{
				parent_sel[0].checked = false;
				this.autoCheck(parent_sel);
			}
		},
		"update" : function(_evt){
			var target = $(_evt.target);
			if(target[0].nodeName.toLowerCase() !== 'input'){
				return;
			}
			if(target[0].checked){
				var child = JC.f.getJqParent( target, 'div.node_ctn' ).next().find('input.js_checkbox');
				for(var i=0;i<child.length;i++){
					child[i].checked = true;
				}
			}
			else{
				var child = JC.f.getJqParent( target, 'div.node_ctn' ).next().find('input.js_checkbox');
				for(var i=0;i<child.length;i++){
					child[i].checked = false;
				}
			}
			this.autoCheck(target);

			// call getSelected callback
			var selectedArray = [];
			this._tree._model._container.find('input.js_checkbox:checked').each(function(){
				selectedArray.push($(this).attr("dataid"));
			});
			this._getSelected(selectedArray, this._tree);
		},
		"init" : function(){
            var _p = this;
			// add delegate
			this._tree._model._container.delegate('input.js_checkbox:checked', 'click', this.expandChild.bind(this));
			this._tree._model._container.delegate('input.js_checkbox:not(:checked)', 'click', this.foldChild.bind(this));

			// rewrite callback
			this._tree.on('RenderLabel', function( _data ){
				var _node = $(this);
				_node.html( JC.f.printf( _p._renderTpl
                        || '<label dataid="{0}" dataname="{1}"><input type="checkbox" class="js_checkbox" dataid="{0}">{1}</label>'
                        , _data[0], _data[1] ) );
			});
			this._tree.on('change', this.update.bind(this));

			// triger tree init
			this._tree.init();
            return this._tree;
		}
        , tree: function(){ return this._tree; }
	};

    return JC.MultiSelectTree;
});}( typeof define === 'function' && define.amd ? define :
        function ( _name, _require, _cb) {
            typeof _name == 'function' && ( _cb = _name );
            typeof _require == 'function' && ( _cb = _require );
            _cb && _cb();
        }
        , window
    )
);


text:
    <link rel="stylesheet" href="styles/main.css">

    <a href="<?php echo URL::to('admin/create') ?>">  New


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Peziza minima Fr.

### Remarks
null


text:
Using a Naive Bayes Classifier to Model Apple Stock

 Original Post

 Originally published on the Inovance blog on 7/21/2014. Link: https://inovancetech.com/blogML2.html

 Description

 This is a basic example of how to use a Naïve Bayes classifier to predict the direction of Apple stock.
We will build a very simple model that uses the day of the week and a moving average cross to predict
whether the day's price will close up or down. We don't expect this model to perform well
on new, out-of-sample data with purpose being to demonstrate how to build these type of models.


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0011_auto_20150321_2317'),
    ]

    operations = [
        migrations.AddField(
            model_name='channel',
            name='chan_id',
            field=models.CharField(default='', help_text='The internal identifier for this channel', max_length=64, verbose_name='Channel ID'),
            preserve_default=True,
        ),
    ]


text:
ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :dbfile => ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define(:version => 1) do
  create_table :products do |t|
    t.string :offer_code
  end
end


text:
class KinectInput
{
public:
	KinectInput();
	virtual ~KinectInput();

	void start();
	void stop();

	//Kinect2::BodyIndexFrame getBodyIndex() const;
	/// returns shared data
	ci::Channel8u getBodyIndex() const;
	double getBodyIndexTimestamp() const;
	/// returns shared data
	ci::Surface8u getColorizedBodyIndex() const;
	Kinect2::BodyFrame getBody() const;
	//Kinect2::DepthFrame getDepth() const;
	/// Returns shared data
	ci::Channel16u getDepthChannel() const;
	double getDepthTimestamp() const;
	/// CV_32FC3. Returns clone.
	cv::Mat getPointCloud() const;
	Kinect2::DeviceRef getKinect() const;
	ci::Vec2i getImageSize() const;

private:
	void depthCallback(Kinect2::DepthFrame const& frame);
	void bodyCallback(Kinect2::BodyFrame const& frame);
	void bodyIndexCallback(Kinect2::BodyIndexFrame const& frame);
	/// Returns CV_32FC2 matrix of the given size.
	static cv::Mat createDepthToWorldSpaceMap(Kinect2::DeviceRef kinect, ci::Vec2i const& size);

	Kinect2::DeviceRef mKinect;
	std::unique_ptr<boost::thread> mThread;
	cv::Mat mDepthToWorldMappingTable;
	bool mIsRunning;

	mutable boost::shared_mutex mMutex;
	// guards the following
	ci::Vec2i mKinectImageSize;
	//Kinect2::BodyIndexFrame mBodyIndex;
	ci::Surface mColorizedBodyIndex;
	Kinect2::BodyFrame mBody;
	//Kinect2::DepthFrame mDepth;
	ci::Channel16u mDepth;
	double mDepthTimestamp;
	ci::Channel8u mBodyIndex;
	double mBodyIndexTimestamp;
	cv::Mat mPointCloud; ///< CV_32FC3, In world coordinates

};


text:
package com.treode.store.paxos

import com.treode.async.Async
import com.treode.async.stubs.StubScheduler
import com.treode.async.stubs.implicits._
import com.treode.cluster.{EphemeralPort, Peer, PortId}
import com.treode.cluster.stubs.{MessageCaptor, StubNetwork, StubPeer}
import com.treode.store.{Bytes, StoreTestTools, TxClock}
import org.scalatest.FreeSpec

import StoreTestTools._

class AcceptorSpec extends FreeSpec {

  private implicit class RicStubPeer (peer: StubPeer) {

    def ask (key: Long, ballot: Long, default: Int, from: MessageCaptor): Unit =
      from.send (Acceptor.ask, peer) (1, key, ballot, default)
  }

  private case class Grant (key: Long, ballot: Long, proposed: Option [(Long, Int)])

  private implicit class RichMessageCaptor (c: MessageCaptor) {

    def expectGrant (peer: StubPeer) (implicit s: StubScheduler): Grant = {
      val ((key, b1, proposed), from) = c.expect (Proposer.grant)
      assertResult (peer.localId) (from.id)
      proposed match {
        case Some ((b2, value)) => Grant (key.long, b1, Some (b2.number, value.int))
        case None => Grant (key.long, b1, None)
      }}}

  val k1 = 0xB91DBC0E0EE50880L
  val v1 = 0xCCEA074C

  "The Acceptor should" - {

    "work" in {
      implicit val (random, scheduler, network) = newKit()
      val captor = MessageCaptor.install()
      val h = StubPaxosHost .install() .expectPass()
      h.ask (k1, 1, v1, captor)
      assertResult (Grant (k1, 1, None)) (captor.expectGrant (h))
    }}}


text:
@implementation NSURL (sfapi)

- (NSString *)authority {
    if (self.port != nil) {
        return [NSString stringWithFormat:@"%@:%@", self.host, self.port];
    }
    else {
        return self.host;
    }
}

- (NSString *)getAuthority {
    if (self.scheme != nil) {
        return [NSString stringWithFormat:@"%@://%@", self.scheme, self.host];
    }
    else {
        return self.host;
    }
}

- (NSNumber *)portWithHTTPSchemeDefaults {
    NSNumber *urlPortNumber = [self port];
    NSUInteger urlPort = 0;
    if (!urlPortNumber) {
        NSString *lowerScheme = self.scheme.lowercaseString;
        if (lowerScheme.length > 0) {
            if ([lowerScheme isEqualToString:NSURLProtectionSpaceHTTPS]) {
                urlPort = 443;
            }
            else if ([lowerScheme isEqualToString:NSURLProtectionSpaceHTTP]) {
                urlPort = 80;
            }
            else if ([lowerScheme isEqualToString:NSURLProtectionSpaceFTP]) {
                urlPort = 21;
            }
        }

        urlPortNumber = [NSNumber numberWithUnsignedInteger:urlPort];
    }
    return urlPortNumber;
}

- (NSURLProtectionSpace *)protectionSpaceWithAuthenticationMethod:(NSString *)authenticationMethod realm:(NSString *)realm isProxy:(BOOL)isProxy {
    NSString *mRelm = realm.lowercaseString;
    NSString *protocol = nil;
    NSString *lowerScheme = self.scheme.lowercaseString;
    if ([lowerScheme isEqualToString:@"http"]) {
        protocol = NSURLProtectionSpaceHTTP;
    }
    else if ([lowerScheme isEqualToString:@"https"]) {
        protocol = NSURLProtectionSpaceHTTPS;
    }
    else if ([lowerScheme isEqualToString:@"ftp"]) {
        protocol = NSURLProtectionSpaceFTP;
    }
    else {
        protocol = lowerScheme;
    }

    NSNumber *port = [self portWithHTTPSchemeDefaults];

    NSURLProtectionSpace *result = nil;
    if (isProxy) {
        result = [[NSURLProtectionSpace alloc] initWithProxyHost:self.host.lowercaseString port:[port integerValue] type:[protocol isEqualToString:NSURLProtectionSpaceHTTPSProxy] ? NSURLProtectionSpaceHTTPSProxy : NSURLProtectionSpaceHTTPProxy realm:mRelm authenticationMethod:authenticationMethod];
    }
    else {
        result = [[NSURLProtectionSpace alloc] initWithHost:self.host.lowercaseString port:[port integerValue] protocol:protocol realm:mRelm authenticationMethod:authenticationMethod];
    }

    return result;
}

@end


text:
function CaseConverter() {
  this.toSnakeCase = toSnakeCase;
  this.toCamelCase = toCamelCase;
}

function toSnakeCase(string) {
  var words = string.split(' ');
  var output = '';
  for (var i = 0; i < words.length; i++) {
    output = output + words[i].charAt(0).toUpperCase() + words[i].slice(1);
  }
  return output;
}

function toCamelCase(string) {
  var snakeCase = toSnakeCase(string);
  return snakeCase.charAt(0).toLowerCase() + snakeCase.slice(1);
}

module.exports = CaseConverter;


text:
<!DOCTYPE  html>

    <meta charset="utf-8">

    <title>doc</title>

grunt-contrib-imagemin v0.9.2

Minify images

Getting Started

This plugin requires Grunt ~0.4.0

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-contrib-imagemin --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-contrib-imagemin');

Imagemin task

Run this task with the grunt imagemin command.

Minify images using imagemin.

Comes bundled with the following optimizers:

gifsicle — Compress GIF images

jpegtran — Compress JPEG images

optipng — Compress PNG images

pngquant — Compress PNG images

svgo — Compress SVG images

We recommend using grunt-newer to only process changed files as minifying images can be quite slow.

Options

Options will only apply to the relevant files, so you don't need separate targets for png/jpg.

optimizationLevel (png)

Type: Number
Default: 3

Select optimization level between 0 and 7.

The optimization level 0 enables a set of optimization operations that require minimal effort. There will be no changes to image attributes like bit depth or color type, and no recompression of existing IDAT datastreams. The optimization level 1 enables a single IDAT compression trial. The trial chosen is what. OptiPNG thinks it's probably the most effective. The optimization levels 2 and higher enable multiple IDAT compression trials; the higher the level, the more trials.

Level and trials:

1 trial

8 trials

16 trials

24 trials

48 trials

120 trials

240 trials

progressive (jpg)

Type: Boolean
Default: true

Lossless conversion to progressive.

interlaced (gif)

Type: Boolean
Default: true

Interlace gif for progressive rendering.

# svgoPlugins (svg)

Type: array
Default: []

Customize which SVGO plugins to use. More here.

use

Type: Array
Default: null

Additional plugins to use with imagemin.

Example config

You can either map your files statically or dynamically.

var mozjpeg = require('imagemin-mozjpeg');

grunt.initConfig({
  imagemin: {                          // Task
    static: {                          // Target
      options: {                       // Target options
        optimizationLevel: 3,
        svgoPlugins: [{ removeViewBox: false }],
        use: [mozjpeg()]
      },
      files: {                         // Dictionary of files
        'dist/img.png': 'src/img.png', // 'destination': 'source'
        'dist/img.jpg': 'src/img.jpg',
        'dist/img.gif': 'src/img.gif'
      }
    },
    dynamic: {                         // Another target
      files: [{
        expand: true,                  // Enable dynamic expansion
        cwd: 'src/',                   // Src matches are relative to this path
        src: ['**/*.{png,jpg,gif}'],   // Actual patterns to match
        dest: 'dist/'                  // Destination path prefix
      }]
    }
  }
});

grunt.loadNpmTasks('grunt-contrib-imagemin');
grunt.registerTask('default', ['imagemin']);

Release History

2014-11-11   v0.9.2   Bump imagemin dependency

2014-10-25   v0.9.1   Update plugin API.

2014-10-22   v0.9.0   Update to imagemin 2.0.

2014-08-27   v0.8.1   Bump dependencies.

2014-08-11   v0.8.0   Better output. Chalk 0.5.0 update. Fixes imagemin options.

2014-08-11   v0.7.2   Fix npm EPEERINVALID

2014-05-31   v0.7.1   Caching original image size before optimization. Remove unused dependencies.

2014-04-29   v0.7.0   Update "imagemin" to 0.4

2014-04-01   v0.6.1   Fix problem with corrupt images being created

2014-03-28   v0.6.0   Updated "imagemin" to 0.2 Added percentage to size saved view - fixes cache option removed. Adds "pretty-bytes".

2014-01-13   v0.5.0   Extract the logic into an external lib imagemin.

2014-01-08   v0.4.1   Prevent "Maximum call stack size exceeded". Speed up loading this task by lazy requiring bin deps.

2013-11-22   v0.4.0   The pngquant option is now false by default instead of true.

2013-09-09   v0.3.0   Add interlace option for gif files.

2013-08-16   v0.2.0   Add gifsicle and pngquant. Cache images so only changed images are optimized. Default optimizationLevel to 7 and progressive to true.

2013-04-10   v0.1.4   Fix exception when running in verbose mode.

2013-04-05   v0.1.3   Fix OptiPNG not being able to overwrite file. Allow overwriting src when dest/src is the same. Limit to 10 concurrent optimizations.

2013-02-22   v0.1.2   Fix OptiPNG not working on some systems. Prevent OptiPNG from producing .bak files.

2013-02-15   v0.1.1   First official release for Grunt 0.4.0.

2013-01-30   v0.1.1rc8   Fix task not creating destination folders

2013-01-30   v0.1.1rc7   Updating to work with grunt v0.4.0rc7. Switching to this.files api.

2012-11-01   v0.1.0   Initial release.

Task submitted by Sindre Sorhus

This file was generated on Tue Nov 11 2014 16:27:08.


text:
module Mail
  module ContentTransferEncoding
    include Treetop::Runtime

    def root
      @root || :primary
    end

    include RFC2822

    include RFC2045

    module Primary0
      def CFWS1
        elements[0]
      end

      def encoding
        elements[1]
      end

      def CFWS2
        elements[2]
      end
    end

    def _nt_primary
      start_index = index
      if node_cache[:primary].has_key?(index)
        cached = node_cache[:primary][index]
        @index = cached.interval.end if cached
        return cached
      end

      i0, s0 = index, []
      r1 = _nt_CFWS
      s0 << r1
      if r1
        r2 = _nt_encoding
        s0 << r2
        if r2
          r3 = _nt_CFWS
          s0 << r3
        end
      end
      if s0.last
        r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
        r0.extend(Primary0)
      else
        @index = i0
        r0 = nil
      end

      node_cache[:primary][start_index] = r0

      r0
    end

    module Encoding0
      def encoding
        known_tokens.text_value || ietf_token.text_value || x_token.text_value
      end
    end

    def _nt_encoding
      start_index = index
      if node_cache[:encoding].has_key?(index)
        cached = node_cache[:encoding][index]
        @index = cached.interval.end if cached
        return cached
      end

      i0 = index
      r1 = _nt_known_tokens
      if r1
        r0 = r1
      else
        r2 = _nt_ietf_token
        if r2
          r0 = r2
        else
          r3 = _nt_x_token
          r3.extend(Encoding0)
          if r3
            r0 = r3
          else
            @index = i0
            r0 = nil
          end
        end
      end

      node_cache[:encoding][start_index] = r0

      r0
    end

    def _nt_known_tokens
      start_index = index
      if node_cache[:known_tokens].has_key?(index)
        cached = node_cache[:known_tokens][index]
        @index = cached.interval.end if cached
        return cached
      end

      i0 = index
      if has_terminal?("7bit", false, index)
        r1 = instantiate_node(SyntaxNode,input, index...(index + 4))
        @index += 4
      else
        terminal_parse_failure("7bit")
        r1 = nil
      end
      if r1
        r0 = r1
      else
        if has_terminal?("8bit", false, index)
          r2 = instantiate_node(SyntaxNode,input, index...(index + 4))
          @index += 4
        else
          terminal_parse_failure("8bit")
          r2 = nil
        end
        if r2
          r0 = r2
        else
          if has_terminal?("binary", false, index)
            r3 = instantiate_node(SyntaxNode,input, index...(index + 6))
            @index += 6
          else
            terminal_parse_failure("binary")
            r3 = nil
          end
          if r3
            r0 = r3
          else
            if has_terminal?("quoted-printable", false, index)
              r4 = instantiate_node(SyntaxNode,input, index...(index + 16))
              @index += 16
            else
              terminal_parse_failure("quoted-printable")
              r4 = nil
            end
            if r4
              r0 = r4
            else
              if has_terminal?("base64", false, index)
                r5 = instantiate_node(SyntaxNode,input, index...(index + 6))
                @index += 6
              else
                terminal_parse_failure("base64")
                r5 = nil
              end
              if r5
                r0 = r5
              else
                @index = i0
                r0 = nil
              end
            end
          end
        end
      end

      node_cache[:known_tokens][start_index] = r0

      r0
    end

  end

  class ContentTransferEncodingParser < Treetop::Runtime::CompiledParser
    include ContentTransferEncoding
  end

end


text:
'use strict';

angular.module('myApp.user_login', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/user/login', {
    templateUrl: 'user_login/user_login.html',
    controller: 'UserLoginCtrl'
  });
}])

.controller('UserLoginCtrl', ['$scope', 'drupal', function($scope, drupal) {
      $scope.submit = function(user) {
        drupal.user_login(user.name, user.pass).then(function(data) {
            alert('Hello world and hello ' + data.user.name + '!');
        });
      };
}]);


text:
int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	QWidget win;

	QFormLayout* mainLayout = new QFormLayout();

	mainLayout->addRow("Item1", new QLabel("Label", &win));
	mainLayout->addRow("Item2", new QCheckBox("Checkbox", &win));
	mainLayout->addRow("Item3", new QPushButton("Button", &win));
	mainLayout->addRow("Item4", new QTextEdit("Text", &win));
	mainLayout->addRow("Item5", new QSpinBox(&win));

	win.setLayout(mainLayout);
	win.show();

	return a.exec();
}


text:
let semver = require('semver');

export function cleanVersion(version) {
    return version.replace('~', '')
                  .replace('^', '')
                  .replace('=', '')
                  .replace('<', '')
                  .replace('>', '')
}

export function getAngularVersionOfProject(packageData) {
    let _result = '';

    if (packageData['dependencies']) {
        let angularCore = packageData['dependencies']['@angular/core'];
        if (angularCore) {
            _result = cleanVersion(angularCore);
        }
    }

    return _result;
}

function isAngularVersionArchived(version) {
    let result;

    try {
        result = semver.compare(version, '2.4.10') <= 0;
    } catch (e) {}

    return result;
}

export function prefixOfficialDoc(version) {
    return isAngularVersionArchived(version) ? 'v2.' : '';
}


text:
/**
 * AdSenseSettingsInheritedProperty.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.dfp.axis.v201505;

/**
 * The property of the AdUnit that specifies how and from where the
 * AdSenseSettings are inherited.
 */
public class AdSenseSettingsInheritedProperty  implements java.io.Serializable {
    /* The AdSenseSettings from which the property is inherited. */
    private com.google.api.ads.dfp.axis.v201505.AdSenseSettings value;

    public AdSenseSettingsInheritedProperty() {
    }

    public AdSenseSettingsInheritedProperty(
           com.google.api.ads.dfp.axis.v201505.AdSenseSettings value) {
           this.value = value;
    }

    /**
     * Gets the value value for this AdSenseSettingsInheritedProperty.
     *
     * @return value   * The AdSenseSettings from which the property is inherited.
     */
    public com.google.api.ads.dfp.axis.v201505.AdSenseSettings getValue() {
        return value;
    }

    /**
     * Sets the value value for this AdSenseSettingsInheritedProperty.
     *
     * @param value   * The AdSenseSettings from which the property is inherited.
     */
    public void setValue(com.google.api.ads.dfp.axis.v201505.AdSenseSettings value) {
        this.value = value;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof AdSenseSettingsInheritedProperty)) return false;
        AdSenseSettingsInheritedProperty other = (AdSenseSettingsInheritedProperty) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.value==null && other.getValue()==null) ||
             (this.value!=null &&
              this.value.equals(other.getValue())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getValue() != null) {
            _hashCode += getValue().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(AdSenseSettingsInheritedProperty.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "AdSenseSettingsInheritedProperty"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("value");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "value"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201505", "AdSenseSettings"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
package io.renren.dao;

import io.renren.entity.MsgTemplateEntity;
/**
 *
 * @author gaoyupeng
 * @date 2017年6月28日
 */
public interface MsgTemplateDao extends BaseDao<MsgTemplateEntity>{

}


text:
<?php

namespace Stalker\Lib\RESTAPI\v2;

class RESTApiController extends RESTApiResource
{
    protected $name;

    public function getName(){
        return $this->name;
    }

}


text:
layout: page
title: Combs 45th Anniversary
date: 2016-05-24
author: Natalie Wall
tags: weekly links, java
status: published
summary: Integer mollis vehicula libero id efficitur. Vivamus non neque.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 08/09/2018
  endDate: 08/13/2018
  ctyhocn: MAFHAHX
  groupCode: C4A
published: true
---
Nulla sollicitudin turpis eget venenatis dictum. Aliquam vel pharetra nisi, at suscipit orci. Sed at maximus turpis, sed maximus dui. Quisque feugiat nulla eu turpis tempus, vel ornare leo sodales. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec rutrum euismod mauris vel varius. Sed quis odio volutpat lorem scelerisque vestibulum vitae id eros. Duis rutrum, nisi at congue egestas, mi nisi euismod lacus, ut posuere mi quam sit amet dolor. Mauris consectetur porttitor nulla vitae euismod. Cras ac enim est. Maecenas efficitur justo eget metus consequat, a tincidunt ex tincidunt. In non feugiat lacus. Nulla facilisi. Ut ornare nunc id imperdiet ullamcorper. Pellentesque vestibulum turpis gravida euismod molestie.

* Cras ultricies lorem ut nibh tincidunt laoreet
* Aenean sodales dolor in ultrices convallis.

Mauris ut ligula vitae lacus mollis aliquam. Morbi in interdum tellus. Nunc aliquet quam at hendrerit pretium. Quisque sit amet nunc consequat, tempus nisi quis, ornare ipsum. Pellentesque eu magna egestas, tempor metus eu, malesuada metus. Phasellus nibh nisl, tempor ut bibendum id, euismod vitae nulla. Quisque tincidunt nisl in eros imperdiet cursus. Fusce quis porta augue, in vehicula nibh. Mauris ut feugiat nisl. Integer ut nunc purus. Cras elementum, nunc a gravida faucibus, dui turpis ullamcorper nulla, vitae feugiat velit mauris ut eros. In facilisis placerat nulla, quis dignissim urna scelerisque nec. Vestibulum ultrices vehicula est, ac iaculis nibh commodo id. Nullam auctor nibh massa, ut accumsan diam eleifend sed.


text:
package com.facebook.litho.specmodels.processor;

import static org.mockito.Mockito.mock;

import com.facebook.litho.annotations.Event;
import com.facebook.litho.annotations.FromTrigger;
import com.facebook.litho.annotations.OnCreateLayout;
import com.facebook.litho.annotations.OnTrigger;
import com.facebook.litho.annotations.OnUpdateState;
import com.facebook.litho.annotations.Param;
import com.facebook.litho.annotations.Prop;
import com.facebook.litho.annotations.State;
import com.facebook.litho.specmodels.internal.ImmutableList;
import com.facebook.litho.specmodels.internal.RunMode;
import com.facebook.litho.specmodels.model.EventDeclarationModel;
import com.facebook.litho.specmodels.model.EventMethod;
import com.facebook.litho.specmodels.model.SpecMethodModel;
import com.google.testing.compile.CompilationRule;
import com.squareup.javapoet.ClassName;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.processing.Messager;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests {@link TriggerMethodExtractor} */
@RunWith(JUnit4.class)
public class TriggerMethodExtractorTest {
  @Rule public CompilationRule mCompilationRule = new CompilationRule();

  static class TestClass {

    @OnCreateLayout
    public void ignored() {}

    @OnTrigger(TestEvent.class)
    public void testMethod(
        @Prop boolean testProp,
        @State int testState,
        @Param Object testPermittedAnnotation,
        @FromTrigger long arg4) {
      // Don't do anything.
    }

    @OnUpdateState
    public void alsoIgnored() {}
  }

  @Event(returnType = Object.class)
  static class TestEvent {
    public long arg4;
  }

  @Test
  public void testMethodExtraction() {
    Elements elements = mCompilationRule.getElements();
    TypeElement typeElement = elements.getTypeElement(TestClass.class.getCanonicalName());

    List<Class<? extends Annotation>> permittedParamAnnotations = new ArrayList<>();

    ImmutableList<SpecMethodModel<EventMethod, EventDeclarationModel>> methods =
        TriggerMethodExtractor.getOnTriggerMethods(
            elements,
            typeElement,
            permittedParamAnnotations,
            ImmutableList.of(),
            mock(Messager.class),
            RunMode.normal());

    ClassName eventClassName =
        ClassName.bestGuess(
            "com.facebook.litho.specmodels.processor.TriggerMethodExtractorTest.TestEvent");

    TriggerMethodExtractorTestHelper.assertMethodExtraction(methods, eventClassName);
  }
}


text:
package org.apache.nifi.minifi;

import org.junit.Assert;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

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

public class FlowParserTest {

    private static final String TEST_FLOW_XML_PATH = "./src/test/resources/flow.xml.gz";

    @Test
    public void testCanParseFlow() {
        FlowParser flowParser = new FlowParser();
        Document parsedFlow = flowParser.parse(new File(TEST_FLOW_XML_PATH));

        Assert.assertNotNull(parsedFlow);

        NodeList processors = parsedFlow.getElementsByTagName(FlowEnricher.PROCESSOR_TAG_NAME);
        NodeList controllerServices = parsedFlow.getElementsByTagName(FlowEnricher.CONTROLLER_SERVICE_TAG_NAME);
        NodeList reportingTasks = parsedFlow.getElementsByTagName(FlowEnricher.REPORTING_TASK_TAG_NAME);

        Assert.assertEquals("Verify correct number of processors", 3, processors.getLength());
        Assert.assertEquals("Verify correct number of controller services", 1, controllerServices.getLength());
        Assert.assertEquals("Verify correct number of reporting tasks", 0, reportingTasks.getLength());
    }

    @Test
    public void testGetChildrenByTagName() {
        FlowParser flowParser = new FlowParser();
        Document parsedFlow = flowParser.parse(new File(TEST_FLOW_XML_PATH));
        NodeList processors = parsedFlow.getElementsByTagName(FlowEnricher.PROCESSOR_TAG_NAME);

        for (int i = 0; i < processors.getLength(); i++) {
            Element processor = (Element) processors.item(i);

            List<Element> classElements = FlowParser.getChildrenByTagName(processor, "class");
            Assert.assertEquals(1, classElements.size());

            List<Element> propertyElements = FlowParser.getChildrenByTagName(processor, "property");
            Assert.assertTrue(propertyElements.size() > 1);
        }
    }
}


text:
const {debug, error} = require('./common');

// Response Builder classes
const {
  V1_TO_V2_PLATFORM_NAME,
  PLATFORMS,
} = require('./rich-responses/rich-response');
const Text = require('./rich-responses/text-response');
const Card = require('./rich-responses/card-response');
const Image = require('./rich-responses/image-response');
const Suggestion = require('./rich-responses/suggestions-response');
const PayloadResponse = require('./rich-responses/payload-response');

// Contexts class
const Contexts = require('./contexts');

// Failed response constants
const ERROR_HTTP_STATUS_CODE = 500;

/**
 * Class representing a v2 Dialogflow agent
 */
class V2Agent {
  /**
   * Constructor for V2Agent object
   * To be used in with WebhookClient class
   *
   * @param {Object} agent instance of WebhookClient class
   */
  constructor(agent) {
    this.agent = agent;
    return this;
  }

  /**
   * Process a v2 Dialogflow webhook request to set class varibles
   * for action, parameters, contexts, request source and orignal user query
   *
   * @private
   */
  processRequest_() {
    /**
     * Dialogflow intent or null if no value
     * https://dialogflow.com/docs/intents
     * @type {string}
     */
    this.agent.intent = this.agent.request_.body.queryResult.intent.displayName;
    debug(`Intent: ${this.agent.intent}`);

    /**
     * Dialogflow action or null if no value: https://dialogflow.com/docs/actions-and-parameters
     * @type {string}
     */
    this.agent.action = this.agent.request_.body.queryResult.action
      ? this.agent.request_.body.queryResult.action
      : null;
    debug(`Action: ${this.agent.action}`);

    /**
     * Dialogflow input contexts included in the request or null if no value
     * https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/WebhookRequest#FIELDS.session
     * @type {string}
     */
    this.agent.session = this.agent.request_.body.session;
    debug(`v2 Session: ${JSON.stringify(this.agent.session)}`);

    /**
     * Dialogflow parameters included in the request or null if no value
     * https://dialogflow.com/docs/actions-and-parameters
     * @type {Object[]}
     */
    this.agent.parameters =
      this.agent.request_.body.queryResult.parameters || {}; // https://dialogflow.com/docs/actions-and-parameters
    debug(`Parameters: ${JSON.stringify(this.agent.parameters)}`);

    /**
     * Dialogflow input contexts included in the request or null if no value
     * convert v2 contexts to v1 contexts
     * https://dialogflow.com/docs/contexts
     * @type {string}
     */
    if (this.agent.request_.body.queryResult.outputContexts) {
      this.agent.contexts = this.agent.request_.body.queryResult.outputContexts.map(
        (context) => this.convertV2ContextToV1Context_(context));
    } else {
      this.agent.contexts = [];
    }
    debug(`Request contexts: ${JSON.stringify(this.agent.contexts)}`);

    /**
     * Instance of Dialogflow contexts class to provide an API to set/get/delete contexts
     *
     * @type {Contexts}
     */
    this.agent.context = new Contexts(
      this.agent.request_.body.queryResult.outputContexts,
      this.agent.session);

    /**
     * Dialogflow source included in the request or null if no value
     * https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/projects.agent.intents#Platform
     * @type {string}
     */
    const detectIntentRequest = this.agent.request_.body.originalDetectIntentRequest;
    if (detectIntentRequest) {
      const requestSource =
        detectIntentRequest.source ||
        (detectIntentRequest.payload && detectIntentRequest.payload.source) ||
        null;
      this.agent.requestSource = V1_TO_V2_PLATFORM_NAME[requestSource] || requestSource;
    }
    debug(`Request source: ${JSON.stringify(this.agent.requestSource)}`);

    /**
     * Dialogflow original request object from detectIntent/query or platform integration
     * (Google Assistant, Slack, etc.) in the request or null if no value
     * https://dialogflow.com/docs/reference/agent/query#query_parameters_and_json_fields
     * @type {object}
     */
    this.agent.originalRequest = this.agent.request_.body.originalDetectIntentRequest;
    debug(`Original Request: ${JSON.stringify(this.agent.originalRequest)}`);

    /**
     * Original user query as indicated by Dialogflow or null if no value
     * https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/
     * projects.agent.sessions/detectIntent#QueryResult.FIELDS.query_text
     * @type {string}
     */
    this.agent.query = this.agent.request_.body.queryResult.queryText;
    debug(`Original query: ${JSON.stringify(this.agent.query)}`);

    /**
     * Original request language code (i.e. "en")
     * @type {string} locale language code indicating the spoken/written language of the original request
     */
     this.agent.locale = this.agent.request_.body.queryResult.languageCode;
     debug(`Request locale: ${JSON.stringify(this.agent.locale)}`);

    /**
     * List of messages defined in Dialogflow's console for the matched intent
     * https://dialogflow.com/docs/rich-messages
     *
     * @type {RichResponse[]}
     */
    if (this.agent.request_.body.queryResult.fulfillmentMessages) {
      const consoleMessages = this.agent.request_.body.queryResult.fulfillmentMessages;
      this.agent.consoleMessages = this.getConsoleMessages_(consoleMessages);
    } else {
      this.agent.consoleMessages = [];
    }
    debug(`Console messages: ${JSON.stringify(this.agent.consoleMessages)}`);

    /**
     * Alternative query results that have a high match score
     * Query results can be from other Dialogflow intents or Knowledge Connectors
     * https://cloud.google.com/dialogflow-enterprise/alpha/docs/knowledge-connectors
     * Note:this feature is only available in Dialogflow API V2
     *
     * @type {object}
     */
    if (this.agent.request_.body.alternativeQueryResults) {
      this.agent.alternativeQueryResults = this.agent.request_.body.alternativeQueryResults;
    }
    debug(`Alternative query result: ${JSON.stringify(this.agent.alternativeQueryResults)}`);
  }

  /**
   * Add v2 text response to Dialogflow fulfillment webhook request based on
   * single, developer defined text response
   *
   * @private
   */
  addTextResponse_() {
    const message = this.agent.responseMessages_[0];
    const fulfillmentText = message.ssml || message.text;
    this.addJson_({fulfillmentText: fulfillmentText});
  }

  /**
   * Add v2 payload response to Dialogflow fulfillment webhook request based
   * on developer defined payload response
   *
   * @param {Object} payload to back to requestSource (i.e. Google, Slack, etc.)
   * @param {string} requestSource string indicating the source of the initial request
   * @private
   */
  addPayloadResponse_(payload, requestSource) {
    this.addJson_({payload: payload.getPayload_(requestSource)});
  }

  /**
   * Add v2 response to Dialogflow fulfillment webhook request based on developer
   * defined response messages and original request source
   *
   * @param {string} requestSource string indicating the source of the initial request
   * @private
   */
  addMessagesResponse_(requestSource) {
    let messages = this.buildResponseMessages_(requestSource);
    if (messages.length > 0) {
      this.addJson_({fulfillmentMessages: messages});
    }
  }

  /**
   * Add v2 response to Dialogflow fulfillment webhook request
   *
   * @param {Object} responseJson JSON to send to Dialogflow
   * @private
   */
  addJson_(responseJson) {
    if (!this.responseJson_) {
      this.responseJson_ = {};
    }
    Object.assign(this.responseJson_, responseJson);
  }

  /**
   * Send v2 response to Dialogflow fulfillment webhook request
   *
   * @param {string} requestSource string indicating the source of the initial request
   * @private
   */
  sendResponses_(requestSource) {
    let responseJson = this.responseJson_;

    if (this.agent.followupEvent_) {
      responseJson = responseJson || {};
      responseJson.followupEventInput = this.agent.followupEvent_;
    }

    if (!responseJson) {
      error(`No responses defined for platform: ${requestSource}`);
      this.agent.response_.status(ERROR_HTTP_STATUS_CODE).send(`No responses defined for platform: ${requestSource}`);
    } else {
      responseJson.outputContexts = this.agent.context.getV2OutputContextsArray();
      if (this.agent.endConversation_) {
        responseJson.triggerEndOfConversation = this.agent.endConversation_;
      }
      debug('Response to Dialogflow: ' + JSON.stringify(responseJson));
      this.agent.response_.json(responseJson);
    }
  }

  /**
   * Builds a list of v2 message objects to send back to Dialogflow based on
   * developer defined responses and the request source
   *
   * @param {string} requestSource string indicating the source of the initial request
   * @return {Object[]} message objects
   * @private
   */
  buildResponseMessages_(requestSource) {
    return this.agent.responseMessages_.map((message) => message.getV2ResponseObject_(requestSource)).
      filter((arr) => arr);
  }

  /**
   * Add an v2 outgoing context
   *
   * @param {object} context an object representing a v1 or v2 outgoing context
   * @private
   */
  addContext_(context) {
    // Check and see if a v2 context object was added
    if (context.name.match('/contexts/')) {
      context = this.convertV2ContextToV1Context_(context);
    }
    this.agent.context.set(context);
  }

  /**
   * Convert a v2 context object to a v1 context object
   *
   * @param {object} v2Context an object representing a v2 context
   * @return {object} v1Context an object representing a v1 context
   * @private
   */
  convertV2ContextToV1Context_(v2Context) {
    let v1Context = {};
    const v2ContextNamePrefixLength = this.agent.session.length + '/contexts/'.length;
    v1Context.name = v2Context.name.slice(v2ContextNamePrefixLength);
    v1Context.lifespan = v2Context.lifespanCount;
    v1Context.parameters = v2Context.parameters;
    return v1Context;
  }

  /**
   * Add an v2 followup event
   *
   * @param {Object} event an object representing a followup event
   * @private
   */
  setFollowupEvent_(event) {
    if (!event.languageCode) {
      event.languageCode = this.agent.locale;
    }

    this.agent.followupEvent_ = event;
  }

  /**
   * Add a response or list of responses to be sent to Dialogflow and end the conversation
   * Note: Only supported on Dialogflow v2's telephony gateway, Google Assistant and Alexa integrations
   *
   * @param {RichResponse|string|RichResponse[]|string[]} responses (list) or single responses
   */
  end_(responses) {
    this.agent.endConversation_ = true;
    this.agent.add(responses);
  }

  /**
   * Add an v2 Actions on Google response
   *
   * @param {Object} response a Actions on Google Dialogflow v2 webhook response
   * @private
   */
  addActionsOnGoogle_(response) {
    if (response.outputContexts) {
      response.outputContexts.forEach((context) => {
        this.addContext_(context);
      });
    }

    this.agent.add(new PayloadResponse(
      PLATFORMS.ACTIONS_ON_GOOGLE,
      response.payload.google)
    );
  }

  /**
   * Get messages defined in Dialogflow's console for matched intent
   *
   * @param {Object[]} consoleMessageList is a list of v2 Dialogflow messages from Dialogflow's console
   * @return {RichResponse[]} list of RichResponse objects
   * @private
   */
  getConsoleMessages_(consoleMessageList) {
    // Functions to transpose fulfillment messages from Dialogflow's console to fulfillment library classes
    const richResponseMapping = {
      text: this.convertTextJson_,
      card: this.convertCardJson_,
      image: this.convertImageJson_,
      payload: this.convertPayloadJson_,
      quickReplies: this.convertQuickRepliesJson_,
      simpleResponses: this.convertSimpleResponsesJson_,
      basicCard: this.convertBasicCardJson_,
      suggestions: this.convertSuggestionsJson_,
    };

    let richConsoleMessages = []; // list of messages to be returned

    // iterate through each message recived in the webhook request
    consoleMessageList.forEach((consoleMessageJson) => {
      const richMessageType = Object.keys(consoleMessageJson).find((key) => key !== 'platform');
      if (richResponseMapping[richMessageType]) {
        const messagePlatform = consoleMessageJson.platform ? consoleMessageJson.platform : undefined;
        // convert the JSON to fufillment classes
        let richResponse = richResponseMapping[richMessageType](consoleMessageJson, messagePlatform);
        richResponse ? richConsoleMessages = richConsoleMessages.concat(richResponse) : null;
      } else {
        debug(`Unsupported console message type "${richMessageType}"`);
      }
    });
    return richConsoleMessages;
  };

  /**
   * Convert incoming text message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertTextJson_(messageJson, platform) {
    if (!messageJson.text.text[0]) {
      return null;
    } else {
      return new Text({text: messageJson.text.text[0], platform: platform});
    }
  }

  /**
   * Convert incoming card message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertCardJson_(messageJson, platform) {
    return new Card({
      title: messageJson.card.title || ' ',
      text: messageJson.card.subtitle,
      imageUrl: messageJson.card.imageUri,
      buttonText: messageJson.card.buttons ? messageJson.card.buttons[0].text : null,
      buttonUrl: messageJson.card.buttons ? messageJson.card.buttons[0].postback : null,
      platform: platform,
    });
  }

  /**
   * Convert incoming image message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertImageJson_(messageJson, platform) {
    return new Image({
      imageUrl: messageJson.image.imageUri,
      platform: platform,
    });
  }

  /**
   * Convert incoming payload message object JSON into a Payload rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertPayloadJson_(messageJson, platform) {
    return new PayloadResponse(platform, messageJson.payload, {
      rawPayload: true,
      sendAsMessage: true,
    });
  }

  /**
   * Convert incoming quick reply message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertQuickRepliesJson_(messageJson, platform) {
    if (!messageJson.suggestions) return null;
    let suggestions = [];
    messageJson.suggestions.forEach((consoleMessageJson, iterator) => {
      suggestions.push(new Suggestion({
        title: messageJson.quickReplies.quickReplies[iterator],
        platform: platform,
      }));
    });
    return suggestions;
  }

  /**
   * Convert incoming simple response message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertSimpleResponsesJson_(messageJson, platform) {
    const message = messageJson.simpleResponses.simpleResponses[0];
    return new Text({
      text: message.textToSpeech || message.displayText,
      ssml: message.ssml,
      platform: platform,
    });
  }

  /**
   * Convert incoming basic card message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertBasicCardJson_(messageJson, platform) {
    return new Card({
      title: messageJson.basicCard.title || ' ',
      text: messageJson.basicCard.formattedText,
      imageUrl: messageJson.basicCard.image ? messageJson.basicCard.image.imageUri : null,
      buttonText: messageJson.basicCard.buttons ? messageJson.basicCard.buttons[0].title : null,
      buttonUrl: messageJson.basicCard.buttons ? messageJson.basicCard.buttons[0].openUriAction.uri : null,
      platform: platform,
    });
  }

  /**
   * Convert incoming suggestions message object JSON into a Text rich response
   *
   * @param {Object} messageJson is a the JSON implementation of the message
   * @param {string} platform is the platform of the message object
   * @return {RichResponse} richResponse implementation of the message
   * @private
   */
  convertSuggestionsJson_(messageJson, platform) {
    if (!messageJson.suggestions) return null;
    let suggestions = [];
    messageJson.suggestions.suggestions.forEach((consoleMessageJson, iterator) => {
      suggestions.push(new Suggestion({
        title: messageJson.suggestions.suggestions[iterator].title,
        platform: platform,
      }));
    });
    return suggestions;
  }
}

module.exports = V2Agent;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Notes – Dadi Zhang</title>
    <link rel="dns-prefetch" href="//maxcdn.bootstrapcdn.com">
    <link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Hi, my name is Dadi Zhang. I am a cloud architect, infrastructure engineer, data scientist, and hardcore Go player.">
    <meta name="robots" content="all">
    <meta name="author" content="Dadi Zhang">

    <link rel="canonical" href="http://localhost:4000/notes/">
    <link rel="alternate" type="application/rss+xml" title="RSS Feed for Dadi Zhang" href="/feed.xml" />

    <link rel="stylesheet" href="/css/pixyll.css?202005271618" type="text/css">

    <link href='//fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Lato:900,300' rel='stylesheet' type='text/css'>
    <link href='//fonts.googleapis.com/css?family=Overpass:900,300' rel='stylesheet' type='text/css'>

      <link href="//maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">

    <meta property="og:locale" content="en_US">
    <meta property="og:type" content="article">
    <meta property="og:title" content="Notes">
    <meta property="og:description" content="Hi, my name is Dadi Zhang. I am a cloud architect, infrastructure engineer, data scientist, and hardcore Go player.">
    <meta property="og:url" content="http://localhost:4000/notes/">
    <meta property="og:site_name" content="Dadi Zhang">

    <meta name="twitter:card" content="summary" />

    <meta name="twitter:title" content="Notes" />
    <meta name="twitter:description" content="Hi, my name is Dadi Zhang. I am a cloud architect, infrastructure engineer, data scientist, and hardcore Go player." />
    <meta name="twitter:url" content="http://localhost:4000/notes/" />

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

      Dadi Zhang

        Blog

        Notes

        About

Winter 2017

ENGL 306A - Introduction to Linguistics

Spring 2016

STAT 231 - Statistics

Spring 2016

PSYCH 101 - Introductory Psychology

Spring 2016

MUSIC 140 - Popular Music and Culture

Spring 2016

CS 246 - Object-Oriented Software Development

      Copyright © 2019 Dadi Zhang. Built with Pixyll.


text:
Notes active

                    {{note.type.type}}

{{note.title}}

                        {{note.text}}

                        Created at: {{note.created_at}}
                        Updated at: {{note.updated_at}}

                        {{notes.typeSelected.type}}

Create a new note

                        <form  ng-submit="notes.save()" role="form">

                                Type of note:
                                <select ng-model="notes.new.type"
                                    ng-options="type.id as type.type for type in notes.types"
                                    ng-change="notes.changeTypeNew()"
                                    name="typeNote">
                                </select>

                                Title of the note
                                <input type="text" class="form-control" id="" placeholder="Title of the note" ng-model="notes.new.title" name="title">
                                Note
                                <textarea class="form-control" ng-model="notes.new.text" name="text"></textarea>

                            <button type="submit" class="btn btn-primary">Save</button>
                        </form>

Create a new type

                  <form ng-submit="notes.saveType()">

                            Colour
                                <input type="color" name="color" class="form-control" ng-model="notes.typeNew.colour">
                                Name of Type
                                <input type="text" class="form-control" ng-model="notes.typeNew.type" name="
                                nombre">

                            <button class="btn btn-primary" type="submit">Save</button>

                    </form>


text:
package pl.edu.agh.iisg.osgiservices;

import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;

public class ServiceUser {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    private BundleContext context;

    public ServiceUser(BundleContext context) {
        this.context = context;
    }

    public void useServices(int n) {
        try {
            for (int i = n - 1; i >= 0; i--) {
                String filter = "(name=" + i + ")";
                Collection<ServiceReference<ISampleService>> references = context.getServiceReferences(ISampleService.class, filter);
                for (ServiceReference<ISampleService> ref : references) {
                    ISampleService service = context.getService(ref);
                    logger.log(Level.FINE, "Using service: " + String.valueOf(service.getValue()));
                }
            }
        } catch (InvalidSyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


text:
//////////////////////////////// -*- C++ -*- //////////////////////////////
//
// FILE NAME
//   InitialCoordsAttrFunctions.hh
//
// AUTHOR
//    A. Shishlo
//
// CREATED
//    03/27/2016
//
// DESCRIPTION
//    A set of functions for bunches with the ParticleInitialCoordinates attribute
//
///////////////////////////////////////////////////////////////////////////

#ifndef PARTICLES_INIT_COORDS_FUNCTIONS_H
#define PARTICLES_INIT_COORDS_FUNCTIONS_H

//ORBIT bunch
#include "Bunch.hh"

#include "Matrix.hh"

#include <cmath>

namespace OrbitUtils{

	/**
	  A function that will copy coordinates of the particles to
	  the 6D initial coordinates Attribute (ParticleInitialCoordinates).
	 */
	void copyCoordsToInitCoordsAttr(Bunch* bunch);

	/**
	  A function that will swap the initial coordinates Attribute
	  (ParticleInitialCoordinates) and the 6D coordinates of the particles.
	  If the bunch does not have the ParticleInitialCoordinates particles attributes
	  they will be created and full out with 0s, and then they will be swept.
	 */
	void swapInitCoordsAttrAndCoords(Bunch* bunch);

	/**
	  Calculates transport matrix A: x_out = A*x_in +b. A is a 7x7 matrix.
		The last column of A is the b vector.
	  It returns 0 if unsuccessful or the size of the statistics otherwise.
	  The function uses the initial coordinates attributes as x_in and the usual
	  coordinates as x_out.
	*/
	int transport_mtrx_from_init_coords(Bunch* bunch, Matrix* A_mtr);

	/** A function analyzes two bunches assuming the vectors of coordinates
	    transformation x_out = A*x_in + b, where x_in the initial coordinates,
			and x_out final. The results are matrix A (7x7) with the last column as a vector b.
	    The function uses the initial coordinates attributes as x_in and the usual
	    coordinates as x_out.
			It returns 0 if unsuccessful or the size of the statistics otherwise.
			For statistics it uses the weights according to Gaussian distribution with
			Twiss parameters.
	*/
	int transport_mtrx_from_init_coords(Bunch* bunch, Matrix* A_mtr, int appl_twiss_x, int appl_twiss_y, int appl_twiss_z);

	/** A function analyzes bunch with (ParticleInitialCoordinates) attributes
	    Macrosizes of macro-particles in the bunch will be
	    multiplied by the numbers wx0*wy0*wz0*wx1*wy1*wz1 where
	    wx(In or Out) = exp(-(x^2+(alphax*x+betax*x')^2)/(2*(betax*emittancex))
	    etc.
	    Alpha, beta, emittance are the Twiss parameters for the corresponding
	    plane.
	*/
	void apply_twiss_weights_for_init_coords(Bunch* bunch,int appl_x,int appl_y,int appl_z);

};
///////////////////////////////////////////////////////////////////////////
//
// END OF FILE
//
///////////////////////////////////////////////////////////////////////////

#endif


text:
package org.apache.spark.mllib.clustering

import scala.util.Random

import org.scalatest.FunSuite

import org.apache.spark.mllib.linalg.{Vector, Vectors}
import org.apache.spark.mllib.util.{LocalClusterSparkContext, MLlibTestSparkContext}
import org.apache.spark.mllib.util.TestingUtils._

class KMeansSuite extends FunSuite with MLlibTestSparkContext {

  import org.apache.spark.mllib.clustering.KMeans.{K_MEANS_PARALLEL, RANDOM}

  test("single cluster") {
    val data = sc.parallelize(Array(
      Vectors.dense(1.0, 2.0, 6.0),
      Vectors.dense(1.0, 3.0, 0.0),
      Vectors.dense(1.0, 4.0, 6.0)
    ))

    val center = Vectors.dense(1.0, 3.0, 4.0)

    // No matter how many runs or iterations we use, we should get one cluster,
    // centered at the mean of the points

    var model = KMeans.train(data, k = 1, maxIterations = 1)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 2)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 1, initializationMode = RANDOM)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(
      data, k = 1, maxIterations = 1, runs = 1, initializationMode = K_MEANS_PARALLEL)
    assert(model.clusterCenters.head ~== center absTol 1E-5)
  }

  test("no distinct points") {
    val data = sc.parallelize(
      Array(
        Vectors.dense(1.0, 2.0, 3.0),
        Vectors.dense(1.0, 2.0, 3.0),
        Vectors.dense(1.0, 2.0, 3.0)),
      2)
    val center = Vectors.dense(1.0, 2.0, 3.0)

    // Make sure code runs.
    var model = KMeans.train(data, k=2, maxIterations=1)
    assert(model.clusterCenters.size === 2)
  }

  test("more clusters than points") {
    val data = sc.parallelize(
      Array(
        Vectors.dense(1.0, 2.0, 3.0),
        Vectors.dense(1.0, 3.0, 4.0)),
      2)

    // Make sure code runs.
    var model = KMeans.train(data, k=3, maxIterations=1)
    assert(model.clusterCenters.size === 3)
  }

  test("deterministic initialization") {
    // Create a large-ish set of points for clustering
    val points = List.tabulate(1000)(n => Vectors.dense(n, n))
    val rdd = sc.parallelize(points, 3)

    for (initMode <- Seq(RANDOM, K_MEANS_PARALLEL)) {
      // Create three deterministic models and compare cluster means
      val model1 = KMeans.train(rdd, k = 10, maxIterations = 2, runs = 1,
        initializationMode = initMode, seed = 42)
      val centers1 = model1.clusterCenters

      val model2 = KMeans.train(rdd, k = 10, maxIterations = 2, runs = 1,
        initializationMode = initMode, seed = 42)
      val centers2 = model2.clusterCenters

      centers1.zip(centers2).foreach { case (c1, c2) =>
        assert(c1 ~== c2 absTol 1E-14)
      }
    }
  }

  test("single cluster with big dataset") {
    val smallData = Array(
      Vectors.dense(1.0, 2.0, 6.0),
      Vectors.dense(1.0, 3.0, 0.0),
      Vectors.dense(1.0, 4.0, 6.0)
    )
    val data = sc.parallelize((1 to 100).flatMap(_ => smallData), 4)

    // No matter how many runs or iterations we use, we should get one cluster,
    // centered at the mean of the points

    val center = Vectors.dense(1.0, 3.0, 4.0)

    var model = KMeans.train(data, k = 1, maxIterations = 1)
    assert(model.clusterCenters.size === 1)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 2)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 1, initializationMode = RANDOM)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 1,
      initializationMode = K_MEANS_PARALLEL)
    assert(model.clusterCenters.head ~== center absTol 1E-5)
  }

  test("single cluster with sparse data") {

    val n = 10000
    val data = sc.parallelize((1 to 100).flatMap { i =>
      val x = i / 1000.0
      Array(
        Vectors.sparse(n, Seq((0, 1.0 + x), (1, 2.0), (2, 6.0))),
        Vectors.sparse(n, Seq((0, 1.0 - x), (1, 2.0), (2, 6.0))),
        Vectors.sparse(n, Seq((0, 1.0), (1, 3.0 + x))),
        Vectors.sparse(n, Seq((0, 1.0), (1, 3.0 - x))),
        Vectors.sparse(n, Seq((0, 1.0), (1, 4.0), (2, 6.0 + x))),
        Vectors.sparse(n, Seq((0, 1.0), (1, 4.0), (2, 6.0 - x)))
      )
    }, 4)

    data.persist()

    // No matter how many runs or iterations we use, we should get one cluster,
    // centered at the mean of the points

    val center = Vectors.sparse(n, Seq((0, 1.0), (1, 3.0), (2, 4.0)))

    var model = KMeans.train(data, k = 1, maxIterations = 1)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 2)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 5)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 1, initializationMode = RANDOM)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    model = KMeans.train(data, k = 1, maxIterations = 1, runs = 1,
      initializationMode = K_MEANS_PARALLEL)
    assert(model.clusterCenters.head ~== center absTol 1E-5)

    data.unpersist()
  }

  test("k-means|| initialization") {

    case class VectorWithCompare(x: Vector) extends Ordered[VectorWithCompare] {
      @Override def compare(that: VectorWithCompare): Int = {
        if(this.x.toArray.foldLeft[Double](0.0)((acc, x) => acc + x * x) >
          that.x.toArray.foldLeft[Double](0.0)((acc, x) => acc + x * x)) -1 else 1
      }
    }

    val points = Seq(
      Vectors.dense(1.0, 2.0, 6.0),
      Vectors.dense(1.0, 3.0, 0.0),
      Vectors.dense(1.0, 4.0, 6.0),
      Vectors.dense(1.0, 0.0, 1.0),
      Vectors.dense(1.0, 1.0, 1.0)
    )
    val rdd = sc.parallelize(points)

    // K-means|| initialization should place all clusters into distinct centers because
    // it will make at least five passes, and it will give non-zero probability to each
    // unselected point as long as it hasn't yet selected all of them

    var model = KMeans.train(rdd, k = 5, maxIterations = 1)

    assert(model.clusterCenters.sortBy(VectorWithCompare(_))
      .zip(points.sortBy(VectorWithCompare(_))).forall(x => x._1 ~== (x._2) absTol 1E-5))

    // Iterations of Lloyd's should not change the answer either
    model = KMeans.train(rdd, k = 5, maxIterations = 10)
    assert(model.clusterCenters.sortBy(VectorWithCompare(_))
      .zip(points.sortBy(VectorWithCompare(_))).forall(x => x._1 ~== (x._2) absTol 1E-5))

    // Neither should more runs
    model = KMeans.train(rdd, k = 5, maxIterations = 10, runs = 5)
    assert(model.clusterCenters.sortBy(VectorWithCompare(_))
      .zip(points.sortBy(VectorWithCompare(_))).forall(x => x._1 ~== (x._2) absTol 1E-5))
  }

  test("two clusters") {
    val points = Seq(
      Vectors.dense(0.0, 0.0),
      Vectors.dense(0.0, 0.1),
      Vectors.dense(0.1, 0.0),
      Vectors.dense(9.0, 0.0),
      Vectors.dense(9.0, 0.2),
      Vectors.dense(9.2, 0.0)
    )
    val rdd = sc.parallelize(points, 3)

    for (initMode <- Seq(RANDOM, K_MEANS_PARALLEL)) {
      // Two iterations are sufficient no matter where the initial centers are.
      val model = KMeans.train(rdd, k = 2, maxIterations = 2, runs = 1, initMode)

      val predicts = model.predict(rdd).collect()

      assert(predicts(0) === predicts(1))
      assert(predicts(0) === predicts(2))
      assert(predicts(3) === predicts(4))
      assert(predicts(3) === predicts(5))
      assert(predicts(0) != predicts(3))
    }
  }
}

class KMeansClusterSuite extends FunSuite with LocalClusterSparkContext {

  test("task size should be small in both training and prediction") {
    val m = 4
    val n = 200000
    val points = sc.parallelize(0 until m, 2).mapPartitionsWithIndex { (idx, iter) =>
      val random = new Random(idx)
      iter.map(i => Vectors.dense(Array.fill(n)(random.nextDouble)))
    }.cache()
    for (initMode <- Seq(KMeans.RANDOM, KMeans.K_MEANS_PARALLEL)) {
      // If we serialize data directly in the task closure, the size of the serialized task would be
      // greater than 1MB and hence Spark would throw an error.
      val model = KMeans.train(points, 2, 2, 1, initMode)
      val predictions = model.predict(points).collect()
      val cost = model.computeCost(points)
    }
  }
}


text:
require_relative 'test_helper'

class BitstampTest < Minitest::Test
  def test_that_it_has_a_version_number
    refute_nil ::Bitstamp::VERSION
  end
end


text:
module Admin
  module Views
    class ApplicationLayout
      include Admin::Layout
    end
  end
end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.quota.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of Quotas. */
public interface Quotas {
    /**
     * Get the quota limit of a resource. The response can be used to determine the remaining quota to calculate a new
     * quota limit that can be submitted with a PUT request.
     *
     * @param resourceName Resource name for a given resource provider. For example: - SKU name for Microsoft.Compute -
     *     SKU or TotalLowPriorityCores for Microsoft.MachineLearningServices For Microsoft.Network PublicIPAddresses.
     * @param scope The target Azure resource URI. For example,
     *     `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`.
     *     This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after
     *     `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the quota limit of a resource.
     */
    CurrentQuotaLimitBase get(String resourceName, String scope);

    /**
     * Get the quota limit of a resource. The response can be used to determine the remaining quota to calculate a new
     * quota limit that can be submitted with a PUT request.
     *
     * @param resourceName Resource name for a given resource provider. For example: - SKU name for Microsoft.Compute -
     *     SKU or TotalLowPriorityCores for Microsoft.MachineLearningServices For Microsoft.Network PublicIPAddresses.
     * @param scope The target Azure resource URI. For example,
     *     `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`.
     *     This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after
     *     `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the quota limit of a resource.
     */
    Response<CurrentQuotaLimitBase> getWithResponse(String resourceName, String scope, Context context);

    /**
     * Get a list of current quota limits of all resources for the specified scope. The response from this GET operation
     * can be leveraged to submit requests to update a quota.
     *
     * @param scope The target Azure resource URI. For example,
     *     `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`.
     *     This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after
     *     `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of current quota limits of all resources for the specified scope.
     */
    PagedIterable<CurrentQuotaLimitBase> list(String scope);

    /**
     * Get a list of current quota limits of all resources for the specified scope. The response from this GET operation
     * can be leveraged to submit requests to update a quota.
     *
     * @param scope The target Azure resource URI. For example,
     *     `/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/qms-test/providers/Microsoft.Batch/batchAccounts/testAccount/`.
     *     This is the target Azure resource URI for the List GET operation. If a `{resourceName}` is added after
     *     `/quotas`, then it's the target Azure resource URI in the GET operation for the specific resource.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return a list of current quota limits of all resources for the specified scope.
     */
    PagedIterable<CurrentQuotaLimitBase> list(String scope, Context context);

    /**
     * Get the quota limit of a resource. The response can be used to determine the remaining quota to calculate a new
     * quota limit that can be submitted with a PUT request.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the quota limit of a resource.
     */
    CurrentQuotaLimitBase getById(String id);

    /**
     * Get the quota limit of a resource. The response can be used to determine the remaining quota to calculate a new
     * quota limit that can be submitted with a PUT request.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the quota limit of a resource.
     */
    Response<CurrentQuotaLimitBase> getByIdWithResponse(String id, Context context);

    /**
     * Begins definition for a new CurrentQuotaLimitBase resource.
     *
     * @param name resource name.
     * @return the first stage of the new CurrentQuotaLimitBase definition.
     */
    CurrentQuotaLimitBase.DefinitionStages.Blank define(String name);
}


text:
describe('Service: bnd.specific.service', function() {
  'use strict';

  var bndSpecific, g;

  beforeEach(module('bnd.specific.service'));

  beforeEach(inject(function(_bndSpecific_) {
    bndSpecific = _bndSpecific_;
    g = bndSpecific();
  }));

  it('should be a factory for Specific Boundary instances', function() {
    expect(g.constructor.name).toBe('SpecificBoundary');
  });

  describe('Specific Boundary', function() {
    it('should have a collection of active hypotheses', function() {
      expect(g.hypotheses).toEqual(jasmine.any(Array));
    });

    it('should have a method to observe an example', function() {
      expect(g.observe).toEqual(jasmine.any(Function));
    });

    it('should track rejected hypotheses by example', function() {
      expect(g.rejections).toEqual(jasmine.any(Array));
    });

    it('should have a list of observed examples', function() {
      expect(g.examples).toEqual(jasmine.any(Array));
    });

    it('should update when given a new hypotheses', function() {
      g.observe({x: 3, y: 3, isPositive: false});
    });

  });
});


text:
package com.pie.tlatoani.Skin.Skull;

import com.pie.tlatoani.Core.Skript.MundoPropertyExpression;
import org.bukkit.SkullType;
import org.bukkit.inventory.ItemStack;

/**
 * Created by Tlatoani on 4/16/18.
 */
public class ExprSkullOfType extends MundoPropertyExpression<SkullType, ItemStack> {

    @Override
    public ItemStack convert(SkullType skullType) {
        return SkullUtil.skullItem(skullType);
    }
}