text:
/**
 * test/SubjectGroups.js
 */
'use strict';
const expect = require('chai').expect;
const SubjectGroups = require('../src/SubjectGroups');
const SubjectGroup = require('../src/SubjectGroup');
const hierarchy = require('./test-hierarchy');
const airportHierarchy = require('./test-us-airport-hierarchy');
const util = require('util');

describe('./test/SubjectGroups.js >', () => {
  describe('getParentGroupForAbsolutePath >', () => {
    const sg = new SubjectGroups(hierarchy);

    it('TypeError if absolutePath arg is undefined', () => {
      expect(() => sg.getParentGroupForAbsolutePath(undefined))
      .to.throw(TypeError);
    });

    it('TypeError if absolutePath arg is null', () => {
      expect(() => sg.getParentGroupForAbsolutePath(null))
      .to.throw(TypeError);
    });

    it('TypeError if absolutePath arg is object', () => {
      expect(() => sg.getParentGroupForAbsolutePath({}))
      .to.throw(TypeError);
    });

    it('TypeError if absolutePath arg is array', () => {
      expect(() => sg.getParentGroupForAbsolutePath([]))
      .to.throw(TypeError);
    });

    it('undefined if absolutePath arg is empty string', () => {
      expect(sg.getParentGroupForAbsolutePath('')).to.equal(undefined);
    });

    it('absolutePath arg is valid sample name', () => {
      const sgrp =
        sg.getParentGroupForAbsolutePath('Fellowship.Aragorn.JJ1.B52|OAUTH');
      expect(sgrp instanceof SubjectGroup).to.be.true;
      expect(sgrp).to.have.property('name', 'Fellowship.Aragorn.JJ1');
    });

    it('absolutePath arg is valid subject absolutePath', () => {
      const sgrp =
        sg.getParentGroupForAbsolutePath('Fellowship.Aragorn.JJ1.B52');
      expect(sgrp instanceof SubjectGroup).to.be.true;
      expect(sgrp).to.have.property('name', 'Fellowship.Aragorn.JJ1');
    });

    it('undefined if neither splitGroup nor normalGroup found for absolutePath', () => {
      const sgrp = sg.getParentGroupForAbsolutePath('a.bcd.efg');
      expect(sgrp).to.equal(undefined);
    });

    it('splitGroupMap does not contain a key for this absolutePath, ' +
    'should use normalGroup', () => {
      expect(sg.splitGroupMap).to.deep.equal({});
      const sgrp =
        sg.getParentGroupForAbsolutePath('Fellowship.Aragorn.JJ1.B52');
      expect(sgrp instanceof SubjectGroup).to.be.true;
      expect(sgrp).to.have.property('name', 'Fellowship.Aragorn.JJ1');
    });
  });

  describe('SubjectGroup maps >', () => {
    let sg;
    let grp;

    before(() => {
      sg = new SubjectGroups(airportHierarchy);
    });

    it('map should be empty when passed in an empty hierarchy', () => {
      const sgs = new SubjectGroups({});
      expect(sgs.map).to.deep.equal({});
    });

    it('map should contain subjectGroup instance keyed off of subject ' +
      'absolutePath. Subjects without children should not have subject group', () => {
      const sgs = new SubjectGroups(airportHierarchy);
      const mapKeys = Object.keys(sgs.map);
      expect(mapKeys).to.include.members(['usa', 'usa.ca', 'usa.ca.sfo',
         'usa.ma']);
      mapKeys.forEach((key) => {
        expect(sg.map[key] instanceof SubjectGroup).to.be.true;
      })
    });

    it('map for hierarchy have just one subject in every level', () => {
      const bosSubject = JSON.parse(JSON.stringify(
        airportHierarchy.children[2].children[0]));
      const sgs = new SubjectGroups(bosSubject);
      expect(Object.keys(sgs.map)).to.include('usa.ma');
      expect(sgs.map['usa.ma'] instanceof SubjectGroup).to.be.true;
      const sg = sgs.map['usa.ma'];
      expect(sg.subjects['usa.ma.bos']).to.deep.equal(bosSubject);
    });
  });

  describe('getParentGroupForAbsolutePath with split group >', () => {
    let sg;
    let grp;

    before(() => {
      sg = new SubjectGroups(hierarchy);
      grp = sg.getParentGroupForAbsolutePath('Fellowship.Gandalf.JJ1');
      sg.splitSubjectGroup(grp);
    });

    it('map does not contain a key for the group name derived from this ' +
    'absolutePath, should use splitGroup', () => {
      const g = sg.getParentGroupForAbsolutePath('Fellowship.Gandalf.JJ1');
      expect(g).to.have.property('splitNum', 1);
      expect(g).to.have.property('split', true);
      expect(g).to.have.property('key', 'fellowship.gandalf-1');
      expect(sg.splitGroupMap).to.have.property('fellowship.gandalf.jj1');
      expect(sg.splitGroupMap['fellowship.gandalf.jj1'])
      .to.have.property('key', 'fellowship.gandalf-1');
      expect(sg.map).to.not.have.property('fellowship.gandalf');
    });
  });

  describe('SubjectGroups.groupName >', () => {
    const sgArgs = { absolutePath: 'a', name: 'a' };
    const sg = new SubjectGroups(sgArgs);

    it('TypeError if key is undefined', () => {
      expect(() => SubjectGroups.groupName(undefined)).to.throw(TypeError);
    });

    it('TypeError if key is null', () => {
      expect(() => SubjectGroups.groupName(null)).to.throw(TypeError);
    });

    it('TypeError if key is object', () => {
      expect(() => SubjectGroups.groupName({})).to.throw(TypeError);
    });

    it('TypeError if key is array', () => {
      expect(() => SubjectGroups.groupName([])).to.throw(TypeError);
    });

    it('TypeError if key is number', () => {
      expect(() => SubjectGroups.groupName(23)).to.throw(TypeError);
    });

    it('key is empty string', () => {
      expect(SubjectGroups.groupName('')).to.equal('');
    });

    it('key is string with no "." character and no "|" character', () => {
      expect(SubjectGroups.groupName('abc#DEF')).to.equal('abc#DEF');
    });

    it('key has leading "." character', () => {
      expect(SubjectGroups.groupName('.abc')).to.equal('.abc');
    });

    it('key has terminating "." character', () => {
      expect(SubjectGroups.groupName('abc.def.')).to.equal('abc.def');
    });

    it('key has non-leading and non-terminating "." character', () => {
      expect(SubjectGroups.groupName('abc.DEF')).to.equal('abc');
    });

    it('key has multiple consecutive "." characters', () => {
      expect(SubjectGroups.groupName('abc..DEF')).to.equal('abc.');
    });

    it('key has multiple non-consecutive "." characters', () => {
      expect(SubjectGroups.groupName('abc.DEF.ghi.JKL'))
      .to.equal('abc.DEF.ghi');
    });

    it('key has "." and |" character', () => {
      expect(SubjectGroups.groupName('abc.DEF.ghi|JKL'))
      .to.equal('abc.DEF');
    });

    it('key has "|" character but no "." character', () => {
      expect(SubjectGroups.groupName('abc|JKL'))
      .to.equal('abc');
    });

    it('key has multiple consecutive "|" characters', () => {
      expect(SubjectGroups.groupName('abc.DEF.ghi||JKL'))
      .to.equal('abc.DEF');
    });

    it('key has multiple non-consecutive "|" characters', () => {
      expect(SubjectGroups.groupName('abc.DEF.ghi|JKL|mno'))
      .to.equal('abc.DEF');
    });
  });

  describe('getPanelsToDraw >', () => {
    it('map is empty', () => {
      const sgArgs = { absolutePath: 'a', name: 'a' };
      const sg = new SubjectGroups({});
      expect(Object.keys(sg.map)).to.be.empty;
      expect(sg.getPanelsToDraw()).to.be.empty;
    });

    it('no aspects or subjects to show', () => {
      const sgArgs = {
        absolutePath: 'a',
        name: 'a',
        children: [
          {
            absolutePath: 'a.a',
            name: 'a',
          },
          {
            absolutePath: 'a.b',
            name: 'b',
            children: [
              {
                absolutePath: 'a.b.a',
                name: 'a',
              },
              {
                absolutePath: 'a.b.b',
                name: 'b',
              },
            ],
          },
        ],
      };
      const sg = new SubjectGroups(sgArgs);
      expect(sg.getPanelsToDraw()).to.be.empty;
    });

    it('showAll false (default state)', () => {
      const sg = new SubjectGroups(hierarchy);
      const panelsToDraw = sg.getPanelsToDraw().map((p) => p.name);
      const sortedPanels = panelsToDraw.slice().sort();
      expect(Object.keys(sg.map).length).to.equal(11);
      expect(panelsToDraw.length).to.equal(5);
      expect(sortedPanels).to.deep.equal(panelsToDraw);
    });

    it('showAll true', () => {
      const sg = new SubjectGroups(hierarchy);
      sg.reset(true);
      const panelsToDraw = sg.getPanelsToDraw().map((p) => p.name);
      const sortedPanels = panelsToDraw.slice().sort();
      expect(Object.keys(sg.map).length).to.equal(11);
      expect(panelsToDraw.length).to.equal(7);
      expect(sortedPanels).to.deep.equal(panelsToDraw);
    });
  });
});


text:
package com.suse.studio.client.model;

import java.util.List;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

@Root(strict = false)
public class Builds {

    @Attribute
    private String type;

    public String getType() {
        return type;
    }

    @ElementList(inline = true, required = false, empty = false)
    private List<Build> build;

    public List<Build> getBuilds() {
        return this.build;
    }
}

redpajama_set_name: RedPajamaGithub


text:
FROM node:alpine

MAINTAINER Gareth Oates

COPY . /var/node

WORKDIR /var/node

RUN npm install

ENTRYPOINT  ["npm", "start"]


text:
"""
Firebase Cloud Messaging
Previously known as GCM / C2DM
Documentation is available on the Firebase Developer website:
https://firebase.google.com/docs/cloud-messaging/
"""

import json

from django.core.exceptions import ImproperlyConfigured

from .compat import Request, urlopen
from .conf import get_manager
from .exceptions import NotificationError
from .models import GCMDevice

# Valid keys for FCM messages. Reference:
# https://firebase.google.com/docs/cloud-messaging/http-server-ref
FCM_TARGETS_KEYS = [
	"to", "condition", "notification_key"
]
FCM_OPTIONS_KEYS = [
	"collapse_key", "priority", "content_available", "delay_while_idle", "time_to_live",
	"restricted_package_name", "dry_run"
]
FCM_NOTIFICATIONS_PAYLOAD_KEYS = [
	"title", "body", "icon", "sound", "badge", "color", "tag", "click_action",
	"body_loc_key", "body_loc_args", "title_loc_key", "title_loc_args", "android_channel_id"
]

class GCMError(NotificationError):
	pass

def _chunks(l, n):
	"""
	Yield successive chunks from list \a l with a minimum size \a n
	"""
	for i in range(0, len(l), n):
		yield l[i:i + n]

