text:
<?php namespace Powerplanetonline\LogViewer\Tests\Utilities;

use Powerplanetonline\LogViewer\Utilities\LogLevels;
use Powerplanetonline\LogViewer\Tests\TestCase;

/**
 * Class     LogLevelsTest
 *
 * @package  Powerplanetonline\LogViewer\Tests\Utilities
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class LogLevelsTest extends TestCase
{
    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    /** @var \Powerplanetonline\LogViewer\Utilities\LogLevels  */
    private $levels;

    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */
    public function setUp()
    {
        parent::setUp();

        $this->levels = $this->app['arcanedev.log-viewer.levels'];
    }

    public function tearDown()
    {
        unset($this->levels);

        parent::tearDown();
    }

    /* ------------------------------------------------------------------------------------------------
     |  Test Functions
     | ------------------------------------------------------------------------------------------------
     */
    /** @test */
    public function it_can_be_instantiated()
    {
        $this->assertInstanceOf(
            'Powerplanetonline\\LogViewer\\Utilities\\LogLevels',
            $this->levels
        );
    }

    /** @test */
    public function it_can_get_all_levels()
    {
        $this->assertLevels($this->levels->lists());
    }

    /** @test */
    public function it_can_get_all_levels_by_static_method()
    {
        $this->assertLevels(LogLevels::all());
    }

    /** @test */
    public function it_can_get_all_translated_levels()
    {
        foreach (self::$locales as $locale) {
            $this->app->setLocale($locale);

            $levels = $this->levels->names($locale);

            $this->assertTranslatedLevels($locale, $levels);
        }
    }

    /** @test */
    public function it_must_choose_the_log_viewer_locale_instead_of_app_locale()
    {
        $this->assertNotEquals('auto', $this->levels->getLocale());
        $this->assertEquals($this->app->getLocale(), $this->levels->getLocale());

        $this->levels->setLocale('fr');

        $this->assertEquals('fr', $this->levels->getLocale());
        $this->assertNotEquals($this->app->getLocale(), $this->levels->getLocale());
    }

    /** @test */
    public function it_can_translate_levels_automatically()
    {
        foreach (self::$locales as $locale) {
            $this->app->setLocale($locale);

            $this->assertTranslatedLevels(
                $this->app->getLocale(),
                $this->levels->names()
            );

            $this->assertTranslatedLevels(
                $this->app->getLocale(),
                $this->levels->names('auto')
            );

            $this->assertTranslatedLevels(
                $locale, $this->levels->names($locale)
            );
        }
    }
}


text:
layout: page
title: 'Opening up your data'
visible: True
tags:
  - misc
  - beginner

---

 - **Authors**: Derek Howard
 - **Lesson topic**: A guided discussion on opening up your research data

## What is open data?
["Open data is data that can be freely used, re-used and redistributed by anyone - subject only, at most, to the requirement to attribute and sharealike."](http://opendatahandbook.org/guide/en/what-is-open-data/)

More specifically, from the open data handbook and [opendefinition.org](http://opendefinition.org/od/2.1/en/):
- Availability and Access: the data must be available as a whole and at no more than a reasonable reproduction cost, preferably by downloading over the internet. The data must also be available in a convenient and modifiable form.
- Re-use and Redistribution: the data must be provided under terms that permit re-use and redistribution including the intermixing with other datasets.
- Universal Participation: everyone must be able to use, re-use and redistribute - there should be no discrimination against fields of endeavour or against persons or groups. For example, 'non-commercial' restrictions that would prevent 'commercial' use, or restrictions of use for certain purposes (e.g. only in education), are not allowed.

## [Why open data?](https://mozillascience.github.io/open-data-primers/1.1-what-and-why.html)
- Maintain accountability:
When data is open, the results or findings of that data can be more easily verified, increasing public trust in research institutions and governments.
- Speed discovery:
When data is open, researchers working in parallel on similar problems don't need to duplicate work and can use each other's data to advance knowledge across their research area.
- Encourage collaboration across disciplines:
When data is open, researchers can more easily find those outside their subject area doing related or relevant work; these connections and collaborations may lead to new ways of approaching and solving problems.
- Solve a broader range of problems:
When data is open, new users-- from academic researchers to citizen scientists to artists-- may use it to answer questions, solve problems, or create public understanding in ways that the original data collector may never have imagined.
- Encourage public engagement with research:
When data is open and the findings are shared in a clear and accessible way, it increases public understanding, creates opportunities for public participation, and bolsters public support of research initiatives.
- Ensure that data is preserved:
When data is open and widely shared, the responsibility for the long-term archiving and preservation of that data is distributed across broader group of interested users.

Grant agencies care about open data:
- Tri-agency (i.e. NSERC, CIHR, SSHRC) policy on data: [Data Management Policy](http://www.science.gc.ca/eic/site/063.nsf/eng/h_83F7624E.html?OpenDocument) and [Open Access Policy](http://www.science.gc.ca/eic/site/063.nsf/eng/h_F6765465.html?OpenDocument)

## Challenges to open data
- reference [handout](https://github.com/mozillascience/open-data-training/blob/master/Materials/Handouts/ODChallengesQI.md) from Mozilla open data training
- ["Differential privacy"](https://www.wired.com/2016/06/apples-differential-privacy-collecting-data/) as a way to anonymize sensitive data. [More technical/not for dummies](https://robertovitillo.com/2016/07/29/differential-privacy-for-dummies/)

## How to open your data
- Metadata
- Create a DATA_README
- Use the [data reuse checklist](https://mozillascience.github.io/checklist/)

## Resources
https://mozillascience.github.io/open-data-primers/
https://mozillascience.github.io/open-data-guides/
https://mozillascience.github.io/working-open-workshop/data_reuse/
http://opendatahandbook.org/guide/en/what-is-open-data/

redpajama_set_name: RedPajamaGithub


text:
import io
import json
import os
import pickle
import shutil
import sys
from collections import defaultdict
from collections import OrderedDict

from django.apps import apps
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connections
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker

from kolibri.core.content.apps import KolibriContentConfig
from kolibri.core.content.constants.schema_versions import CONTENT_SCHEMA_VERSION
from kolibri.core.content.constants.schema_versions import CURRENT_SCHEMA_VERSION
from kolibri.core.content.utils.sqlalchemybridge import get_default_db_string
from kolibri.core.content.utils.sqlalchemybridge import SCHEMA_PATH_TEMPLATE
from kolibri.core.content.utils.sqlalchemybridge import SharingPool

DATA_PATH_TEMPLATE = os.path.join(
    os.path.dirname(__file__), "../../fixtures/{name}_content_data.json"
)

def get_dict(item):
    value = {
        key: value
        for key, value in item.__dict__.items()
        if key != "_sa_instance_state"
    }
    return value

class Command(BaseCommand):
    """
    This management command produces SQLAlchemy schema reflections of the content database app.
    It should be run when the Content Models schema is updated, and if it is a change between released
    versions the CONTENT_DB_SCHEMA version should have been incremented.
    It also produces a data dump of the content test fixture that fits to this database schema,
    so that we can use it for testing purposes.
    """

    def add_arguments(self, parser):
        parser.add_argument("version", type=str, nargs="?")

    def handle(self, *args, **options):

        version = options["version"]

        if not version:
            version = str(int(CONTENT_SCHEMA_VERSION) + 1)

        no_export_schema = version == CURRENT_SCHEMA_VERSION

        app_name = KolibriContentConfig.label

        if not no_export_schema:
            settings.DATABASES["default"] = {
                "ENGINE": "django.db.backends.sqlite3",
                "NAME": ":memory:",
            }
            # Force a reload of the default connection after changing settings.
            del connections["default"]

            settings.INSTALLED_APPS = ("kolibri.core.content.contentschema",)
            apps.app_configs = OrderedDict()
            apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False
            apps.all_models = defaultdict(OrderedDict)
            apps.clear_cache()
            apps.populate(settings.INSTALLED_APPS)
            call_command("makemigrations", app_name, interactive=False)

        call_command("migrate", app_name)

        engine = create_engine(
            get_default_db_string(), poolclass=SharingPool, convert_unicode=True
        )

        metadata = MetaData()

        app_config = apps.get_app_config(app_name)
        # Exclude channelmetadatacache in case we are reflecting an older version of Kolibri
        table_names = [
            model._meta.db_table
            for name, model in app_config.models.items()
            if name != "channelmetadatacache"
        ]
        metadata.reflect(bind=engine, only=table_names)
        Base = automap_base(metadata=metadata)
        # TODO map relationship backreferences using the django names
        Base.prepare()
        session = sessionmaker(bind=engine, autoflush=False)()

        with open(SCHEMA_PATH_TEMPLATE.format(name=version), "wb") as f:
            pickle.dump(metadata, f, protocol=2)

        # Only do this if we are generating a new export schema version
        if not no_export_schema:

            # Load fixture data into the test database with Django
            call_command("loaddata", "content_import_test.json", interactive=False)

            data = {}

            for table_name, record in Base.classes.items():
                data[table_name] = [get_dict(r) for r in session.query(record).all()]

            data_path = DATA_PATH_TEMPLATE.format(name=version)
            # Handle Python 2 unicode issue by opening the file in binary mode
            # with no encoding as the data has already been encoded
            if sys.version[0] == "2":
                with io.open(data_path, mode="wb") as f:
                    json.dump(data, f)
            else:
                with io.open(data_path, mode="w", encoding="utf-8") as f:
                    json.dump(data, f)

            shutil.rmtree(
                os.path.join(
                    os.path.dirname(__file__), "../../contentschema/migrations"
                )
            )

            os.system("kolibri manage generate_schema " + CURRENT_SCHEMA_VERSION)


text:
class testApp : public ofBaseApp {
public:
	void setup();
	void update();
	void draw();
	void decodeAndSave(string filename);
	void keyPressed(int key);

	ofImage camImage, proImage;
	vector<cv::Point2f> camImagePoints, proImagePoints;
	vector<cv::Point3f> resultPoints;
	cv::Size proSize, camSize;
	cv::Mat camMatrix, proMatrix;
	cv::Mat camDistCoeffs, proDistCoeffs;
	cv::Mat rotation, translation;
	ofEasyCam cam;
	ofVboMesh mesh;
	vector<unsigned char> colors;

	ofxAutoControlPanel panel;
};


text:
<?php
// src/OC/PlatformBundle/Controller/AdvertController.php
namespace OC\PlatformBundle\Controller;
use OC\PlatformBundle\Entity\Advert;
use OC\PlatformBundle\Form\AdvertEditType;
use OC\PlatformBundle\Form\AdvertType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class AdvertController extends Controller
{
    public function indexAction($page)
    {
        if ($page < 1) {
            throw new NotFoundHttpException('Page "'.$page.'" inexistante.');
        }
        // Ici je fixe le nombre d'annonces par page à 3
        // Mais bien sûr il faudrait utiliser un paramètre, et y accéder via $this->container->getParameter('nb_per_page')
        $nbPerPage = 3;
        // On récupère notre objet Paginator
        $listAdverts = $this->getDoctrine()
            ->getManager()
            ->getRepository('OCPlatformBundle:Advert')
            ->getAdverts($page, $nbPerPage)
        ;
        // On calcule le nombre total de pages grâce au count($listAdverts) qui retourne le nombre total d'annonces
        $nbPages = ceil(count($listAdverts) / $nbPerPage);
        // Si la page n'existe pas, on retourne une 404
        if ($page > $nbPages) {
            throw $this->createNotFoundException("La page ".$page." n'existe pas.");
        }
        // On donne toutes les informations nécessaires à la vue
        return $this->render('OCPlatformBundle:Advert:index.html.twig', array(
            'listAdverts' => $listAdverts,
            'nbPages'     => $nbPages,
            'page'        => $page,
        ));
    }
    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();
        // Pour récupérer une seule annonce, on utilise la méthode find($id)
        $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);
        // $advert est donc une instance de OC\PlatformBundle\Entity\Advert
        // ou null si l'id $id n'existe pas, d'où ce if :
        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }
        // Récupération de la liste des candidatures de l'annonce
        $listApplications = $em
            ->getRepository('OCPlatformBundle:Application')
            ->findBy(array('advert' => $advert))
        ;
        // Récupération des AdvertSkill de l'annonce
        $listAdvertSkills = $em
            ->getRepository('OCPlatformBundle:AdvertSkill')
            ->findBy(array('advert' => $advert))
        ;
        return $this->render('OCPlatformBundle:Advert:view.html.twig', array(
            'advert'           => $advert,
            'listApplications' => $listApplications,
            'listAdvertSkills' => $listAdvertSkills,
        ));
    }
    public function addAction(Request $request)
    {
        $advert = new Advert();
        $form   = $this->get('form.factory')->create(AdvertType::class, $advert);
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($advert);
            $em->flush();
            $request->getSession()->getFlashBag()->add('notice', 'Annonce bien enregistrée.');
            return $this->redirectToRoute('oc_platform_view', array('id' => $advert->getId()));
        }
        return $this->render('OCPlatformBundle:Advert:add.html.twig', array(
            'form' => $form->createView(),
        ));
    }
    public function editAction($id, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);
        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }
        $form = $this->get('form.factory')->create(AdvertEditType::class, $advert);
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            // Inutile de persister ici, Doctrine connait déjà notre annonce
            $em->flush();
            $request->getSession()->getFlashBag()->add('notice', 'Annonce bien modifiée.');
            return $this->redirectToRoute('oc_platform_view', array('id' => $advert->getId()));
        }
        return $this->render('OCPlatformBundle:Advert:edit.html.twig', array(
            'advert' => $advert,
            'form'   => $form->createView(),
        ));
    }
    public function deleteAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);
        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }
        // On crée un formulaire vide, qui ne contiendra que le champ CSRF
        // Cela permet de protéger la suppression d'annonce contre cette faille
        $form = $this->get('form.factory')->create();
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $em->remove($advert);
            $em->flush();
            $request->getSession()->getFlashBag()->add('info', "L'annonce a bien été supprimée.");
            return $this->redirectToRoute('oc_platform_home');
        }

        return $this->render('OCPlatformBundle:Advert:delete.html.twig', array(
            'advert' => $advert,
            'form'   => $form->createView(),
        ));
    }
    public function menuAction($limit)
    {
        $em = $this->getDoctrine()->getManager();
        $listAdverts = $em->getRepository('OCPlatformBundle:Advert')->findBy(
            array(),                 // Pas de critère
            array('date' => 'desc'), // On trie par date décroissante
            $limit,                  // On sélectionne $limit annonces
            0                        // À partir du premier
        );
        return $this->render('OCPlatformBundle:Advert:menu.html.twig', array(
            'listAdverts' => $listAdverts
        ));
    }
    // Méthode facultative pour tester la purge
    public function purgeAction($days, Request $request)
    {
        // On récupère notre service
        $purger = $this->get('oc_platform.purger.advert');
        // On purge les annonces
        $purger->purge($days);
        // On ajoute un message flash arbitraire
        $request->getSession()->getFlashBag()->add('info', 'Les annonces plus vieilles que '.$days.' jours ont été purgées.');
        // On redirige vers la page d'accueil
        return $this->redirectToRoute('oc_platform_home');
    }
}


