text:
import json
import time
from scraper import getheadlines, getheadlines_JS
from textanalyser import generatesentiment
import boto
from time import gmtime, strftime
import sys

# In[70]:

def generateheadlinefile(source_file, output_file, s3key, scraperfn):
    with open(source_file) as data_file:
        sources = json.load(data_file)
        data = {}
        data["time"] = time.strftime("%c %Z")
        data["news-data"] = []

    for source in sources:
        print(source)
        headlines = scraperfn(source["url"], source["xpath"], source.get("remove"))
        sentiments = [generatesentiment("headline", headline) for headline in headlines]

        data["news-data"].append({
            "name": source["name"],
            "sentiments": sentiments
        })

#     with open(output_file, 'w') as outfile:
#         json.dump(data, outfile)

    filename = strftime("%Y-%m-%d", gmtime())
    s3 = boto.connect_s3()
    bucket = s3.create_bucket('data.newsemote')
    key = bucket.new_key(s3key + '/' + filename + '.json')
    key.set_contents_from_string(json.dumps(data))
    key.set_acl('public-read')

    #keep copy of file in latest.json
    latest = bucket.new_key(s3key + '/latest.json')
    latest.set_contents_from_string(json.dumps(data))
    latest.set_acl('public-read')

    #retrieve files in bucket
    files = bucket.list(prefix=s3key)
    files = sorted(files, key=lambda k: k.last_modified, reverse=True)
    filtered = [f for f in files if f.name != s3key + '/latest.json' and f.name != 'last7.json']
    filtered = filtered[:7]
    filelist = [file.name for file in filtered]
    print(filelist)

    #write to list file
    latestlist = bucket.new_key(s3key + '/last7.json')
    latestlist.set_contents_from_string(json.dumps(filelist))
    latestlist.set_acl('public-read')

# In[71]:

def au():
  generateheadlinefile('data/news_sources_au.json', 'data-au.json', "au", getheadlines)

def uk():
  generateheadlinefile('data/news_sources_uk.json', 'data-uk.json', "uk", getheadlines)

def us():
  generateheadlinefile('data/news_sources_us.json', 'data-us.json', 'us', getheadlines_JS)

def default():
  au()
  us()

run_options = {
  'au' : au,
  'uk' : uk,
  'us' : us,
  'all' : default
}

try:
  run = sys.argv[1]
except IndexError:
  run = 'all'

run_options[run]()

# In[ ]:


text:
{% load i18n %}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>{% block title %}{% endblock title %}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="{{ STATIC_URL|default:'/static/' }}css/bootstrap.min.css" rel="stylesheet">

    <link href="{{ STATIC_URL|default:'/static/' }}css/bootstrap-responsive.min.css" rel="stylesheet">

    {% block extra-header %}{% endblock extra-header %}

    {% block wrapper %}
    {% block header-wrapper %}

          {% block header-title %}{% endblock header-title %}
          {% block header-user %}
          {% if user.is_authenticated %}

                 {{ user.username }}

{% trans 'Profile' %}

{% trans 'Sign Out' %}

          {% endif %}
          {% endblock header-user %}

                {% block header-nav %}
                {% endblock header-nav %}

            {% block header-nav-extra %}
            {% endblock header-nav-extra %}
            {% block user-nav %}
            {% if not user.is_authenticated %}

{% trans 'Register' %} | {% trans 'Login' %}

            {% endif %}
            {% endblock user-nav %}

    {% endblock header-wrapper %}
    {% block content-wrapper %}

        {% block content-message %}
        {% if messages %}
            {% for message in messages %}

                ×
                {{ message }}

            {% endfor %}
        {% endif %}
        {% endblock content-message %}
        {% block breadcrumb %}{% endblock breadcrumb %}
        {% block content-block %}

{% block content-title %}{% endblock content-title %}

                {% block content %}{% endblock content %}

        {% endblock content-block %}
        {% block extra-block %}{% endblock extra-block %}

    {% block extra-content-block %}{% endblock extra-content-block %}
    {% endblock content-wrapper %}
    {% block footer-wrapper %}

{% block footer %}{% endblock footer %}

    {% endblock footer-wrapper %}
    {% endblock wrapper %}

    {% block extra-js %}{% endblock extra-js %}

redpajama_set_name: RedPajamaGithub


text:
"""
hyper/cli
~~~~~~~~~

Command line interface for Hyper inspired by Httpie.
"""
import json
import locale
import logging
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
from argparse import OPTIONAL, ZERO_OR_MORE
from pprint import pformat
from textwrap import dedent

from hyper import HTTPConnection, HTTP20Connection
from hyper import __version__
from hyper.compat import is_py2, urlencode, urlsplit, write_to_stdout
from hyper.common.util import to_host_port_tuple

log = logging.getLogger('hyper')

PREFERRED_ENCODING = locale.getpreferredencoding()

# Various separators used in args
SEP_HEADERS = ':'
SEP_QUERY = '=='
SEP_DATA = '='

SEP_GROUP_ITEMS = [
    SEP_HEADERS,
    SEP_QUERY,
    SEP_DATA,
]

class KeyValue(object):
    """Base key-value pair parsed from CLI."""

    def __init__(self, key, value, sep, orig):
        self.key = key
        self.value = value
        self.sep = sep
        self.orig = orig

class KeyValueArgType(object):
    """A key-value pair argument type used with `argparse`.

    Parses a key-value arg and constructs a `KeyValue` instance.
    Used for headers, form data, and other key-value pair types.
    This class is inspired by httpie and implements simple tokenizer only.
    """
    def __init__(self, *separators):
        self.separators = separators

    def __call__(self, string):
        for sep in self.separators:
            splitted = string.split(sep, 1)
            if len(splitted) == 2:
                key, value = splitted
                return KeyValue(key, value, sep, string)

def make_positional_argument(parser):
    parser.add_argument(
        'method', metavar='METHOD', nargs=OPTIONAL, default='GET',
        help=dedent("""
        The HTTP method to be used for the request
        (GET, POST, PUT, DELETE, ...).
        """))
    parser.add_argument(
        '_url', metavar='URL',
        help=dedent("""
        The scheme defaults to 'https://' if the URL does not include one.
        """))
    parser.add_argument(
        'items',
        metavar='REQUEST_ITEM',
        nargs=ZERO_OR_MORE,
        type=KeyValueArgType(*SEP_GROUP_ITEMS),
        help=dedent("""
        Optional key-value pairs to be included in the request.
        The separator used determines the type:

        ':' HTTP headers:

            Referer:http://httpie.org  Cookie:foo=bar  User-Agent:bacon/1.0

        '==' URL parameters to be appended to the request URI:

            search==hyper

        '=' Data fields to be serialized into a JSON object:

            name=Hyper  language=Python  description='CLI HTTP client'
        """))

def make_troubleshooting_argument(parser):
    parser.add_argument(
        '--version', action='version', version=__version__,
        help='Show version and exit.')
    parser.add_argument(
        '--debug', action='store_true', default=False,
        help='Show debugging information (loglevel=DEBUG)')
    parser.add_argument(
        '--h2', action='store_true', default=False,
        help="Do HTTP/2 directly in plaintext: skip plaintext upgrade")

def set_url_info(args):
    def split_host_and_port(hostname):
        if ':' in hostname:
            return to_host_port_tuple(hostname, default_port=443)
        return hostname, None

    class UrlInfo(object):
        def __init__(self):
            self.fragment = None
            self.host = 'localhost'
            self.netloc = None
            self.path = '/'
            self.port = 443
            self.query = None
            self.scheme = 'https'
            self.secure = False

    info = UrlInfo()
    _result = urlsplit(args._url)
    for attr in vars(info).keys():
        value = getattr(_result, attr, None)
        if value:
            setattr(info, attr, value)

    if info.scheme == 'http' and not _result.port:
        info.port = 80

    # Set the secure arg is the scheme is HTTPS, otherwise do unsecured.
    info.secure = info.scheme == 'https'

    if info.netloc:
        hostname, _ = split_host_and_port(info.netloc)
        info.host = hostname  # ensure stripping port number
    else:
        if _result.path:
            _path = _result.path.split('/', 1)
            hostname, port = split_host_and_port(_path[0])
            info.host = hostname
            if info.path == _path[0]:
                info.path = '/'
            elif len(_path) == 2 and _path[1]:
                info.path = '/' + _path[1]
            if port is not None:
                info.port = port

    log.debug('Url Info: %s', vars(info))
    args.url = info

def set_request_data(args):
    body, headers, params = {}, {}, {}
    for i in args.items:
        if i.sep == SEP_HEADERS:
            if i.key:
                headers[i.key] = i.value
            else:
                # when overriding a HTTP/2 special header there will be a leading
                # colon, which tricks the command line parser into thinking
                # the header is empty
                k, v = i.value.split(':', 1)
                headers[':' + k] = v
        elif i.sep == SEP_QUERY:
            params[i.key] = i.value
        elif i.sep == SEP_DATA:
            value = i.value
            if is_py2:  # pragma: no cover
                value = value.decode(PREFERRED_ENCODING)
            body[i.key] = value

    if params:
        args.url.path += '?' + urlencode(params)

    if body:
        content_type = 'application/json'
        headers.setdefault('content-type', content_type)
        args.body = json.dumps(body)

    if args.method is None:
        args.method = 'POST' if args.body else 'GET'

    args.headers = headers

def parse_argument(argv=None):
    parser = ArgumentParser(formatter_class=RawTextHelpFormatter)
    parser.set_defaults(body=None, headers={})
    make_positional_argument(parser)
    make_troubleshooting_argument(parser)
    args = parser.parse_args(sys.argv[1:] if argv is None else argv)

    if args.debug:
        handler = logging.StreamHandler()
        handler.setLevel(logging.DEBUG)
        log.addHandler(handler)
        log.setLevel(logging.DEBUG)

    set_url_info(args)
    set_request_data(args)
    return args

def get_content_type_and_charset(response):
    charset = 'utf-8'
    content_type = response.headers.get('content-type')
    if content_type is None:
        return 'unknown', charset

    content_type = content_type[0].decode('utf-8').lower()
    type_and_charset = content_type.split(';', 1)
    ctype = type_and_charset[0].strip()
    if len(type_and_charset) == 2:
        charset = type_and_charset[1].strip().split('=')[1]

    return ctype, charset

def request(args):
    if not args.h2:
        conn = HTTPConnection(
            args.url.host, args.url.port, secure=args.url.secure
        )
    else:  # pragma: no cover
        conn = HTTP20Connection(
            args.url.host, args.url.port, secure=args.url.secure
        )

    conn.request(args.method, args.url.path, args.body, args.headers)
    response = conn.get_response()
    log.debug('Response Headers:\n%s', pformat(response.headers))
    ctype, charset = get_content_type_and_charset(response)
    data = response.read()
    return data