def _gcm_send(data, content_type, application_id):
	key = get_manager().get_gcm_api_key(application_id)

	headers = {
		"Content-Type": content_type,
		"Authorization": "key=%s" % (key),
		"Content-Length": str(len(data)),
	}
	request = Request(get_manager().get_post_url("GCM", application_id), data, headers)
	return urlopen(
		request, timeout=get_manager().get_error_timeout("GCM", application_id)
	).read().decode("utf-8")

def _fcm_send(data, content_type, application_id):
	key = get_manager().get_fcm_api_key(application_id)

	headers = {
		"Content-Type": content_type,
		"Authorization": "key=%s" % (key),
		"Content-Length": str(len(data)),
	}
	request = Request(get_manager().get_post_url("FCM", application_id), data, headers)
	return urlopen(
		request, timeout=get_manager().get_error_timeout("FCM", application_id)
	).read().decode("utf-8")

def _cm_handle_response(registration_ids, response_data, cloud_type, application_id=None):
	response = response_data
	if response.get("failure") or response.get("canonical_ids"):
		ids_to_remove, old_new_ids = [], []
		throw_error = False
		for index, result in enumerate(response["results"]):
			error = result.get("error")
			if error:
				# https://firebase.google.com/docs/cloud-messaging/http-server-ref#error-codes
				# If error is NotRegistered or InvalidRegistration, then we will deactivate devices
				# because this registration ID is no more valid and can't be used to send messages,
				# otherwise raise error
				if error in ("NotRegistered", "InvalidRegistration"):
					ids_to_remove.append(registration_ids[index])
				else:
					throw_error = True
			result["original_registration_id"] = registration_ids[index]
			# If registration_id is set, replace the original ID with the new value (canonical ID)
			# in your server database. Note that the original ID is not part of the result, you need
			# to obtain it from the list of registration_ids in the request (using the same index).
			new_id = result.get("registration_id")
			if new_id:
				old_new_ids.append((registration_ids[index], new_id))

		if ids_to_remove:
			removed = GCMDevice.objects.filter(
				registration_id__in=ids_to_remove, cloud_message_type=cloud_type
			)
			removed.update(active=False)

		for old_id, new_id in old_new_ids:
			_cm_handle_canonical_id(new_id, old_id, cloud_type)

		if throw_error:
			raise GCMError(response)
	return response

def _cm_send_request(
	registration_ids, data, cloud_type="GCM", application_id=None,
	use_fcm_notifications=True, **kwargs
):
	"""
	Sends a FCM or GCM notification to one or more registration_ids as json data.
	The registration_ids needs to be a list.
	"""

	payload = {"registration_ids": registration_ids} if registration_ids else {}

	data = data.copy()

	# If using FCM, optionnally autodiscovers notification related keys
	# https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
	if cloud_type == "FCM" and use_fcm_notifications:
		notification_payload = {}
		if "message" in data:
			notification_payload["body"] = data.pop("message", None)

		for key in FCM_NOTIFICATIONS_PAYLOAD_KEYS:
			value_from_extra = data.pop(key, None)
			if value_from_extra:
				notification_payload[key] = value_from_extra
			value_from_kwargs = kwargs.pop(key, None)
			if value_from_kwargs:
				notification_payload[key] = value_from_kwargs
		if notification_payload:
			payload["notification"] = notification_payload

	if data:
		payload["data"] = data

	# Attach any additional non falsy keyword args (targets, options)
	# See ref : https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
	payload.update({
		k: v for k, v in kwargs.items() if v and (k in FCM_TARGETS_KEYS or k in FCM_OPTIONS_KEYS)
	})

	# Sort the keys for deterministic output (useful for tests)
	json_payload = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")

	# Sends requests and handles the response
	if cloud_type == "GCM":
		response = json.loads(_gcm_send(
			json_payload, "application/json", application_id=application_id
		))
	elif cloud_type == "FCM":
		response = json.loads(_fcm_send(
			json_payload, "application/json", application_id=application_id
		))
	else:
		raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))
	return _cm_handle_response(registration_ids, response, cloud_type, application_id)

def _cm_handle_canonical_id(canonical_id, current_id, cloud_type):
	"""
	Handle situation when FCM server response contains canonical ID
	"""
	devices = GCMDevice.objects.filter(cloud_message_type=cloud_type)
	if devices.filter(registration_id=canonical_id, active=True).exists():
		devices.filter(registration_id=current_id).update(active=False)
	else:
		devices.filter(registration_id=current_id).update(registration_id=canonical_id)

def send_message(registration_ids, data, cloud_type, application_id=None, **kwargs):
	"""
	Sends a FCM (or GCM) notification to one or more registration_ids. The registration_ids
	can be a list or a single string. This will send the notification as json data.

	A reference of extra keyword arguments sent to the server is available here:
	https://firebase.google.com/docs/cloud-messaging/http-server-ref#table1
	"""
	if cloud_type in ("FCM", "GCM"):
		max_recipients = get_manager().get_max_recipients(cloud_type, application_id)
	else:
		raise ImproperlyConfigured("cloud_type must be FCM or GCM not %s" % str(cloud_type))

	# Checks for valid recipient
	if registration_ids is None and "/topics/" not in kwargs.get("to", ""):
		return

	# Bundles the registration_ids in an list if only one is sent
	if not isinstance(registration_ids, list):
		registration_ids = [registration_ids] if registration_ids else None

	# FCM only allows up to 1000 reg ids per bulk message
	# https://firebase.google.com/docs/cloud-messaging/server#http-request
	if registration_ids:
		ret = []
		for chunk in _chunks(registration_ids, max_recipients):
			ret.append(_cm_send_request(
				chunk, data, cloud_type=cloud_type, application_id=application_id, **kwargs
			))
		return ret[0] if len(ret) == 1 else ret
	else:
		return _cm_send_request(None, data, cloud_type=cloud_type, **kwargs)

send_bulk_message = send_message


text:
pickArguments

Create a function that invokes a provided function with specified arguments.

Usage

var pickArguments = require( '@stdlib/utils/pick-arguments' );

pickArguments( fcn, indices[, thisArg] )

Returns a function that invokes a provided function with specified arguments.

function foo( a, b ) {
    return [ a, b ];
}

var bar = pickArguments( foo, [ 0, 2 ] );

var out = bar( 1, 2, 3 );
// returns [ 1, 3 ]

To set the this context when invoking the provided function, provide a thisArg.

function Foo() {
    this.x = 1;
    this.y = 2;
}

Foo.prototype.scale = function scale( a, b ) {
    return [ this.x*a, this.y*b ];
};

var ctx = {
    'x': 10,
    'y': 20
};

var foo = new Foo();

var bar = pickArguments( foo.scale, [ 0, 2 ], ctx );

var out = bar( 1, 2, 3 );
// returns [ 10, 60 ]

Examples

var filledarrayBy = require( '@stdlib/array/filled-by' );
var add = require( '@stdlib/math/base/ops/add' );
var pickArguments = require( '@stdlib/utils/pick-arguments' );

function fill( i ) {
    return i;
}

// Create a data array:
var x = filledarrayBy( 10, 'float64', fill );

// Compute the sum of consecutive elements...
var f;
var i;
for ( i = 1; i < x.length; i++ ) {
    f = pickArguments( add, [ i-1, i ] );
    console.log( 'sum(x_%d, x_%d) = %d', i-1, i, f.apply( null, x ) );
}


text:
<?php
/*!
* Hybridauth
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth
*  (c) 2020 Hybridauth authors | https://hybridauth.github.io/license.html
*/

namespace Hybridauth\Provider;

use Hybridauth\Exception\InvalidArgumentException;
use Hybridauth\Exception\UnexpectedApiResponseException;
use Hybridauth\Exception\InvalidApplicationCredentialsException;
use Hybridauth\Exception\UnexpectedValueException;

use Hybridauth\Adapter\OAuth2;
use Hybridauth\Data;
use Hybridauth\User;

use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;

use \Firebase\JWT\JWT;
use \Firebase\JWT\JWK;

/**
 * Apple OAuth2 provider adapter.
 *
 * Example:
 *
 *   $config = [
 *       'callback' => Hybridauth\HttpClient\Util::getCurrentUrl(),
 *       'keys'     => [ 'id' => '', 'team_id' => '', 'key_id' => '', 'key_file' => '', 'key_content' => '' ],
 *       'scope'    => 'name email',
 *
 *        // Apple's custom auth url params
 *       'authorize_url_parameters' => [
 *              'response_mode' => 'form_post'
 *       ]
 *   ];
 *
 *   $adapter = new Hybridauth\Provider\Apple( $config );
 *
 *   try {
 *       $adapter->authenticate();
 *
 *       $userProfile = $adapter->getUserProfile();
 *       $tokens = $adapter->getAccessToken();
 *       $response = $adapter->setUserStatus("Hybridauth test message..");
 *   }
 *   catch( Exception $e ){
 *       echo $e->getMessage() ;
 *   }
 *
 * Requires:
 *
 * composer require codercat/jwk-to-pem
 * composer require firebase/php-jwt
 *
 * @see https://github.com/sputnik73/hybridauth-sign-in-with-apple
 * @see https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api
 */
class Apple extends OAuth2
{
    /**
     * {@inheritdoc}
     */
    protected $scope = 'name email';

    /**
     * {@inheritdoc}
     */
    protected $apiBaseUrl = 'https://appleid.apple.com/auth/';

    /**
     * {@inheritdoc}
     */
    protected $authorizeUrl = 'https://appleid.apple.com/auth/authorize';

    /**
     * {@inheritdoc}
     */
    protected $accessTokenUrl = 'https://appleid.apple.com/auth/token';

    /**
     * {@inheritdoc}
     */
    protected $apiDocumentation = 'https://developer.apple.com/documentation/sign_in_with_apple';

    /**
     * {@inheritdoc}
     * The Sign in with Apple servers require percent encoding (or URL encoding)
     * for its query parameters. If you are using the Sign in with Apple REST API,
     * you must provide values with encoded spaces (`%20`) instead of plus (`+`) signs.
     */
    protected $AuthorizeUrlParametersEncType = PHP_QUERY_RFC3986;

    /**
     * {@inheritdoc}
     */
    protected function initialize()
    {
        parent::initialize();
        $this->AuthorizeUrlParameters['response_mode'] = 'form_post';
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $keys = $this->config->get('keys');
        $keys['secret'] = $this->getSecret();
        $this->config->set('keys', $keys);
        return parent::configure();
    }

    /**
     * {@inheritdoc}
     *
     * include id_token $tokenNames
     */
    public function getAccessToken()
    {
        $tokenNames = [
            'access_token',
            'id_token',
            'access_token_secret',
            'token_type',
            'refresh_token',
            'expires_in',
            'expires_at',
        ];

        $tokens = [];

        foreach ($tokenNames as $name) {
            if ($this->getStoredData($name)) {
                $tokens[$name] = $this->getStoredData($name);
            }
        }

        return $tokens;
    }