text:
<?php
require_once("Report.php");
class Summary_suppliers extends Report
{
	function __construct()
	{
		parent::__construct();
	}

	public function getDataColumns()
	{
		return array($this->lang->line('reports_supplier'), $this->lang->line('reports_count'), $this->lang->line('reports_subtotal'), $this->lang->line('reports_total'), $this->lang->line('reports_tax'), $this->lang->line('reports_cost'), $this->lang->line('reports_profit'));
	}

	public function getData(array $inputs)
	{
		$this->db->select('CONCAT(company_name, " (", first_name, " ",last_name, ")") as supplier, sum(quantity_purchased) as quantity_purchased, sum(subtotal) as subtotal, sum(total) as total, sum(tax) as tax, sum(cost) as cost, sum(profit) as profit', false);
		$this->db->from('sales_items_temp');
		$this->db->join('suppliers', 'suppliers.person_id = sales_items_temp.supplier_id');
		$this->db->join('people', 'suppliers.person_id = people.person_id');
		$this->db->where('sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].'"');

		if ($inputs['sale_type'] == 'sales')
        {
            $this->db->where('quantity_purchased > 0');
        }
        elseif ($inputs['sale_type'] == 'returns')
        {
            $this->db->where('quantity_purchased < 0');
        }

		$this->db->group_by('supplier_id');
		$this->db->order_by('last_name');

		return $this->db->get()->result_array();
	}

	public function getSummaryData(array $inputs)
	{
		$this->db->select('sum(subtotal) as subtotal, sum(total) as total, sum(tax) as tax, sum(cost) as cost, sum(profit) as profit');
		$this->db->from('sales_items_temp');
		$this->db->join('suppliers', 'suppliers.person_id = sales_items_temp.supplier_id');
		$this->db->join('people', 'suppliers.person_id = people.person_id');
		$this->db->where('sale_date BETWEEN "'. $inputs['start_date']. '" and "'. $inputs['end_date'].'"');

		if ($inputs['sale_type'] == 'sales')
        {
            $this->db->where('quantity_purchased > 0');
        }
        elseif ($inputs['sale_type'] == 'returns')
        {
            $this->db->where('quantity_purchased < 0');
        }

		return $this->db->get()->row_array();
	}
}
?>


text:
package ninja.leaping.permissionsex.backend.sql.tables;

import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "segments")
public class SqlSegment {
    @DatabaseField(generatedId = true)
    private int id;

    @DatabaseField(foreign = true)
    private SqlSubject subject;

    @DatabaseField(uniqueIndexName = "ident")
    private String type;
    @DatabaseField(uniqueIndexName = "ident")
    private String identifier;

    @ForeignCollectionField
    private ForeignCollection<SqlInheritance> parents;

    @ForeignCollectionField
    private ForeignCollection<SqlPermission> permissions;

    @ForeignCollectionField
    private ForeignCollection<SqlOption> options;
}


text:
require 'chef_zero/chef_data/data_normalizer'

module ChefZero
  module Endpoints
    # /organizations/ORG/policies
    class PoliciesEndpoint < RestBase
      # GET /organizations/ORG/policies
      def get(request)
        response_data = {}
        policy_names = list_data(request)
        policy_names.each do |policy_name|
          policy_path = request.rest_path + [policy_name]
          policy_uri = build_uri(request.base_uri, policy_path)
          revisions = list_data(request, policy_path + ["revisions"])

          response_data[policy_name] = {
            uri: policy_uri,
            revisions: hashify_list(revisions)
          }
        end

        return json_response(200, response_data)
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using AppIdent.Metrics;
using AppIdent.Misc;
using AppIdent.Models;
using Framework.Models;
using Netfox.Core.Enums;

namespace AppIdent.Features.Bases
{
    public class ByteFrequencyBase : FeatureBase
    {
        public ByteFrequencyBase() { }
        public ByteFrequencyBase(L7Conversation l7Conversation, DaRFlowDirection flowDirection) : base(l7Conversation, flowDirection) { }
        public ByteFrequencyBase(double featureValue) : base(featureValue) { }

        public override FeatureKind FeatureKind { get; } = FeatureKind.Continous;

        public override double ComputeDistanceToProtocolModel(FeatureBase sampleFeature)
        {
            return Math.Abs(this.Normalize(this.FeatureValue) - this.Normalize(sampleFeature.FeatureValue));
        }

        public override double ComputeFeature(L7Conversation l7Conversation, DaRFlowDirection flowDirection)
        {
            var byteFreq = new double[256];
            byte[] firstMsg = null;
            switch(flowDirection)
            {
                case DaRFlowDirection.up:
                    firstMsg = l7Conversation.UpFlowPDUs.FirstOrDefault()?.PDUByteArr;
                    break;
                case DaRFlowDirection.down:
                    firstMsg = l7Conversation.DownFlowPDUs.FirstOrDefault()?.PDUByteArr;
                    break;
                case DaRFlowDirection.non:
                    firstMsg = l7Conversation.L7PDUs.FirstOrDefault()?.PDUByteArr;
                    break;
                default: throw new ArgumentOutOfRangeException(nameof(flowDirection), flowDirection, null);
            }

            if(firstMsg == null) { return -1; }

            for(var i = 0; i < firstMsg.Length; i++) { byteFreq[Convert.ToInt32(firstMsg.GetValue(i))]++; }
            var tmpMin = 1.0;
            var freq = new List<double>();
            for(var i = 0; i < 256; i++)
            {
                if(!byteFreq[i].Equals(0.0))
                {
                    byteFreq[i] /= firstMsg.Length;
                    if(tmpMin.CompareTo(byteFreq[i]) > 0) { tmpMin = byteFreq[i]; }
                    freq.Add(byteFreq[i]);
                }
                //Console.WriteLine("Byte: " + i + " FeatureValue: " + byteFreq[i] );
            }
            return Utilities.StandardDeviation(freq);
        }

        public override void ComputeFeatureForProtocolModel(IFeatureCollectionWrapper<FeatureBase> featureValues)
        {
            this.FeatureValue = FeatureMetrics.FeatureMetricAverage(featureValues);
            this.Weight = WeightMetrics.WeightUsingNormEntropy(featureValues);
        }
    }
}


text:
import os
from collections import defaultdict

import requests

from db.team import Team
from db.division import Division

def test_division_import():
    """
    Tests whether team abbreviations used in division configuration file
    correspond with team abbreviations used by team definitions in database.
    """
    div_src = os.path.join(os.path.dirname(__file__), 'test_division_config.txt')
    lines = [line.strip() for line in open(div_src).readlines()]

    team_abbs = set()

    for line in lines:
        if line.startswith('#'):
            continue
        tokens = line.split(';')
        raw_abbs = tokens[2][1:-1].split(',')
        for raw_abb in raw_abbs:
            team_abbs.add(raw_abb)

    for abb in sorted(team_abbs):
        t = Team.find(abb)
        assert abb in [t.abbr, t.orig_abbr]

def test_division_1974():

    divisions = Division.get_divisions_and_teams(1974)

    assert sorted(divisions.keys()) == ['Adams', 'Norris', 'Patrick', 'Smythe']
    assert [t.name for t in divisions['Adams']] == [
        'Boston Bruins',
        'Buffalo Sabres',
        'California Golden Seals',
        'Toronto Maple Leafs']
    assert [t.name for t in divisions['Norris']] == [
        'Detroit Red Wings',
        'Los Angeles Kings',
        'Montréal Canadiens',
        'Pittsburgh Penguins',
        'Washington Capitals']
    assert [t.name for t in divisions['Patrick']] == [
        'Atlanta Flames',
        'New York Islanders',
        'New York Rangers',
        'Philadelphia Flyers']
    assert [t.name for t in divisions['Smythe']] == [
        'Chicago Blackhawks',
        'Kansas City Scouts',
        'Minnesota North Stars',
        'St. Louis Blues',
        'Vancouver Canucks']

def test_division_now():

    # retrieving current divisions and teams from database
    divisions_from_db = Division.get_divisions_and_teams()

    # urls with current division and team data
    divisions_url = "https://statsapi.web.nhl.com/api/v1/divisions/"
    teams_url = "https://statsapi.web.nhl.com/api/v1/teams/"

    response = requests.get(divisions_url)
    divisions_from_url = [d['name'] for d in response.json()['divisions']]

    response = requests.get(teams_url)
    teams_by_division_from_url = defaultdict(list)
    for team_json in response.json()['teams']:
        team_name = team_json['name']
        team_division = team_json['division']['name']
        teams_by_division_from_url[team_division].append(team_name)

    assert sorted(divisions_from_db.keys()) == sorted(divisions_from_url)

    for division in divisions_from_db:
        assert sorted(
            [t.name for t in divisions_from_db[division]]
        ) == sorted(
            teams_by_division_from_url[division]
        )