def main(argv=None):
    args = parse_argument(argv)
    log.debug('Commandline Argument: %s', args)
    data = request(args)
    write_to_stdout(data)

if __name__ == '__main__':  # pragma: no cover
    main()


text:
package cc.redstone;

public class SidedRedstone implements IRedstone {
    public final String side;

    public SidedRedstone(String side) {
        this.side = side;
    }

    native public boolean getInput();
    native public boolean getOutput();
    native public void setOutput(boolean on);

    native public int getAnalogInput();
    native public int getAnalogOutput();
    native public void setAnalogOutput(int val);

    static {
        System.load("cc/native/SidedRedstone.lua");
    }
}


text:
package com.yuzhouwan.bigdata.hadoop.reverse.index;

import com.yuzhouwan.bigdata.hadoop.util.ConfUtil;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;

public class PatentPartitioner extends Partitioner<Text, Text> {

    /**
     * Partitioner 的核心方法.
     *
     * @param key
     * @param value
     * @param numPartitions
     * @return
     */
    @Override
    public int getPartition(Text key, Text value, int numPartitions) {

        //这里可以暂时不指定(使用 Hadoop默认分区),到后面能掌握好 Partition的级别程度,可以加入进行调整
        return ConfUtil.getMax();
    }
}


text:
<resources>
    <string name="app_name">Slim</string>
</resources>


text:
define(
({
	add: "Tambahkan",
	addAuthor: "Tambahkan Penulis",
	addContributor: "Tambahkan Kontributor"
})
);


text:
require 'active_record'

module ScramblerFu
  module Acts #:nodoc:
    module Scramblable #:nodoc:

      def self.included(mod)
        mod.extend(ClassMethods)
      end

      module ClassMethods
        def self.extended(base)
          base.class_inheritable_accessor :scrambler_options
        end

        def acts_as_scramblable(options = {})
          self.scrambler_options ||= {}

          self.scrambler_options[:columns] = options.dup

          extend  ScramblerFu::Acts::Scramblable::SingletonMethods
          include ScramblerFu::Acts::Scramblable::InstanceMethods

          Scrambler.register(self)
        end
      end

      module SingletonMethods
        def scramble!(columns = nil)
          scrambler_options[:columns].each do |column, actions|
            action_methods(actions).each do |action|
              send(action, column)
            end
          end
        end

        protected
          def scramble_order!(column)
            ordered   = find(:all)
            scrambled = find(:all, :select => column, :order => 'RAND()')

            ordered.each do |record|
              record.send("#{column}=", scrambled.shift.send("#{column}"))
              record.update_without_callbacks
            end

            log_scramble_info('order', column)
          end

          def scramble_letters!(column)
            list = find(:all)
            list.each do |record|
              record.scramble_letters(column)
              record.update_without_callbacks
            end

            log_scramble_info('letters', column)
          end

          def scramble_numbers!(column)
            list = find(:all)
            list.each do |record|
              record.scramble_numbers(column)
              record.update_without_callbacks
            end

            log_scramble_info('numbers', column)
          end

        private
          def action_methods(actions)
            actions = [actions] unless Array === actions
            actions.map { |action| "scramble_#{action}!" }.map(&:to_sym)
          end

          def log_scramble_info(method, column)
            logger.info("#{self.name}: Scrambled #{method} for column '#{column}'")
          end
      end

      module InstanceMethods
        def scramble_letters(column)
          value = self.send("#{column}")
          return false unless value

          self.send("#{column}=", Scrambler.scramble_letters(self.send("#{column}")))
        end

        def scramble_numbers(column)
          value = self.send("#{column}")
          return false unless value

          self.send("#{column}=", Scrambler.scramble_numbers(self.send("#{column}")))
        end
      end

    end
  end
end


text:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.core.utils import ChromeType

def get_test_driver():
    return webdriver.Chrome(
        service=Service(
            ChromeDriverManager(chrome_type=ChromeType.GOOGLE).install()
        )
    )


text:
<!-- NOTE
Please be aware that the Selenium Grid 3.x is being deprecated in favour of the
upcoming version 4.x. We won't be receiving any PRs related to the Grid 3.x code. Thanks!
-->