    /**
     * {@inheritdoc}
     */
    protected function validateAccessTokenExchange($response)
    {
        $collection = parent::validateAccessTokenExchange($response);

        $this->storeData('id_token', $collection->get('id_token'));

        return $collection;
    }

    public function getUserProfile()
    {
        $id_token = $this->getStoredData('id_token');

        $verifyTokenSignature =
            ($this->config->exists('verifyTokenSignature')) ? $this->config->get('verifyTokenSignature') : true;

        if (!$verifyTokenSignature) {
            // payload extraction by https://github.com/omidborjian
            // https://github.com/hybridauth/hybridauth/issues/1095#issuecomment-626479263
            // JWT splits the string to 3 components 1) first is header 2) is payload 3) is signature
            $payload = explode('.', $id_token)[1];
            $payload = json_decode(base64_decode($payload));
        } else {
            // validate the token signature and get the payload
            $publicKeys = $this->apiRequest('keys');

            \Firebase\JWT\JWT::$leeway = 120;

            foreach ($publicKeys->keys as $publicKey) {
                try {
                    $rsa = new RSA();
                    $jwk = (array) $publicKey;

                    $rsa->loadKey(
                        [
                            'e' => new BigInteger(base64_decode($jwk['e']), 256),
                            'n' => new BigInteger(base64_decode(strtr($jwk['n'], '-_', '+/'), true), 256)
                        ]
                    );
                    $pem = $rsa->getPublicKey();

                    $payload = JWT::decode($id_token, $pem, ['RS256']);
                    $error = false;
                    break;
                } catch (\Exception $e) {
                    $error = $e->getMessage();
                    if ($e instanceof \Firebase\JWT\ExpiredException) {
                        break;
                    }
                }
            }
            if ($error) {
                throw new \Exception($error);
            }
        }

        $data = new Data\Collection($payload);

        if (!$data->exists('sub')) {
            throw new UnexpectedValueException('Missing token payload.');
        }

        $userProfile = new User\Profile();
        $userProfile->identifier = $data->get('sub');
        $userProfile->email = $data->get('email');
        $this->storeData('expires_at', $data->get('exp'));

        if (!empty($_REQUEST['user'])) {
            $objUser = json_decode($_REQUEST['user']);
            $user = new Data\Collection($objUser);
            if (!$user->isEmpty()) {
                $name = $user->get('name');
                $userProfile->firstName = $name->firstName;
                $userProfile->lastName = $name->lastName;
                $userProfile->displayName = join(' ', [ $userProfile->firstName, $userProfile->lastName ]);
            }
        }

        return $userProfile;
    }

    /**
     * @return string secret token
     */
    private function getSecret()
    {
        // Your 10-character Team ID
        if (!$team_id = $this->config->filter('keys')->get('team_id')) {
            throw new InvalidApplicationCredentialsException(
                'Missing parameter team_id: your team id is required to generate the JWS token.'
            );
        }

        // Your Services ID, e.g. com.aaronparecki.services
        if (!$client_id = $this->config->filter('keys')->get('id') ?: $this->config->filter('keys')->get('key')) {
            throw new InvalidApplicationCredentialsException(
                'Missing parameter id: your client id is required to generate the JWS token.'
            );
        }

        // Find the 10-char Key ID value from the portal
        if (!$key_id = $this->config->filter('keys')->get('key_id')) {
            throw new InvalidApplicationCredentialsException(
                'Missing parameter key_id: your key id is required to generate the JWS token.'
            );
        }

        // Find the 10-char Key ID value from the portal
        $key_content = $this->config->filter('keys')->get('key_content');

        // Save your private key from Apple in a file called `key.txt`
        if (!$key_content) {
            if (!$key_file = $this->config->filter('keys')->get('key_file')) {
                throw new InvalidApplicationCredentialsException(
                    'Missing parameter key_content or key_file: your key is required to generate the JWS token.'
                );
            }

            if (!file_exists($key_file)) {
                throw new InvalidApplicationCredentialsException(
                    "Your key file $key_file does not exist."
                );
            }

            $key_content = file_get_contents($key_file);
        }

        $data = [
            'iat' => time(),
            'exp' => time() + 86400 * 180,
            'iss' => $team_id,
            'aud' => 'https://appleid.apple.com',
            'sub' => $client_id
        ];

        $secret = JWT::encode($data, $key_content, 'ES256', $key_id);

        return $secret;
    }
}


text:
package quadrum.lib;

import java.util.ArrayList;

import com.google.common.collect.Lists;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

import quadrum.block.data.BlockData;
import quadrum.lib.data.Drop;

public class BlockStaticMethodHandler {

	public static ArrayList<ItemStack> getDrops(Block block, BlockData blockData, World world, int x, int y, int z, int metadata, int fortune) {
		ArrayList<ItemStack> stackList = Lists.newArrayList();
		if (blockData.dropsSelf) {
			int count = block.quantityDropped(metadata, fortune, world.rand);
			for (int i = 0; i < count; i++) {
				Item item = block.getItemDropped(metadata, world.rand, fortune);
				if (item != null)
					stackList.add(new ItemStack(item, 1, block.damageDropped(metadata)));
			}
		}
		for (Drop drop : blockData.drops)
			stackList.add(new ItemStack(drop.getDrop(), drop.getDropAmount(), drop.damage));
		return stackList;
	}
}


text:
import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';

class F7BlockFooter extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  render() {
    const props = this.props;
    const {
      className,
      id,
      style
    } = props;
    const classes = Utils.classNames(className, 'block-footer', Mixins.colorClasses(props));
    return React.createElement('div', {
      id: id,
      style: style,
      className: classes
    }, this.slots['default']);
  }

  get slots() {
    return __reactComponentSlots(this.props);
  }

}

__reactComponentSetProps(F7BlockFooter, Object.assign({
  id: [String, Number]
}, Mixins.colorProps));

F7BlockFooter.displayName = 'f7-block-footer';
export default F7BlockFooter;