text:
package com.amazonaws.mturk.test;

import java.util.ArrayList;
import java.util.Properties;

import junit.framework.TestCase;
import junit.textui.TestRunner;

import com.amazonaws.mturk.addon.HITDataBuffer;
import com.amazonaws.mturk.addon.HITProperties;
import com.amazonaws.mturk.addon.HITQuestion;
import com.amazonaws.mturk.requester.Comparator;
import com.amazonaws.mturk.requester.EventType;
import com.amazonaws.mturk.requester.HIT;
import com.amazonaws.mturk.requester.NotificationSpecification;
import com.amazonaws.mturk.requester.NotificationTransport;
import com.amazonaws.mturk.requester.QualificationRequirement;
import com.amazonaws.mturk.requester.QualificationType;
import com.amazonaws.mturk.requester.QualificationTypeStatus;
import com.amazonaws.mturk.service.axis.RequesterService;
import com.amazonaws.mturk.service.exception.ServiceException;
import com.amazonaws.mturk.util.PropertiesClientConfig;

public abstract class TestBase extends TestCase {

  protected static RequesterService service =
      new RequesterService(new PropertiesClientConfig("etc/test/requesterTest.properties"));

  protected static String luckyWorker = "A1DTY366E1E1JO";
  protected static String testHITId = null;
  protected static String testHITTypeId = null;
  protected static String testQualTypeId = null;

  protected static String unique;

  protected static String defaultHITTitle;
  protected static String defaultHITDescription;
  protected static String defaultHITKeywords;
  protected static long defaultAssignmentDurationInSeconds;
  protected static long defaultAutoApprovalDelayInSeconds;
  protected static long defaultLifetimeInSeconds;
  protected static int defaultMaxAssignments;
  protected static double defaultReward;
  protected static String defaultAnnotation;
  protected static String defaultQuestion;
  protected static String defaultAnswer;
  protected static QualificationRequirement[] defaultQualRequirements;

  protected static String defaultQualificationName;
  protected static String defaultQualificationDescription;
  protected static String defaultQuery;
  protected static long defaultRetryDelayInSeconds;

  protected static String defaultQuestionIdentifier;

  protected static int defaultMaxAssignmentsIncrement;
  protected static long defaultExpirationIncrementInSeconds;
  protected static String defaultReason;

  protected static Integer defaultPageNum;
  protected static Integer defaultPageSize;
  protected static NotificationSpecification defaultNotificationSpec;
  protected static int defaultWorkerAcceptLimit;

  protected static HITDataBuffer defaultHITInput;
  protected static HITProperties defaultHITProperties;
  protected static HITQuestion defaultHITQuestion;
  protected static HITDataBuffer defaultSuccess;

  protected static String defaultTestDir;
  protected static String defaultQuestionFileName;
  protected static String defaultInvalidQuestionFileName;
  protected static String defaultFormattedContentQuestionFileName;
  protected static String defaultInvalidFormattedContentQuestionFileName;
  protected static String defaultExternalQuestionFileName;
  protected static String defaultInvalidExternalQuestionFileName;
  protected static String defaultHTMLQuestionFileName;
  protected static String defaultInvalidHTMLQuestionFileName;
  protected static String defaultScriptFormattedContentQuestionFileName;
  protected static String defaultPreviewFileName;
  protected static String defaultInputFileName;
  protected static String defaultNoHeaderInputFileName;
  protected static String defaultOutputFileName;
  protected static String defaultPlaceholder;
  protected static String defaultUTF8PropertiesFileName;
  protected static String defaultUTF8QuestionFileName;

  protected static ArrayList<String[]> defaultHITInputData;
  protected static String[] defaultHITInputFields;

  protected final static String BOGUS_STR = "BOGUSVALUE";
  protected final static String BOGUS_HITID = "BOGUS9ZF5WWA6JCBOGUS";
  protected final static QualificationRequirement[] NULL_QUAL_REQUIREMENTS = null;
  protected final static String SYSTEM_QUAL_TYPE_ID =
    "00000000000000000000";  // HIT submission rate %
  protected final static String DEFAULT_ANSWER_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    + "<QuestionFormAnswers xmlns=\"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionFormAnswers.xsd\">"
    + "<Answer>"
    + "<QuestionIdentifier>freeText</QuestionIdentifier>"
    + "<FreeText>freeText_answer</FreeText>"
    + "</Answer>"
    + "<Answer>"
    + "<QuestionIdentifier>otherSelection</QuestionIdentifier>"
    + "<OtherSelectionText>otherSelection_answer</OtherSelectionText>"
    + "</Answer>"
    + "<Answer>"
    + "<QuestionIdentifier>url</QuestionIdentifier>"
    + "<UploadedFileSizeInBytes>100</UploadedFileSizeInBytes>"
    + "<UploadedFileKey>uploadedFileKey</UploadedFileKey>"
    + "</Answer>"
    + "<Answer>"
    + "<QuestionIdentifier>selectionIdentifier</QuestionIdentifier>"
    + "<SelectionIdentifier>selection_answer</SelectionIdentifier>"
    + "<SelectionIdentifier>selection_answer2</SelectionIdentifier>"
    + "</Answer>"
    + "</QuestionFormAnswers>";

  static {

    defaultHITTitle = "Test HIT";
    defaultHITDescription = "This is a test HIT description.";
    defaultHITKeywords = "test";
    defaultAssignmentDurationInSeconds = 30;
    defaultAutoApprovalDelayInSeconds = 30;
    defaultLifetimeInSeconds = 30;
    defaultMaxAssignments = 1;
    defaultReward = 0.01;
    defaultAnnotation = "testannotation";
    defaultQuestion = "This is a test question";
    defaultAnswer = "Test Answer";
    QualificationRequirement q = new QualificationRequirement();
    q.setQualificationTypeId(SYSTEM_QUAL_TYPE_ID);
    q.setComparator(Comparator.GreaterThanOrEqualTo);
    q.setIntegerValue(0);
    defaultQualRequirements = new QualificationRequirement[] { q };

    defaultQualificationName = "Test qualification name";
    defaultQualificationDescription = "This is a test qualification.";
    defaultQuery = "test";
    defaultRetryDelayInSeconds = 1;

    defaultMaxAssignmentsIncrement = 1;
    defaultExpirationIncrementInSeconds = 60 * 60; // 1 hour
    defaultReason = "This is a test reason.";

    defaultPageNum = 1;
    defaultPageSize = 10;
    defaultWorkerAcceptLimit = 11;

    String[] headers = new String[] { "testheader1","testheader2"};
    String[] line1 = new String[] { "testvalue1_1","testvalue1_2"};
    String[] line2 = new String[] { "testvalue2_1","testvalue2_2"};
    String[] line3 = new String[] { "testvalue3_1","testvalue3_2"};
    defaultHITInputData = new ArrayList<String[]>();
    defaultHITInputData.add( headers );
    defaultHITInputData.add( line1 );
    defaultHITInputData.add( line2 );
    defaultHITInputData.add( line3 );
    defaultHITInput = new HITDataBuffer();
    defaultHITInput.setRows(defaultHITInputData);

    defaultPlaceholder = "testheader";

    defaultSuccess = new HITDataBuffer();
    ArrayList<String[]> defaultSuccessData = new ArrayList<String[]>();
    defaultSuccessData.add( new String[] { "hitid","hittypeid"} );
    defaultSuccessData.add( new String[] { "test_hitid1","test_hittypeid1"} );
    defaultSuccessData.add( new String[] { "test_hitid2","test_hittypeid2"} );
    defaultSuccess.setRows( defaultSuccessData );

    defaultTestDir = "etc/test";
    defaultPreviewFileName = defaultTestDir + "/testPreview.html";
    defaultInputFileName = defaultTestDir + "/testInput.tab";
    defaultNoHeaderInputFileName = defaultTestDir + "/testNoHeaderInput.tab";
    defaultOutputFileName = "testHITDataWriter.tmp";
    defaultQuestionFileName = defaultTestDir + "/testQuestion.txt";
    defaultInvalidQuestionFileName = defaultTestDir + "/testInvalidQuestion.txt";
    defaultFormattedContentQuestionFileName = defaultTestDir + "/testFormattedContentQuestion.txt";
    defaultInvalidFormattedContentQuestionFileName = defaultTestDir + "/testInvalidFormattedContentQuestion.txt";
    defaultScriptFormattedContentQuestionFileName = defaultTestDir + "/testScriptFormattedContent.txt";
    defaultExternalQuestionFileName = defaultTestDir + "/testExternalQuestion.txt";
    defaultInvalidExternalQuestionFileName = defaultTestDir + "/testInvalidExternalQuestion.txt";
    defaultHTMLQuestionFileName = defaultTestDir + "/testHTMLQuestion.txt";
    defaultInvalidHTMLQuestionFileName = defaultTestDir + "/testInvalidHTMLQuestion.txt";
    defaultUTF8PropertiesFileName = defaultTestDir + "/testUTF8.properties";
    defaultUTF8QuestionFileName = defaultTestDir + "/testUTF8Question.xml";

    Properties props = new Properties();
    props.setProperty(HITProperties.HITField.Title.getFieldName(), defaultHITTitle);
    props.setProperty(HITProperties.HITField.Description.getFieldName(), defaultHITDescription);
    props.setProperty(HITProperties.HITField.Keywords.getFieldName(), defaultHITKeywords);
    props.setProperty(HITProperties.HITField.AssignmentDuration.getFieldName(),
        Long.toString(defaultAssignmentDurationInSeconds));
    props.setProperty(HITProperties.HITField.AutoApprovalDelay.getFieldName(),
        Long.toString(defaultAutoApprovalDelayInSeconds));
    props.setProperty(HITProperties.HITField.Lifetime.getFieldName(),
        Long.toString(defaultLifetimeInSeconds));
    props.setProperty(HITProperties.HITField.MaxAssignments.getFieldName(),
        Long.toString(defaultMaxAssignments));
    props.setProperty(HITProperties.HITField.Reward.getFieldName(),
        Double.toString(defaultReward));
    props.setProperty(HITProperties.HITField.Annotation.getFieldName(), defaultAnnotation);
    defaultHITProperties = new HITProperties(props);
    defaultHITProperties.setQualificationComparator(1, "greaterthan");
    defaultHITProperties.setQualificationType(1, RequesterService.APPROVAL_RATE_QUALIFICATION_TYPE_ID);
    defaultHITProperties.setQualificationValue(1, "25");

    defaultHITQuestion = new HITQuestion();
    defaultHITQuestion.setQuestion( RequesterService.getBasicFreeTextQuestion( defaultQuestion) );

    defaultNotificationSpec = new NotificationSpecification();
    defaultNotificationSpec.setTransport(NotificationTransport.REST);
    defaultNotificationSpec.setVersion(RequesterService.NOTIFICATION_VERSION);
    defaultNotificationSpec.setEventType(new EventType[] { EventType.AssignmentAbandoned,
        EventType.AssignmentReturned });
    defaultNotificationSpec.setDestination("http://example.com:8080/mt/notifications.cgi");
  }

  public static void main(String[] args) {
    TestRunner.run(TestBase.class);
  }

  public TestBase(String arg0) {
    super(arg0);
  }

  protected void setUp() throws Exception {
    super.setUp();

    unique = Long.toString(System.currentTimeMillis());

  }
  protected void tearDown() throws Exception {
      super.tearDown();
  }

  protected String getTestHITTypeId() throws ServiceException {
      if (testHITTypeId == null) {
        getTestHITId();
      }

      return testHITTypeId;
  }
  protected String getTestHITId() throws ServiceException {
      if (testHITId == null) {

        HIT hit = createHIT();
        testHITId = hit.getHITId();
        testHITTypeId = hit.getHITTypeId();

      }

      return testHITId;
    }

  protected void clearTestHITIds() {
      testHITTypeId = null;
      testHITId = null;
 }

  protected String getTestQualificationTypeId() throws ServiceException {
      testQualTypeId = createQualificationType().getQualificationTypeId();

    return testQualTypeId;
  }