- [ ] By placing an `X` in the preceding checkbox, I verify that I have signed the [Contributor License Agreement](https://github.com/SeleniumHQ/selenium/blob/master/CONTRIBUTING.md#step-6-sign-the-cla)


text:
/**
 */
package at.fhj.gaar.androidapp.appDsl;

/**
 *
 * A representation of the model object 'Element Enabled Attribute'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute#isEnabled Enabled}

 *

 *

 *
 * @see at.fhj.gaar.androidapp.appDsl.AppDslPackage#getElementEnabledAttribute()
 * @model
 * @generated
 */
public interface ElementEnabledAttribute extends ActivityAttribute, BroadcastReceiverAttribute, ServiceAttribute
{
  /**
   * Returns the value of the 'Enabled' attribute.
   *
   *

   * If the meaning of the 'Enabled' attribute isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Enabled' attribute.
   * @see #setEnabled(boolean)
   * @see at.fhj.gaar.androidapp.appDsl.AppDslPackage#getElementEnabledAttribute_Enabled()
   * @model
   * @generated
   */
  boolean isEnabled();

  /**
   * Sets the value of the '{@link at.fhj.gaar.androidapp.appDsl.ElementEnabledAttribute#isEnabled Enabled}' attribute.
   *
   *
   * @param value the new value of the 'Enabled' attribute.
   * @see #isEnabled()
   * @generated
   */
  void setEnabled(boolean value);

} // ElementEnabledAttribute


text:
<?php

/**
 * Short description for class.
 *
 * @package		ratings
 * @subpackage	config.schema
 */
class RatingsSchema extends CakeSchema {

/**
 * Schema name
 *
 * @var string
 * @access public
 */
	public $name = 'Ratings';

/**
 * Before callback
 *
 * @return boolean
 * @access public
 */
	public function before($event = array()) {
		return true;
	}

/**
 * After callback
 *
 * @return void
 * @access public
 */
	public function after($event = array()) {

	}

/**
 * Schema for ratings table
 *
 * @var array
 * @access public
 */
	public $ratings = array(
		'id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36, 'key' => 'primary'),
		'parent_id' => array('type' => 'string', 'null' => true, 'default' => NULL, 'length' => 36, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'lft' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
		'rght' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
		'user_id' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36),
		'foreign_key' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 36),
		'model' => array('type' => 'string', 'null' => false, 'default' => NULL, 'key' => 'index'),
		'value' => array('type' => 'float', 'null' => true, 'default' => '0', 'length' => '8,4'),
		'type' => array('type' => 'string', 'null' => false, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'title' => array('type' => 'string', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'review' => array('type' => 'text', 'null' => true, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'count' => array('type' => 'integer', 'null' => true, 'default' => NULL, 'length' => 10),
		'data' => array('type' => 'text', 'null' => false, 'default' => NULL, 'collate' => 'utf8_general_ci', 'charset' => 'utf8'),
		'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
		'modified' => array('type' => 'datetime', 'null' => true, 'default' => NULL),
		'indexes' => array(
			'PRIMARY' => array('column' => 'id', 'unique' => 1),
			'UNIQUE_RATING' => array('column' => array('user_id', 'foreign_key', 'model'), 'unique' => 0)
		)
	);

}


text:
<?php

class BWP_GXS_MODULE_TAXONOMY extends BWP_GXS_MODULE
{
	public function __construct()
	{
		// @since 1.3.0 use ::set_sort_column to set the appropriate column to
		// sort data by
		$this->set_sort_column('lastmod');
	}

	protected function generate_data()
	{
		global $wpdb, $bwp_gxs;

		$requested = $this->requested;

		// @since 1.3.0 do not fetch posts that are password-protected
		$latest_post_query = '
			SELECT
				MAX(p.post_modified) as post_modified,
				MAX(p.post_modified_gmt) as post_modified_gmt,
				MAX(p.comment_count) as comment_count,
				tt.term_id
			FROM ' . $wpdb->term_relationships . ' tr
			INNER JOIN ' . $wpdb->posts . ' p
				ON tr.object_id = p.ID
			INNER JOIN ' . $wpdb->term_taxonomy . ' tt
				ON tr.term_taxonomy_id = tt.term_taxonomy_id' . "
			WHERE p.post_status = 'publish'
				AND p.post_password = ''" . '
				AND tt.taxonomy = %s
				AND tt.count > 0
			GROUP BY tt.term_id
			ORDER BY tt.term_id DESC';

		$latest_posts = $this->get_results($wpdb->prepare($latest_post_query, $requested));

		if (!isset($latest_posts) || 0 == sizeof($latest_posts))
			return false;

		/**
		 * Filter terms that are added to a taxonomy-based sitemaps.
		 *
		 * @example hooks/filter_bwp_gxs_excluded_terms.php 2
		 *
		 * @param array $term_ids  Term IDs to exclude.
		 * @param string $taxonomy The current taxonomy. See
		 * http://codex.wordpress.org/Function_Reference/register_taxonomy for
		 * more info.
		 *
		 * @since 1.3.0
		 */
		$excluded_term_ids = apply_filters('bwp_gxs_excluded_terms', array(), $requested);

		$excluded_term_ids_sql = count($excluded_term_ids) > 0
			? ' AND t.term_id NOT IN (' . implode(',', array_map('intval', $excluded_term_ids)) . ') ' : '';

		// @deprecated 1.3.0, use `bwp_gxs_excluded_term_slugs` instead
		$excluded_terms = apply_filters('bwp_gxs_term_exclude', array(), $requested);

		/**
		 * Filter terms that are added to a taxonomy-based sitemaps using their slugs.
		 *
		 * @example hooks/filter_bwp_gxs_excluded_term_slugs.php 2
		 *
		 * @param array $term_slugs Term slugs to exclude, e.g. 'tag1', 'category-2' etc.
		 * @param string $taxonomy The current taxonomy.
		 *
		 * @since 1.4.0
		 */
		$excluded_term_slugs = apply_filters('bwp_gxs_excluded_term_slugs', $excluded_terms, $requested);
		$excluded_term_slugs_placeholders = array_fill(0, count($excluded_term_slugs), '%s');

		$excluded_term_slugs_sql = count($excluded_term_slugs) > 0
			? ' AND t.slug NOT IN (' . implode(',', $excluded_term_slugs_placeholders) . ') ' : '';

		$excluded_term_slugs_sql = !empty($excluded_term_slugs_sql)
			? $wpdb->prepare($excluded_term_slugs_sql, $excluded_term_slugs) : '';

		$term_query = '
			SELECT t.*, tt.*
			FROM ' . $wpdb->terms  . ' as t
			INNER JOIN ' . $wpdb->term_taxonomy . ' as tt
				ON t.term_id = tt.term_id
			WHERE tt.taxonomy = %s
				AND tt.count > 0 '
				. $excluded_term_ids_sql
				. $excluded_term_slugs_sql . '
			ORDER BY t.term_id DESC';

		$terms = $this->get_results($wpdb->prepare($term_query, $requested));

		if (!isset($terms) || 0 == sizeof($terms))
			return false;

		// build an array with term_id as key
		$term2post = array();

		for ($i = 0; $i < sizeof($latest_posts); $i++)
		{
			$post = $latest_posts[$i];

			if (!empty($post->term_id) && !isset($term2post[$post->term_id]))
				$term2post[$post->term_id] = $post;

			unset($post);
		}

		$data = array();

		for ($i = 0; $i < sizeof($terms); $i++)
		{
			$term = $terms[$i];

			$data = $this->init_data($data);

			$data['location'] = $this->get_term_link($term, $requested);

			if (isset($term2post[$term->term_id]))
			{
				// this term has at least one post
				$post = $term2post[$term->term_id];

				$data['lastmod']  = $this->get_lastmod($post);
				$data['freq']     = $this->cal_frequency($post);
				$data['priority'] = $this->cal_priority($post, $data['freq']);
			}
			else
			{
				// this term does not have any post, no lastmod can be generated
				$data['freq']     = $this->cal_frequency();
				$data['priority'] = $this->cal_priority(false, $data['freq']);
			}

			$this->data[] = $data;

			unset($post);
			unset($term);
		}

		unset($latest_posts);
		unset($term2post);
		unset($terms);

		return true;
	}
}


text:
<?php

/**
 * @covers puzzle_post_PostFile
 */
class puzzle_test_post_PostFileTest extends PHPUnit_Framework_TestCase
{
    public function testCreatesFromString()
    {
        $p = new puzzle_post_PostFile('foo', 'hi', '/path/to/test.php');
        $this->assertInstanceOf('puzzle_post_PostFileInterface', $p);
        $this->assertEquals('hi', $p->getContent());
        $this->assertEquals('foo', $p->getName());
        $this->assertEquals('/path/to/test.php', $p->getFilename());
        $headers = $p->getHeaders();
        $this->assertEquals(
            'form-data; name="foo"; filename="test.php"',
            $headers['Content-Disposition']
        );
    }

    public function testGetsFilenameFromMetadata()
    {
        $p = new puzzle_post_PostFile('foo', fopen(__FILE__, 'r'));
        $this->assertEquals(__FILE__, $p->getFilename());
    }

    public function testDefaultsToNameWhenNoFilenameExists()
    {
        $p = new puzzle_post_PostFile('foo', 'bar');
        $this->assertEquals('foo', $p->getFilename());
    }

    public function testCreatesFromMultipartFormData()
    {
        $mp = $this->getMockBuilder('puzzle_post_MultipartBody')
            ->setMethods(array('getBoundary'))
            ->disableOriginalConstructor()
            ->getMock();
        $mp->expects($this->once())
            ->method('getBoundary')
            ->will($this->returnValue('baz'));

        $p = new puzzle_post_PostFile('foo', $mp);
        $headers = $p->getHeaders();
        $this->assertEquals(
            'form-data; name="foo"',
            $headers['Content-Disposition']
        );
        $this->assertEquals(
            'multipart/form-data; boundary=baz',
            $headers['Content-Type']
        );
    }

    public function testCanAddHeaders()
    {
        $p = new puzzle_post_PostFile('foo', puzzle_stream_Stream::factory('hi'), 'test.php', array(
            'X-Foo' => '123',
            'Content-Disposition' => 'bar'
        ));
        $headers = $p->getHeaders();
        $this->assertEquals('bar', $headers['Content-Disposition']);
        $this->assertEquals('123', $headers['X-Foo']);
    }
}


text:
using SSW.DataOnion.Interfaces;

namespace SSW.DataOnion.Core
{
    public class RepositoryLocator : IRepositoryLocator
    {
        private readonly IRepositoryResolver resolver;

        public RepositoryLocator(IRepositoryResolver resolver)
        {
            this.resolver = resolver;
        }

        public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
        {
            return this.resolver.Resolve<TEntity>();
        }
    }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once
#include "BehaviorTree/BTTaskNode.h"
#include "Components/SkeletalMeshComponent.h"
#include "BTTask_PlayAnimation.generated.h"

class UAnimationAsset;

/**
 *	Play indicated AnimationAsset on Pawn controlled by BT
 *	Note that this node is generic and is handing multiple special cases,
 *	If you want a more efficient solution you'll need to implement it yourself (or wait for our BTTask_PlayCharacterAnimation)
 */
UCLASS()
class AIMODULE_API UBTTask_PlayAnimation : public UBTTaskNode
{
	GENERATED_UCLASS_BODY()

	/** Animation asset to play. Note that it needs to match the skeleton of pawn this BT is controlling */
	UPROPERTY(Category = Node, EditAnywhere)
	UAnimationAsset* AnimationToPlay;

	UPROPERTY(Category = Node, EditAnywhere)
	uint32 bLooping : 1;

	/** if true the task will just trigger the animation and instantly finish. Fire and Forget. */
	UPROPERTY(Category = Node, EditAnywhere)
	uint32 bNonBlocking : 1;

	UPROPERTY()
	UBehaviorTreeComponent* MyOwnerComp;

	UPROPERTY()
	USkeletalMeshComponent* CachedSkelMesh;

	EAnimationMode::Type PreviousAnimationMode;

	FTimerDelegate TimerDelegate;
	FTimerHandle TimerHandle;

	virtual EBTNodeResult::Type ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
	virtual EBTNodeResult::Type AbortTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory) override;
	virtual FString GetStaticDescription() const override;

	void OnAnimationTimerDone();

#if WITH_EDITOR
	virtual FName GetNodeIconName() const override;
#endif // WITH_EDITOR

protected:
	void CleanUp(UBehaviorTreeComponent& OwnerComp);
};


text:
class StorePrice < ActiveRecord::Base
  belongs_to :store
  has_many :variants
end


text:
using System.Text;
using Newtonsoft.Json;

namespace Shard
{
    /// <summary>
    /// Static class to serialize and deserialize objects
    /// </summary>
    public static class SerializationHelper
    {
        /// <summary>
        /// Serializes the specified object into a byte array.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <returns></returns>
        public static byte[] Serialize(object o)
        {
            var data = JsonConvert.SerializeObject(o);
            return Encoding.UTF8.GetBytes(data);
        }

        /// <summary>
        /// Deserializes the specified bytes back into the specified type.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes">The bytes.</param>
        /// <returns></returns>
        public static T Deserialize<T>(byte[] bytes)
        {
            var str = Encoding.UTF8.GetString(bytes);
            return JsonConvert.DeserializeObject<T>(str);
        }
    }
}


text:
const path = require("path")
const WebpackManifestPlugin = require("webpack-manifest-plugin")
const { HashedModuleIdsPlugin } = require("webpack")
const { getCSSManifest } = require("../utils/getCSSManifest")
const TerserPlugin = require("terser-webpack-plugin")

const {
  BUILD_SERVER,
  DEBUG,
  NODE_ENV,
  isProduction,
} = require("../../src/lib/environment")

const buildCSS = isProduction && !BUILD_SERVER

exports.productionConfig = {
  parallelism: 75,
  mode: DEBUG ? "development" : NODE_ENV,
  devtool: "source-map",
  output: {
    filename: "[name].[contenthash].js",
  },
  plugins: [
    new HashedModuleIdsPlugin(),
    new WebpackManifestPlugin({
      fileName: path.resolve(__dirname, "../../manifest.json"),
      basePath: "/assets/",
      seed: buildCSS ? getCSSManifest() : {},
    }),
  ],
  optimization: DEBUG
    ? {}
    : {
        minimizer: [
          new TerserPlugin({
            cache: false,
            parallel: false,
            sourceMap: true, // Must be set to true if using source-maps in production
          }),
        ],
      },
}


text:
import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise'; // http.get Observable no native toPromise conversion
import { Hero } from './hero';

@Component({
    moduleId: module.id,
    selector: 'my-testapi',
    // template: '
hello api.
',
    templateUrl: '../UI/dashboard.component.html',
    styleUrls: ['../UI/dashboard.component.css']
})

export class testApi implements OnInit {

    heroes: Hero[] = [];

    private myheroesUrl = 'api/myheroes'; // refactor for express API

    constructor(private http: Http){}

    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.myheroesUrl)
            .toPromise() // execute rxjs promise-converter
            // .then(response => console.log(response.json()))
            .then(response => response.json() as Hero[]) // native http resp
            .catch(this.handleError);
    }

    ngOnInit(): void {
        this.getHeroes()
            .then(heroesdata => {
                console.log(heroesdata);
                return this.heroes = heroesdata
            });
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occured', error);
        return Promise.reject(error.message || error);
    }
}


text:
package com.nesscomputing.exception;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Provider;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import com.google.inject.name.Names;

import com.nesscomputing.httpclient.guice.HttpClientModule;

/**
 * Add support for mapping NessApiException subclasses to and from HTTP responses.
 */
public final class NessApiExceptionModule extends AbstractModule
{
    private final Annotation httpClientAnnotation;

    public NessApiExceptionModule(final String httpClientName)
    {
        this(Names.named(httpClientName));
    }

    public NessApiExceptionModule(final Annotation httpClientAnnotation)
    {
        this.httpClientAnnotation = Preconditions.checkNotNull(httpClientAnnotation, "null binding annotation");
    }

    @Override
    protected void configure()
    {
        install(new SharedNessApiExceptionModule());

        HttpClientModule.bindNewObserver(binder(), httpClientAnnotation).to(Key.get(ExceptionObserver.class, httpClientAnnotation));
        bind(ExceptionObserver.class).annotatedWith(httpClientAnnotation).toProvider(new ExceptionObserverProvider()).in(Scopes.SINGLETON);

        // Constructing the binder creates the MapBinder, so we don't have undeclared dependencies
        // even if there end up being no bindings, just an empty map.
        NessApiExceptionBinder.of(binder(), httpClientAnnotation);
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + (httpClientAnnotation == null ? 0 : httpClientAnnotation.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj)
    {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final NessApiExceptionModule other = (NessApiExceptionModule) obj;
        if (httpClientAnnotation == null) {
            if (other.httpClientAnnotation != null) {
                return false;
            }
        }
        else if (!httpClientAnnotation.equals(other.httpClientAnnotation)) {
            return false;
        }
        return true;
    }

    class ExceptionObserverProvider implements Provider<ExceptionObserver>
    {
        private Injector injector;

        @Inject
        void setInjector(final Injector injector)
        {
            this.injector = injector;
        }

        @Override
        public ExceptionObserver get()
        {
            final TypeLiteral<Map<String, Set<ExceptionReviver>>> type = new TypeLiteral<Map<String, Set<ExceptionReviver>>>() {};
            final Key<Map<String, Set<ExceptionReviver>>> mapBindingKey = Key.get(type, httpClientAnnotation);

            final ObjectMapper mapper = injector.getInstance(ObjectMapper.class);
            final Map<String, Set<ExceptionReviver>> revivers = injector.getInstance(mapBindingKey);

            return new ExceptionObserver(mapper, revivers);
        }
    }

    /**
     * Bindings that are shared by every NessApiExceptionModule.
     */
    static final class SharedNessApiExceptionModule extends AbstractModule
    {
        @Override
        protected void configure()
        {
            bind(ResponseMapper.class);
        }

        @Override
        public int hashCode()
        {
            return SharedNessApiExceptionModule.class.hashCode();
        }

        @Override
        public boolean equals(final Object obj)
        {
            return obj instanceof SharedNessApiExceptionModule;
        }
    }
}


text:
using System;
using ModestTree;
using System.Linq;

namespace Zenject
{
    public class FactorySubContainerBinder<TParam1, TParam2, TParam3, TParam4, TParam5, TContract>
        : FactorySubContainerBinderWithParams<TContract>
    {
        public FactorySubContainerBinder(
            BindInfo bindInfo, Type factoryType,
            BindFinalizerWrapper finalizerWrapper, object subIdentifier)
            : base(bindInfo, factoryType, finalizerWrapper, subIdentifier)
        {
        }

        public ConditionBinder ByMethod(ModestTree.Util.Action<DiContainer, TParam1, TParam2, TParam3, TParam4, TParam5> installerMethod)
        {
            SubFinalizer = CreateFinalizer(
                (container) => new SubContainerDependencyProvider(
                    ContractType, SubIdentifier,
                    new SubContainerCreatorByMethod<TParam1, TParam2, TParam3, TParam4, TParam5>(
                        container, installerMethod)));

            return new ConditionBinder(BindInfo);
        }
    }
}


text:
All notable changes to this project will be documented in this file.
`Starscream` adheres to [Semantic Versioning](http://semver.org/).

#### [1.0.2](https://github.com/daltoniam/Starscream/tree/1.0.2)

Added TVOS support.

#### [1.0.1](https://github.com/daltoniam/Starscream/tree/1.0.1)

Fixes for #121, #123

#### [1.0.0](https://github.com/daltoniam/Starscream/tree/1.0.0)

first release of Swift 2 support.


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

[name]

		This class stores data for an attribute (such as vertex positions, face indices, normals,
		colors, UVs, and any custom attributes ) associated with a [page:BufferGeometry], which allows
		for more efficient passing of data to the GPU. See that page for details and a usage example.

		Data is stored as vectors of any length (defined by [page:BufferAttribute.itemSize itemSize]),
		and in general in the methods outlined below if passing in an index, this is automatically
		multiplied by the vector length.

Constructor

[name]( [page:TypedArray array], [page:Integer itemSize], [page:Boolean normalized] )

		[page:TypedArray array] -- Must be a [link:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/TypedArray TypedArray].
		Used to instantiate the buffer.

		This array should have
	 	itemSize * numVertices
		elements, where numVertices is the number of vertices in the associated [page:BufferGeometry BufferGeometry].

		[page:Integer itemSize] --  the number of values of the array that should be associated with
		a particular vertex. For instance, if this
		attribute is storing a 3-component vector (such as a position, normal, or color), then itemSize should be 3.

		[page:Boolean normalized] -- (optional) Indicates how the underlying data in the buffer maps
		to the values in the GLSL code. For instance, if [page:TypedArray array] is an instance of
		UInt16Array, and [page:Boolean normalized] is true, the values 0 - +65535 in the array
		 data will be mapped to 0.0f - +1.0f in the GLSL attribute. An Int16Array (signed) would map
		 from -32767 - +32767  to -1.0f - +1.0f. If [page:Boolean normalized] is false, the values
		 will be converted to floats which contain the exact value, i.e. 32767 becomes 32767.0f.

Properties

[property:TypedArray array]

		The [page:TypedArray array] holding data stored in the buffer.

[property:Integer count]

		Stores the [page:BufferAttribute.array array]'s length divided by the [page:BufferAttribute.itemSize itemSize].

		If the buffer is storing a 3-component vector (such as a position, normal, or color),
		then this will count the number of such vectors stored.

[property:Boolean dynamic]

			Whether the buffer is dynamic or not. Default is *false*.

			If false, the GPU is informed that contents of the buffer are likely to be used often and not change often.
			This corresponds to the  [link:https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData gl.STATIC_DRAW] flag.

			if true, the GPU is informed that contents of the buffer are likely to be used often and change often.
			This corresponds to the  [link:https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData gl.DYNAMIC_DRAW] flag.

[property:Boolean isBufferAttribute]

			Used to check whether this or derived classes are BufferAttributes. Default is *true*.

			You should not change this, as it used internally for optimisation.

[property:Integer itemSize]

The length of vectors that are being stored in the [page:BufferAttribute.array array].

[property:String name]

		Optional name for this attribute instance. Default is an empty string.

[property:Boolean needsUpdate]

		Flag to indicate that this attribute has changed and should be re-sent to the GPU.
		Set this to true when you modify the value of the array.

		Setting this to true also increments the [page:BufferAttribute.version version].

[property:Boolean normalized]

		Indicates how the underlying data in the buffer maps to the values in the GLSL shader code.
		See the constructor above for details.

[property:Function onUploadCallback]

		A callback function that is executed after the Renderer has transfered the attribute array data to the GPU.

[property:Object updateRange]

Object containing:

			[page:Integer offset]: Default is *0*. Position at whcih to start update.

			[page:Integer count]: Default is *-1*, which means don't use update ranges.

			This can be used to only update some components of stored vectors (for example, just the component
			related to color).

[property:String uuid]

		[link:http://en.wikipedia.org/wiki/Universally_unique_identifier UUID] of this object instance.
		This gets automatically assigned and this shouldn't be edited.

[property:Integer version]

A version number, incremented every time the [page:BufferAttribute.needsUpdate needsUpdate] property is set to true.

Methods

[method:BufferAttribute clone]()

Return a copy of this bufferAttribute.

[method:BufferAttribute copyArray]( array )

Copy the array given here (which can be a normal array or TypedArray) into
			[page:BufferAttribute.array array].

			See [link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set TypedArray.set]
			for notes on requirements if copying a TypedArray.

[method:null copyAt] ( [page:Integer index1], [page:BufferAttribute bufferAttribute], [page:Integer index2] )

Copy a vector from bufferAttribute[index2] to [page:BufferAttribute.array array][index1].

[method:BufferAttribute copyColorsArray]( colors )

Copy an array representing RGB color values into [page:BufferAttribute.array array].

[method:BufferAttribute copyIndicesArray]( indices )

Copy an array representing [page:Face3] indices into [page:BufferAttribute.array array].

[method:BufferAttribute copyVector2sArray]( vectors )

Copy an array representing [page:Vector2]s into [page:BufferAttribute.array array].

[method:BufferAttribute copyVector3sArray]( vectors )

Copy an array representing [page:Vector3]s into [page:BufferAttribute.array array].

[method:BufferAttribute copyVector4sArray]( vectors )

Copy an array representing [page:Vector4]s into [page:BufferAttribute.array array].

[method:Number getX]( index )

Returns the x component of the vector at the given index.

[method:Number getY]( index )

Returns the y component of the vector at the given index.

[method:Number getZ]( index )

Returns the z component of the vector at the given index.

[method:Number getW]( index )

Returns the w component of the vector at the given index.

[method:null onUpload]( [page:Function callback] )

		Sets the value of the onUploadCallback property.

		In the [example:webgl_buffergeometry WebGL / Buffergeometry] this is used to free memory
		after the buffer has been	transfered to the GPU.

[method:null set] ( [page:Array value], [page:Integer offset] )

		value -- an [page:Array] or [page:TypedArray] from which to copy values.

		offset -- (optional) index of the [page:BufferAttribute.array array] at which to start copying.

		Calls	[link:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set TypedArray.set]( [page:Array value], [page:Integer offset] )
		on the [page:BufferAttribute.array array].

		In particular, see that page for requirements on [page:Array value]
		being a [page:TypedArray].

[method:null setArray] ( [page:TypedArray array] )

		[page:BufferAttribute.array array] to the TypedArray passed in here.

		After setting the array, [page:BufferAttribute.needsUpdate needsUpdate] should be set to true.

[method:BufferAttribute setDynamic] ( [page:Boolean value] )

Set [page:BufferAttribute.dynamic dynamic] to value.

[method:null setX]( index, x )

Sets the x component of the vector at the given index.

[method:null setY]( index, y )

Sets the y component of the vector at the given index.

[method:null setZ]( index, z )

Sets the z component of the vector at the given index.

[method:null setW]( index, w )

Sets the w component of the vector at the given index.

[method:null setXY]( index, x, y )

Sets the x and y components of the vector at the given index.

[method:null setXYZ]( index, x, y, z )

Sets the x, y and z components of the vector at the given index.

[method:null setXYZW]( index, x, y, z, w )

Sets the x, y, z and w components of the vector at the given index.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
published: false
---
## Creating a User backend with node

Objectives

- TESTS! I'm a fan of TDD and will show you how to use it in this process
- create users and securly save them in a database
- verify passwords
- link metadata to the user

**Links**
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://semaphoreci.com/community/tutorials/a-tdd-approach-to-building-a-todo-api-using-node-js-and-mongodb
http://mongoosejs.com/docs/index.html
http://blog.slatepeak.com/refactoring-a-basic-authenticated-api-with-node-express-and-mongo/
http://stackoverflow.com/questions/28514790/how-to-set-limit-for-array-size-in-mongoose-schema/29418656


text:
package org.red5.server.stream;

import java.io.IOException;
import java.util.LinkedList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.red5.logging.Red5LoggerFactory;
import org.red5.server.api.IConnection;
import org.red5.server.api.IContext;
import org.red5.server.api.Red5;
import org.red5.server.api.scheduling.IScheduledJob;
import org.red5.server.api.scheduling.ISchedulingService;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.statistics.IPlaylistSubscriberStreamStatistics;
import org.red5.server.api.stream.IPlayItem;
import org.red5.server.api.stream.IPlaylistController;
import org.red5.server.api.stream.IPlaylistSubscriberStream;
import org.red5.server.api.stream.IStreamAwareScopeHandler;
import org.red5.server.api.stream.OperationNotSupportedException;
import org.red5.server.api.stream.StreamState;
import org.slf4j.Logger;

/**
 * Stream of playlist subscriber
 */
public class PlaylistSubscriberStream extends AbstractClientStream implements IPlaylistSubscriberStream, IPlaylistSubscriberStreamStatistics {

    private static final Logger log = Red5LoggerFactory.getLogger(PlaylistSubscriberStream.class);

    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private final Lock read = readWriteLock.readLock();

    private final Lock write = readWriteLock.writeLock();

    /**
     * Playlist controller
     */
    private IPlaylistController controller;

    /**
     * Default playlist controller
     */
    private IPlaylistController defaultController;

    /**
     * Playlist items
     */
    private final LinkedList<IPlayItem> items;

    /**
     * Current item index
     */
    private int currentItemIndex = 0;

    /**
     * Plays items back
     */
    protected PlayEngine engine;

    /**
     * Rewind mode state
     */
    protected boolean rewind;

    /**
     * Random mode state
     */
    protected boolean random;

    /**
     * Repeat mode state
     */
    protected boolean repeat;

    /**
     * Service used to provide notifications, keep client buffer filled, clean up, etc...
     */
    protected ISchedulingService schedulingService;

    /**
     * Scheduled job names
     */
    protected CopyOnWriteArraySet<String> jobs = new CopyOnWriteArraySet<String>();

    /**
     * Interval in ms to check for buffer underruns in VOD streams.
     */
    protected int bufferCheckInterval = 0;

    /**
     * Number of pending messages at which a
     *
     *

     * NetStream.Play.InsufficientBW
     *

     *
     * message is generated for VOD streams.
     */
    protected int underrunTrigger = 10;

    /**
     * Timestamp this stream was created.
     */
    protected long creationTime = System.currentTimeMillis();

    /**
     * Number of bytes sent.
     */
    protected long bytesSent = 0;

    /**
     * see PlayEngine.maxPendingVideoFrames
     */
    private int maxPendingVideoFrames = 10;

    /**
     * see PlayEngine.maxSequentialPendingVideoFrames
     */
    private int maxSequentialPendingVideoFrames = 10;

    /** Constructs a new PlaylistSubscriberStream. */
    public PlaylistSubscriberStream() {
        defaultController = new SimplePlaylistController();
        items = new LinkedList<IPlayItem>();
    }

    /**
     * Creates a play engine based on current services (scheduling service, consumer service, and provider service). This method is useful
     * during unit testing.
     */
    PlayEngine createEngine(ISchedulingService schedulingService, IConsumerService consumerService, IProviderService providerService) {
        engine = new PlayEngine.Builder(this, schedulingService, consumerService, providerService).build();
        // set the max pending video frames to the play engine
        engine.setMaxPendingVideoFrames(maxPendingVideoFrames);
        // set the max sequential pending video frames to the play engine
        engine.setMaxSequentialPendingVideoFrames(maxSequentialPendingVideoFrames);
        return engine;
    }

    /**
     * Set interval to check for buffer underruns. Set to 0 to disable.
     *
     * @param bufferCheckInterval
     *            interval in ms
     */
    public void setBufferCheckInterval(int bufferCheckInterval) {
        this.bufferCheckInterval = bufferCheckInterval;
    }

    /**
     * Set maximum number of pending messages at which a
     *
     *

     * NetStream.Play.InsufficientBW
     *

     *
     * message will be generated for VOD streams
     *
     * @param underrunTrigger
     *            the maximum number of pending messages
     */
    public void setUnderrunTrigger(int underrunTrigger) {
        this.underrunTrigger = underrunTrigger;
    }

    /** {@inheritDoc} */
    public void start() {
        //ensure the play engine exists
        if (engine == null) {
            IScope scope = getScope();
            if (scope != null) {
                IContext ctx = scope.getContext();
                if (ctx.hasBean(ISchedulingService.BEAN_NAME)) {
                    schedulingService = (ISchedulingService) ctx.getBean(ISchedulingService.BEAN_NAME);
                } else {
                    //try the parent
                    schedulingService = (ISchedulingService) scope.getParent().getContext().getBean(ISchedulingService.BEAN_NAME);
                }
                IConsumerService consumerService = null;
                if (ctx.hasBean(IConsumerService.KEY)) {
                    consumerService = (IConsumerService) ctx.getBean(IConsumerService.KEY);
                } else {
                    //try the parent
                    consumerService = (IConsumerService) scope.getParent().getContext().getBean(IConsumerService.KEY);
                }
                IProviderService providerService = null;
                if (ctx.hasBean(IProviderService.BEAN_NAME)) {
                    providerService = (IProviderService) ctx.getBean(IProviderService.BEAN_NAME);
                } else {
                    //try the parent
                    providerService = (IProviderService) scope.getParent().getContext().getBean(IProviderService.BEAN_NAME);
                }
                engine = new PlayEngine.Builder(this, schedulingService, consumerService, providerService).build();
            } else {
                throw new IllegalStateException("Scope was null on start playing");
            }
        }
        //set buffer check interval
        engine.setBufferCheckInterval(bufferCheckInterval);
        //set underrun trigger
        engine.setUnderrunTrigger(underrunTrigger);
        // set the max pending video frames to the play engine
        engine.setMaxPendingVideoFrames(maxPendingVideoFrames);
        // set the max sequential pending video frames to the play engine
        engine.setMaxSequentialPendingVideoFrames(maxSequentialPendingVideoFrames);
        // Start playback engine
        engine.start();
        // Notify subscribers on start
        onChange(StreamState.STARTED);
    }

    /** {@inheritDoc} */
    public void play() throws IOException {
        // Check how many is yet to play...
        int count = items.size();
        // Return if playlist is empty
        if (count > 0) {
            // Move to next if current item is set to -1
            if (currentItemIndex == -1) {
                moveToNext();
            }
            // If there's some more items on list then play current item
            while (count-- > 0) {
                IPlayItem item = null;
                read.lock();
                try {
                    // Get playlist item
                    item = items.get(currentItemIndex);
                    engine.play(item);
                    break;
                } catch (StreamNotFoundException e) {
                    // go for next item
                    moveToNext();
                    if (currentItemIndex == -1) {
                        // we reaches the end.
                        break;
                    }
                    item = items.get(currentItemIndex);
                } catch (IllegalStateException e) {
                    // an stream is already playing
                    break;
                } finally {
                    read.unlock();
                }
            }
        }
    }

    /** {@inheritDoc} */
    public void pause(int position) {
        try {
            engine.pause(position);
        } catch (IllegalStateException e) {
            log.debug("pause caught an IllegalStateException");
        }
    }

    /** {@inheritDoc} */
    public void resume(int position) {
        try {
            engine.resume(position);
        } catch (IllegalStateException e) {
            log.debug("resume caught an IllegalStateException");
        }
    }

    /** {@inheritDoc} */
    public void stop() {
        if (log.isDebugEnabled()) {
            log.debug("stop");
        }
        try {
            engine.stop();
        } catch (IllegalStateException e) {
            if (log.isTraceEnabled()) {
                log.warn("stop caught an IllegalStateException", e);
            } else if (log.isDebugEnabled()) {
                log.debug("stop caught an IllegalStateException");
            }
        }
    }

    /** {@inheritDoc} */
    public void seek(int position) throws OperationNotSupportedException {
        try {
            engine.seek(position);
        } catch (IllegalStateException e) {
            log.debug("seek caught an IllegalStateException");
        }
    }

    /** {@inheritDoc} */
    public void close() {
        if (log.isDebugEnabled()) {
            log.debug("close");
        }
        if (engine != null) {
            // before or on close we may need to allow the queued messages a chance to clear
            engine.close();
            onChange(StreamState.CLOSED);
            items.clear();
            // clear jobs
            if (schedulingService != null && !jobs.isEmpty()) {
                for (String jobName : jobs) {
                    schedulingService.removeScheduledJob(jobName);
                }
                jobs.clear();
            }
        }
    }

    /** {@inheritDoc} */
    public boolean isPaused() {
        return state.get() == StreamState.PAUSED;
    }

    /** {@inheritDoc} */
    public void addItem(IPlayItem item) {
        write.lock();
        try {
            items.add(item);
        } finally {
            write.unlock();
        }
    }

    /** {@inheritDoc} */
    public void addItem(IPlayItem item, int index) {
        write.lock();
        try {
            items.add(index, item);
        } finally {
            write.unlock();
        }
    }

    /** {@inheritDoc} */
    public void removeItem(int index) {
        if (index < 0 || index >= items.size()) {
            return;
        }
        int originSize = items.size();
        write.lock();
        try {
            items.remove(index);
        } finally {
            write.unlock();
        }
        if (currentItemIndex == index) {
            // set the next item.
            if (index == originSize - 1) {
                currentItemIndex = index - 1;
            }
        }
    }

    /** {@inheritDoc} */
    public void removeAllItems() {
        // we try to stop the engine first
        stop();
        write.lock();
        try {
            items.clear();
        } finally {
            write.unlock();
        }
    }

    /** {@inheritDoc} */
    public void previousItem() {
        stop();
        moveToPrevious();
        if (currentItemIndex == -1) {
            return;
        }
        IPlayItem item = null;
        int count = items.size();
        while (count-- > 0) {
            read.lock();
            try {
                item = items.get(currentItemIndex);
                engine.play(item);
                break;
            } catch (IOException err) {
                log.error("Error while starting to play item, moving to previous.", err);
                // go for next item
                moveToPrevious();
                if (currentItemIndex == -1) {
                    // we reaches the end.
                    break;
                }
            } catch (StreamNotFoundException e) {
                // go for next item
                moveToPrevious();
                if (currentItemIndex == -1) {
                    // we reaches the end.
                    break;
                }
            } catch (IllegalStateException e) {
                // an stream is already playing
                break;
            } finally {
                read.unlock();
            }
        }
    }

    /** {@inheritDoc} */
    public boolean hasMoreItems() {
        int nextItem = currentItemIndex + 1;
        if (nextItem >= items.size() && !repeat) {
            return false;
        } else {
            return true;
        }
    }

    /** {@inheritDoc} */
    public void nextItem() {
        moveToNext();
        if (currentItemIndex == -1) {
            return;
        }
        IPlayItem item = null;
        int count = items.size();
        while (count-- > 0) {
            read.lock();
            try {
                item = items.get(currentItemIndex);
                engine.play(item, false);
                break;
            } catch (IOException err) {
                log.error("Error while starting to play item, moving to next", err);
                // go for next item
                moveToNext();
                if (currentItemIndex == -1) {
                    // we reaches the end.
                    break;
                }
            } catch (StreamNotFoundException e) {
                // go for next item
                moveToNext();
                if (currentItemIndex == -1) {
                    // we reaches the end.
                    break;
                }
            } catch (IllegalStateException e) {
                // an stream is already playing
                break;
            } finally {
                read.unlock();
            }
        }
    }

    /** {@inheritDoc} */
    public void setItem(int index) {
        if (index < 0 || index >= items.size()) {
            return;
        }
        stop();
        currentItemIndex = index;
        read.lock();
        try {
            IPlayItem item = items.get(currentItemIndex);
            engine.play(item);
        } catch (IOException e) {
            log.error("setItem caught a IOException", e);
        } catch (StreamNotFoundException e) {
            // let the engine retain the STOPPED state
            // and wait for control from outside
            log.debug("setItem caught a StreamNotFoundException");
        } catch (IllegalStateException e) {
            log.error("Illegal state exception on playlist item setup", e);
        } finally {
            read.unlock();
        }
    }

    /** {@inheritDoc} */
    public boolean isRandom() {
        return random;
    }

    /** {@inheritDoc} */
    public void setRandom(boolean random) {
        this.random = random;
    }

    /** {@inheritDoc} */
    public boolean isRewind() {
        return rewind;
    }

    /** {@inheritDoc} */
    public void setRewind(boolean rewind) {
        this.rewind = rewind;
    }

    /** {@inheritDoc} */
    public boolean isRepeat() {
        return repeat;
    }

    /** {@inheritDoc} */
    public void setRepeat(boolean repeat) {
        this.repeat = repeat;
    }

    /**
     * Seek to current position to restart playback with audio and/or video.
     */
    private void seekToCurrentPlayback() {
        if (engine.isPullMode()) {
            try {
                // TODO: figure out if this is the correct position to seek to
                final long delta = System.currentTimeMillis() - engine.getPlaybackStart();
                engine.seek((int) delta);
            } catch (OperationNotSupportedException err) {
                // Ignore error, should not happen for pullMode engines
            }
        }
    }

    /** {@inheritDoc} */
    public void receiveVideo(boolean receive) {
        if (engine != null) {
            boolean receiveVideo = engine.receiveVideo(receive);
            if (!receiveVideo && receive) {
                // video has been re-enabled
                seekToCurrentPlayback();
            }
        } else {
            log.debug("PlayEngine was null, receiveVideo cannot be modified");
        }
    }

    /** {@inheritDoc} */
    public void receiveAudio(boolean receive) {
        if (engine != null) {
            // check if engine currently receives audio, returns previous value
            boolean receiveAudio = engine.receiveAudio(receive);
            if (receiveAudio && !receive) {
                // send a blank audio packet to reset the player
                engine.sendBlankAudio(true);
            } else if (!receiveAudio && receive) {
                // do a seek
                seekToCurrentPlayback();
            }
        } else {
            log.debug("PlayEngine was null, receiveAudio cannot be modified");
        }
    }

    /** {@inheritDoc} */
    public void setPlaylistController(IPlaylistController controller) {
        this.controller = controller;
    }

    /** {@inheritDoc} */
    public int getItemSize() {
        return items.size();
    }

    /** {@inheritDoc} */
    public int getCurrentItemIndex() {
        return currentItemIndex;
    }

    /**
     * {@inheritDoc}
     */
    public IPlayItem getCurrentItem() {
        return getItem(getCurrentItemIndex());
    }

    /** {@inheritDoc} */
    public IPlayItem getItem(int index) {
        read.lock();
        try {
            return items.get(index);
        } catch (IndexOutOfBoundsException e) {
            return null;
        } finally {
            read.unlock();
        }
    }

    /** {@inheritDoc} */
    public boolean replace(IPlayItem oldItem, IPlayItem newItem) {
        boolean result = false;
        read.lock();
        try {
            int index = items.indexOf(oldItem);
            items.remove(index);
            items.set(index, newItem);
            result = true;
        } catch (Exception e) {

        } finally {
            read.unlock();
        }
        return result;
    }

    /**
     * Move the current item to the next in list.
     */
    private void moveToNext() {
        if (controller != null) {
            currentItemIndex = controller.nextItem(this, currentItemIndex);
        } else {
            currentItemIndex = defaultController.nextItem(this, currentItemIndex);
        }
    }

    /**
     * Move the current item to the previous in list.
     */
    private void moveToPrevious() {
        if (controller != null) {
            currentItemIndex = controller.previousItem(this, currentItemIndex);
        } else {
            currentItemIndex = defaultController.previousItem(this, currentItemIndex);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void onChange(final StreamState state, final Object... changed) {
        final IConnection conn = Red5.getConnectionLocal();
        IStreamAwareScopeHandler handler = getStreamAwareHandler();
        Notifier notifier = null;
        switch (state) {
            case SEEK:
                //notifies subscribers on seek
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            //make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            //get item being played
                            IPlayItem item = (IPlayItem) changed[0];
                            //seek position
                            int position = (Integer) changed[1];
                            try {
                                handler.streamPlayItemSeek(stream, item, position);
                            } catch (Throwable t) {
                                log.error("error notify streamPlayItemSeek", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case PAUSED:
                // set the paused state
                setState(StreamState.PAUSED);
                // notifies subscribers on pause
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            //make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            //get item being played
                            IPlayItem item = (IPlayItem) changed[0];
                            //playback position
                            int position = (Integer) changed[1];
                            try {
                                handler.streamPlayItemPause(stream, item, position);
                            } catch (Throwable t) {
                                log.error("error notify streamPlayItemPause", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case RESUMED:
                // resume playing
                setState(StreamState.PLAYING);
                // notifies subscribers on resume
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            // make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            // get item being played
                            IPlayItem item = (IPlayItem) changed[0];
                            // playback position
                            int position = (Integer) changed[1];
                            try {
                                handler.streamPlayItemResume(stream, item, position);
                            } catch (Throwable t) {
                                log.error("error notify streamPlayItemResume", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case PLAYING:
                // notifies subscribers on play
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            // make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            // get item being played
                            IPlayItem item = (IPlayItem) changed[0];
                            // is it a live broadcast
                            boolean isLive = (Boolean) changed[1];
                            try {
                                handler.streamPlayItemPlay(stream, item, isLive);
                            } catch (Throwable t) {
                                log.error("error notify streamPlayItemPlay", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case CLOSED:
                // notifies subscribers on close
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            // make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            try {
                                handler.streamSubscriberClose(stream);
                            } catch (Throwable t) {
                                log.error("error notify streamSubscriberClose", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case STARTED:
                // notifies subscribers on start
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            // make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            try {
                                handler.streamSubscriberStart(stream);
                            } catch (Throwable t) {
                                log.error("error notify streamSubscriberStart", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case STOPPED:
                // set the stopped state
                setState(StreamState.STOPPED);
                //notifies subscribers on stop
                if (handler != null) {
                    notifier = new Notifier(this, handler, conn) {
                        public void execute(ISchedulingService service) {
                            //make sure those notified have the correct connection
                            Red5.setConnectionLocal(conn);
                            //get the item that was stopped
                            IPlayItem item = (IPlayItem) changed[0];
                            try {
                                handler.streamPlayItemStop(stream, item);
                            } catch (Throwable t) {
                                log.error("error notify streamPlaylistItemStop", t);
                            } finally {
                                // clear thread local reference
                                Red5.setConnectionLocal(null);
                            }
                        }
                    };
                }
                break;
            case END:
                // notified by the play engine when the current item reaches the end
                nextItem();
                break;
            default:
                //there is no "default" handling
                log.warn("Unhandled change: {}", state);
        }
        if (notifier != null) {
            scheduleOnceJob(notifier);
        }
    }

    /** {@inheritDoc} */
    public IPlaylistSubscriberStreamStatistics getStatistics() {
        return this;
    }

    /** {@inheritDoc} */
    public long getCreationTime() {
        return creationTime;
    }

    /** {@inheritDoc} */
    public int getCurrentTimestamp() {
        int lastMessageTs = engine.getLastMessageTimestamp();
        if (lastMessageTs >= 0) {
            return 0;
        }
        return lastMessageTs;
    }

    /** {@inheritDoc} */
    public long getBytesSent() {
        return bytesSent;
    }

    /** {@inheritDoc} */
    public double getEstimatedBufferFill() {
        // check to see if any messages have been sent
        int lastMessageTs = engine.getLastMessageTimestamp();
        if (lastMessageTs < 0) {
            // nothing has been sent yet
            return 0.0;
        }
        // buffer size as requested by the client
        final long buffer = getClientBufferDuration();
        if (buffer == 0) {
            return 100.0;
        }
        // duration the stream is playing
        final long delta = System.currentTimeMillis() - engine.getPlaybackStart();
        // expected amount of data present in client buffer
        final long buffered = lastMessageTs - delta;
        return (buffered * 100.0) / buffer;
    }

    /**
     * @param maxPendingVideoFrames
     *            the maxPendingVideoFrames to set
     */
    public void setMaxPendingVideoFrames(int maxPendingVideoFrames) {
        this.maxPendingVideoFrames = maxPendingVideoFrames;
    }

    /**
     * @param maxSequentialPendingVideoFrames
     *            the maxSequentialPendingVideoFrames to set
     */
    public void setMaxSequentialPendingVideoFrames(int maxSequentialPendingVideoFrames) {
        this.maxSequentialPendingVideoFrames = maxSequentialPendingVideoFrames;
    }

    /** {@inheritDoc} */
    public String scheduleOnceJob(IScheduledJob job) {
        String jobName = schedulingService.addScheduledOnceJob(10, job);
        return jobName;
    }

    /** {@inheritDoc} */
    public String scheduleWithFixedDelay(IScheduledJob job, int interval) {
        String jobName = schedulingService.addScheduledJob(interval, job);
        jobs.add(jobName);
        return jobName;
    }

    /** {@inheritDoc} */
    public void cancelJob(String jobName) {
        schedulingService.removeScheduledJob(jobName);
    }

    /**
     * Handles notifications in a separate thread.
     */
    public class Notifier implements IScheduledJob {

        final IPlaylistSubscriberStream stream;

        final IStreamAwareScopeHandler handler;

        final IConnection conn;

        public Notifier(IPlaylistSubscriberStream stream, IStreamAwareScopeHandler handler, IConnection conn) {
            log.trace("Notifier - stream: {} handler: {}", stream, handler);
            this.conn = conn;
            this.stream = stream;
            this.handler = handler;
        }

        public void execute(ISchedulingService service) {
        }

    }

}


text:
var fs = require('fs');

var readFile = function (fileName) {
  return new Promise(function (resolve, reject) {
    fs.readFile(fileName, function(error, data) {
      if (error) reject(error);
      resolve(data);
    });
  });
};

var asyncReadFile = async function (){
  var f1 = await readFile('/etc/fstab');
  var f2 = await readFile('/etc/shells');
  console.log(f1.toString());
  console.log(f2.toString());
  return "fan"
};
asyncReadFile().then((v)=>{console.log("执行完毕"+(typeof v))});


text:
<?php

namespace Doctrine\ORM;

use function implode;
use function sprintf;

/**
 * Exception thrown when a Proxy fails to retrieve an Entity result.
 */
class EntityNotFoundException extends ORMException
{
    /**
     * Static constructor.
     *
     * @param string   $className
     * @param string[] $id
     *
     * @return self
     */
    public static function fromClassNameAndIdentifier($className, array $id)
    {
        $ids = [];

        foreach ($id as $key => $value) {
            $ids[] = $key . '(' . $value . ')';
        }

        return new self(
            'Entity of type \'' . $className . '\'' . ($ids ? ' for IDs ' . implode(', ', $ids) : '') . ' was not found'
        );
    }

    /**
     * Instance for which no identifier can be found
     *
     * @psalm-param class-string $className
     */
    public static function noIdentifierFound(string $className): self
    {
        return new self(sprintf(
            'Unable to find "%s" entity identifier associated with the UnitOfWork',
            $className
        ));
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=constant.BS1.html">

Redirecting to constant.BS1.html...


text:
package tonius.neiintegration.mods.forestry;

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

import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.gui.inventory.GuiCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import tonius.neiintegration.RecipeHandlerBase;
import tonius.neiintegration.Utils;
import codechicken.nei.PositionedStack;
import forestry.core.utils.ShapedRecipeCustom;

public class RecipeHandlerShapedCustom extends RecipeHandlerBase {

    public class CachedShapedCustomRecipe extends CachedBaseRecipe {

        public List<PositionedStack> inputs = new ArrayList<PositionedStack>();
        public PositionedStack output;

        public CachedShapedCustomRecipe(ShapedRecipeCustom recipe) {
            if (recipe.getIngredients() != null && recipe.getIngredients().length > 0) {
                this.setIngredients(recipe.getWidth(), recipe.getHeight(), recipe.getIngredients());
            }
            if (recipe.getRecipeOutput() != null) {
                this.output = new PositionedStack(recipe.getRecipeOutput(), 119, 24);
            }
        }

        public void setIngredients(int width, int height, Object[] items) {
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    if (items.length <= y * width + x || items[y * width + x] == null) {
                        continue;
                    }
                    PositionedStack stack = new PositionedStack(items[y * width + x], 25 + x * 18, 6 + y * 18);
                    stack.setMaxSize(1);
                    this.inputs.add(stack);
                }
            }
        }

        @Override
        public List<PositionedStack> getIngredients() {
            return this.getCycledIngredients(RecipeHandlerShapedCustom.this.cycleticks / 20, this.inputs);
        }

        @Override
        public PositionedStack getResult() {
            return this.output;
        }

    }

    @Override
    public String getRecipeID() {
        return "crafting";
    }

    @Override
    public String getRecipeName() {
        return Utils.translate("handler.forestry.shaped");
    }

    @Override
    public String getGuiTexture() {
        return "minecraft:textures/gui/container/crafting_table.png";
    }

    @Override
    public void loadTransferRects() {
        this.addTransferRect(84, 23, 24, 18);
    }

    @Override
    public Class<? extends GuiContainer> getGuiClass() {
        return GuiCrafting.class;
    }

    @Override
    public String getOverlayIdentifier() {
        return this.getRecipeID();
    }

    @Override
    public void loadAllRecipes() {
        for (Object recipe : CraftingManager.getInstance().getRecipeList()) {
            if (recipe instanceof ShapedRecipeCustom) {
                this.arecipes.add(new CachedShapedCustomRecipe((ShapedRecipeCustom) recipe));
            }
        }
    }

    @Override
    public void loadCraftingRecipes(ItemStack result) {
        for (Object recipe : CraftingManager.getInstance().getRecipeList()) {
            if (recipe instanceof ShapedRecipeCustom && Utils.areStacksSameTypeCraftingSafe(((ShapedRecipeCustom) recipe).getRecipeOutput(), result)) {
                this.arecipes.add(new CachedShapedCustomRecipe((ShapedRecipeCustom) recipe));
            }
        }
    }

    @Override
    public void loadUsageRecipes(ItemStack ingredient) {
        for (Object recipe : CraftingManager.getInstance().getRecipeList()) {
            if (recipe instanceof ShapedRecipeCustom) {
                CachedShapedCustomRecipe crecipe = new CachedShapedCustomRecipe((ShapedRecipeCustom) recipe);
                if (crecipe.inputs != null && crecipe.contains(crecipe.inputs, ingredient)) {
                    crecipe.setIngredientPermutationNBT(crecipe.inputs, ingredient);
                    this.arecipes.add(crecipe);
                }
            }
        }
    }

}


text:
/*!
 * FileInput French Translations
 *
 * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * @see http://github.com/kartik-v/bootstrap-fileinput
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
(function ($) {
    "use strict";

    $.fn.fileinputLocales['fr'] = {
        fileSingle: 'fichier',
        filePlural: 'fichiers',
        browseLabel: 'Parcourir…',
        removeLabel: 'Retirer',
        removeTitle: 'Retirer les fichiers sélectionnés',
        cancelLabel: 'Annuler',
        cancelTitle: "Annuler l'envoi en cours",
        uploadLabel: 'Transférer',
        uploadTitle: 'Transférer les fichiers sélectionnés',
        msgNo: 'Non',
        msgNoFilesSelected: '',
        msgCancelled: 'Annulé',
        msgPlaceholder: 'Select {files}...',
        msgZoomModalHeading: 'Aperçu détaillé',
        msgFileRequired: 'Vous devez sélectionner un fichier à uploader.',
        msgSizeTooSmall: 'Le fichier "{name}" ({size} KB) est inférieur à la taille minimale de {minSize} KB.',
        msgSizeTooLarge: 'Le fichier "{name}" ({size} Ko) dépasse la taille maximale autorisée qui est de {maxSize} Ko.',
        msgFilesTooLess: 'Vous devez sélectionner au moins {n} {files} à transmettre.',
        msgFilesTooMany: 'Le nombre de fichier sélectionné ({n}) dépasse la quantité maximale autorisée qui est de {m}.',
        msgFileNotFound: 'Le fichier "{name}" est introuvable !',
        msgFileSecured: "Des restrictions de sécurité vous empêchent d'accéder au fichier \"{name}\".",
        msgFileNotReadable: 'Le fichier "{name}" est illisible.',
        msgFilePreviewAborted: 'Prévisualisation du fichier "{name}" annulée.',
        msgFilePreviewError: 'Une erreur est survenue lors de la lecture du fichier "{name}".',
        msgInvalidFileName: 'Caractères invalides ou non supportés dans le nom de fichier "{name}".',
        msgInvalidFileType: 'Type de document invalide pour "{name}". Seulement les documents de type "{types}" sont autorisés.',
        msgInvalidFileExtension: 'Extension invalide pour le fichier "{name}". Seules les extensions "{extensions}" sont autorisées.',
        msgFileTypes: {
            'image': 'image',
            'html': 'HTML',
            'text': 'text',
            'video': 'video',
            'audio': 'audio',
            'flash': 'flash',
            'pdf': 'PDF',
            'object': 'object'
        },
        msgUploadAborted: 'Le transfert du fichier a été interrompu',
        msgUploadThreshold: 'En cours...',
        msgUploadBegin: 'Initialisation...',
        msgUploadEnd: 'Terminé',
        msgUploadEmpty: 'Aucune donnée valide disponible pour transmission.',
        msgUploadError: 'Error',
        msgValidationError: 'Erreur de validation',
        msgLoading: 'Transmission du fichier {index} sur {files}…',
        msgProgress: 'Transmission du fichier {index} sur {files} - {name} - {percent}% faits.',
        msgSelected: '{n} {files} sélectionné(s)',
        msgFoldersNotAllowed: 'Glissez et déposez uniquement des fichiers ! {n} répertoire(s) exclu(s).',
        msgImageWidthSmall: 'Largeur de fichier image "{name}" doit être d\'au moins {size} px.',
        msgImageHeightSmall: 'Hauteur de fichier image "{name}" doit être d\'au moins {size} px.',
        msgImageWidthLarge: 'Largeur de fichier image "{name}" ne peut pas dépasser {size} px.',
        msgImageHeightLarge: 'Hauteur de fichier image "{name}" ne peut pas dépasser {size} px.',
        msgImageResizeError: "Impossible d'obtenir les dimensions de l'image à redimensionner.",
        msgImageResizeException: "Erreur lors du redimensionnement de l'image.
{errors}
",
        msgAjaxError: "Une erreur s'est produite pendant l'opération de {operation}. Veuillez réessayer plus tard.",
        msgAjaxProgressError: '{operation} échoué',
        ajaxOperations: {
            deleteThumb: 'suppression de fichier',
            uploadThumb: 'transfert de fichier',
            uploadBatch: 'transfert des fichiers',
            uploadExtra: 'soumission des données de formulaire'
        },
        dropZoneTitle: 'Glissez et déposez les fichiers ici…',
        dropZoneClickTitle: '
(ou cliquez pour sélectionner manuellement)',
        fileActionSettings: {
            removeTitle: 'Supprimer le fichier',
            uploadTitle: 'Transférer le fichier',
            uploadRetryTitle: 'Retry upload',
            zoomTitle: 'Voir les détails',
            dragTitle: 'Déplacer / Réarranger',
            indicatorNewTitle: 'Pas encore transféré',
            indicatorSuccessTitle: 'Posté',
            indicatorErrorTitle: 'Ajouter erreur',
            indicatorLoadingTitle: 'En cours...'
        },
        previewZoomButtonTitles: {
            prev: 'Voir le fichier précédent',
            next: 'Voir le fichier suivant',
            toggleheader: 'Masquer le titre',
            fullscreen: 'Mode plein écran',
            borderless: 'Mode cinéma',
            close: "Fermer l'aperçu"
        }
    };
})(window.jQuery);


text:
cask 'transmission-nightly' do
  version '14736'
  sha256 'e56ad5ff03d9437b8c099dafea616b3e1b4e072a7f5dd06df9abc09576347ee1'

  url "https://build.transmissionbt.com/job/trunk-mac/lastSuccessfulBuild/artifact/release/Transmission-#{version}.dmg"
  name 'Transmission'
  homepage 'https://www.transmissionbt.com'
  license :gpl

  app 'Transmission.app'

  zap delete: [
                '~/Library/Application Support/Transmission',
                '~/Library/Preferences/org.m0k.transmission.plist',
                '~/Library/Preferences/org.m0k.transmission.LSSharedFileList.plist',
                '~/Library/Caches/org.m0k.transmission',
                '~/Library/Saved Application State/org.m0k.transmission.savedState',
              ]
end


text:
//
//  NSDate+Extend.h
//  categoryKitDemo
//
//  Created by zhanghao on 2016/7/23.
//  Copyright © 2017年 zhanghao. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSDate (Extend)

// 获取当前的时间☟
@property (nonatomic, assign, readonly) NSInteger year;
@property (nonatomic, assign, readonly) NSInteger month;
@property (nonatomic, assign, readonly) NSInteger day;
@property (nonatomic, assign, readonly) NSInteger hour;
@property (nonatomic, assign, readonly) NSInteger minute;
@property (nonatomic, assign, readonly) NSInteger second;
@property (nonatomic, assign, readonly) NSInteger weekday;

/**
 获取星期几(名称)

 @return Return weekday as a localized string
 [1 - Sunday]
 [2 - Monday]
 [3 - Tuerday]
 [4 - Wednesday]
 [5 - Thursday]
 [6 - Friday]
 [7 - Saturday]
 */
- (NSString *)dayFromWeekday; // 星期几的形式
- (NSString *)dayFromWeekday2; // 周几的形式
- (NSString *)dayFromWeekday3; // 英文的形式
+ (NSString *)dayFromWeekday:(NSDate *)date; // 星期几的形式
+ (NSString *)dayFromWeekday2:(NSDate *)date; // 周几的形式
+ (NSString *)dayFromWeekday3:(NSDate *)date; // 英文的形式

+ (NSString *)ymdFormatJoinedByString:(NSString *)string;
+ (NSString *)ymdHmsFormat;
+ (NSString *)ymdFormat;
+ (NSString *)hmsFormat;
+ (NSString *)dmyFormat; // day month years format
+ (NSString *)myFormat; // month years format

/// 获取当前时间戳字符串
+ (NSString *)currentTimeString;

/// 当前date转换成时间字符串 (+方法)
+ (NSString *)stringWithFormat:(NSString *)format;

/// 将date转换成时间字符串 (NSDate => TimeString)
+ (NSString *)stringWithDate:(NSDate *)date format:(NSString *)format;

/**
 将时间字符串转换成date (TimeString ==> NSDate)
 Example:
 NSString *string = @"2017-09-15";
 NSDate *date = [NSDate dateWithString:string format:@"yyyy-MM-dd"];
 */
+ (NSDate *)dateWithString:(NSString *)dateString format:(NSString *)format;

/// 将date转换成时间戳 (NSDate => Timestamp)
+ (NSInteger)timestampFromDate:(NSDate *)date;

/// 将时间戳转换成date (Timestamp => NSDate)
+ (NSDate *)dateFromTimestamp:(NSInteger)timestamp;

/**
 将时间字符串转换成时间戳 (TimeString => Timestamp) / 北京时间
 Example:
 NSString *timeString = @"2017-09-15 15:39";
 NSInteger timestamp = [NSDate timestampFromTimeString:timeString formatter:@"yyyy-MM-dd HH:mm"];
 */
+ (NSInteger)timestampFromTimeString:(NSString *)timeString formatter:(NSString *)format;

/// 将时间戳转换成时间字符串 (Timestamp => TimeString) / 北京时间
+ (NSString *)timeStringFromTimestamp:(NSInteger)timestamp formatter:(NSString *)format;

/// 获取当前系统时间的时间戳 / 北京时间
+ (NSInteger)getNowTimestampWithFormatter:(NSString *)format;

/// 获取某个月的天数
+ (NSInteger)getSumOfDaysMonth:(NSInteger)month inYear:(NSInteger)year;

/// 获取当前的"年月日时分"
+ (NSArray<NSString *> *)getCurrentTimeComponents;

/** 比较两个date的大小关系 return NSComparisonResult
 NSOrderedAscending     => (dateString1 < dateString2)
 NSOrderedDescending    => (dateString1 > dateString2)
 NSOrderedSame          => (dateString1 = dateString2)
 */
- (NSComparisonResult)compareDateString1:(NSString *)dateString1
                             dateString2:(NSString *)dateString2
                               formatter:(NSString *)format;

/// 是否小于当前时间(过去时间)
- (BOOL)isInPast;
/// 是否大于当前时间(未来时间)
- (BOOL)isInFuture;

/// 是否是今天
- (BOOL)isToday;

/**
 获取未来的日期时间

 如:获取2天后的时间 [date backward:2 unitType:NSCalendarUnitDay];
 */
+ (NSDate *)backward:(NSInteger)backwardN unitType:(NSCalendarUnit)unit;

/**
 获取之前的日期时间

 如:获取2天前的时间 [date forward:2 unitType:NSCalendarUnitDay];
 */
+ (NSDate *)forward:(NSInteger)forwardN unitType:(NSCalendarUnit)unit;

@end


text:
#ifndef GLM_GTX_rotate_vector
#define GLM_GTX_rotate_vector GLM_VERSION

// Dependency:
#include "../glm.hpp"
#include "../gtx/transform.hpp"

#if(defined(GLM_MESSAGES) && !defined(glm_ext))
#	pragma message("GLM: GLM_GTX_rotate_vector extension included")
#endif

namespace glm
{
	/// @addtogroup gtx_rotate_vector
	/// @{

	//! Rotate a two dimensional vector.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec2<T> rotate(
        detail::tvec2<T> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around an axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec3<T> rotate(
        detail::tvec3<T> const & v,
		T const & angle,
        detail::tvec3<T> const & normal);

	//! Rotate a four dimensional vector around an axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec4<T> rotate(
        detail::tvec4<T> const & v,
        T const & angle,
		detail::tvec3<T> const & normal);

	//! Rotate a three dimensional vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec3<T> rotateX(
        detail::tvec3<T> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around the Y axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec3<T> rotateY(
		detail::tvec3<T> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around the Z axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec3<T> rotateZ(
        detail::tvec3<T> const & v,
		T const & angle);

	//! Rotate a four dimentionnals vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec4<T> rotateX(
        detail::tvec4<T> const & v,
		T const & angle);

	//! Rotate a four dimensional vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec4<T> rotateY(
        detail::tvec4<T> const & v,
		T const & angle);

	//! Rotate a four dimensional vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tvec4<T> rotateZ(
        detail::tvec4<T> const & v,
		T const & angle);

	//! Build a rotation matrix from a normal and a up vector.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T>
	detail::tmat4x4<T> orientation(
        detail::tvec3<T> const & Normal,
        detail::tvec3<T> const & Up);

	/// @}
}//namespace glm

#include "rotate_vector.inl"

#endif//GLM_GTX_rotate_vector


text:
package ucar.ui.widget;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * Popup Help window.
 *
 * @author jcaron
 * @version 1.0
 *
 *          Example:
 *
 *          <pre>
 *          if (help != null) {
 *            helpButton = new JButton("help");
 *            helpButton.addActionListener(new AbstractAction() {
 *              public void actionPerformed(ActionEvent e) {
 *                if (helpWindow == null)
 *                  helpWindow = new HelpWindow(null, "Help on " + tit, helpMessage);
 *                helpWindow.show(helpButton);
 *              }
 *            });
 *            butts.add(helpButton);
 *          }
 *          </pre>
 */

public class HelpWindow extends IndependentDialog {
  private String helpMessage;
  private JTextArea ta;

  public HelpWindow(JFrame parent, String title, String helpMessage) {
    super(parent, true, title);
    this.helpMessage = helpMessage;
  }

  public void show(Component source) {
    if (ta == null) {
      ta = new JTextArea(7, 30);
      ta.setLineWrap(true); // need to insert \n ourself, because XML removes \n ? or use IndependentWinfow ?
      ta.setWrapStyleWord(true);
      ta.setEditable(false);
      ta.setText(helpMessage);

      Container cp = getContentPane();
      cp.setLayout(new BorderLayout());
      cp.add(ta, BorderLayout.CENTER);
      pack();
    }

    Point op = new Point(source.getLocation());
    if (parent != null)
      SwingUtilities.convertPoint(source, op, parent);
    else
      SwingUtilities.convertPointToScreen(op, source);

    setLocation(op);
    super.setVisible(true);
  }

  public void show() {
    show(this);
  }

}


text:
.menu-dropdown {
  position: fixed;
  top: 0px;
  right: 0px;
  margin: 5px;
  z-index: 99999;
}
.menu-dropdown .menu-button {
  border: 0px;
  background-color: #1d2528;
  color: lightblue;
}
.menu-dropdown .menu-icon {
  color: lightblue;
  font-size: 3em;
}
.menu-dropdown .menu-icon:hover {
  color: green;
}
.menu-dropdown ul,
.menu-dropdown a {
  background-color: #28130f;
  color: lightblue;
  font-size: large;
}
.menu-dropdown a:hover
{
  background-color: #415359;
  color: #eef7fa;
  font-weight: bold;
  font-size: large;
}
.menu-dropdown li {
  text-align: right;
}


text:
ON=0
OFF=1

# RPI2 pinouts
PINOUT_LIGHT=5
PINOUT_RELEASE=6

# ODROID pinouts
if [ $(grep ODROID /proc/cpuinfo | wc -l ) -gt 0 ];then
    PINOUT_LIGHT=173
    PINOUT_RELEASE=171
fi

DEV=/sys/class/gpio
LIGHT=$DEV/gpio${PINOUT_LIGHT}
RELAY=$DEV/gpio${PINOUT_RELEASE}

function flash_light(){
    echo $ON  > $LIGHT/value ; sleep .5 ;
    echo $OFF > $LIGHT/value ; sleep .5 ;
};

# initialize gpio directories
if [ ! -e $DEV/gpio${PINOUT_LIGHT} ] ; then echo ${PINOUT_LIGHT} > $DEV/export ; fi
if [ ! -e $DEV/gpio${PINOUT_RELEASE} ] ; then echo ${PINOUT_RELEASE} > $DEV/export ; fi

# initialize pin outputs
echo out > $RELAY/direction
echo out > $LIGHT/direction

# toggle dispensing relay
( echo $ON > $RELAY/value ; sleep .3 ; echo $OFF > $RELAY/value) &

# flash sign lights
( for x in `seq 1`; do flash_light ; done ) &