text:
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module DatabaseStatements
      def initialize
        super
        reset_transaction
      end

      # Converts an arel AST to SQL
      def to_sql(arel, binds = [])
        if arel.respond_to?(:ast)
          binds = binds.dup
          visitor.accept(arel.ast) do
            quote(*binds.shift.reverse)
          end
        else
          arel
        end
      end

      # Returns an ActiveRecord::Result instance.
      def select_all(arel, name = nil, binds = [])
        arel, binds = binds_from_relation arel, binds
        select(to_sql(arel, binds), name, binds)
      end

      # Returns a record hash with the column names as keys and column values
      # as values.
      def select_one(arel, name = nil, binds = [])
        select_all(arel, name, binds).first
      end

      # Returns a single value from a record
      def select_value(arel, name = nil, binds = [])
        if result = select_one(arel, name, binds)
          result.values.first
        end
      end

      # Returns an array of the values of the first column in a select:
      #   select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
      def select_values(arel, name = nil)
        arel, binds = binds_from_relation arel, []
        select_rows(to_sql(arel, binds), name, binds).map(&:first)
      end

      # Returns an array of arrays containing the field values.
      # Order is the same as that returned by +columns+.
      def select_rows(sql, name = nil, binds = [])
      end
      undef_method :select_rows

      # Executes the SQL statement in the context of this connection.
      def execute(sql, name = nil)
      end
      undef_method :execute

      # Executes +sql+ statement in the context of this connection using
      # +binds+ as the bind substitutes. +name+ is logged along with
      # the executed +sql+ statement.
      def exec_query(sql, name = 'SQL', binds = [])
      end

      # Executes insert +sql+ statement in the context of this connection using
      # +binds+ as the bind substitutes. +name+ is logged along with
      # the executed +sql+ statement.
      def exec_insert(sql, name, binds, pk = nil, sequence_name = nil)
        exec_query(sql, name, binds)
      end

      # Executes delete +sql+ statement in the context of this connection using
      # +binds+ as the bind substitutes. +name+ is logged along with
      # the executed +sql+ statement.
      def exec_delete(sql, name, binds)
        exec_query(sql, name, binds)
      end

      # Executes update +sql+ statement in the context of this connection using
      # +binds+ as the bind substitutes. +name+ is logged along with
      # the executed +sql+ statement.
      def exec_update(sql, name, binds)
        exec_query(sql, name, binds)
      end

      # Returns the last auto-generated ID from the affected table.
      #
      # +id_value+ will be returned unless the value is nil, in
      # which case the database will attempt to calculate the last inserted
      # id and return that value.
      #
      # If the next id was calculated in advance (as in Oracle), it should be
      # passed in as +id_value+.
      def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = [])
        sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds)
        value      = exec_insert(sql, name, binds, pk, sequence_name)
        id_value || last_inserted_id(value)
      end

      # Executes the update statement and returns the number of rows affected.
      def update(arel, name = nil, binds = [])
        exec_update(to_sql(arel, binds), name, binds)
      end

      # Executes the delete statement and returns the number of rows affected.
      def delete(arel, name = nil, binds = [])
        exec_delete(to_sql(arel, binds), name, binds)
      end

      # Returns +true+ when the connection adapter supports prepared statement
      # caching, otherwise returns +false+
      def supports_statement_cache?
        false
      end

      # Runs the given block in a database transaction, and returns the result
      # of the block.
      #
      # == Nested transactions support
      #
      # Most databases don't support true nested transactions. At the time of
      # writing, the only database that supports true nested transactions that
      # we're aware of, is MS-SQL.
      #
      # In order to get around this problem, #transaction will emulate the effect
      # of nested transactions, by using savepoints:
      # http://dev.mysql.com/doc/refman/5.0/en/savepoint.html
      # Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8'
      # supports savepoints.
      #
      # It is safe to call this method if a database transaction is already open,
      # i.e. if #transaction is called within another #transaction block. In case
      # of a nested call, #transaction will behave as follows:
      #
      # - The block will be run without doing anything. All database statements
      #   that happen within the block are effectively appended to the already
      #   open database transaction.
      # - However, if +:requires_new+ is set, the block will be wrapped in a
      #   database savepoint acting as a sub-transaction.
      #
      # === Caveats
      #
      # MySQL doesn't support DDL transactions. If you perform a DDL operation,
      # then any created savepoints will be automatically released. For example,
      # if you've created a savepoint, then you execute a CREATE TABLE statement,
      # then the savepoint that was created will be automatically released.
      #
      # This means that, on MySQL, you shouldn't execute DDL operations inside
      # a #transaction call that you know might create a savepoint. Otherwise,
      # #transaction will raise exceptions when it tries to release the
      # already-automatically-released savepoints:
      #
      #   Model.connection.transaction do  # BEGIN
      #     Model.connection.transaction(requires_new: true) do  # CREATE SAVEPOINT active_record_1
      #       Model.connection.create_table(...)
      #       # active_record_1 now automatically released
      #     end  # RELEASE SAVEPOINT active_record_1  <--- BOOM! database error!
      #   end
      #
      # == Transaction isolation
      #
      # If your database supports setting the isolation level for a transaction, you can set
      # it like so:
      #
      #   Post.transaction(isolation: :serializable) do
      #     # ...
      #   end
      #
      # Valid isolation levels are:
      #
      # * <tt>:read_uncommitted</tt>
      # * <tt>:read_committed</tt>
      # * <tt>:repeatable_read</tt>
      # * <tt>:serializable</tt>
      #
      # You should consult the documentation for your database to understand the
      # semantics of these different levels:
      #
      # * http://www.postgresql.org/docs/9.1/static/transaction-iso.html
      # * https://dev.mysql.com/doc/refman/5.0/en/set-transaction.html
      #
      # An <tt>ActiveRecord::TransactionIsolationError</tt> will be raised if:
      #
      # * The adapter does not support setting the isolation level
      # * You are joining an existing open transaction
      # * You are creating a nested (savepoint) transaction
      #
      # The mysql, mysql2 and postgresql adapters support setting the transaction
      # isolation level. However, support is disabled for mysql versions below 5,
      # because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170]
      # which means the isolation level gets persisted outside the transaction.
      def transaction(options = {})
        options.assert_valid_keys :requires_new, :joinable, :isolation

        if !options[:requires_new] && current_transaction.joinable?
          if options[:isolation]
            raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction"
          end

          yield
        else
          within_new_transaction(options) { yield }
        end
      rescue ActiveRecord::Rollback
        # rollbacks are silently swallowed
      end

      def within_new_transaction(options = {}) #:nodoc:
        transaction = begin_transaction(options)
        yield
      rescue Exception => error
        rollback_transaction if transaction
        raise
      ensure
        begin
          commit_transaction unless error
        rescue Exception
          rollback_transaction
          raise
        end
      end

      def current_transaction #:nodoc:
        @transaction
      end

      def transaction_open?
        @transaction.open?
      end

      def begin_transaction(options = {}) #:nodoc:
        @transaction = @transaction.begin(options)
      end

      def commit_transaction #:nodoc:
        @transaction = @transaction.commit
      end

      def rollback_transaction #:nodoc:
        @transaction = @transaction.rollback
      end

      def reset_transaction #:nodoc:
        @transaction = ClosedTransaction.new(self)
      end

      # Register a record with the current transaction so that its after_commit and after_rollback callbacks
      # can be called.
      def add_transaction_record(record)
        @transaction.add_record(record)
      end

      # Begins the transaction (and turns off auto-committing).
      def begin_db_transaction()    end

      def transaction_isolation_levels
        {
          read_uncommitted: "READ UNCOMMITTED",
          read_committed:   "READ COMMITTED",
          repeatable_read:  "REPEATABLE READ",
          serializable:     "SERIALIZABLE"
        }
      end

      # Begins the transaction with the isolation level set. Raises an error by
      # default; adapters that support setting the isolation level should implement
      # this method.
      def begin_isolated_db_transaction(isolation)
        raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation"
      end

      # Commits the transaction (and turns on auto-committing).
      def commit_db_transaction()   end

      # Rolls back the transaction (and turns on auto-committing). Must be
      # done if the transaction block raises an exception or returns false.
      def rollback_db_transaction() end

      def default_sequence_name(table, column)
        nil
      end

      # Set the sequence to the max value of the table's column.
      def reset_sequence!(table, column, sequence = nil)
        # Do nothing by default. Implement for PostgreSQL, Oracle, ...
      end

      # Inserts the given fixture into the table. Overridden in adapters that require
      # something beyond a simple insert (eg. Oracle).
      def insert_fixture(fixture, table_name)
        columns = schema_cache.columns_hash(table_name)

        key_list   = []
        value_list = fixture.map do |name, value|
          key_list << quote_column_name(name)
          quote(value, columns[name])
        end

        execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", 'Fixture Insert'
      end

      def empty_insert_statement_value
        "DEFAULT VALUES"
      end

      def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key)
        "WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})"
      end

      # Sanitizes the given LIMIT parameter in order to prevent SQL injection.
      #
      # The +limit+ may be anything that can evaluate to a string via #to_s. It
      # should look like an integer, or a comma-delimited list of integers, or
      # an Arel SQL literal.
      #
      # Returns Integer and Arel::Nodes::SqlLiteral limits as is.
      # Returns the sanitized limit parameter, either as an integer, or as a
      # string which contains a comma-delimited list of integers.
      def sanitize_limit(limit)
        if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral)
          limit
        elsif limit.to_s.include?(',')
          Arel.sql limit.to_s.split(',').map{ |i| Integer(i) }.join(',')
        else
          Integer(limit)
        end
      end

      # The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
      # on mysql (even when aliasing the tables), but mysql allows using JOIN directly in
      # an UPDATE statement, so in the mysql adapters we redefine this to do that.
      def join_to_update(update, select) #:nodoc:
        key = update.key
        subselect = subquery_for(key, select)

        update.where key.in(subselect)
      end

      def join_to_delete(delete, select, key) #:nodoc:
        subselect = subquery_for(key, select)

        delete.where key.in(subselect)
      end

      protected

        # Returns a subquery for the given key using the join information.
        def subquery_for(key, select)
          subselect = select.clone
          subselect.projections = [key]
          subselect
        end

        # Returns an ActiveRecord::Result instance.
        def select(sql, name = nil, binds = [])
        end
        undef_method :select

        # Returns the last auto-generated ID from the affected table.
        def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
          execute(sql, name)
          id_value
        end

        # Executes the update statement and returns the number of rows affected.
        def update_sql(sql, name = nil)
          execute(sql, name)
        end

        # Executes the delete statement and returns the number of rows affected.
        def delete_sql(sql, name = nil)
          update_sql(sql, name)
        end

        def sql_for_insert(sql, pk, id_value, sequence_name, binds)
          [sql, binds]
        end

        def last_inserted_id(result)
          row = result.rows.first
          row && row.first
        end

        def binds_from_relation(relation, binds)
          if relation.is_a?(Relation) && binds.blank?
            relation, binds = relation.arel, relation.bind_values
          end
          [relation, binds]
        end
    end
  end
end


text:
package es.currexify.server.model;

import java.io.Serializable;

import javax.persistence.*;

import com.google.appengine.api.datastore.Key;

@Entity
@Table(name="EURO_BUDGET_MODEL")
public class CurrencyBudgetModel implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="ID")
	private Key key;
	@Column(name="CARD_N")
	private String cardN;
	@Column(name="CURRENCY")
	private String currency;
	@Column(name="BUDGET")
	private double budget;
	@Column(name="BLOCKED")
	private double blocked;

	public CurrencyBudgetModel(String cardN, String currency, double budget) {
		this.cardN = cardN;
		this.currency = currency;
		this.budget = budget;
		this.blocked = 0.0;
	}
	public Key getId() {
		return key;
	}
	public void setId(Key key) {
		this.key = key;
	}
	public String getCardN() {
		return cardN;
	}
	public void setCardN(String cardN) {
		this.cardN = cardN;
	}
	public String getCurrency() {
		return currency;
	}
	public void setCurrency(String currency) {
		this.currency = currency;
	}
	public double getBudget() {
		return budget;
	}
	public void setBudget(double budget) {
		this.budget = budget;
	}
	public double getBlocked() {
		return blocked;
	}
	public void setBlocked(double blocked) {
		this.blocked = blocked;
	}
}


text:
import numpy
import six

import chainer
from chainer import cuda
from chainer import function_node
from chainer.utils import type_check

class EmbedIDFunction(function_node.FunctionNode):

    def __init__(self, ignore_label=None):
        self.ignore_label = ignore_label

    def check_type_forward(self, in_types):
        type_check.expect(in_types.size() == 2)
        x_type, w_type = in_types
        type_check.expect(
            x_type.dtype == numpy.int32,
            x_type.ndim >= 1,
        )
        type_check.expect(
            w_type.dtype == numpy.float32,
            w_type.ndim == 2
        )

    def forward(self, inputs):
        self.retain_inputs((0,))
        x, W = inputs
        self._w_shape = W.shape

        if not type_check.same_types(*inputs):
            raise ValueError('numpy and cupy must not be used together\n'
                             'type(W): {0}, type(x): {1}'
                             .format(type(W), type(x)))

        xp = cuda.get_array_module(*inputs)
        if chainer.is_debug():
            valid_x = xp.logical_and(0 <= x, x < len(W))
            if self.ignore_label is not None:
                valid_x = xp.logical_or(valid_x, x == self.ignore_label)
            if not valid_x.all():
                raise ValueError('Each not ignored `x` value need to satisfy'
                                 '`0 <= x < len(W)`')

        if self.ignore_label is not None:
            mask = (x == self.ignore_label)
            return xp.where(
                mask[..., None], 0, W.take(xp.where(mask, 0, x), axis=0)),

        return W.take(x, axis=0),

    def backward(self, indexes, grad_outputs):
        inputs = self.get_retained_inputs()
        gW = EmbedIDGrad(
            self._w_shape, self.ignore_label).apply(inputs + grad_outputs)[0]
        return None, gW

class EmbedIDGrad(function_node.FunctionNode):

    def __init__(self, w_shape, ignore_label=None):
        self.w_shape = w_shape
        self.ignore_label = ignore_label

    def forward(self, inputs):
        self.retain_inputs((0,))
        xp = cuda.get_array_module(*inputs)
        x, gy = inputs
        self._gy_shape = gy.shape
        gW = xp.zeros(self.w_shape, dtype=gy.dtype)

        if xp is numpy:
            # It is equivalent to `numpy.add.at(gW, x, gy)` but ufunc.at is
            # too slow.
            for ix, igy in six.moves.zip(x.ravel(),
                                         gy.reshape(x.size, -1)):
                if ix == self.ignore_label:
                    continue
                gW[ix] += igy
        else:
            if self.ignore_label is None:
                cuda.elementwise(
                    'T gy, int32 x, int32 n_out', 'raw T gW',
                    'int w_ind[] = {x, i % n_out}; atomicAdd(&gW[w_ind], gy)',
                    'embed_id_bwd')(
                        gy, xp.expand_dims(x, -1), gW.shape[1], gW)
            else:
                cuda.elementwise(
                    'T gy, int32 x, int32 n_out, int32 ignore', 'raw T gW',
                    '''
                    if (x != ignore) {
                      int w_ind[] = {x, i % n_out};
                      atomicAdd(&gW[w_ind], gy);
                    }
                    ''',
                    'embed_id_bwd_ignore_label')(
                        gy, xp.expand_dims(x, -1), gW.shape[1],
                        self.ignore_label, gW)
        return gW,

    def backward(self, indexes, grads):
        xp = cuda.get_array_module(*grads)
        x = self.get_retained_inputs()[0].data
        ggW = grads[0]

        if self.ignore_label is not None:
            mask = x == self.ignore_label
            # To prevent index out of bounds, we need to check if ignore_label
            # is inside of W.
            if not (0 <= self.ignore_label < self.w_shape[1]):
                x = xp.where(mask, 0, x)

        ggy = ggW[x]

        if self.ignore_label is not None:
            mask, zero, _ = xp.broadcast_arrays(
                mask[..., None], xp.zeros((), 'f'), ggy.data)
            ggy = chainer.functions.where(mask, zero, ggy)
        return None, ggy