  protected HIT createHIT() throws ServiceException {
    return createHIT(null);
  }

  protected HIT createHIT(QualificationRequirement qualRequirement) throws ServiceException {
    QualificationRequirement[] qualRequirements = null;
    if (qualRequirement != null) {
      qualRequirements = new QualificationRequirement[] { qualRequirement };
    }

    HIT hit = service.createHIT(null, // HITTypeId
        defaultHITTitle + unique,
        defaultHITDescription, null, // keywords
        RequesterService.getBasicFreeTextQuestion(defaultQuestion), defaultReward,
        defaultAssignmentDurationInSeconds, defaultAutoApprovalDelayInSeconds,
        defaultLifetimeInSeconds, defaultMaxAssignments, null, // requesterAnnotation
        qualRequirements,
        null  // responseGroup
      );

    assertNotNull(hit);
    assertNotNull(hit.getHITId());

    return hit;
  }

  protected QualificationType createQualificationType() throws ServiceException {
    QualificationType qualType = service.createQualificationType(
        defaultQualificationName + unique,
        null, // keywords
        defaultQualificationDescription, QualificationTypeStatus.Active, (long) 0,
        null, // test
        null, // answerKey
        null, // testDurationInSeconds
        null, // autoGranted
        null // autoGrantedValue
      );

    assertNotNull(qualType);

    return qualType;
  }

  protected void assertContains(String message, String substring, String full) {
    assertTrue(
        String.format("%s expected substring:<%s> but was:<%s>", message, substring, full),
        full.contains(substring));
  }
}


text:
package com.element.onyx;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

/**
 * This code is in no manner open for anyone to use. The use of this code
 * in any manner anywhere is governed by Siddhant Vinchurkar (yours truly)
 * for all eternity. Now go die.
 **/

public class ErrorLogActivity extends AppCompatActivity {

    // Object Declaration

    TextView errortv;
    FloatingActionButton clear_log;
    Toolbar toolbar;
    Typeface ubuntu_r;
    String logs;

    // Variable Declaration

    boolean clear_logs;

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

        // Object Initialization

        ubuntu_r = Typeface.createFromAsset(getApplicationContext().getAssets(), "ubuntu_r.ttf");

        logs = null;

        // Variable Initialization

        clear_logs = false;

        // View Bindings

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

        clear_log = (FloatingActionButton) findViewById(R.id.clear_log);

        errortv = (TextView) findViewById(R.id.errortv);

        // Set toolbar up

        setSupportActionBar(toolbar);

        // Read error logs

        logs = GlobalClass.readLog(getApplicationContext());

        // Display error logs with custom font (Ubuntu-R)

        errortv.setTypeface(ubuntu_r);
        errortv.setText(logs);

        clear_log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Clear all error logs

                errortv.setText(getResources().getString(R.string.error_error_log));
                clear_logs = true;

                Snackbar.make(view, "Logs cleared", Snackbar.LENGTH_LONG)
                        .setAction("Undo", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                errortv.setText(logs);
                                clear_logs = false;

                            }
                        }).show();
            }
        });

    }

    @Override
    protected void onPause() {

        /* The 'finish()' method will end the splash activity to prevent it from appearing
         * should the user press the back button */

        // Clear logs if needed

        if(clear_logs)
        {

            GlobalClass.deleteLog(getApplicationContext());

        }

        finish();

        super.onPause();
    }

    @Override
    public void onBackPressed() {

        startActivity(new Intent(ErrorLogActivity.this, MainActivity.class));

        super.onBackPressed();
    }

    @Override
    protected void onResume() {

        super.onResume();
    }
}


text:
"""
reverse_linked_list_ii.py

Created by Shengwei on 2014-07-25.
"""

# https://oj.leetcode.com/problems/reverse-linked-list-ii/
# tags: medium, linked-list, pointer, dummy head, edge cases, reverse

"""
Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
"""

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param m, an integer
    # @param n, an integer
    # @return a ListNode
    def reverseBetween(self, head, m, n):

        cursor = dummy_head = ListNode(0)
        dummy_head.next = head
        for _ in range(m - 1):
            cursor = cursor.next

        keeper = cursor
        pre = cursor.next
        cursor = pre.next

        for _ in range(n - m):
            post = cursor.next
            cursor.next = pre
            pre = cursor
            cursor = post

        keeper.next.next = cursor
        keeper.next = pre

        return dummy_head.next


text:
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'word-filter',
  styleUrls: [ './word-filter.component.scss' ],
  templateUrl: './word-filter.component.html'
})

export class WordFilterComponent {

  @Output('onFilterChange') onFilterChange = new EventEmitter();
  constructor() {}

  onFilterKeyUp (event) {
    this.onFilterChange.emit(event.target.value);
  }
}


text:
<?php

ITSEC_Modules::register_module( 'database-prefix', dirname( __FILE__ ), 'always-active' );


text:
package org.apache.phoenix.end2end;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimeZone;

import org.apache.phoenix.exception.SQLExceptionCode;
import org.junit.Test;

public class TimezoneOffsetFunctionIT extends BaseHBaseManagedTimeTableReuseIT {

	@Test
	public void testTimezoneOffset() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test
				+ " (k1 INTEGER NOT NULL, dates DATE CONSTRAINT pk PRIMARY KEY (k1))";
		conn.createStatement().execute(ddl);
		String dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates) VALUES (1, TO_DATE('2014-02-02 00:00:00'))";
		conn.createStatement().execute(dml);
		dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates) VALUES (2, TO_DATE('2014-06-02 00:00:00'))";
		conn.createStatement().execute(dml);
		conn.commit();

		ResultSet rs = conn.createStatement().executeQuery(
				"SELECT k1, dates, TIMEZONE_OFFSET('Indian/Cocos', dates) FROM " + timezone_offset_test);

		assertTrue(rs.next());
		assertEquals(390, rs.getInt(3));
		assertTrue(rs.next());
		assertEquals(390, rs.getInt(3));

	}

	@Test
	public void testUnknownTimezone() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test
				+ " (k1 INTEGER NOT NULL, dates DATE CONSTRAINT pk PRIMARY KEY (k1))";
		conn.createStatement().execute(ddl);
		String dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates) VALUES (1, TO_DATE('2014-02-02 00:00:00'))";
		conn.createStatement().execute(dml);
		conn.commit();

		try {
			ResultSet rs = conn.createStatement().executeQuery(
					"SELECT k1, dates, TIMEZONE_OFFSET('Unknown_Timezone', dates) FROM "
							+ timezone_offset_test);

			rs.next();
			assertEquals(0, rs.getInt(3));
			fail();
        } catch (SQLException e) {
            assertEquals(SQLExceptionCode.ILLEGAL_DATA.getErrorCode(), e.getErrorCode());
        }
	}

	@Test
	public void testInRowKeyDSTTimezoneDesc() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test + " "
				+ "(k1 INTEGER NOT NULL, dates DATE NOT NULL CONSTRAINT pk PRIMARY KEY (k1, dates DESC))";
		conn.createStatement().execute(ddl);
		String dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates) VALUES (1, TO_DATE('2014-02-02 00:00:00'))";
		conn.createStatement().execute(dml);
		dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates) VALUES (2, TO_DATE('2014-06-02 00:00:00'))";
		conn.createStatement().execute(dml);
		conn.commit();

		ResultSet rs = conn.createStatement().executeQuery(
				"SELECT k1, dates, TIMEZONE_OFFSET('Europe/Prague', dates)"
				+ "FROM " + timezone_offset_test + " ORDER BY k1 ASC");

		assertTrue(rs.next());
		assertEquals(60, rs.getInt(3));
		assertTrue(rs.next());
		assertEquals(120, rs.getInt(3));
	}

	@Test
	public void testBothParametersNull() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test + " "
				+ "(k1 INTEGER NOT NULL, dates DATE, v1 VARCHAR CONSTRAINT pk PRIMARY KEY (k1))";
		conn.createStatement().execute(ddl);
		String dml = "UPSERT INTO " + timezone_offset_test + " (k1, dates, v1) VALUES (2, null, null)";
		conn.createStatement().execute(dml);
		conn.commit();

		ResultSet rs = conn.createStatement().executeQuery(
				"SELECT k1, dates, TIMEZONE_OFFSET(v1, dates)"
				+ "FROM " + timezone_offset_test + " ORDER BY k1 ASC");

		assertTrue(rs.next());
		rs.getInt(3);
		assertTrue(rs.wasNull());
	}

	@Test
	public void timezoneParameterNull() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test + " "
				+ "(k1 INTEGER NOT NULL, dates DATE, v1 VARCHAR CONSTRAINT pk PRIMARY KEY (k1))";
		conn.createStatement().execute(ddl);
		String dml = "UPSERT INTO " + timezone_offset_test
				+ " (k1, dates, v1) VALUES (2, TO_DATE('2014-06-02 00:00:00'), null)";
		conn.createStatement().execute(dml);
		conn.commit();

		ResultSet rs = conn.createStatement().executeQuery(
				"SELECT k1, dates, TIMEZONE_OFFSET(v1, dates)"
				+ "FROM " + timezone_offset_test + " ORDER BY k1 ASC");

		assertTrue(rs.next());
		rs.getInt(3);
		assertTrue(rs.wasNull());
	}

	@Test
	public void dateParameterNull() throws Exception {
		Connection conn = DriverManager.getConnection(getUrl());
		String timezone_offset_test = generateRandomString();
		String ddl = "CREATE TABLE IF NOT EXISTS " + timezone_offset_test + " "
				+ "(k1 INTEGER NOT NULL, dates DATE, v1 VARCHAR CONSTRAINT pk PRIMARY KEY (k1))";
		conn.createStatement().execute(ddl);
		String dml =
				"UPSERT INTO " + timezone_offset_test + " (k1, dates, v1) VALUES (2, null, 'Asia/Aden')";
		conn.createStatement().execute(dml);
		conn.commit();

		ResultSet rs = conn.createStatement().executeQuery(
				"SELECT k1, dates, TIMEZONE_OFFSET(v1, dates)"
				+ "FROM " + timezone_offset_test + " ORDER BY k1 ASC");

		assertTrue(rs.next());
		rs.getInt(3);
		assertTrue(rs.wasNull());
	}

	@Test
	public void testInsertingRetrivingTimestamp() throws Exception {
	    Connection conn = DriverManager.getConnection(getUrl());
		String t = generateRandomString();
		String ddl = "CREATE TABLE " + t + " (K INTEGER NOT NULL PRIMARY KEY, V TIMESTAMP)";
        conn.createStatement().execute(ddl);
        String dml = "UPSERT INTO " + t + " VALUES (?, ?)";
        PreparedStatement stmt = conn.prepareStatement(dml);
        stmt.setInt(1, 1);
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("US/Hawaii"));
        long time = System.currentTimeMillis();
        stmt.setTimestamp(2, new Timestamp(time), cal);
        stmt.executeUpdate();
        conn.commit();
        String query = "SELECT V FROM " + t;
        ResultSet rs = conn.createStatement().executeQuery(query);
        rs.next();
        assertEquals(new Timestamp(time), rs.getTimestamp(1));
        assertEquals(new Timestamp(time), rs.getTimestamp("V"));
        assertEquals(new Timestamp(time), rs.getTimestamp(1, cal));
        assertEquals(new Timestamp(time), rs.getTimestamp("V", cal));
    }

}


text:
@implementation UISpecDemoAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {

	EmployeeAdmin *employeeAdmin = [[[EmployeeAdmin alloc] initWithFrame:[window frame]] autorelease];
	[[ApplicationFacade getInstance] startup:employeeAdmin];
	[window addSubview:employeeAdmin];
    [window makeKeyAndVisible];
}

- (void)dealloc {
    [window release];
    [super dealloc];
}

@end


text:
package com.twitter.chill.java;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.serializers.JavaSerializer;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import com.twitter.chill.IKryoRegistrar;
import com.twitter.chill.SingleRegistrar;

import java.util.Locale;

/** The java serializer uses an cache of allocated instances so
 * it is probably a bit hard to beat, so why bother
 */