def embed_id(x, W, ignore_label=None):
    """Efficient linear function for one-hot input.

    This function implements so called *word embeddings*. It takes two
    arguments: a set of IDs (words) ``x`` in :math:`B` dimensional integer
    vector, and a set of all ID (word) embeddings ``W`` in :math:`V \\times d`
    float32 matrix. It outputs :math:`B \\times d` matrix whose ``i``-th
    column is the ``x[i]``-th column of ``W``.

    This function is only differentiable on the input ``W``.

    Args:
        x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
        :class:`cupy.ndarray`):
            Batch vectors of IDs. Each element must be :class:`numpy.int32`.
        W (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \
        :class:`cupy.ndarray`):
            Distributed representation of each ID (a.k.a. word embeddings).
        ignore_label (:class:`int` or :class:`None`):
            If ``ignore_label`` is an int value, ``i``-th column of return
            value is filled with ``0``.

    Returns:
        ~chainer.Variable: Output variable.

    .. seealso:: :class:`~chainer.links.EmbedID`

    .. admonition:: Example

        >>> x = np.array([2, 1]).astype('i')
        >>> x
        array([2, 1], dtype=int32)
        >>> W = np.array([[0, 0, 0],
        ...               [1, 1, 1],
        ...               [2, 2, 2]]).astype('f')
        >>> W
        array([[ 0.,  0.,  0.],
               [ 1.,  1.,  1.],
               [ 2.,  2.,  2.]], dtype=float32)
        >>> F.embed_id(x, W).data
        array([[ 2.,  2.,  2.],
               [ 1.,  1.,  1.]], dtype=float32)
        >>> F.embed_id(x, W, ignore_label=1).data
        array([[ 2.,  2.,  2.],
               [ 0.,  0.,  0.]], dtype=float32)

    """
    return EmbedIDFunction(ignore_label=ignore_label).apply((x, W))[0]


text:
package com.sohu.jafka.common.annotations;

/**
 * @author adyliu (imxylz@gmail.com)
 * @since 1.0
 */
public @interface ServerSide {

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.09 at 09:22:32 PM IST
//

package com.pacificmetrics.ims.apip.qti.item;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for EmptyPrimitiveType.Type complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="EmptyPrimitiveType.Type">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmptyPrimitiveType.Type")
@XmlSeeAlso({
    OutcomeMinMaxType.class,
    NumberType.class,
    MapResponseType.class,
    ItemSessionControlType.class,
    AssessmentStimulusRef.class,
    MapEntry.class,
    AreaMapEntry.class,
    MatchTableEntry.class,
    InterpolationTableEntry.class,
    Stylesheet.class,
    AssociableHotspot.class,
    Col.class,
    Hr.class,
    EndAttemptInteraction.class,
    Gap.class,
    TextEntryInteraction.class,
    Br.class,
    Img.class,
    Param.class,
    PrintedVariable.class,
    TestVariables.class,
    Variable.class,
    RandomFloat.class,
    RandomInteger.class,
    Default.class,
    Correct.class,
    MathConstant.class,
    HotspotChoice.class
})
public class EmptyPrimitiveTypeType {

}


text:
<?php

namespace Jme\ArticleBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', 'text')
                ->add('brief', 'textarea')
                ->add('content', 'textarea')
                ->add('published', 'checkbox')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Jme\ArticleBundle\Entity\Article',
        ));
    }

    public function getName()
    {
        return 'article';
    }
}


text:
import pandas as pd

Z = pd.read_csv('32.76mM.txt', header = None)
ppm = pd.read_csv('ppm.txt', header = None)


text:
var Promise = require('bluebird');

/**
 * Backup instance constructor
 * @prototype
 * @class Backup
 */
function Backup(instance) {
  this.vultr = instance || {};
  this.service = 'backup';
}

/**
 * Retrieve list of Backup's available
 * @return {Promise}            Object with data
 */
Backup.prototype.list = function list() {
  return this.vultr.communicate(this.service, 'list');
};

module.exports = Backup;


text:
from collections import namedtuple

from . import common, scraping

PairInfoBase = namedtuple("PairInfoBase",
    ["decimal_places", "min_price", "max_price", "min_amount", "max_amount", "min_total", "hidden", "fee"])

class PairInfo(PairInfoBase):
    def format_currency(self, value):
        return common.formatCurrencyDigits(value, self.decimal_places)

    def truncate_amount(self, value):
        return common.truncateAmountDigits(value, self.decimal_places)

    def validate_order(self, trade_type, rate, amount):
        if trade_type not in ("buy", "sell"):
            raise common.InvalidTradeTypeException("Unrecognized trade type: %r" % trade_type)

        if rate < self.min_price or rate > self.max_price:
            raise common.InvalidTradePriceException(
                "Allowed price range is from %f to %f" % (self.min_price, self.max_price))

        formatted_min_amount = self.format_currency(self.min_amount)
        if amount < self.min_amount:
            msg = "Trade amount %r too small; should be >= %s" % \
                  (amount, formatted_min_amount)
            raise common.InvalidTradeAmountException(msg)

class APIInfo(object):
    def __init__(self, connection):
        self.connection = connection
        self.currencies = None
        self.pair_names = None
        self.pairs = None
        self.server_time = None

        self._scrape_pair_index = 0

        self.update()

    def update(self):
        info = self.connection.makeJSONRequest("/api/3/info")
        if type(info) is not dict:
            raise TypeError("The response is not a dict.")

        self.server_time = info.get(u"server_time")

        pairs = info.get(u"pairs")
        if type(pairs) is not dict:
            raise TypeError("The pairs item is not a dict.")

        self.pairs = {}
        currencies = set()
        for name, data in pairs.items():
            self.pairs[name] = PairInfo(**data)
            a, b = name.split(u"_")
            currencies.add(a)
            currencies.add(b)

        self.currencies = list(currencies)
        self.currencies.sort()

        self.pair_names = list(self.pairs.keys())
        self.pair_names.sort()

    def validate_pair(self, pair):
        if pair not in self.pair_names:
            if "_" in pair:
                a, b = pair.split("_", 1)
                swapped_pair = "%s_%s" % (b, a)
                if swapped_pair in self.pair_names:
                    msg = "Unrecognized pair: %r (did you mean %s?)"
                    msg = msg % (pair, swapped_pair)
                    raise common.InvalidTradePairException(msg)
            raise common.InvalidTradePairException("Unrecognized pair: %r" % pair)

    def get_pair_info(self, pair):
        self.validate_pair(pair)
        return self.pairs[pair]

    def validate_order(self, pair, trade_type, rate, amount):
        self.validate_pair(pair)

        pair_info = self.pairs[pair]
        pair_info.validate_order(trade_type, rate, amount)

    def format_currency(self, pair, amount):
        self.validate_pair(pair)

        pair_info = self.pairs[pair]
        return pair_info.format_currency(amount)

    def scrapeMainPage(self):
        parser = scraping.BTCEScraper()

        # Rotate through the currency pairs between chat requests so that the
        # chat pane contents will update more often than every few minutes.
        self._scrape_pair_index = (self._scrape_pair_index + 1) % len(self.pair_names)
        current_pair = self.pair_names[self._scrape_pair_index]

        response = self.connection.makeRequest('/exchange/%s' % current_pair, with_cookie=True)

        parser.feed(parser.unescape(response.decode('utf-8')))
        parser.close()

        r = scraping.ScraperResults()
        r.messages = parser.messages
        r.devOnline = parser.devOnline
        r.supportOnline = parser.supportOnline
        r.adminOnline = parser.adminOnline

        return r

Ticker = namedtuple("Ticker",
    ["high", "low", "avg", "vol", "vol_cur", "last", "buy", "sell", "updated"])

def getTicker(pair, connection=None, info=None):
    """Retrieve the ticker for the given pair.  Returns a Ticker instance."""

    if info is not None:
        info.validate_pair(pair)

    if connection is None:
        connection = common.Connection()

    response = connection.makeJSONRequest("/api/3/ticker/%s" % pair)

    if type(response) is not dict:
        raise TypeError("The response is a %r, not a dict." % type(response))
    elif u'error' in response:
        raise common.APIResponseError("There is an error \"%s\" while obtaining ticker %s" % (response['error'], pair))
    else:
        ticker = Ticker(**response[pair])

    return ticker

def getDepth(pair, connection=None, info=None, limit=None):
    """Retrieve the depth for the given pair.  Returns a tuple (asks, bids);
    each of these is a list of (price, volume) tuples."""

    if info is not None:
        info.validate_pair(pair)

    if connection is None:
        connection = common.Connection()

    url = "/api/3/depth/%s%s" % (pair, "?limit=%d" % limit if limit else "")
    response = connection.makeJSONRequest(url)
    if type(response) is not dict:
        raise TypeError("The response is not a dict.")

    if u"error" in response:
        raise common.APIResponseError("There is an error while obtaining depth for '%s' pair: '%s'" % (pair, response['error']))

    depth = response.get(pair)
    if type(depth) is not dict:
        raise TypeError("The pair depth is not a dict.")

    asks = depth.get(u'asks')
    if type(asks) is not list:
        raise TypeError("The response does not contain an asks list.")

    bids = depth.get(u'bids')
    if type(bids) is not list:
        raise TypeError("The response does not contain a bids list.")

    return asks, bids

Trade = namedtuple("Trade", ['pair', 'type', 'price', 'tid', 'amount', 'timestamp'])

def getTradeHistory(pair, connection=None, info=None, count=None):
    """Retrieve the trade history for the given pair.  Returns a list of
    Trade instances.  If count is not None, it should be an integer, and
    specifies the number of items from the trade history that will be
    processed and returned."""

    if info is not None:
        info.validate_pair(pair)

    if connection is None:
        connection = common.Connection()

    response = connection.makeJSONRequest("/api/3/trades/%s" % pair)
    if type(response) is not dict:
        raise TypeError("The response is not a dict.")

    history = response.get(pair)
    if type(history) is not list:
        raise TypeError("The response is a %r, not a list." % type(history))

    result = []

    # Limit the number of items returned if requested.
    if count is not None:
        history = history[:count]

    for h in history:
        h["pair"] = pair
        t = Trade(**h)
        result.append(t)
    return result


text:
var Http = require( 'http' ),
    Router = require( 'router' ),
    server,
    router;

router = new Router( );

server = Http.createServer( function( request, response ) {
    router( request, response, function( error ) {
        if( !error ) {
            response.writeHead( 404 );
        } else {
            //Handle errors
            console.log( error.message, error.stack );
            response.writeHead( 400 );
        }
        response.end( '\n' );
    });
});

var BodyParser = require( 'body-parser' );
router.use( BodyParser.text( ) );

var counter = 0,
    messages = { };

function createMessage( request, response ) {
    var id = counter += 1,
        message = request.body;

    console.log( 'Create message', id, message );
    messages[ id ] = message;
    response.writeHead( 201, {
        'Content-Type': 'text/plain',
        'Location': '/message/' + id
    });
    response.end( message );
}
router.post( '/message', createMessage );