public class LocaleSerializer extends JavaSerializer {
   static public IKryoRegistrar registrar() {
      return new SingleRegistrar(Locale.class, new LocaleSerializer());
    }
}


text:
REG_FIDDLE(ColorGetG, 256, 256, false, 3) {
void draw(SkCanvas* canvas) {
    canvas->drawBitmap(source, 0, 0);
    SkPaint bgPaint;
    bgPaint.setColor(0xafffffff);
    canvas->drawRect({20, 50, 80, 70}, bgPaint);
    uint8_t green = SkColorGetG(source.getColor(57, 192));
    canvas->drawString(std::to_string(green).c_str(), 40, 65, SkPaint());
    canvas->drawLine(80, 70, 57, 192, SkPaint());
}
}  // END FIDDLE
#endif  // Disabled until updated to use current API.


text:
namespace Wiz.Econ;

public enum RegularSuit
{
    Hearts,
    Diamonds,
    Clubs,
    Spades
}


text:
package org.apache.reef.runtime.common.driver.context;

import org.apache.reef.annotations.audience.DriverSide;
import org.apache.reef.annotations.audience.Private;
import org.apache.reef.driver.context.ContextMessage;

/**
 * Driver-side representation of a context message.
 */
@Private
@DriverSide
public final class ContextMessageImpl implements ContextMessage {
  private final byte[] theMessage;
  private final String theContextID;
  private final String theMessageSourceId;

  public ContextMessageImpl(final byte[] theMessage, final String theContextID, final String theMessageSourceId) {
    this.theMessage = theMessage;
    this.theContextID = theContextID;
    this.theMessageSourceId = theMessageSourceId;
  }

  @Override
  public byte[] get() {
    return this.theMessage;
  }

  @Override
  public String getId() {
    return this.theContextID;
  }

  @Override
  public String getMessageSourceID() {
    return this.theMessageSourceId;
  }
}


text:
package org.apache.catalina.mbeans;

import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;
import javax.management.modelmbean.InvalidTargetObjectTypeException;

import org.apache.catalina.deploy.ContextEnvironment;
import org.apache.catalina.deploy.NamingResources;
import org.apache.tomcat.util.modeler.BaseModelMBean;

/**
 *
A ModelMBean implementation for the
 * org.apache.catalina.deploy.ContextEnvironment component.

 *
 * @author Amy Roh
 * @version $Id: ContextEnvironmentMBean.java 939305 2010-04-29 13:43:39Z kkolinko $
 */

public class ContextEnvironmentMBean extends BaseModelMBean {

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a ModelMBean with default
     * ModelMBeanInfo information.
     *
     * @exception MBeanException if the initializer of an object
     *  throws an exception
     * @exception RuntimeOperationsException if an IllegalArgumentException
     *  occurs
     */
    public ContextEnvironmentMBean()
        throws MBeanException, RuntimeOperationsException {

        super();

    }

    // ----------------------------------------------------- Instance Variables

    // ------------------------------------------------------------- Attributes

    /**
     * Set the value of a specific attribute of this MBean.
     *
     * @param attribute The identification of the attribute to be set
     *  and the new value
     *
     * @exception AttributeNotFoundException if this attribute is not
     *  supported by this MBean
     * @exception MBeanException if the initializer of an object
     *  throws an exception
     * @exception ReflectionException if a Java reflection exception
     *  occurs when invoking the getter
     */
     @Override
    public void setAttribute(Attribute attribute)
        throws AttributeNotFoundException, MBeanException,
        ReflectionException {

        super.setAttribute(attribute);

        ContextEnvironment ce = null;
        try {
            ce = (ContextEnvironment) getManagedResource();
        } catch (InstanceNotFoundException e) {
            throw new MBeanException(e);
        } catch (InvalidTargetObjectTypeException e) {
             throw new MBeanException(e);
        }

        // cannot use side-effects.  It's removed and added back each time
        // there is a modification in a resource.
        NamingResources nr = ce.getNamingResources();
        nr.removeEnvironment(ce.getName());
        nr.addEnvironment(ce);
    }

}


text:
"""Integration test for sequence feature columns with SequenceExamples."""

import string
import tempfile

from google.protobuf import text_format

from tensorflow.core.example import example_pb2
from tensorflow.python.feature_column import feature_column_v2 as fc
from tensorflow.python.feature_column import sequence_feature_column as sfc
from tensorflow.python.ops import parsing_ops
from tensorflow.python.platform import test
from tensorflow.python.util import compat

class SequenceExampleParsingTest(test.TestCase):

  def test_seq_ex_in_sequence_categorical_column_with_identity(self):
    self._test_parsed_sequence_example(
        'int_list', sfc.sequence_categorical_column_with_identity,
        10, [3, 6], [2, 4, 6])

  def test_seq_ex_in_sequence_categorical_column_with_hash_bucket(self):
    self._test_parsed_sequence_example(
        'bytes_list', sfc.sequence_categorical_column_with_hash_bucket,
        10, [3, 4], [compat.as_bytes(x) for x in 'acg'])

  def test_seq_ex_in_sequence_categorical_column_with_vocabulary_list(self):
    self._test_parsed_sequence_example(
        'bytes_list', sfc.sequence_categorical_column_with_vocabulary_list,
        list(string.ascii_lowercase), [3, 4],
        [compat.as_bytes(x) for x in 'acg'])

  def test_seq_ex_in_sequence_categorical_column_with_vocabulary_file(self):
    _, fname = tempfile.mkstemp()
    with open(fname, 'w') as f:
      f.write(string.ascii_lowercase)
    self._test_parsed_sequence_example(
        'bytes_list', sfc.sequence_categorical_column_with_vocabulary_file,
        fname, [3, 4], [compat.as_bytes(x) for x in 'acg'])

  def _test_parsed_sequence_example(
      self, col_name, col_fn, col_arg, shape, values):
    """Helper function to check that each FeatureColumn parses correctly.

    Args:
      col_name: string, name to give to the feature column. Should match
        the name that the column will parse out of the features dict.
      col_fn: function used to create the feature column. For example,
        sequence_numeric_column.
      col_arg: second arg that the target feature column is expecting.
      shape: the expected dense_shape of the feature after parsing into
        a SparseTensor.
      values: the expected values at index [0, 2, 6] of the feature
        after parsing into a SparseTensor.
    """
    example = _make_sequence_example()
    columns = [
        fc.categorical_column_with_identity('int_ctx', num_buckets=100),
        fc.numeric_column('float_ctx'),
        col_fn(col_name, col_arg)
    ]
    context, seq_features = parsing_ops.parse_single_sequence_example(
        example.SerializeToString(),
        context_features=fc.make_parse_example_spec_v2(columns[:2]),
        sequence_features=fc.make_parse_example_spec_v2(columns[2:]))

    with self.cached_session() as sess:
      ctx_result, seq_result = sess.run([context, seq_features])
      self.assertEqual(list(seq_result[col_name].dense_shape), shape)
      self.assertEqual(
          list(seq_result[col_name].values[[0, 2, 6]]), values)
      self.assertEqual(list(ctx_result['int_ctx'].dense_shape), [1])
      self.assertEqual(ctx_result['int_ctx'].values[0], 5)
      self.assertEqual(list(ctx_result['float_ctx'].shape), [1])
      self.assertAlmostEqual(ctx_result['float_ctx'][0], 123.6, places=1)

_SEQ_EX_PROTO = """
context {
  feature {
    key: "float_ctx"
    value {
      float_list {
        value: 123.6
      }
    }
  }
  feature {
    key: "int_ctx"
    value {
      int64_list {
        value: 5
      }
    }
  }
}
feature_lists {
  feature_list {
    key: "bytes_list"
    value {
      feature {
        bytes_list {
          value: "a"
        }
      }
      feature {
        bytes_list {
          value: "b"
          value: "c"
        }
      }
      feature {
        bytes_list {
          value: "d"
          value: "e"
          value: "f"
          value: "g"
        }
      }
    }
  }
  feature_list {
    key: "float_list"
    value {
      feature {
        float_list {
          value: 1.0
        }
      }
      feature {
        float_list {
          value: 3.0
          value: 3.0
          value: 3.0
        }
      }
      feature {
        float_list {
          value: 5.0
          value: 5.0
          value: 5.0
          value: 5.0
          value: 5.0
        }
      }
    }
  }
  feature_list {
    key: "int_list"
    value {
      feature {
        int64_list {
          value: 2
          value: 2
        }
      }
      feature {
        int64_list {
          value: 4
          value: 4
          value: 4
          value: 4
        }
      }
      feature {
        int64_list {
          value: 6
          value: 6
          value: 6
          value: 6
          value: 6
          value: 6
        }
      }
    }
  }
}
"""

def _make_sequence_example():
  example = example_pb2.SequenceExample()
  return text_format.Parse(_SEQ_EX_PROTO, example)

if __name__ == '__main__':
  test.main()


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message/extract' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'Click here to create an account:' => 'Нажмите сюда, чтобы создать учетную запись:',
    '{username} invited you to join "{space}" on {name}.' => '{username} пригласил вас присоединиться "{space}" к {name}.',
    '{username} invited you to {name}.' => '{username} пригласил вас в {name}.',
];


text:
	#include <string>

	//sanity check platform/endianess
	#if !defined(WIN_ENV) && !defined(MAC_ENV) && !defined(UNIX_ENV)
		#error "XMP environment error - must define one of MAC_ENV, WIN_ENV, or UNIX_ENV"
	#endif

	#ifdef WIN_ENV
		#define XMPQE_LITTLE_ENDIAN 1
	#elif defined(MAC_ENV)
		#if __BIG_ENDIAN__
			#define XMPQE_BIG_ENDIAN 1
		#elif __LITTLE_ENDIAN__
			#define XMPQE_LITTLE_ENDIAN 1
		#else
			#error "Neither __BIG_ENDIAN__ nor __LITTLE_ENDIAN__ is set"
		#endif
	#elif defined(UNIX_ENV)
		#include "XMP_UnixEndian.h"
		#if kBigEndianHost
			#define XMPQE_BIG_ENDIAN 1
		#else
			#define XMPQE_BIG_ENDIAN 0
		#endif
	#else
		#error "Unknown build environment, neither WIN_ENV nor MAC_ENV nor UNIX_ENV"
	#endif

	const static unsigned int XMPQE_BUFFERSIZE=4096; //should do for all my buffer output, but you never now (stdarg dilemma)

	const char OMNI_CSTRING[]={0x41,0xE4,0xB8,0x80,0x42,0xE4,0xBA,0x8C,0x43,0xC3,0x96,0x44,0xF0,0x90,0x81,0x91,0x45,'\0'};
	const char BOM_CSTRING[]={0xEF,0xBB,0xBF,'\0'}; // nb: forgetting the '\0' is a very evil mistake.
	const std::string OMNI_STRING(OMNI_CSTRING);
	// if plain utf8 conversion, mac/win local encoding is a different story...
	const std::string OMNI_BUGINESE("A<E4 B8 80>B<E4 BA 8C>C<C3 96>D<F0 90 81 91>E");
	// if utf16LE
	const std::string OMNI_BUGINESE_16LE("A<00 4E>B<8C 4E>C<D6 00>D<00 D8 51 DC>E");
	// if utf16 BE
	const std::string OMNI_BUGINESE_16BE("A<4E 00>B<4E 8C>C<00 D6>D<D8 00 DC 51>E");

	// degraded version of omni-strings
	// (sometimes useful for asserts after roundtrips, for setting values see OMNI_STRING in TestCase.h)
	// ==> filed bug 2302354 on this issue.
	#if WIN_ENV
		// a *wrongly* degraded omni-string (non-BMP-char to ??)
		const std::string DEG_OMNI_BUGINESE("A?B?C<C3 96>D??E");
		// ditto albeit MacRoman encoding
		const std::string MAC_OMNI_BUGINESE("A?B?C<85>D??E");
	#else
		// a *correctly* degraded omni-string (non-BMP-char to ?)
		const std::string DEG_OMNI_BUGINESE("A?B?C<C3 96>D?E");
		// ditto albeit MacRoman encoding
		const std::string MAC_OMNI_BUGINESE("A?B?C<85>D?E");
	#endif
	//  -> #issue# the non-BMP character in OMNI_STRING between D and E gets converted
	//      into two question marks (wrong) , not into one (correct)

	const char OEAEUE_UTF8_CSTRING[]={0xC3, 0x84, 0xC3, 0x96, 0xC3, 0x9C,'\0'};
	const std::string AEOEUE_UTF8(OEAEUE_UTF8_CSTRING);
	const std::string AEOEUE_UTF8_BUGINESE("<C3 84 C3 96 C3 9C>");

	const std::string AEOEUE_WIN_LOCAL_BUGINESE("<C4 D6 DC>");
	const std::string AEOEUE_MAC_LOCAL_BUGINESE("<80 85 86>");

	const std::string AEOEUE_WIN_MOJIBAKE_BUGINESE("<E2 82 AC E2 80 A6 E2 80 A0>");
	const std::string AEOEUE_MAC_MOJIBAKE_BUGINESE("<C6 92 C3 B7 E2 80 B9>");
	const std::string AEOEUE_LATIN1_MOJIBAKE_BUGINESE("<C2 80 C2 85 C2 86>");

	#if MAC_ENV
		const std::string AEOEUE_WIN_LOCAL_TO_UTF8 = AEOEUE_MAC_MOJIBAKE_BUGINESE;
		const std::string AEOEUE_MAC_LOCAL_TO_UTF8 = AEOEUE_UTF8_BUGINESE;
	#elif WIN_ENV
		const std::string AEOEUE_WIN_LOCAL_TO_UTF8 = AEOEUE_UTF8_BUGINESE;
		const std::string AEOEUE_MAC_LOCAL_TO_UTF8 = AEOEUE_WIN_MOJIBAKE_BUGINESE;
	#else
		// windows local encoding will work for UNIX (Latin1), but mac will result MOJIBAKE
		const std::string AEOEUE_WIN_LOCAL_TO_UTF8 = AEOEUE_UTF8_BUGINESE;
		const std::string AEOEUE_MAC_LOCAL_TO_UTF8 = AEOEUE_LATIN1_MOJIBAKE_BUGINESE;
	#endif