function readMessage( request, response ) {
    var id = request.params.id,
        message = messages[ id ];

    if( typeof message !== 'string' ) {
        console.log( 'Message not found', id );

        response.writeHead( 404 );
        response.end( '\n' );
        return;
    }

    console.log( 'Read message', id, message );

    response.writeHead( 200, {
        'Content-Type': 'text/plain'
    });
    response.end( message );
}
router.get( '/message/:id', readMessage );

function deleteMessage( request, response ) {
    var id = request.params.id,
        message = messages[ id ];

    if( typeof message !== 'string' ) {
        console.log( 'Message not found', id );

        response.writeHead( 404 );
        response.end( '\n' );
        return;
    }

    console.log( 'Delete message', id );

    messages[ id ] = undefined;

    response.writeHead( 204, { } );

    response.end( '' );
}

router.delete( '/message/:id', deleteMessage );

server.listen( 8080, function( ) {
    console.log( 'Listening on port 8080' );
});


text:
module PS
  API_URL="http://census.soe.com/get/ps2:v2/"

  EXTRA_ITEMS=[
    "1", # Vehicle decoration
    "13", # Title
    "17", # camo
    "27", # Weapon attachment
    "28", # Boost
    "33", # Vehicle skill
    "36", # Class skill
    "38", # Vehicle decoration
    "39", # Character decoration
  ]

  class Character

    attr_reader :id, :name, :battle_rank, :aerospace, :infantry, :mechanized, :items, :online

    def initialize(opts={})
      @id = opts["character_id"]
      @name = opts["name"]["first"]
      @online = opts["online_status"] != "0"
      @battle_rank = opts["battle_rank"]["value"]
      @aerospace = opts["currency"]["aerospace"]
      @infantry = opts["currency"]["infantry"]
      @mechanized = opts["currency"]["mechanized"]
      @items = opts["items"].map{|i| Item.new(i)}.select{|i| !EXTRA_ITEMS.include?(i.type_id)}
    end
  end

  class Item

    attr_reader :id, :type_id, :name

    def initialize(opts={})
      @id = opts["item_id"]
      @type_id = opts["item_type_id"]
      @name = opts["name"]["en"] rescue "(unknown)"
    end
  end

  def self.get_character_id_by_name(name)
    response = HTTParty.get "#{API_URL}/character_name/?name.first_lower=#{name.downcase}&c:show=character_id"
    response.parsed_response["character_name_list"].first["character_id"]
  end

  def self.get_characters_by_name(names)
    get_characters_by_id get_character_ids_by_name(names)
  end

  def self.get_characters_by_ids(ids)
    response = HTTParty.get "#{API_URL}/character/?character_id=#{ids.join(",")}&c:resolve=currency,online_status,item_full"
    response.parsed_response["character_list"].map{|u| Character.new(u)}
  end

  def self.get_servers
    response = HTTParty.get "#{API_URL}/world/?c:limit=100"
    response.parsed_response["world_list"].map{|world| world["name"]["en"]}
  end

  def self.get_friends_of(ids)
    return [] if ids.empty?
    response = HTTParty.get "#{API_URL}/characters_friend/?character_id=#{ids.join(",")}&c:resolve=character_name"
    response.parsed_response["characters_friend_list"].map{|u| u["friend_list"].map{|f| f["name"]["first"] rescue nil}}.flatten.uniq.compact
  end
end


text:
Anagrams

* http://codekata.com/kata/kata06-anagrams/


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Sesdep extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Jakarta");

		$this->load->model('M_kebijakan');
		$this->load->model('M_agenda');
		if (empty($this->session->userdata('session'))) {
			redirect('login');
		}
	}
	public function index($value='')
	{
		//Load view
		$result['data'] = $this->M_agenda->getByAsdep('sesdep');
		//print_r($result['data']);die();
		$this->load->view('frontend/header');
		$this->load->view('frontend/list_agenda',$result);
		$this->load->view('frontend/footerf');
	}
	public function edit($value='')
	{
		$result['data'] = $this->M_agenda->getId($value);
		$this->load->view('frontend/header');
		$this->load->view('frontend/edit_sesdep',$result);
		$this->load->view('frontend/footerf');
	}
	public function update($value='')
	{
		$data = array('tglPencairan'=>substr($this->input->post('tglPencairan'), 6,4)."-".substr($this->input->post('tglPencairan'), 0,2)."-".substr($this->input->post('tglPencairan'), 3,2),'tglSpd'=>substr($this->input->post('tglSpd'), 6,4)."-".substr($this->input->post('tglSpd'), 0,2)."-".substr($this->input->post('tglSpd'), 3,2),'tglPengajuanSpd'=>substr($this->input->post('tglPengajuanSpd'), 6,4)."-".substr($this->input->post('tglPengajuanSpd'), 0,2)."-".substr($this->input->post('tglPengajuanSpd'), 3,2));
		//print_r($data);die();
		$this->M_agenda->updateId($data,$value);
		redirect('agenda');
	}

}


text:
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.

/* Example script to import a reddit dataset and run an example */

var dataset_config = {
    'type'    : 'sparse.mutable',
    'id'      : 'reddit_dataset',
};

var dataset = mldb.createDataset(dataset_config)
plugin.log("Reddit data loader created dataset")

var dataset_address = 'file://mldb/mldb_test_data/reddit.csv.zst'
var now = new Date();

var stream = mldb.openStream(dataset_address);

var numLines = 10000;

var lineNum = 0;
while (!stream.eof() && lineNum < numLines) {
    ++lineNum;
    var line = stream.readLine();
    var fields = line.split(',');
    var tuples = [];
    for (var i = 1;  i < fields.length;  ++i) {
        tuples.push([fields[i], '1', now]);
    }

    dataset.recordRow(fields[0], tuples);
}

plugin.log("Committing dataset")
dataset.commit()

function checkSuccess(response)
{
    if (response.responseCode > 200 && response.responseCode < 400)
        return;
    throw "Error: " + JSON.stringify(response);
}

function checkOutput(title, response)
{
    plugin.log(title, response);
    checkSuccess(response);
}

// Create and train an SVD procedure.  It gets 1/4 of the data

var trainSvd = true;

if (trainSvd) {

    var svdConfig = {
        type: "svd.train",
        params: {
            numSingularValues: 200,
            trainingData: { from : {"id": "reddit_dataset" },
            select: "* EXCLUDING (adventuretime)"
                             },
            columnOutputDataset: { "id": "svd_output", type: "embedding" },
            rowOutputDataset: { "id": "svd_embedding", type: "embedding" }
        }
    };

    checkOutput("svd procedure", mldb.put("/v1/procedures/reddit_svd", svdConfig));
    checkOutput("svd training", mldb.put("/v1/procedures/reddit_svd/runs/1", {}));
}

// Merge the two datasets to get the SVD

var mergedConfig = {
    type: "merged",
    id: "reddit_embeddings",
    params: {
        "datasets": [
            { "id": "reddit_dataset" },
            { "id": "svd_embedding" }
        ]
    }
};

var mergedDataset = mldb.createDataset(mergedConfig);

plugin.log(mldb.perform("GET", "/v1/datasets/reddit_embeddings"));

plugin.log(mldb.query("select count(1) from reddit_embeddings where adventuretime is not null group by 1 limit 10"));

var trainClassifier = true;

if (trainClassifier) {

    var trainClassifierProcedureConfig = {
        id: "reddit_cls_train",
        type: "classifier.train",
        params: {
            trainingData: {
                select: '{embedding*} as features, adventuretime IS NOT NULL as label',
                where: "rowHash() % 4 = 1",
                from : "reddit_embeddings"
            },
            configuration: {
                bbdt: {
                    type: "bagging",
                    verbosity: 3,
                    weak_learner:  {
                        type: "boosting",
                        verbosity: 3,
                        weak_learner: {
                            type: "decision_tree",
                            max_depth: 3,
                            verbosity: 0,
                            update_alg: "gentle",
                            random_feature_propn: 0.5,
                        },
                        min_iter: 5,
                        max_iter: 30,
                    },
                    num_bags: 5,
                },
                glz: {
                    type: "glz",
                    verbosity: 3,
                    normalize: true,
                    regularization: 'l2'
                }
            },
            algorithm: "glz",
            modelFileUrl: "file://tmp/reddit.cls",
            equalizationFactor: 1.0
        }
    };

    checkOutput("cls procedure", mldb.put("/v1/procedures/reddit_cls_train", trainClassifierProcedureConfig));
    checkOutput("cls training", mldb.put("/v1/procedures/reddit_cls_train/runs/1", {}));
}

var classifierFunctionConfig = {
    id: "classifier",
    type: "classifier",
    params: {
        modelFileUrl: "file://tmp/reddit.cls"
    }
};

checkOutput("classifier", mldb.put("/v1/functions/classifier", classifierFunctionConfig));

var trainProbabilizer = true;

if (trainProbabilizer) {

    var trainProbabilizerProcedureConfig = {
        id: "reddit_prob_train",
        type: "probabilizer.train",
        params: {
            trainingData: {
                select: "classifier({{ * EXCLUDING (adventuretime)} AS features})[score] as score, adventuretime IS NOT NULL as label",
                where: "rowHash() % 4 = 2",
                from: { id: "reddit_embeddings" },
            },
            modelFileUrl: "file://tmp/reddit_probabilizer.json",
            functionName: "probabilizer"
       }
    };

    checkOutput("prob-train procedure", mldb.put("/v1/procedures/reddit_prob_train", trainProbabilizerProcedureConfig));
    checkOutput("prob-train training", mldb.put("/v1/procedures/reddit_prob_train/runs/1", {}));
}

var testClassifier = true;

if (testClassifier) {
    var testClassifierProcedureConfig = {
        id: "accuracy",
        type: "classifier.test",
        params: {
            testingData: "select adventuretime IS NOT NULL as label, \
                          probabilizer(classifier({{ * EXCLUDING (adventuretime) } AS features}))[prob] as score \
                          from reddit_embeddings where rowHash() % 4 = 3",
            outputDataset: { id: "cls_test_results", type: "sparse.mutable" }
        }
    };

    checkOutput("accuracy procedure", mldb.put("/v1/procedures/accuracy", testClassifierProcedureConfig));
    checkOutput("accuracy training", mldb.put("/v1/procedures/accuracy/runs/1", {}));
}

plugin.log(mldb.query("select * from cls_test_results order by index limit 100"));

// The output of the last line of the script is returned as the result of the script,
// just like in Javscript eval
"success"


text:
package org.altbeacon.beacon.service;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import android.os.Build;

import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.logging.LogManager;
import org.altbeacon.beacon.logging.Loggers;
import org.altbeacon.beacon.service.scanner.CycledLeScanCallback;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.lang.reflect.Constructor;
import java.util.concurrent.ThreadPoolExecutor;

import static org.junit.Assert.assertEquals;

/**
 * Created by dyoung on 7/1/15.
 */
@RunWith(RobolectricTestRunner.class)
@Config(emulateSdk = 18)
public class BeaconServiceTest {

    @Before
    public void before() {
        org.robolectric.shadows.ShadowLog.stream = System.err;
        LogManager.setLogger(Loggers.verboseLogger());
        LogManager.setVerboseLoggingEnabled(true);
        BeaconManager.setsManifestCheckingDisabled(true);
    }

    /**
     * This test verifies that processing a beacon in a scan (which starts its own thread) does not
     * affect the size of the available threads in the main Android AsyncTask.THREAD_POOL_EXECUTOR
     * @throws Exception
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Test
    public void beaconScanCallbackTest() throws Exception {
        BeaconService beaconService = new BeaconService();
        beaconService.onCreate();
        CycledLeScanCallback callback = beaconService.mCycledLeScanCallback;

        ThreadPoolExecutor executor = (ThreadPoolExecutor) AsyncTask.THREAD_POOL_EXECUTOR;
        int activeThreadCountBeforeScan = executor.getActiveCount();

        byte[] scanRecord = new byte[1];
        callback.onLeScan(null, -59, scanRecord);

        int activeThreadCountAfterScan = executor.getActiveCount();

        assertEquals("The size of the Android thread pool should be unchanged by beacon scanning",
                activeThreadCountBeforeScan, activeThreadCountAfterScan);

        // Need to sleep here until the thread in the above method completes, otherwise an exception
        // is thrown.  Maybe we don't care about this exception, so we could remove this.
        Thread.sleep(100);
    }
}


text:
package org.artifactory.webapp.wicket.page.build.actionable;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.html.panel.Panel;
import org.artifactory.api.security.AuthorizationService;
import org.artifactory.build.BuildRun;
import org.artifactory.webapp.actionable.ActionableItemBase;
import org.artifactory.webapp.wicket.page.browse.treebrowser.tabs.build.action.ShowInCiServerAction;
import org.artifactory.webapp.wicket.page.build.action.DeleteBuildAction;
import org.artifactory.webapp.wicket.util.ItemCssClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * The build list actionable item
 *
 * @author Noam Y. Tenne
 */
public class BuildActionableItem extends ActionableItemBase {

    @SuppressWarnings("UnusedDeclaration")
    private static final Logger log = LoggerFactory.getLogger(BuildActionableItem.class);

    private BuildRun buildRun;

    /**
     * Main constructor
     *
     * @param buildRun Basic build info to act up-on
     */
    public BuildActionableItem(BuildRun buildRun) {
        this.buildRun = buildRun;
        String ciServerUrl = buildRun.getCiUrl();
        if (StringUtils.isNotBlank(ciServerUrl)) {
            getActions().add(new ShowInCiServerAction(ciServerUrl));
        }
    }

    @Override
    public Panel newItemDetailsPanel(String id) {
        return null;
    }

    @Override
    public String getDisplayName() {
        return buildRun.getName();
    }

    @Override
    public String getCssClass() {
        return ItemCssClass.doc.getCssClass();
    }

    @Override
    public void filterActions(AuthorizationService authService) {
        if (authService.isAdmin()) {
            getActions().add(new DeleteBuildAction(buildRun));
        }
    }

    /**
     * Returns the started time of the build
     *
     * @return Selected build start time
     */
    public String getStarted() {
        return buildRun.getStarted();
    }

    /**
     * Returns the started time of the build as a date
     *
     * @return Selected build start time as date
     */
    public Date getStartedDate() {
        return buildRun.getStartedDate();
    }

    /**
     * Returns the number of the selected build
     *
     * @return Selected build number
     */
    public String getBuildNumber() {
        return buildRun.getNumber();
    }

    /**
     * Returns the latest release status of the build
     *
     * @return Build latest release status if exists, null if not
     */
    public String getLastReleaseStatus() {
        return buildRun.getReleaseStatus();
    }
}


text:
<?php
/**
 * ISO 639-2T Test
 *
 * @author Wenzel Pünter <wenzel@phelix.me>
 * @version 1.0.0
 * @package Lingua\Test
*/
namespace Lingua\Test\Code\Language;

use PHPUnit\Framework\TestCase;
use Lingua\Code\Language\ISO639Part2T;
use Lingua\Exception\FileNotFound;
use ReflectionClass;

/**
 * ISO 639-2T Test
 *
 * @coversDefaultClass Lingua\Code\Language\ISO639Part2T
*/
class ISO639Part2TTest extends TestCase
{
    /**
     * Test Code Validation
     *
     * @covers ::validate
    */
    public function testCodeValidation()
    {
        $code = new ISO639Part2T();
        $this->assertTrue($code->validate('bod'));
        $this->assertFalse($code->validate('tib'));
    }

    /**
     * Test Uppercase Code Validation
     *
     * @covers ::validate
    */
    public function testUppercaseCodeValidation()
    {
        $code = new ISO639Part2T();
        $this->assertTrue($code->validate('SWE'));
        $this->assertTrue($code->validate('rUs'));
    }

    /**
     * Test Code Translation
     *
     * @covers ::translate
    */
    public function testCodeTranslation()
    {
        $code = new ISO639Part2T();
        $this->assertSame($code->translate('bod'), 'bod');
        $this->assertNull($code->translate('xxxx'));
        $this->assertSame($code->translate('iNd'), 'ind');
    }

    /**
     * Test Code Unification
     *
     * @covers ::unify
    */
    public function testCodeUnification()
    {
        $code = new ISO639Part2T();
        $this->assertSame($code->unify('eng'), 'eng');
        $this->assertNull($code->unify('xxxx'));
        $this->assertSame($code->unify('dEu'), 'deu');
    }

    /**
     * Test Data Unavailable Exception
     *
     * @covers ::validate
    */
    public function testDataUnavailableException()
    {
        $registryFile = __DIR__.'/../../../'.ISO639Part2T::FILE;
        $tempFile = sys_get_temp_dir().'/'.uniqid();

        //Clear cache, move base data away
        rename($registryFile, $tempFile);
        $class = new ReflectionClass('Lingua\Code\Language\ISO639Part2T');
        $property = $class->getProperty('listCache');
        $property->setAccessible(true);
        $property->setValue(null);

        $exceptionThrown = false;
        try {
            $code = new ISO639Part2T();
            $code->validate('deu');
        } catch (FileNotFound $e) {
            $exceptionThrown = true;
        }

        rename($tempFile, $registryFile);
        $this->assertTrue($exceptionThrown);
    }

    /**
     * Test Translate Data Unavailable Exception
     *
     * @covers ::translate
    */
    public function testTranslateDataUnavailableException()
    {
        $registryFile = __DIR__.'/../../../'.ISO639Part2T::TRANSLATE_FILE;
        $tempFile = sys_get_temp_dir().'/'.uniqid();

        //Clear cache, move base data away
        rename($registryFile, $tempFile);
        $class = new ReflectionClass('Lingua\Code\Language\ISO639Part2T');
        $property = $class->getProperty('translateCache');
        $property->setAccessible(true);
        $property->setValue(null);

        $exceptionThrown = false;
        try {
            $code = new ISO639Part2T();
            $code->translate('deu');
        } catch (FileNotFound $e) {
            $exceptionThrown = true;
        }

        rename($tempFile, $registryFile);
        $this->assertTrue($exceptionThrown);
    }

    /**
     * Test Unite Data Unavailable Exception
     *
     * @covers ::unify
    */
    public function testUniteDataUnavailableException()
    {
        $registryFile = __DIR__.'/../../../'.ISO639Part2T::UNIFY_FILE;
        $tempFile = sys_get_temp_dir().'/'.uniqid();

        //Clear cache, move base data away
        rename($registryFile, $tempFile);
        $class = new ReflectionClass('Lingua\Code\Language\ISO639Part2T');
        $property = $class->getProperty('unifyCache');
        $property->setAccessible(true);
        $property->setValue(null);

        $exceptionThrown = false;
        try {
            $code = new ISO639Part2T();
            $code->unify('deu');
        } catch (FileNotFound $e) {
            $exceptionThrown = true;
        }

        rename($tempFile, $registryFile);
        $this->assertTrue($exceptionThrown);
    }
}


text:
module VirtualBox
  module COM
    module Interface
      module Version_4_1_X
        class USBDeviceFilter < AbstractInterface
          IID = "d6831fb4-1a94-4c2c-96ef-8d0d6192066d"

          property :name, WSTRING
          property :active, T_BOOL
          property :vendor_id, WSTRING
          property :product_id, WSTRING
          property :revision, WSTRING
          property :manufacturer, WSTRING
          property :product, WSTRING
          property :serial_number, WSTRING
          property :port, WSTRING
          property :remote, WSTRING
          property :masked_interfaces, T_UINT32
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
                                    xmlns:card_view="http://schemas.android.com/apk/res-auto"
                                    xmlns:tools="http://schemas.android.com/tools"
                                    android:layout_width="match_parent"
                                    android:layout_height="wrap_content"
                                    android:layout_marginLeft="4dp"
                                    android:layout_marginRight="4dp"
                                    android:layout_marginTop="8dp"
                                    android:clickable="true"
                                    android:foreground="?android:attr/selectableItemBackground"
                                    android:orientation="vertical"
                                    card_view:cardCornerRadius="4dp"
                                    card_view:cardElevation="2dp"
                                    card_view:contentPadding="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/object_image"
            android:transitionName="@string/object_image"
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_alignParentLeft="true"
            android:layout_marginRight="8dp"
            android:contentDescription="@string/image_preview"
            android:scaleType="fitCenter"
            tools:ignore="RtlHardcoded"/>

        <TextView
            android:id="@+id/object_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/object_image"
            android:textSize="16sp"
            tools:ignore="RtlHardcoded"/>

        <TextView
            android:id="@+id/object_summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/object_name"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@id/object_image"
            android:ellipsize="end"
            android:maxLines="2"
            android:textColor="#818181"
            android:textSize="12sp"
            tools:ignore="RtlHardcoded"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
package org.nephtys.keepaseat

import java.io.File
import java.nio.file.{Files, Paths}
import java.util.concurrent.atomic.AtomicInteger

import org.nephtys.keepaseat.internal.eventdata.{Event, EventElementBlock}
import slick.lifted.ProvenShape

import scala.collection.mutable
import scala.concurrent.Await
import scala.concurrent.duration.Duration

// Use H2Driver to connect to an H2 database
import slick.driver.H2Driver.api._

import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent.Future

/**
  * simple implementation of the Databaseable trait, using an embedded h2 database (file based) and synchronization
  * features
  *
  * Created by nephtys on 9/29/16.
  */
class BasicSlickH2Database(db: Database) extends Databaseable {

  //def isDebug = false