#endif // XMPQE_GLOBALS_H


text:
var GameOfLife;
GameOfLife = GameOfLife || function GameOfLife() {
  if(this.initialize) {
    this.initialize.apply(this, arguments);
  }
};
GameOfLife.prototype.currentCellGeneration =  null ;
GameOfLife.prototype.cellSize = 7;
GameOfLife.prototype.numberOfRows = 50;
GameOfLife.prototype.numberOfColumns = 50;
GameOfLife.prototype.seedProbability = 0.4;
GameOfLife.prototype.tickLength = 100;
GameOfLife.prototype.canvas =  null ;
GameOfLife.prototype.drawingContext =  null ;
GameOfLife.prototype.running =  false ;
GameOfLife.prototype.initialize = function() {
  this.createCanvas();
  this.resizeCanvas();
  this.createDrawingContext();
  this.clear();
};
GameOfLife.prototype.start = function() {
  if(this.running) {
     return  null ;
  };
  this.running =  true ;
  this.tick();
};
GameOfLife.prototype.stop = function() {
  this.running =  false ;
};
GameOfLife.prototype.createCanvas = function() {
  this.canvas = document.createElement('canvas');
  document.body.appendChild(this.canvas);
};
GameOfLife.prototype.resizeCanvas = function() {
  this.canvas.height =  this.cellSize * this.numberOfRows;
  this.canvas.width =  this.cellSize * this.numberOfColumns;
};
GameOfLife.prototype.createDrawingContext = function() {
  this.drawingContext = this.canvas.getContext('2d');
};
GameOfLife.prototype.seed = function() {

  var row,column,seedCell;
  this.currentCellGeneration = [];
  for(row = 0; row < this.numberOfRows;row++) {
  this.currentCellGeneration[row] = [];
  for(column = 0; column < this.numberOfColumns;column++) {
  seedCell = this.createSeedCell(row,column);
  this.currentCellGeneration[row][column] = seedCell;
  };
  };
  this.drawCells();
};
GameOfLife.prototype.clear = function() {

  var row,column,seedCell;
  this.currentCellGeneration = [];
  for(row = 0; row < this.numberOfRows;row++) {
  this.currentCellGeneration[row] = [];
  for(column = 0; column < this.numberOfColumns;column++) {
  seedCell = this.createSeedCell(row,column);
  seedCell.isAlive =  false ;
  this.currentCellGeneration[row][column] = seedCell;
  };
  };
  this.drawCells();
};
GameOfLife.prototype.createSeedCell = function(row,column) {
   return {    "isAlive":  Math.random() < this.seedProbability,     "row": row,     "column": column};
};
GameOfLife.prototype.drawCell = function(cell) {

  var x,y,fillStyle;
  x =  cell.column * this.cellSize;
  y =  cell.row * this.cellSize;
  if(cell.isAlive) {
    fillStyle = "rgb(242, 198, 65)";
  } else {
    fillStyle = "rgb(38, 38, 38)";
  };
  this.drawingContext.strokeStyle = "rgba(242, 198, 65, 0.1)";
  this.drawingContext.strokeRect(x,y,this.cellSize,this.cellSize);
  this.drawingContext.fillStyle = fillStyle;
  this.drawingContext.fillRect(x,y,this.cellSize,this.cellSize);
};
GameOfLife.prototype.drawCells = function() {

  var row,column;
  for(row = 0; row < this.numberOfRows;row++) {
  for(column = 0; column < this.numberOfColumns;column++) {
  this.drawCell(this.currentCellGeneration[row][column]);
  };
  };
};
GameOfLife.prototype.tick = function() {

  var newCellGeneration,row,column,evolvedCell,_this;
  this.drawCells();
  newCellGeneration = [];
  for(row = 0; row < this.numberOfRows;row++) {
  newCellGeneration[row] = [];
  for(column = 0; column < this.numberOfColumns;column++) {
  evolvedCell = this.evolveCell(this.currentCellGeneration[row][column]);
  newCellGeneration[row][column] = evolvedCell;
  };
  };
  this.currentCellGeneration = newCellGeneration;
  if(this.running) {
    _this = this;
    setTimeout(function() {
      _this.tick();
    },100);
  };
};
GameOfLife.prototype.sleep = function(milliseconds) {

  var start,i;
  start =  new Date().getTime();
  for(i = 0; i < 1e7;i++) {
  if( ( new  Date().getTime() - start) > milliseconds) {
    break;
  };
  };
};
GameOfLife.prototype.evolveCell = function(cell) {

  var evolvedCell,numberOfAliveNeighbors;
  evolvedCell = {    "row": cell.row,     "column": cell.column,     "isAlive": cell.isAlive};
  numberOfAliveNeighbors = this.countAliveNeighbors(cell);
  evolvedCell.isAlive =  false ;
  if( cell.isAlive &&  numberOfAliveNeighbors === 2) {
    evolvedCell.isAlive =  true ;
  }else if( cell.isAlive &&  numberOfAliveNeighbors === 3) {
    evolvedCell.isAlive =  true ;
  }else if( cell.isAlive ===   false  &&  numberOfAliveNeighbors === 3) {
    evolvedCell.isAlive =  true ;
  };
   return evolvedCell;
};
GameOfLife.prototype.countAliveNeighbors = function(cell) {

  var lowerRowBound,upperRowBound,lowerColumnBound,upperColumnBound,numberOfAliveNeighbors,row,column;
  lowerRowBound = Math.max( cell.row - 1,0);
  upperRowBound = Math.min( cell.row + 1, this.numberOfRows - 1);
  lowerColumnBound = Math.max( cell.column - 1,0);
  upperColumnBound = Math.min( cell.column + 1, this.numberOfColumns - 1);
  numberOfAliveNeighbors = 0;
  for(row = lowerRowBound; row <= upperRowBound;row++) {
  for(column = lowerColumnBound; column <= upperColumnBound;column++) {
  if( row ===  cell.row &&  column === cell.column) {
    continue;
  };
  if(this.currentCellGeneration[row][column].isAlive) {
    numberOfAliveNeighbors++;
  };
  };
  };
   return numberOfAliveNeighbors;
};
;
window.GameOfLife = GameOfLife;


text:
"use strict";

const { ServiceMgr } = require("service");
const { assertType } = require("misc");
const { Type } = require("typelib");
const { VERSION_SCHEMES } = require("version");
const BackendProxy = require("../backend_proxy");

class Repository extends Type {
    constructor(data) {
        super();

        this.backend = false;
        this.versionScheme = "default";
        this.hashAlgorithms = [ "md5", "sha1" ];

        if (data) {
            this.set(data);
        }
    }

    static get serviceName() {
        return ServiceMgr.instance.serviceName;
    }

    static get typeName() {
        return "repository";
    }

    static async _getDb() {
        return await ServiceMgr.instance.use("db");
    }

    static async _getMb() {
        return ServiceMgr.instance.msgBus;
    }

    async appendLog(id, data) {
        await BackendProxy.instance.appendLog(this, id, data);
    }

    async uploadLog(log, data) {
        return await BackendProxy.instance.uploadLog(this, log, data);
    }

    async saveLog(log) {
        await BackendProxy.instance.saveLog(this, log);
    }

    async _saveHook(olddata) {
        if (!olddata) {
            await BackendProxy.instance.createRepo(this);
        } else {
            await BackendProxy.instance.updateRepo(this);
        }
    }

    async _removeHook() {
        await BackendProxy.instance.removeRepo(this);
    }

    static async validate(event, data) {
        if (event === "create") {
            assertType(data.backend, "data.backend", "string");
            // Check that backend exists
            await BackendProxy.instance.getBackend(data.backend);

            if (data.versionScheme &&
                VERSION_SCHEMES.indexOf(data.versionScheme) === -1) {
                throw new Error(`Invalid version scheme ${data.versionScheme}`);
            }
        } else if (event === "update") {
            // TODO: Do some real check here
        }
    }
}

module.exports = Repository;


text:
namespace lly {

	class CommonUtil
	{
	public:
		static void log(const char* format, ...);

	private:
		CommonUtil();
		~CommonUtil();
	};
}

#endif


text:
// -----------------------------------------------------------------------
//  <copyright file="AbstractBuilder.cs" company="OSharp开源团队">
//      Copyright (c) 2014 OSharp. All rights reserved.
//  </copyright>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2014:07:05 20:52</last-date>
// -----------------------------------------------------------------------

using System.Security.Cryptography;
using System.Text;

using Xunit;

namespace OSharp.Utility.Secutiry.Tests
{

    public class DesHelperTests
    {
        [Fact()]
        public void DesHelperTest()
        {
            Assert.Equal(new DesHelper(false).Key.Length, 8);
            Assert.Equal(new DesHelper(true).Key.Length, 24);
        }

        [Fact()]
        public void EncryptTest()
        {
            string key = "12345678";
            string actual = "TMR29YtnGPI=";
            DesHelper des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Encrypt("admin"), actual);
            Assert.Equal(DesHelper.Encrypt("admin", key), actual);

            //弱密钥
            key = "123456781234567812345678";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Throws<CryptographicException>(() => des.Encrypt("admin"));

            key = "!@#$%^&*QWERTYUI12345678";
            actual = "Qp4r67VJ8Z0=";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Encrypt("admin"), actual);
            Assert.Equal(DesHelper.Encrypt("admin", key), actual);
        }

        [Fact()]
        public void DecryptTest()
        {
            string key = "12345678";
            string actual = "TMR29YtnGPI=";
            DesHelper des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Decrypt(actual), "admin");
            Assert.Equal(DesHelper.Decrypt(actual, key), "admin");

            key = "!@#$%^&*QWERTYUI12345678";
            actual = "Qp4r67VJ8Z0=";
            des = new DesHelper(Encoding.UTF8.GetBytes(key));
            Assert.Equal(des.Decrypt(actual), "admin");
            Assert.Equal(DesHelper.Decrypt(actual, key), "admin");
        }

        public void EncryptAndDecryptTest()
        {
            DesHelper des = new DesHelper();
            Assert.Equal(des.Decrypt(des.Encrypt("admin")), "admin");
            des = new DesHelper(true);
            Assert.Equal(des.Decrypt(des.Encrypt("admin")), "admin");
        }
    }
}