  override def retrieve(fromInclusiveDate: Long, toExclusiveDate: Long): Future[IndexedSeq[Event]] = {
    /*if(isDebug) {
      println(s"Retreiving $fromInclusiveDate - $toExclusiveDate: ${
        Await.result(db.run(BasicSlickH2Database
          .queries.getBetween(fromInclusiveDate, toExclusiveDate)
          .result), Duration(10, "seconds"))
      }")
      println(s"Table Events: ${
        Await.result(db.run(BasicSlickH2Database.tableDefinitions.events.result), Duration(10,
          "seconds"))
      }")
      println(s"Table Blocks: ${
        Await.result(db.run(BasicSlickH2Database.tableDefinitions.blocks.result), Duration(10,
          "seconds"))
      }")
    }*/

    db.run(BasicSlickH2Database
      .queries.getBetween(fromInclusiveDate, toExclusiveDate)
      .result).map(_.groupBy(_._1).map(a => {
      def eventraw = a._1
      def blocksraw = a._2.map(_._2).toIndexedSeq
      val blocks: IndexedSeq[EventElementBlock] = blocksraw.map(p => EventElementBlock(p._3, p._4, p._5))
      Event(eventraw._1, blocks, eventraw._2, eventraw._3, eventraw._4, eventraw._5, eventraw._6)
    }).toIndexedSeq)
  }

  override def update(event: Event): Future[Option[Event]] = {
    println(s"Updating event to $event")
    retrieveSpecific(event.id).map(a => {
      println(s"Retrieving in update with result $a vs updated: $event")
      a
    }).flatMap(oldevent => if (oldevent.isDefined) {
      val updated = db.run(DBIO.seq(BasicSlickH2Database.queries.updateBlocks(event.id, event.elements),
          BasicSlickH2Database.queries.updateEvent(event)
      ))
      updated.map(a => Some(event))
    } else {
      Future.successful(None)
    })
  }

  override def create(eventWithoutID: Event): Future[Option[Event]] = {
    //TODO: this should be done in one single DBIOAction to prevent multi threading issues

    val from = eventWithoutID.elements.map(_.from).min
    val to = eventWithoutID.elements.map(_.to).max

    val eles = eventWithoutID.elements.map(_.element)

    //check against specific elements
    val blockingElements : Future[Seq[String]] = retrieve(from, to).map(a => a.flatMap(_.elements.map(_.element)))
    val free: Future[Boolean] = blockingElements.map(seq => eles.forall(k => !seq.contains(k)))
    println("in Create")
    println(Await.result(blockingElements, Duration(10, "seconds")))
    println(Await.result(free, Duration(10, "seconds")))

    val eventinsert: Future[(Boolean, Long)] = free.flatMap(b => if (b) {
      db.run(BasicSlickH2Database.queries
        .insertEvent
        (eventWithoutID)).map(i => (b, i))
    } else {
      Future.successful(b, 0.asInstanceOf[Long])
    })
    val blockInsert: Future[(Boolean, Long)] = eventinsert.flatMap(tuple => {
      println("Tuple" + tuple)
      if (tuple._1) {
        db.run(BasicSlickH2Database.queries.insertBlocks(tuple._2, eventWithoutID.elements)).map(a => tuple)
      } else {
        Future.successful(tuple)
      }
    })
    blockInsert.map {
      case (true, eid) => Some(eventWithoutID.copy(id = eid))
      case _ => None
    }
  }

  override def delete(id: Long): Future[Option[Event]] = {
    retrieveSpecific(id).flatMap(b => {
      if (b.isDefined) {
        val deleteBlocks: Future[Int] = db.run(BasicSlickH2Database.queries.removeBlocks(id))
        val deleteEvent: Future[_] = deleteBlocks.flatMap(t => db.run(BasicSlickH2Database.queries.removeElement(id)))
        deleteEvent.map(i =>  b)
      } else {
        Future.successful(b)
      }
    })
  }

  override def retrieveSpecific(id: Long): Future[Option[Event]] = db.run(BasicSlickH2Database.queries.getWithID(id)
    .result).map(_.groupBy(_._1).headOption.map(a => {
    def eventraw = a._1
    def blocksraw = a._2.map(_._2).toIndexedSeq
    val blocks: IndexedSeq[EventElementBlock] = blocksraw.map(p => EventElementBlock(p._3, p._4, p._5))
    Event(eventraw._1, blocks, eventraw._2, eventraw._3, eventraw._4, eventraw._5, eventraw._6)
  }))

  /**
    * return true if update was successful
    *
    * @param eventID
    * @param confirmstatus
    * @return
    */
  override def updateConfirmation(eventID: Long, confirmstatus: Boolean): Future[Option[Event]] = {
    db.run(BasicSlickH2Database.queries.updateConfirmation(eventID, confirmstatus)).flatMap(i => if (i == 1) {
      retrieveSpecific(eventID)
    } else {
      println(s"Confirm update on $eventID was not successful")
      Future.successful(None)
    })
  }
  override def couldInsert(event: Event): Future[Boolean] = {
    val from = event.elements.map(_.from).min
    val to = event.elements.map(_.to).max
    retrieve(from, to).map(_.isEmpty)
  }
}

/**
  * automatically create schema at first call
  */
object BasicSlickH2Database {
  private val ai = new AtomicInteger(1)

  def dbRandomInMemory: Database = {
    val db: Database = Database.forURL("jdbc:h2:mem:keepaseat_inmemory_" + ai.getAndIncrement() + ";DB_CLOSE_DELAY=-1", driver = "org.h2" +
      ".Driver",
      keepAliveConnection = true)
    //db created, now create schema
    println("Creating Schema")
    Await.result(db.run(DBIO.seq((tableDefinitions.events.schema ++ tableDefinitions.blocks.schema).create)).map(a => println("Created schema: " + a)),
      Duration.apply
    (1,
      "minute"))
    db
  }

  private val dbFac: scala.collection.mutable.Map[String, Database] = mutable.Map.empty[String, Database]

  def dbFromFile(filepath: String): Database = {
    dbFac.getOrElseUpdate(filepath, {
      val db: Database = Database.forURL("jdbc:h2:" + absolutifyFilepath(filepath) + ";MV_STORE=FALSE;" +
        "DB_CLOSE_DELAY=1", driver = "org.h2" +
        ".Driver",
        keepAliveConnection = true)
      //db created, now create schema if file was non-existing before
      if (Files.notExists(Paths.get(filepath + ".h2.db"))) {
        //TODO: this is actually not a smart solution to this problem. Should be improved
        Await.result(db.run(DBIO.seq((tableDefinitions.events.schema ++ tableDefinitions.blocks.schema).create)),
          Duration.apply(1, "minute"))
      }
      db
    })
  }

  def absolutifyFilepath(relativeFilepath: String): String = {
    new File(relativeFilepath).getAbsolutePath
  }

  object tableDefinitions {

    class EventElementBlocks(tag: Tag) extends Table[(Long, Long, String, Long, Long)](tag,
      "ELEMENTSTOEVENT") {
      def ownid = column[Long]("ELEMENTEVENT_ID", O.PrimaryKey, O.AutoInc)

      def eventID = column[Long]("EVENT_ID")

      def event = foreignKey("EVENT_FK", eventID, events)(_.id)

      def from = column[Long]("TIME_FROM")

      def to = column[Long]("TIME_TO")

      def elementName = column[String]("ELEMENT_NAME")

      def * = (ownid, eventID, elementName, from, to)

    }

    val blocks = TableQuery[EventElementBlocks]

    class Events(tag: Tag) extends Table[(Long, String, String, String, String, Boolean)](tag, "EVENTS") {
      def id = column[Long]("EVENT_ID", O.PrimaryKey, O.AutoInc)

      // This is the primary key column
      def name = column[String]("USER_NAME")

      def email = column[String]("EMAIL")

      def telephone = column[String]("TELEPHONE")

      def commentary = column[String]("COMMENTARY")

      def confirmedBySupseruser = column[Boolean]("CONFIRMED")

      // Every table needs a * projection with the same type as the table's type parameter
      def * = (id, name, email, telephone, commentary, confirmedBySupseruser)
    }

    val events = TableQuery[Events]

  }

  object queries {

    def getWithID(lid: Long) = tableDefinitions.events.join(tableDefinitions.blocks).on(_.id === _.eventID).filter(_
      ._1.id === lid)

    def getBetween(from: Long, to: Long) = tableDefinitions.events.join(tableDefinitions.blocks).on(_
      .id === _
      .eventID).filterNot(b => b._2.from > to || b._2.to <= from)

    def insertEvent(event: Event) = (tableDefinitions.events returning tableDefinitions.events.map(_.id)) +=
      (-1.asInstanceOf[Long], event.name, event.email, event.telephone, event.commentary, event.confirmedBySupseruser)

    def insertBlocks(eventId: Long, blocks: Seq[EventElementBlock]) = tableDefinitions.blocks ++= blocks.map(block =>
      (-1.asInstanceOf[Long], eventId, block.element, block.from, block.to))

    def removeElement(elementId: Long) = {
      val q = tableDefinitions.events.filter(_.id === elementId)
      val action = q.delete
      action
    }

    def removeBlocks(elementId: Long) = {
      val q = tableDefinitions.blocks.filter(_.eventID === elementId)
      val action = q.delete
      action
    }

    def tupleWithOutID(e: Event): (String, String, String, String, Boolean) = (e.name, e.email, e.telephone, e
      .commentary, e.confirmedBySupseruser)

    def updateEvent(updatedElement: Event) = {
      val q = tableDefinitions.events.filter(_.id === updatedElement.id).map(e => {
        (e.name, e.email, e.telephone, e.commentary, e.confirmedBySupseruser)
      }).update(tupleWithOutID(updatedElement))
      q
    }

    def updateConfirmation(id : Long, newconfirmation : Boolean) = {
      val q = tableDefinitions.events.filter(_.id === id).map(e => e.confirmedBySupseruser).update(newconfirmation)
      q
    }

    /** just reset them all, it's better this way
      *
      * @param elemntid
      * @param blocks
      * @return
      */
    def updateBlocks(elemntid: Long, blocks: Seq[EventElementBlock]) = DBIO.seq(removeBlocks(elemntid),
      insertBlocks(elemntid, blocks))
  }

}


text:
REST API
========

Endpoint | Description
--- | ---
`GET /torrents` | will return the list of all torrents
`GET /torrents/{infoHash}` | will return one torrent
`GET /torrents/{infoHash}/stats` | will return the torrent stats (speed, bandwidth, etc.)
`GET /torrents/{infoHash}/files` | will return the M3U playlist
`GET /torrents/{infoHash}/files/{path}` | will start streaming the file (honoring the `Range` header)
`POST /torrents` | will add a new torrent (`{"link":"magnet link or URL"}`)
`POST /upload` | will accept a .torrent file as an attachment (`file` field in `multipart/form-data`)
`DELETE /torrents/{infoHash}` | will delete the torrent


text:
from setuptools import setup, find_packages

from sys import version_info, platform

if version_info[:2] > (2, 5):
    install_requires = []
else:
    install_requires = ['simplejson >= 2.0.0']

# Python 2.6 and below requires argparse
if version_info[:2] < (2, 7):
    install_requires += ['argparse']

install_requires += ['ambari_client']
setup(
  name='ambari_shell',
  author_email="ambari-dev@incubator.apache.org",
  version="1.6.0-SNAPSHOT",
  packages=['ambari_shell'],
  install_requires=install_requires,
  description='Ambari Python Shell',
  license='Apache License 2.0'
)