text:
package br.gov.siscomex.portalunico.duimp_api.model;

import java.util.List;

import javax.validation.Valid;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "CondicaoVendaConsultaItemCover", propOrder =
    { "metodoValoracao", "incoterm", "valorBRL", "valorMoedaNegociada", "frete", "seguro", "acrescimosDeducoes"
})

@XmlRootElement(name="CondicaoVendaConsultaItemCover")
/**
  * Condição de venda da mercadoria.
 **/
@ApiModel(description="Condição de venda da mercadoria.")
public class CondicaoVendaConsultaItemCover  {

  @XmlElement(name="metodoValoracao")
  @ApiModelProperty(value = "")
  @Valid
  private MetodoValoracaoCover metodoValoracao = null;

  @XmlElement(name="incoterm")
  @ApiModelProperty(value = "")
  @Valid
  private IncotermCover incoterm = null;

  @XmlElement(name="valorBRL")
  @ApiModelProperty(example = "1.0", value = "Valor na moeda negociada convertido em R$ (Reais).
Tamanho: 13,2
Formato: Decimal, com até 2 casas decimais separadas por ponto.")
 /**
   * Valor na moeda negociada convertido em R$ (Reais).
Tamanho: 13,2
Formato: Decimal, com até 2 casas decimais separadas por ponto.
  **/
  private Double valorBRL = null;

  @XmlElement(name="valorMoedaNegociada")
  @ApiModelProperty(example = "1.0", value = "Valor na moeda negociada.
Tamanho: 13,2
Formato: Decimal, com até 2 casas decimais separadas por ponto.")
 /**
   * Valor na moeda negociada.
Tamanho: 13,2
Formato: Decimal, com até 2 casas decimais separadas por ponto.
  **/
  private Double valorMoedaNegociada = null;

  @XmlElement(name="frete")
  @ApiModelProperty(value = "")
  @Valid
  private FreteConsultaItemCover frete = null;

  @XmlElement(name="seguro")
  @ApiModelProperty(value = "")
  @Valid
  private SeguroConsultaItemCover seguro = null;

  @XmlElement(name="acrescimosDeducoes")
  @ApiModelProperty(value = "")
  @Valid
  private List<AcrescimoDeducaoConsultaItemCover> acrescimosDeducoes = null;
 /**
   * Get metodoValoracao
   * @return metodoValoracao
  **/
  @JsonProperty("metodoValoracao")
  public MetodoValoracaoCover getMetodoValoracao() {
    return metodoValoracao;
  }

  public void setMetodoValoracao(MetodoValoracaoCover metodoValoracao) {
    this.metodoValoracao = metodoValoracao;
  }

  public CondicaoVendaConsultaItemCover metodoValoracao(MetodoValoracaoCover metodoValoracao) {
    this.metodoValoracao = metodoValoracao;
    return this;
  }

 /**
   * Get incoterm
   * @return incoterm
  **/
  @JsonProperty("incoterm")
  public IncotermCover getIncoterm() {
    return incoterm;
  }

  public void setIncoterm(IncotermCover incoterm) {
    this.incoterm = incoterm;
  }

  public CondicaoVendaConsultaItemCover incoterm(IncotermCover incoterm) {
    this.incoterm = incoterm;
    return this;
  }

 /**
   * Valor na moeda negociada convertido em R$ (Reais).<br>Tamanho: 13,2<br>Formato: Decimal, com até 2 casas decimais separadas por ponto.
   * @return valorBRL
  **/
  @JsonProperty("valorBRL")
  public Double getValorBRL() {
    return valorBRL;
  }

  public void setValorBRL(Double valorBRL) {
    this.valorBRL = valorBRL;
  }

  public CondicaoVendaConsultaItemCover valorBRL(Double valorBRL) {
    this.valorBRL = valorBRL;
    return this;
  }

 /**
   * Valor na moeda negociada.<br>Tamanho: 13,2<br>Formato: Decimal, com até 2 casas decimais separadas por ponto.
   * @return valorMoedaNegociada
  **/
  @JsonProperty("valorMoedaNegociada")
  public Double getValorMoedaNegociada() {
    return valorMoedaNegociada;
  }

  public void setValorMoedaNegociada(Double valorMoedaNegociada) {
    this.valorMoedaNegociada = valorMoedaNegociada;
  }

  public CondicaoVendaConsultaItemCover valorMoedaNegociada(Double valorMoedaNegociada) {
    this.valorMoedaNegociada = valorMoedaNegociada;
    return this;
  }

 /**
   * Get frete
   * @return frete
  **/
  @JsonProperty("frete")
  public FreteConsultaItemCover getFrete() {
    return frete;
  }

  public void setFrete(FreteConsultaItemCover frete) {
    this.frete = frete;
  }

  public CondicaoVendaConsultaItemCover frete(FreteConsultaItemCover frete) {
    this.frete = frete;
    return this;
  }

 /**
   * Get seguro
   * @return seguro
  **/
  @JsonProperty("seguro")
  public SeguroConsultaItemCover getSeguro() {
    return seguro;
  }

  public void setSeguro(SeguroConsultaItemCover seguro) {
    this.seguro = seguro;
  }

  public CondicaoVendaConsultaItemCover seguro(SeguroConsultaItemCover seguro) {
    this.seguro = seguro;
    return this;
  }

 /**
   * Get acrescimosDeducoes
   * @return acrescimosDeducoes
  **/
  @JsonProperty("acrescimosDeducoes")
  public List<AcrescimoDeducaoConsultaItemCover> getAcrescimosDeducoes() {
    return acrescimosDeducoes;
  }

  public void setAcrescimosDeducoes(List<AcrescimoDeducaoConsultaItemCover> acrescimosDeducoes) {
    this.acrescimosDeducoes = acrescimosDeducoes;
  }

  public CondicaoVendaConsultaItemCover acrescimosDeducoes(List<AcrescimoDeducaoConsultaItemCover> acrescimosDeducoes) {
    this.acrescimosDeducoes = acrescimosDeducoes;
    return this;
  }

  public CondicaoVendaConsultaItemCover addAcrescimosDeducoesItem(AcrescimoDeducaoConsultaItemCover acrescimosDeducoesItem) {
    this.acrescimosDeducoes.add(acrescimosDeducoesItem);
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CondicaoVendaConsultaItemCover {\n");

    sb.append("    metodoValoracao: ").append(toIndentedString(metodoValoracao)).append("\n");
    sb.append("    incoterm: ").append(toIndentedString(incoterm)).append("\n");
    sb.append("    valorBRL: ").append(toIndentedString(valorBRL)).append("\n");
    sb.append("    valorMoedaNegociada: ").append(toIndentedString(valorMoedaNegociada)).append("\n");
    sb.append("    frete: ").append(toIndentedString(frete)).append("\n");
    sb.append("    seguro: ").append(toIndentedString(seguro)).append("\n");
    sb.append("    acrescimosDeducoes: ").append(toIndentedString(acrescimosDeducoes)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private static String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
VERSION=${1}

if [ -z "$VERSION" ]; then
    echo "Usage: ${0} <version>"
    exit 1
fi

cd `dirname $0`

DIR="release-${VERSION}"
rm -fr ${DIR}
mkdir ${DIR}
cd ${DIR}

# iOS

CORE_DIR="adswitcher-ios-${VERSION}"
ADAPTERS_DIR="adswitcher-ios-adapters-${VERSION}"

mkdir ios
cd ios

mkdir ${CORE_DIR}
mkdir ${ADAPTERS_DIR}

cp -R ../../AdSwitcher-iOS/AdSwitcher/AdSwitcher ./${CORE_DIR}
cp -R ../../AdSwitcher-iOS/AdSwitcher/Adapters ./${ADAPTERS_DIR}

find . -name ".*" -type f | xargs -I{} rm -f {}
find ${ADAPTERS_DIR} -name "Libraries" -type d | xargs -I{} rm -fr {}

zip -r ${CORE_DIR}.zip ${CORE_DIR}
zip -r ${ADAPTERS_DIR}.zip ${ADAPTERS_DIR}

rm -fr ${CORE_DIR}
rm -fr ${ADAPTERS_DIR}

cd ..

# Android

mkdir android
cd android

CORE_DIR="adswitcher-android-${VERSION}"
ADAPTERS_DIR="adswitcher-android-adapters-${VERSION}"

mkdir ${CORE_DIR}
mkdir ${ADAPTERS_DIR}

cp ../../AdSwitcher-Android/libs/*.jar ${ADAPTERS_DIR}
mv ${ADAPTERS_DIR}/adswitcher.jar ${CORE_DIR}

zip -r ${CORE_DIR}.zip ${CORE_DIR}
zip -r ${ADAPTERS_DIR}.zip ${ADAPTERS_DIR}

rm -fr ${CORE_DIR}
rm -fr ${ADAPTERS_DIR}

cd ..

# Unity

mkdir unity
cd unity

CORE_DIR="adswitcher-unity-${VERSION}"
ADAPTERS_DIR="adswitcher-unity-adapters-${VERSION}"

mkdir ${CORE_DIR}
mkdir ${ADAPTERS_DIR}

cp ../../AdSwitcher-Unity/AdSwitcher.unitypackage ${CORE_DIR}
cp ../../AdSwitcher-Unity/Adapters/*.unitypackage ${ADAPTERS_DIR}/.

zip -r ${CORE_DIR}.zip ${CORE_DIR}
zip -r ${ADAPTERS_DIR}.zip ${ADAPTERS_DIR}

rm -fr ${CORE_DIR}
rm -fr ${ADAPTERS_DIR}

cd ..


text:
/*global Worker, Blob*/

/* https://github.com/zevero/worker-create
 * Create a worker without using a seperate worker.js file either from function or from string
 */

'use strict';
Worker.createURL = function(func_or_string){
    var str = (typeof func_or_string === 'function')?func_or_string.toString():func_or_string;
    var blob = new Blob(['\'use strict\';\nself.onmessage ='+str], { type: 'text/javascript' });
    return window.URL.createObjectURL(blob);
};

Worker.create = function(func_or_string){
  return new Worker(Worker.createURL(func_or_string));
};


text:
#include "common.h"
#include "hash.h"
#include "str.h"
#include "strescape.h"
#include "ostream.h"
#include "connect-limit.h"

struct ident_pid {
	/* ident string points to ident_hash keys */
	const char *ident;
	pid_t pid;
	unsigned int refcount;
};

struct connect_limit {
	/* ident => unsigned int refcount */
	HASH_TABLE(char *, void *) ident_hash;
	/* struct ident_pid => struct ident_pid */
	HASH_TABLE(struct ident_pid *, struct ident_pid *) ident_pid_hash;
};

static unsigned int ident_pid_hash(const struct ident_pid *i)
{
	return str_hash(i->ident) ^ i->pid;
}

static int ident_pid_cmp(const struct ident_pid *i1, const struct ident_pid *i2)
{
	if (i1->pid < i2->pid)
		return -1;
	else if (i1->pid > i2->pid)
		return 1;
	else
		return strcmp(i1->ident, i2->ident);
}

struct connect_limit *connect_limit_init(void)
{
	struct connect_limit *limit;

	limit = i_new(struct connect_limit, 1);
	hash_table_create(&limit->ident_hash, default_pool, 0, str_hash, strcmp);
	hash_table_create(&limit->ident_pid_hash, default_pool, 0,
			  ident_pid_hash, ident_pid_cmp);
	return limit;
}

void connect_limit_deinit(struct connect_limit **_limit)
{
	struct connect_limit *limit = *_limit;

	*_limit = NULL;
	hash_table_destroy(&limit->ident_hash);
	hash_table_destroy(&limit->ident_pid_hash);
	i_free(limit);
}

unsigned int connect_limit_lookup(struct connect_limit *limit,
				  const char *ident)
{
	void *value;

	value = hash_table_lookup(limit->ident_hash, ident);
	return POINTER_CAST_TO(value, unsigned int);
}

void connect_limit_connect(struct connect_limit *limit, pid_t pid,
			   const char *ident)
{
	struct ident_pid *i, lookup_i;
	char *key;
	void *value;

	if (!hash_table_lookup_full(limit->ident_hash, ident,
				    &key, &value)) {
		key = i_strdup(ident);
		value = POINTER_CAST(1);
		hash_table_insert(limit->ident_hash, key, value);
	} else {
		value = POINTER_CAST(POINTER_CAST_TO(value, unsigned int) + 1);
		hash_table_update(limit->ident_hash, key, value);
	}

	lookup_i.ident = ident;
	lookup_i.pid = pid;
	i = hash_table_lookup(limit->ident_pid_hash, &lookup_i);
	if (i == NULL) {
		i = i_new(struct ident_pid, 1);
		i->ident = key;
		i->pid = pid;
		i->refcount = 1;
		hash_table_insert(limit->ident_pid_hash, i, i);
	} else {
		i->refcount++;
	}
}

static void
connect_limit_ident_hash_unref(struct connect_limit *limit, const char *ident)
{
	char *key;
	void *value;
	unsigned int new_refcount;

	if (!hash_table_lookup_full(limit->ident_hash, ident, &key, &value))
		i_panic("connect limit hash tables are inconsistent");

	new_refcount = POINTER_CAST_TO(value, unsigned int) - 1;
	if (new_refcount > 0) {
		value = POINTER_CAST(new_refcount);
		hash_table_update(limit->ident_hash, key, value);
	} else {
		hash_table_remove(limit->ident_hash, key);
		i_free(key);
	}
}

void connect_limit_disconnect(struct connect_limit *limit, pid_t pid,
			      const char *ident)
{
	struct ident_pid *i, lookup_i;

	lookup_i.ident = ident;
	lookup_i.pid = pid;

	i = hash_table_lookup(limit->ident_pid_hash, &lookup_i);
	if (i == NULL) {
		i_error("connect limit: disconnection for unknown "
			"pid %s + ident %s", dec2str(pid), ident);
		return;
	}

	if (--i->refcount == 0) {
		hash_table_remove(limit->ident_pid_hash, i);
		i_free(i);
	}

	connect_limit_ident_hash_unref(limit, ident);
}

void connect_limit_disconnect_pid(struct connect_limit *limit, pid_t pid)
{
	struct hash_iterate_context *iter;
	struct ident_pid *i, *value;

	/* this should happen rarely (or never), so this slow implementation
	   should be fine. */
	iter = hash_table_iterate_init(limit->ident_pid_hash);
	while (hash_table_iterate(iter, limit->ident_pid_hash, &i, &value)) {
		if (i->pid == pid) {
			hash_table_remove(limit->ident_pid_hash, i);
			for (; i->refcount > 0; i->refcount--)
				connect_limit_ident_hash_unref(limit, i->ident);
			i_free(i);
		}
	}
	hash_table_iterate_deinit(&iter);
}

void connect_limit_dump(struct connect_limit *limit, struct ostream *output)
{
	struct hash_iterate_context *iter;
	struct ident_pid *i, *value;
	string_t *str = t_str_new(256);

	iter = hash_table_iterate_init(limit->ident_pid_hash);
	while (hash_table_iterate(iter, limit->ident_pid_hash, &i, &value)) {
		str_truncate(str, 0);
		str_append_tabescaped(str, i->ident);
		str_printfa(str, "\t%ld\t%u\n", (long)i->pid, i->refcount);
		if (o_stream_send(output, str_data(str), str_len(str)) < 0)
			break;
	}
	hash_table_iterate_deinit(&iter);
	o_stream_nsend(output, "\n", 1);
}


text:
package ch.epfl.bbp.uima.ae;

import static ch.epfl.bbp.uima.BlueCasUtil.haveSameBeginEnd;
import static ch.epfl.bbp.uima.ae.CopyAnnotationsAnnotator.DELETE_FROM;
import static ch.epfl.bbp.uima.ae.CopyAnnotationsAnnotator.FROM_ANNOTATION;
import static ch.epfl.bbp.uima.ae.CopyAnnotationsAnnotator.TO_ANNOTATION;
import static ch.epfl.bbp.uima.testutils.UimaTests.getTestCas;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.pipeline.SimplePipeline.runPipeline;
import static org.apache.uima.fit.util.JCasUtil.exists;
import static org.apache.uima.fit.util.JCasUtil.select;

import java.util.Collection;

import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.junit.Test;

import ch.epfl.bbp.uima.types.Measure;
import ch.epfl.bbp.uima.types.Protein;

public class CopyAnnotationsAnnotatorTest {

    @Test
    public void test() throws Exception {

        AnalysisEngineDescription copyAnnots = createEngineDescription(
                CopyAnnotationsAnnotator.class, //
                FROM_ANNOTATION, Protein.class.getName(),//
                TO_ANNOTATION, Measure.class.getName());

        JCas jCas = getTestCas();
        assertEquals("has a DocumentAnnotation at first", 1,
                select(jCas, Annotation.class).size());

        Protein p = new Protein(jCas, 5, 10);
        p.addToIndexes();
        runPipeline(jCas, copyAnnots);

        assertTrue(!exists(jCas, Protein.class));
        Collection<Measure> m = select(jCas, Measure.class);
        assertEquals("copied to measure", 1, m.size());
        assertTrue(haveSameBeginEnd(p, m.iterator().next()));

        // copy it back
        AnalysisEngineDescription copyAnnotsBack = createEngineDescription(
                CopyAnnotationsAnnotator.class, //
                FROM_ANNOTATION, Measure.class.getName(), //
                TO_ANNOTATION, Protein.class.getName());
        runPipeline(jCas, copyAnnotsBack);

        assertTrue(!exists(jCas, Measure.class));
        Collection<Protein> pBack = select(jCas, Protein.class);
        assertEquals("copied to protein", 1, pBack.size());
        assertTrue(haveSameBeginEnd(p, pBack.iterator().next()));
    }

    @Test
    public void testDoNotDelete() throws Exception {

        AnalysisEngineDescription copyAnnots = createEngineDescription(
                CopyAnnotationsAnnotator.class, //
                FROM_ANNOTATION, Protein.class.getName(),//
                TO_ANNOTATION, Measure.class.getName(),//
                DELETE_FROM, false);

        JCas jCas = getTestCas();
        assertEquals("has a DocumentAnnotation at first", 1,
                select(jCas, Annotation.class).size());

        Protein p = new Protein(jCas, 5, 10);
        p.addToIndexes();
        runPipeline(jCas, copyAnnots);
        assertTrue(exists(jCas, Protein.class));
    }
}


text:
package org.apache.syncope.ext.scimv2.api.service;

import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import org.apache.syncope.ext.scimv2.api.SCIMConstants;
import org.apache.syncope.ext.scimv2.api.data.ListResponse;
import org.apache.syncope.ext.scimv2.api.data.SCIMResource;
import org.apache.syncope.ext.scimv2.api.data.SCIMSearchRequest;
import org.apache.syncope.ext.scimv2.api.type.SortOrder;

public interface ReadService<R extends SCIMResource> {

    @GET
    @Path("{id}")
    @Produces({ SCIMConstants.APPLICATION_SCIM_JSON })
    R get(@NotNull @PathParam("id") String id,
            @QueryParam("attributes") String attributes,
            @QueryParam("excludedAttributes") String excludedAttributes);

    @GET
    @Produces({ SCIMConstants.APPLICATION_SCIM_JSON })
    ListResponse<R> search(
            @QueryParam("attributes") String attributes,
            @QueryParam("excludedAttributes") String excludedAttributes,
            @QueryParam("filter") String filter,
            @QueryParam("sortBy") String sortBy,
            @QueryParam("sortOrder") SortOrder sortOrder,
            @QueryParam("startIndex") Integer startIndex,
            @QueryParam("count") Integer count);

    @POST
    @Path(".search")
    @Produces({ SCIMConstants.APPLICATION_SCIM_JSON })
    @Consumes({ SCIMConstants.APPLICATION_SCIM_JSON })
    ListResponse<R> search(SCIMSearchRequest request);
}


text:
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  get '/', to: 'main#index'
  post '/send_email', to: 'main#send_email'

  # Serve websocket cable requests in-process
  # mount ActionCable.server => '/cable'
end


text:
export declare type JobType = 'dps' | 'healer' | 'tank' | 'hand' | 'land' | 'unknown';
export interface EncounterData {
    duration: string;
    durationSeconds: number;
    zoneName: string;
    dps: number;
    last10DPS: number;
    last30DPS: number;
    last60DPS: number;
    hps: number;
    damage: number;
    healed: number;
    shield: number;
}
export interface LimitBreakData {
    name: 'Limit Break';
    dps: number;
    hps: number;
    damage: number;
    healed: number;
    shield: number;
    maxHit: string;
    maxHeal: string;
}
export interface CombatantData {
    name: string;
    job: string;
    jobType: JobType;
    dps: number;
    last10DPS: number;
    last30DPS: number;
    last60DPS: number;
    hps: number;
    swings: number;
    hits: number;
    deaths: number;
    directHits: number;
    directHitPct: string;
    critHits: number;
    critHitPct: string;
    directCritHits: number;
    directCritHitPct: string;
    damage: number;
    damageTaken: number;
    damagePct: string;
    healed: number;
    healsTaken: number;
    healsPct: string;
    overHeal: number;
    overHealPct: string;
    shield: number;
    shieldPct: string;
    maxHit: string;
    maxHitDamage: number;
    maxHeal: string;
    maxHealDamage: number;
}
export interface ExtendData {
    isActive: boolean;
    encounter: EncounterData;
    combatant: CombatantData[];
    limitBreak?: LimitBreakData;
}
export declare type EventType = 'CombatData' | 'LogLine' | 'ImportedLogLines' | 'ChangeZone' | 'ChangePrimaryPlayer' | 'OnlineStatusChanged' | 'PartyChanged' | 'BroadcastMessage';
export interface EventData {
    type: EventType;
    extendData?: ExtendData;
    rseq?: number;
    [key: string]: any;
}
export declare type EventCallback = (data: EventData) => any;


text:
module RepositoriesHelper
  def field_for_attribute(attribute, t_class, form)
    unless t_class.columns_hash[attribute].nil?
      self.send(("field_for_" + t_class.columns_hash[attribute].type.to_s).to_sym, attribute, form, t_class)
    else
      # this is for the simple-enum fields, which are not present in the columns hash, as is...
      field_for_enum(attribute, form, t_class)
    end
  end

  def field_for_string(attribute, form, t_class)
    if attribute.include?("password")
      return form.password_field(attribute, default_value(attribute, t_class))
    else
      return form.text_field(attribute, default_value(attribute, t_class))
    end
  end

  def field_for_datetime(attribute, form, t_class)
    return form.datetime_select(attribute, default_value(attribute, t_class))
  end

  def field_for_integer(attribute, form, t_class)
    return form.number_field(attribute, default_value(attribute, t_class))
  end

  def field_for_boolean(attribute, form, t_class)
    return form.check_box(attribute, default_value(attribute, t_class))
  end

  def field_for_text(attribute, form, t_class)
    return form.text_area(attribute, default_value(attribute, t_class).merge({:rows => 5}))
  end

  def field_for_enum(attribute, form, t_class)
    return form.select(attribute, options_from_collection_for_select(t_class.class_eval(attribute.pluralize).keys, "to_s", "to_s"))
  end

  def default_value(attribute, t_class)
    if t_class.respond_to?("default_#{attribute}".to_sym)
      return {:value => t_class.send("default_#{attribute}".to_sym)}
    else
      return {}
    end
  end
end