text:
import os.path as op

import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_allclose,
                           assert_equal)
import pytest

import copy as cp

import mne
from mne.datasets import testing
from mne.io import read_raw_fif
from mne import (compute_proj_epochs, compute_proj_evoked, compute_proj_raw,
                 pick_types, read_events, Epochs, sensitivity_map,
                 read_source_estimate)
from mne.io.proj import (make_projector, activate_proj,
                         _needs_eeg_average_ref_proj)
from mne.proj import (read_proj, write_proj, make_eeg_average_ref_proj,
                      _has_eeg_average_ref_proj)
from mne.utils import _TempDir, run_tests_if_main

base_dir = op.join(op.dirname(__file__), '..', 'io', 'tests', 'data')
raw_fname = op.join(base_dir, 'test_raw.fif')
event_fname = op.join(base_dir, 'test-eve.fif')
proj_fname = op.join(base_dir, 'test-proj.fif')
proj_gz_fname = op.join(base_dir, 'test-proj.fif.gz')
bads_fname = op.join(base_dir, 'test_bads.txt')

sample_path = op.join(testing.data_path(download=False), 'MEG', 'sample')
fwd_fname = op.join(sample_path, 'sample_audvis_trunc-meg-eeg-oct-4-fwd.fif')
sensmap_fname = op.join(sample_path,
                        'sample_audvis_trunc-%s-oct-4-fwd-sensmap-%s.w')

eog_fname = op.join(sample_path, 'sample_audvis_eog-proj.fif')
ecg_fname = op.join(sample_path, 'sample_audvis_ecg-proj.fif')

def test_bad_proj():
    """Test dealing with bad projection application."""
    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    picks = pick_types(raw.info, meg=True, stim=False, ecg=False,
                       eog=False, exclude='bads')
    picks = picks[2:18:3]
    _check_warnings(raw, events, picks)
    # still bad
    raw.pick_channels([raw.ch_names[ii] for ii in picks])
    _check_warnings(raw, events)
    # "fixed"
    raw.info.normalize_proj()  # avoid projection warnings
    _check_warnings(raw, events, count=0)
    # eeg avg ref is okay
    raw = read_raw_fif(raw_fname, preload=True).pick_types(meg=False, eeg=True)
    raw.set_eeg_reference(projection=True)
    _check_warnings(raw, events, count=0)
    raw.info['bads'] = raw.ch_names[:10]
    _check_warnings(raw, events, count=0)

    raw = read_raw_fif(raw_fname)
    pytest.raises(ValueError, raw.del_proj, 'foo')
    n_proj = len(raw.info['projs'])
    raw.del_proj(0)
    assert_equal(len(raw.info['projs']), n_proj - 1)
    raw.del_proj()
    assert_equal(len(raw.info['projs']), 0)

    # Ensure we deal with newer-style Neuromag projs properly, were getting:
    #
    #     Projection vector "PCA-v2" has magnitude 1.00 (should be unity),
    #     applying projector with 101/306 of the original channels available
    #     may be dangerous.
    raw = read_raw_fif(raw_fname).crop(0, 1)
    raw.info['bads'] = ['MEG 0111']
    meg_picks = mne.pick_types(raw.info, meg=True, exclude=())
    ch_names = [raw.ch_names[pick] for pick in meg_picks]
    for p in raw.info['projs'][:-1]:
        data = np.zeros((1, len(ch_names)))
        idx = [ch_names.index(ch_name) for ch_name in p['data']['col_names']]
        data[:, idx] = p['data']['data']
        p['data'].update(ncol=len(meg_picks), col_names=ch_names, data=data)
    mne.cov.regularize(mne.compute_raw_covariance(raw, verbose='error'),
                       raw.info)

def _check_warnings(raw, events, picks=None, count=3):
    """Count warnings."""
    with pytest.warns(None) as w:
        Epochs(raw, events, dict(aud_l=1, vis_l=3),
               -0.2, 0.5, picks=picks, preload=True, proj=True)
    assert len(w) == count
    assert all('dangerous' in str(ww.message) for ww in w)

@testing.requires_testing_data
def test_sensitivity_maps():
    """Test sensitivity map computation."""
    fwd = mne.read_forward_solution(fwd_fname)
    fwd = mne.convert_forward_solution(fwd, surf_ori=True)
    projs = read_proj(eog_fname)
    projs.extend(read_proj(ecg_fname))
    decim = 6
    for ch_type in ['eeg', 'grad', 'mag']:
        w = read_source_estimate(sensmap_fname % (ch_type, 'lh')).data
        stc = sensitivity_map(fwd, projs=None, ch_type=ch_type,
                              mode='free', exclude='bads')
        assert_array_almost_equal(stc.data, w, decim)
        assert stc.subject == 'sample'
        # let's just make sure the others run
        if ch_type == 'grad':
            # fixed (2)
            w = read_source_estimate(sensmap_fname % (ch_type, '2-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='fixed',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'mag':
            # ratio (3)
            w = read_source_estimate(sensmap_fname % (ch_type, '3-lh')).data
            stc = sensitivity_map(fwd, projs=None, mode='ratio',
                                  ch_type=ch_type, exclude='bads')
            assert_array_almost_equal(stc.data, w, decim)
        if ch_type == 'eeg':
            # radiality (4), angle (5), remaining (6), and  dampening (7)
            modes = ['radiality', 'angle', 'remaining', 'dampening']
            ends = ['4-lh', '5-lh', '6-lh', '7-lh']
            for mode, end in zip(modes, ends):
                w = read_source_estimate(sensmap_fname % (ch_type, end)).data
                stc = sensitivity_map(fwd, projs=projs, mode=mode,
                                      ch_type=ch_type, exclude='bads')
                assert_array_almost_equal(stc.data, w, decim)

    # test corner case for EEG
    stc = sensitivity_map(fwd, projs=[make_eeg_average_ref_proj(fwd['info'])],
                          ch_type='eeg', exclude='bads')
    # test corner case for projs being passed but no valid ones (#3135)
    pytest.raises(ValueError, sensitivity_map, fwd, projs=None, mode='angle')
    pytest.raises(RuntimeError, sensitivity_map, fwd, projs=[], mode='angle')
    # test volume source space
    fname = op.join(sample_path, 'sample_audvis_trunc-meg-vol-7-fwd.fif')
    fwd = mne.read_forward_solution(fname)
    sensitivity_map(fwd)

def test_compute_proj_epochs():
    """Test SSP computation on epochs."""
    tempdir = _TempDir()
    event_id, tmin, tmax = 1, -0.2, 0.3

    raw = read_raw_fif(raw_fname, preload=True)
    events = read_events(event_fname)
    bad_ch = 'MEG 2443'
    picks = pick_types(raw.info, meg=True, eeg=False, stim=False, eog=False,
                       exclude=[])
    epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks,
                    baseline=None, proj=False)

    evoked = epochs.average()
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1)
    write_proj(op.join(tempdir, 'test-proj.fif.gz'), projs)
    for p_fname in [proj_fname, proj_gz_fname,
                    op.join(tempdir, 'test-proj.fif.gz')]:
        projs2 = read_proj(p_fname)

        assert len(projs) == len(projs2)

        for p1, p2 in zip(projs, projs2):
            assert p1['desc'] == p2['desc']
            assert p1['data']['col_names'] == p2['data']['col_names']
            assert p1['active'] == p2['active']
            # compare with sign invariance
            p1_data = p1['data']['data'] * np.sign(p1['data']['data'][0, 0])
            p2_data = p2['data']['data'] * np.sign(p2['data']['data'][0, 0])
            if bad_ch in p1['data']['col_names']:
                bad = p1['data']['col_names'].index('MEG 2443')
                mask = np.ones(p1_data.size, dtype=np.bool)
                mask[bad] = False
                p1_data = p1_data[:, mask]
                p2_data = p2_data[:, mask]
            corr = np.corrcoef(p1_data, p2_data)[0, 1]
            assert_array_almost_equal(corr, 1.0, 5)
            if p2['explained_var']:
                assert_array_almost_equal(p1['explained_var'],
                                          p2['explained_var'])

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, epochs.ch_names, bads=[])

    assert nproj == 2
    assert U.shape[1] == 2

    # test that you can save them
    epochs.info['projs'] += projs
    evoked = epochs.average()
    evoked.save(op.join(tempdir, 'foo-ave.fif'))

    projs = read_proj(proj_fname)

    projs_evoked = compute_proj_evoked(evoked, n_grad=1, n_mag=1, n_eeg=0)
    assert len(projs_evoked) == 2
    # XXX : test something

    # test parallelization
    projs = compute_proj_epochs(epochs, n_grad=1, n_mag=1, n_eeg=0, n_jobs=1,
                                desc_prefix='foobar')
    assert all('foobar' in x['desc'] for x in projs)
    projs = activate_proj(projs)
    proj_par, _, _ = make_projector(projs, epochs.ch_names, bads=[])
    assert_allclose(proj, proj_par, rtol=1e-8, atol=1e-16)

    # test warnings on bad filenames
    proj_badname = op.join(tempdir, 'test-bad-name.fif.gz')
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        write_proj(proj_badname, projs)
    with pytest.warns(RuntimeWarning, match='-proj.fif'):
        read_proj(proj_badname)

@pytest.mark.slowtest
def test_compute_proj_raw():
    """Test SSP computation on raw."""
    tempdir = _TempDir()
    # Test that the raw projectors work
    raw_time = 2.5  # Do shorter amount for speed
    raw = read_raw_fif(raw_fname).crop(0, raw_time)
    raw.load_data()
    for ii in (0.25, 0.5, 1, 2):
        with pytest.warns(RuntimeWarning, match='Too few samples'):
            projs = compute_proj_raw(raw, duration=ii - 0.1, stop=raw_time,
                                     n_grad=1, n_mag=1, n_eeg=0)

        # test that you can compute the projection matrix
        projs = activate_proj(projs)
        proj, nproj, U = make_projector(projs, raw.ch_names, bads=[])

        assert nproj == 2
        assert U.shape[1] == 2

        # test that you can save them
        raw.info['projs'] += projs
        raw.save(op.join(tempdir, 'foo_%d_raw.fif' % ii), overwrite=True)

    # Test that purely continuous (no duration) raw projection works
    with pytest.warns(RuntimeWarning, match='Too few samples'):
        projs = compute_proj_raw(raw, duration=None, stop=raw_time,
                                 n_grad=1, n_mag=1, n_eeg=0)

    # test that you can compute the projection matrix
    projs = activate_proj(projs)
    proj, nproj, U = make_projector(projs, raw.ch_names, bads=[])

    assert nproj == 2
    assert U.shape[1] == 2

    # test that you can save them
    raw.info['projs'] += projs
    raw.save(op.join(tempdir, 'foo_rawproj_continuous_raw.fif'))

    # test resampled-data projector, upsampling instead of downsampling
    # here to save an extra filtering (raw would have to be LP'ed to be equiv)
    raw_resamp = cp.deepcopy(raw)
    raw_resamp.resample(raw.info['sfreq'] * 2, n_jobs=2, npad='auto')
    projs = compute_proj_raw(raw_resamp, duration=None, stop=raw_time,
                             n_grad=1, n_mag=1, n_eeg=0)
    projs = activate_proj(projs)
    proj_new, _, _ = make_projector(projs, raw.ch_names, bads=[])
    assert_array_almost_equal(proj_new, proj, 4)

    # test with bads
    raw.load_bad_channels(bads_fname)  # adds 2 bad mag channels
    with pytest.warns(RuntimeWarning, match='Too few samples'):
        projs = compute_proj_raw(raw, n_grad=0, n_mag=0, n_eeg=1)

    # test that bad channels can be excluded
    proj, nproj, U = make_projector(projs, raw.ch_names,
                                    bads=raw.ch_names)
    assert_array_almost_equal(proj, np.eye(len(raw.ch_names)))

def test_make_eeg_average_ref_proj():
    """Test EEG average reference projection."""
    raw = read_raw_fif(raw_fname, preload=True)
    eeg = mne.pick_types(raw.info, meg=False, eeg=True)

    # No average EEG reference
    assert not np.all(raw._data[eeg].mean(axis=0) < 1e-19)

    # Apply average EEG reference
    car = make_eeg_average_ref_proj(raw.info)
    reref = raw.copy()
    reref.add_proj(car)
    reref.apply_proj()
    assert_array_almost_equal(reref._data[eeg].mean(axis=0), 0, decimal=19)

    # Error when custom reference has already been applied
    raw.info['custom_ref_applied'] = True
    pytest.raises(RuntimeError, make_eeg_average_ref_proj, raw.info)

    # test that an average EEG ref is not added when doing proj
    raw.set_eeg_reference(projection=True)
    assert _has_eeg_average_ref_proj(raw.info['projs'])
    raw.del_proj(idx=-1)
    assert not _has_eeg_average_ref_proj(raw.info['projs'])
    raw.apply_proj()
    assert not _has_eeg_average_ref_proj(raw.info['projs'])

def test_has_eeg_average_ref_proj():
    """Test checking whether an EEG average reference exists."""
    assert not _has_eeg_average_ref_proj([])

    raw = read_raw_fif(raw_fname)
    raw.set_eeg_reference(projection=True)
    assert _has_eeg_average_ref_proj(raw.info['projs'])

def test_needs_eeg_average_ref_proj():
    """Test checking whether a recording needs an EEG average reference."""
    raw = read_raw_fif(raw_fname)
    assert _needs_eeg_average_ref_proj(raw.info)

    raw.set_eeg_reference(projection=True)
    assert not _needs_eeg_average_ref_proj(raw.info)

    # No EEG channels
    raw = read_raw_fif(raw_fname, preload=True)
    eeg = [raw.ch_names[c] for c in pick_types(raw.info, meg=False, eeg=True)]
    raw.drop_channels(eeg)
    assert not _needs_eeg_average_ref_proj(raw.info)

    # Custom ref flag set
    raw = read_raw_fif(raw_fname)
    raw.info['custom_ref_applied'] = True
    assert not _needs_eeg_average_ref_proj(raw.info)

run_tests_if_main()


text:
"""
 Copyright (c) 2018-2019 Masahiko Hashimoto <hashimom@geeko.jp>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
"""
import argparse
import json
import os
from kasuga.parser import Parser

class Reader(object):
    def __init__(self, in_file, output_cb):
        self.in_file = in_file
        self.output_cb = output_cb

    def __call__(self):
        for line in open(self.in_file, 'r'):
            # 改行文字の削除
            line = line.replace('\n', '')

            # 「。」毎にパースを行う ※それ以外は未対応
            for context in line.replace("。", "。___").split("___"):
                if len(context) == 0:
                    continue

                self.parse_to_cb(context)

    def parse_to_cb(self, context):
        p = Parser()
        info = p(context)
        if info is not None:
            # パースしたデータをコールバック関数へ渡す
            self.output_cb(info)

class JsonWriter(Reader):
    def __init__(self, in_file, out_dir):
        super().__init__(in_file, self.output_cb)
        self.in_file = in_file
        self.out_dir = out_dir
        self.cnt = 1
        if not os.path.isdir(out_dir):
            os.makedirs(out_dir)

    def __call__(self):
        super().__call__()

    def output_cb(self, info):
        file_name = self.out_dir + "/" + "json_" + "{:08d}".format(self.cnt) + ".json"
        with open(file_name, 'w') as f:
            json.dump(info, f, indent=2, ensure_ascii=False)
            self.cnt += 1

def main():
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-f', nargs='?', help='input text file', required=True)
    arg_parser.add_argument('-o', nargs='?', help='output json file')
    args = arg_parser.parse_args()

    writer = JsonWriter(args.f, args.o)
    writer()

if __name__ == "__main__":
    main()

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace Inventory.Model
{

    public class SWS_SCRAP_DOC
    {
        public string sws_guid { get; set; }
        public string rp_guid { get; set; }
        public string sws_id { get; set; }
        public string itm_id { get; set; }
        public decimal sws_qty { get; set; }
        public long bg_dt { get; set; }
        public string rac_id { get; set; }
        public string rac_name { get; set; }
        public string ws_id { get; set; }
        public string ws_no { get; set; }
        public decimal tar_qty { get; set; }
        public decimal rp_qty { get; set; }
        public decimal scraped_qty { get; set; }
        public int scrap_on_rac { get; set; }
        public string wo_id { get; set; }
        public List<RAC_SCRAP_VIEW> scrap_list { get; set; }
        public List<RAC_VIEW> rac_list { get; set; }
    }
}


text:
//-----------------------------------------------------------------------
// <copyright file="ThreadLocalRandom.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Threading;

namespace Akka.Util
{
    /// <summary>
    /// Create random numbers with Thread-specific seeds.
    ///
    /// Borrowed form Jon Skeet's brilliant C# in Depth: http://csharpindepth.com/Articles/Chapter12/Random.aspx
    /// </summary>
    public static class ThreadLocalRandom
    {
        private static int _seed = Environment.TickCount;

        private static ThreadLocal<Random> _rng = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref _seed)));

        /// <summary>
        /// The current random number seed available to this thread
        /// </summary>
        public static Random Current
        {
            get
            {
                return _rng.Value;
            }
        }
    }
}


text:
elastic-controllers
===================

Base project for the development of elastic controllers for the cloud


text:
package test.ml.ga;

import ml.ga.Gene;
import ml.ga.GeneticAlgorithm;
import ml.ga.Genome;
import ml.nn.NNGeneticHelper;
import ml.nn.NeuralNetwork;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

import java.util.function.Function;

/**
 * Created by bolster on 2017-03-30.
 */
public class GeneticAlgorithmTest {

    @Test
    void basicUnboundedGrowth() {
        int initalValue = 1;
        int size = 100;
        GeneticAlgorithm ga = new GeneticAlgorithm();
        Genome[] population = new Genome[size];
        for(int i=0; i < population.length; i++) {
            Gene[] genes = {new Gene(initalValue)};
            population[i] = new Genome(genes, null);
        }
        Function<Genome, Double> fitFunc = genome -> {
            Gene[] genes = genome.information;
            double sum = 0;
            for(int i=0; i < genes.length; i++) {
                sum += genes[i].getElement();
            }
            return sum;
        };
        assertTrue(initalValue < (
                ga.trainPopulation(population, 1_000, fitFunc))[1].getFitness(fitFunc));
    }

    @Test
    void trainXORNN() {
        int size = 100;
        int[] XOR_Topology = {2,2,1};
        NeuralNetwork BasicNN = new NeuralNetwork(XOR_Topology);
        GeneticAlgorithm ga = new GeneticAlgorithm();
        Genome[] population = new Genome[size];
        for(int i=0; i < population.length; i++) {
            population[i] = NNGeneticHelper.toGenome(new NeuralNetwork(XOR_Topology));
        }
        Function<Genome, Double> fitFunc = genes -> {
            NeuralNetwork nn2 = NNGeneticHelper.fromGenome(genes , BasicNN);
            double[][] trainInput = {
                    {0,0},
                    {0,1},
                    {1,0},
                    {1,1}
            };
            double[][] trainOutput = {
                    {0},
                    {1},
                    {1},
                    {0}
            };

            return 1.0 / NNGeneticHelper.NetworkError(nn2, trainInput, trainOutput);
        };
        //we use 1.0 / error because we want to maximize fitness but minimize error
        assertTrue(1.0 / 0.6 < ga.trainPopulation(population, 10_000, fitFunc)[size-1].getFitness(fitFunc));
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.content.model;

/**
 * Model definition for TransitTable.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Content API for Shopping. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class TransitTable extends com.google.api.client.json.GenericJson {

  /**
   * A list of postal group names. The last value can be "all other locations". Example: ["zone 1",
   * "zone 2", "all other locations"]. The referred postal code groups must match the delivery
   * country of the service.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> postalCodeGroupNames;

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<TransitTableTransitTimeRow> rows;

  /**
   * A list of transit time labels. The last value can be "all other labels". Example: ["food",
   * "electronics", "all other labels"].
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<java.lang.String> transitTimeLabels;

  /**
   * A list of postal group names. The last value can be "all other locations". Example: ["zone 1",
   * "zone 2", "all other locations"]. The referred postal code groups must match the delivery
   * country of the service.
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getPostalCodeGroupNames() {
    return postalCodeGroupNames;
  }

  /**
   * A list of postal group names. The last value can be "all other locations". Example: ["zone 1",
   * "zone 2", "all other locations"]. The referred postal code groups must match the delivery
   * country of the service.
   * @param postalCodeGroupNames postalCodeGroupNames or {@code null} for none
   */
  public TransitTable setPostalCodeGroupNames(java.util.List<java.lang.String> postalCodeGroupNames) {
    this.postalCodeGroupNames = postalCodeGroupNames;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.util.List<TransitTableTransitTimeRow> getRows() {
    return rows;
  }

  /**
   * @param rows rows or {@code null} for none
   */
  public TransitTable setRows(java.util.List<TransitTableTransitTimeRow> rows) {
    this.rows = rows;
    return this;
  }

  /**
   * A list of transit time labels. The last value can be "all other labels". Example: ["food",
   * "electronics", "all other labels"].
   * @return value or {@code null} for none
   */
  public java.util.List<java.lang.String> getTransitTimeLabels() {
    return transitTimeLabels;
  }

  /**
   * A list of transit time labels. The last value can be "all other labels". Example: ["food",
   * "electronics", "all other labels"].
   * @param transitTimeLabels transitTimeLabels or {@code null} for none
   */
  public TransitTable setTransitTimeLabels(java.util.List<java.lang.String> transitTimeLabels) {
    this.transitTimeLabels = transitTimeLabels;
    return this;
  }

  @Override
  public TransitTable set(String fieldName, Object value) {
    return (TransitTable) super.set(fieldName, value);
  }

  @Override
  public TransitTable clone() {
    return (TransitTable) super.clone();
  }

}


text:
package com.yammer.schedulizer.fixtures;

import com.google.common.collect.Lists;
import com.yammer.schedulizer.auth.ExtAppType;
import com.yammer.schedulizer.entities.Employee;
import com.yammer.schedulizer.managers.EmployeeManager;
import com.yammer.schedulizer.test.TestUtils;
import org.hibernate.SessionFactory;

import java.util.List;

public class EmployeesFixture {

    private List<Employee> employees;
    private boolean saved;

    public EmployeesFixture() {
        saved = false;
        employees = Lists.newArrayList(new Employee("John", TestUtils.nextExtAppId(), ExtAppType.yammer),
                new Employee("Mary", TestUtils.nextExtAppId(), ExtAppType.yammer),
                new Employee("Louise", TestUtils.nextExtAppId(), ExtAppType.yammer));
    }

    public void save(SessionFactory sessionFactory) {
        if (saved) return;
        saved = true;
        EmployeeManager employeeManager = new EmployeeManager(sessionFactory);
        employees.stream().forEach(e -> employeeManager.save(e));
    }

    public List<Employee> getEmployees() {
        return employees;
    }
}


text:
class Scoreboard
  DISPLAY_FONT_SIZE = 24
  MARGIN_HORIZONTAL = 15

  def initialize(referee)
    @ref = referee
    @font = Gosu::Font.new(DISPLAY_FONT_SIZE)

    @score = @wrong = @misses = 0
  end

  def update
    @score  = @ref.correct
    @wrong  = @ref.incorrect
    @misses = @ref.misses
  end

  def draw
    @font.draw(score_text, 800 - text_width - MARGIN_HORIZONTAL, 600 - DISPLAY_FONT_SIZE, 0, 1, 1, Gosu::Color::GREEN)
    @font.draw(wrong_text, MARGIN_HORIZONTAL, 600 - DISPLAY_FONT_SIZE, 0, 1, 1, Gosu::Color::GREEN)
    @font.draw(miss_text, MARGIN_HORIZONTAL, 600 - DISPLAY_FONT_SIZE - DISPLAY_FONT_SIZE, 0, 1, 1, Gosu::Color::GREEN)
  end

  def new_word_at(milliseconds)
    @first_word_at ||= milliseconds
  end

  private

  def score_text
    "score: #{@score}, wpm: #{wpm}"
  end

  def wrong_text
    "wrong: #{'x' * @wrong}"
  end

  def miss_text
    "miss: #{'o' * @misses}"
  end

  def wpm
    case
    when @ref.correct.zero? then 0
    when elapsed_time.zero? then "n/a"
    else
      (@ref.correct / elapsed_time).round(1)
    end
  end

  def elapsed_time
    if @first_word_at
      (Gosu.milliseconds - @first_word_at).to_f / 60_000
    else
      Float::INFINITY
    end
  end

  def text_width
    @font.text_width(score_text)
  end
end


text:
'use strict'

const os = require('os');
const fs = require('fs');
const path = require('path');
const EventEmitter = require('events').EventEmitter;
const async = require('async');
const dataURIBuffer = require('data-uri-to-buffer');
const uuid = require('uuid');
const listFiles = require('./list');
const ffmpeg = require('./ffmpeg');
const concat = require('concat-stream');

module.exports = function(images){

  let events = new EventEmitter();
  let count = 0;
  let baseName = uuid.v4();
  let tmpDir = os.tmpDir();
  let video;

  async.series([
    decodeImages,
    createVideo,
    encodeVideo,
    cleanup
    ], convertFinished)

  function decodeImages(done){
    async.eachSeries(images, decodeImage, done)
  }

  function decodeImage(image, done){
    let fileName = `${baseName}-${count++}.jpg`;
    let buffer = dataURIBuffer(image);
    let ws = fs.createWriteStream(path.join(tmpDir, fileName));

    ws.on('error', done)
      .end(buffer, done)

     events.emit('log', `Converting ${fileName}`)
  }

  function createVideo(done){
    ffmpeg({
      baseName: baseName,
      folder: tmpDir
    }, done);
  }

  function encodeVideo(done){
    let fileName = `${baseName}.webm`;
    let rs = fs.createReadStream(path.join(tmpDir, fileName));

    rs.pipe(concat(function(videoBuffer){
      video = `data:video/webm;base64,${videoBuffer.toString('base64')}`;
      done()
    }));

    rs.on('error', done);
  }

  function cleanup(done){
    events.emit('log', 'Cleaning up' );

    listFiles(tmpDir, baseName, function(err,files){
      if(err) return done(err);

      deleteFiles(files, done);

    });

  }

  function deleteFiles(files, done){
    async.each(files, deleteFile, done)
  }

  function deleteFile(file, done){
    events.emit('log', `Deleting ${file}`);

    fs.unlink(path.join(tmpDir, file), function(err){
      //ignore error
      done();
    })
  }

  function convertFinished(err){
    if(err) return events.emit('error', err);

    events.emit('video', video);

  }

  return events

}


text:
NSLock *tvPoolLock;

@implementation CEVoodooTVPool

static DirectEnumerationResult
player_callback( void                   *ctx,
                const VoodooPlayInfo    *info,
                const VoodooPlayVersion *version,
                const char              *address )
{
    if( strcmp(info->name,"PhilipsTV") == 0 ) {
        if ( ![(CEVoodooTVPool *)ctx containsTVWithAddress:address] ){
            NSArray *objects = [NSArray arrayWithObjects:[NSString stringWithUTF8String:info->name],
                                                         [NSString stringWithUTF8String:info->vendor],
                                                         [NSString stringWithUTF8String:info->model],
                                                         [NSString stringWithUTF8String:address],nil];

            NSArray *keys = [NSArray arrayWithObjects:@"name", @"vendor", @"model", @"ipaddress", nil];
            NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

            [(CEVoodooTVPool *)ctx TVFoundWithOptions:(NSDictionary *)dictionary ];
        } else {
            [[(CEVoodooTVPool *)ctx TVWithAddress:address] resetPings];
        }

    }

    return DENUM_OK;
}

- (id)init
{
	// allow superclass to initialize its state first
	if (self = [super init]) {
        tvPool = [[NSMutableDictionary alloc] init];
        tvPoolAddresses = [[NSMutableArray alloc] init];
	}

	return self;
}

- (void) startScanning{
    [NSThread detachNewThreadSelector:@selector(scan) toTarget:self withObject:nil];
}

- (void) scan{
    do {
        NSAutoreleasePool	 *autoreleasepool = [[NSAutoreleasePool alloc] init];
        DFBResult ret;
        // I have to destroy the player because he remembers all the TVs he found, also the ones
        // that are not responding (have to consider to fix this in the player).

        ret = voodoo_player_create( NULL, &player );
        if (ret) {
            D_ERROR( "Voodoo/Play: Could not create the player (%s)!\n", DirectFBErrorString(ret) );
        }

        voodoo_player_broadcast( player );

        usleep( 1000000 );
        voodoo_player_enumerate( player, (VoodooPlayerCallback) player_callback, (void*) self );
        [tvPoolLock lock];
            NSEnumerator *enumerator = [tvPool keyEnumerator];
            for(NSString *anipaddress in enumerator){
                [[tvPool valueForKey:anipaddress] decreaseLifePings];
                if([[tvPool valueForKey:anipaddress] lifePings] == 0){
                    [NSThread detachNewThreadSelector:@selector(TVLostWithAddress:) toTarget:self withObject:anipaddress];
                }
            }
        [tvPoolLock unlock];
        [autoreleasepool release];
        voodoo_player_destroy( player );
    } while (true);
}

- (void) TVFoundWithOptions:(NSDictionary *)dictionary{
    [dictionary retain];

    CEVoodooTV *voodooTV = [[CEVoodooTV alloc] initWithDictionary:dictionary];
    [tvPool setObject:voodooTV forKey:[dictionary objectForKey:@"ipaddress"]];
    [tvPoolAddresses addObject:[dictionary objectForKey:@"ipaddress"]];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"CEVoodooTVFound" object:self];

    [dictionary release];
}

- (void) TVLostWithAddress:(NSString *)ipaddress{
    NSAutoreleasePool	 *autoreleasepool = [[NSAutoreleasePool alloc] init];

    [tvPoolLock lock];
        NSNumber *position = [NSNumber numberWithInt:[tvPoolAddresses indexOfObject:[[tvPool objectForKey:ipaddress] ipaddress]]];
        NSDictionary* dict = [NSDictionary dictionaryWithObject:position forKey:@"index"];

        [[NSNotificationCenter defaultCenter] postNotificationName:@"CEVoodooTVLost" object:self userInfo: dict];

        [tvPoolAddresses removeObject:[[tvPool objectForKey:ipaddress] ipaddress]];
        [tvPool removeObjectForKey:ipaddress];
    [tvPoolLock unlock];
    [autoreleasepool release];
}

- (BOOL) containsTVWithAddress:(const char *)ipaddress{
    return [tvPool objectForKey:[NSString stringWithUTF8String:ipaddress]]!=nil ;
}

- (CEVoodooTV *) TVWithAddress:(const char *)ipaddress{
    return [tvPool objectForKey:[NSString stringWithUTF8String:ipaddress]];
}

- (CEVoodooTV *) TVAtPosition:(NSInteger)position{
    if (position < [self amountOfTVsInPool] && position >= 0) {
        return [tvPool objectForKey:[tvPoolAddresses objectAtIndex:position]];
    }else {
        return  nil;
    }
}

- (NSUInteger) amountOfTVsInPool{
    return [tvPool count];
}

- (void) dealloc
{
    voodoo_player_destroy(player);
    for (id key in tvPool) {
        [[tvPool objectForKey:key] release];
    }
    [tvPool release];
    [tvPoolAddresses release];
    [super dealloc];
}

@end


text:
CefRefPtr<CefBrowserHost> CefBrowserCToCpp::GetHost() {
  if (CEF_MEMBER_MISSING(struct_, get_host))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_browser_host_t* _retval = struct_->get_host(struct_);

  // Return type: refptr_same
  return CefBrowserHostCToCpp::Wrap(_retval);
}

bool CefBrowserCToCpp::CanGoBack() {
  if (CEF_MEMBER_MISSING(struct_, can_go_back))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->can_go_back(struct_);

  // Return type: bool
  return _retval?true:false;
}

void CefBrowserCToCpp::GoBack() {
  if (CEF_MEMBER_MISSING(struct_, go_back))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  struct_->go_back(struct_);
}

bool CefBrowserCToCpp::CanGoForward() {
  if (CEF_MEMBER_MISSING(struct_, can_go_forward))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->can_go_forward(struct_);

  // Return type: bool
  return _retval?true:false;
}

void CefBrowserCToCpp::GoForward() {
  if (CEF_MEMBER_MISSING(struct_, go_forward))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  struct_->go_forward(struct_);
}

bool CefBrowserCToCpp::IsLoading() {
  if (CEF_MEMBER_MISSING(struct_, is_loading))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->is_loading(struct_);

  // Return type: bool
  return _retval?true:false;
}

void CefBrowserCToCpp::Reload() {
  if (CEF_MEMBER_MISSING(struct_, reload))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  struct_->reload(struct_);
}

void CefBrowserCToCpp::ReloadIgnoreCache() {
  if (CEF_MEMBER_MISSING(struct_, reload_ignore_cache))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  struct_->reload_ignore_cache(struct_);
}

void CefBrowserCToCpp::StopLoad() {
  if (CEF_MEMBER_MISSING(struct_, stop_load))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  struct_->stop_load(struct_);
}

int CefBrowserCToCpp::GetIdentifier() {
  if (CEF_MEMBER_MISSING(struct_, get_identifier))
    return 0;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->get_identifier(struct_);

  // Return type: simple
  return _retval;
}

bool CefBrowserCToCpp::IsSame(CefRefPtr<CefBrowser> that) {
  if (CEF_MEMBER_MISSING(struct_, is_same))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Verify param: that; type: refptr_same
  DCHECK(that.get());
  if (!that.get())
    return false;

  // Execute
  int _retval = struct_->is_same(struct_,
      CefBrowserCToCpp::Unwrap(that));

  // Return type: bool
  return _retval?true:false;
}

bool CefBrowserCToCpp::IsPopup() {
  if (CEF_MEMBER_MISSING(struct_, is_popup))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->is_popup(struct_);

  // Return type: bool
  return _retval?true:false;
}

bool CefBrowserCToCpp::HasDocument() {
  if (CEF_MEMBER_MISSING(struct_, has_document))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  int _retval = struct_->has_document(struct_);

  // Return type: bool
  return _retval?true:false;
}

CefRefPtr<CefFrame> CefBrowserCToCpp::GetMainFrame() {
  if (CEF_MEMBER_MISSING(struct_, get_main_frame))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_frame_t* _retval = struct_->get_main_frame(struct_);

  // Return type: refptr_same
  return CefFrameCToCpp::Wrap(_retval);
}

CefRefPtr<CefFrame> CefBrowserCToCpp::GetFocusedFrame() {
  if (CEF_MEMBER_MISSING(struct_, get_focused_frame))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_frame_t* _retval = struct_->get_focused_frame(struct_);

  // Return type: refptr_same
  return CefFrameCToCpp::Wrap(_retval);
}

CefRefPtr<CefFrame> CefBrowserCToCpp::GetFrame(int64 identifier) {
  if (CEF_MEMBER_MISSING(struct_, get_frame_byident))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  cef_frame_t* _retval = struct_->get_frame_byident(struct_,
      identifier);

  // Return type: refptr_same
  return CefFrameCToCpp::Wrap(_retval);
}

CefRefPtr<CefFrame> CefBrowserCToCpp::GetFrame(const CefString& name) {
  if (CEF_MEMBER_MISSING(struct_, get_frame))
    return NULL;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Unverified params: name

  // Execute
  cef_frame_t* _retval = struct_->get_frame(struct_,
      name.GetStruct());

  // Return type: refptr_same
  return CefFrameCToCpp::Wrap(_retval);
}

size_t CefBrowserCToCpp::GetFrameCount() {
  if (CEF_MEMBER_MISSING(struct_, get_frame_count))
    return 0;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Execute
  size_t _retval = struct_->get_frame_count(struct_);

  // Return type: simple
  return _retval;
}

void CefBrowserCToCpp::GetFrameIdentifiers(std::vector<int64>& identifiers) {
  if (CEF_MEMBER_MISSING(struct_, get_frame_identifiers))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Translate param: identifiers; type: simple_vec_byref
  size_t identifiersSize = identifiers.size();
  size_t identifiersCount = std::max(GetFrameCount(), identifiersSize);
  int64* identifiersList = NULL;
  if (identifiersCount > 0) {
    identifiersList = new int64[identifiersCount];
    DCHECK(identifiersList);
    if (identifiersList) {
       memset(identifiersList, 0, sizeof(int64)*identifiersCount);
    }
    if (identifiersList && identifiersSize > 0) {
      for (size_t i = 0; i < identifiersSize; ++i) {
        identifiersList[i] = identifiers[i];
      }
    }
  }

  // Execute
  struct_->get_frame_identifiers(struct_,
      &identifiersCount,
      identifiersList);

  // Restore param:identifiers; type: simple_vec_byref
  identifiers.clear();
  if (identifiersCount > 0 && identifiersList) {
    for (size_t i = 0; i < identifiersCount; ++i) {
      identifiers.push_back(identifiersList[i]);
    }
    delete [] identifiersList;
  }
}

void CefBrowserCToCpp::GetFrameNames(std::vector<CefString>& names) {
  if (CEF_MEMBER_MISSING(struct_, get_frame_names))
    return;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Translate param: names; type: string_vec_byref
  cef_string_list_t namesList = cef_string_list_alloc();
  DCHECK(namesList);
  if (namesList)
    transfer_string_list_contents(names, namesList);

  // Execute
  struct_->get_frame_names(struct_,
      namesList);

  // Restore param:names; type: string_vec_byref
  if (namesList) {
    names.clear();
    transfer_string_list_contents(namesList, names);
    cef_string_list_free(namesList);
  }
}

bool CefBrowserCToCpp::SendProcessMessage(CefProcessId target_process,
    CefRefPtr<CefProcessMessage> message) {
  if (CEF_MEMBER_MISSING(struct_, send_process_message))
    return false;

  // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING

  // Verify param: message; type: refptr_same
  DCHECK(message.get());
  if (!message.get())
    return false;

  // Execute
  int _retval = struct_->send_process_message(struct_,
      target_process,
      CefProcessMessageCToCpp::Unwrap(message));

  // Return type: bool
  return _retval?true:false;
}

#ifndef NDEBUG
template<> base::AtomicRefCount CefCToCpp<CefBrowserCToCpp, CefBrowser,
    cef_browser_t>::DebugObjCt = 0;
#endif


text:
$DSCModuleName   = 'AccessControlDSC'
$DSCResourceName = 'RegistryAccessEntry'

Import-Module "$($PSScriptRoot)\..\TestHelper.psm1" -Force
Import-Module Pester -Force

$ModuleRoot = Split-Path -Path $Script:MyInvocation.MyCommand.Path -Parent | Split-Path -Parent | Split-Path -Parent

if (
    (-not (Test-Path -Path (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests') -PathType Container)) -or
    (-not (Test-Path -Path (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -PathType Leaf))
)
{
    & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests'))
}

Import-Module -Name (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force

$TestEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $DSCModuleName `
    -DSCResourceName $DSCResourceName `
    -TestType Integration

#endregion

try
{
    $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($DSCResourceName).Config.ps1"
    . $ConfigFile

    #Create a temporary file to hold the configuration
    $configPath = "C:\TestRegConfig"
    New-Item -Path $configPath -ItemType Directory

    Describe "$($DSCResourceName)_Integration" {

        #Create temporary Registry Key
        $TestRegistryKey = Set-NewTempRegKeyAcl -Path $TestParameter.Path -PassThru
        $Acl = $TestRegistryKey.GetAccessControl()
        $Acl.SetAccessRuleProtection($false, $false)
        Set-Acl -Path $TestParameter.Path -AclObject $Acl

        $ConfigurationName = "$($DSCResourceName)_Test"
        It 'Should compile without throwing' {
            {
                & $ConfigurationName -OutputPath $ConfigPath
                Start-DscConfiguration -Path $configPath -ComputerName localhost -Force -Verbose -Wait
            } | Should Not Throw
        }

        It 'Should be able to call Get-DscConfiguration without throwing' {

            { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not Throw
        }

        # This test will pass locally but will fail in AppVeyor. Remove the Pending switch to run locally.
        It -Pending 'Should have set the resource and all the parameters should match' {

            Start-DscConfiguration -Path $configPath -ComputerName localhost -Force -Verbose -Wait

            $CurrentConfiguration = Get-DscConfiguration | Where-Object -FilterScript {$_.ConfigurationName -eq $ConfigurationName}

            Test-Path -Path $TestParameter.Path

            $CurrentConfiguration.AccessControlList.ForcePrincipal | Should Be $TestParameter.ForcePrincipal
            $CurrentConfiguration.Path | Should Be $TestParameter.Path
            $CurrentConfiguration.AccessControlList.Principal | Should Be $TestParameter.Principal
        }

        It 'Actual configuration should match the desired configuration' {
            Test-DscConfiguration -Verbose | Should Be $true
        }
    }
}
finally
{
    Restore-TestEnvironment -TestEnvironment $TestEnvironment

    #Remove temporary directory
    if (Test-Path $TestParameter.path)
    {
        Remove-Item -Path $TestParameter.path -Force -Recurse -Verbose
    }
    if (Test-Path $configPath)
    {
        Remove-Item -Path $configPath -Force -Recurse -Verbose
    }
}


text:
var Rectangle = require(__dirname + '/../../src/shapes/Rectangle');

exports.construct = function(test){
    // STUB
    test.done();
};

exports.computeAABB = function(test){
    // STUB
    test.done();
};

exports.computeMomentOfInertia = function(test){
    // STUB
    test.done();
};

exports.updateBoundingRadius = function(test){
    // STUB
    test.done();
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:background="@color/activity_background"
              android:orientation="vertical">

    <!-- Divider below pager title -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="1dp"
        android:layout_gravity="top"
        android:background="@color/theme_blue"
        android:textColor="@color/transparent">
    </TextView>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/activity_background">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:orientation="vertical"
            android:paddingBottom="32dp">

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:gravity="center"
                android:text="Original Gravity"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_og_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                android:text="1.052 - 1.060"
                android:textColor="@color/text"
                android:textSize="16sp"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:gravity="center"
                android:text="Final Gravity"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_fg_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                android:text="1.052 - 1.060"
                android:textColor="@color/text"
                android:textSize="16sp"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:gravity="center"
                android:text="ABV"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_abv_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                android:text="4.3% - 5.2%"
                android:textColor="@color/text"
                android:textSize="16sp"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:gravity="center"
                android:text="Bitterness (IBU)"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_ibu_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                android:text="25 - 50"
                android:textColor="@color/text"
                android:textSize="16sp"/>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:gravity="center"
                android:text="Color (SRM)"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_color_view"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:text="7.5 - 9.5"
                android:textColor="@color/text"
                android:textSize="16sp"/>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:gravity="center"
                android:orientation="horizontal">

                <ImageView
                    android:id="@+id/min_color_icon"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentLeft="true"
                    android:layout_gravity="center|center_vertical"
                    android:layout_margin="4dp"
                    android:background="@color/transparent"
                    android:contentDescription="icon"
                    android:src="@drawable/colored_circle"/>

                <ImageView
                    android:id="@+id/thirtythree_percent_color_icon"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentLeft="true"
                    android:layout_gravity="center|center_vertical"
                    android:layout_margin="4dp"
                    android:background="@color/transparent"
                    android:contentDescription="icon"
                    android:src="@drawable/colored_circle"/>

                <ImageView
                    android:id="@+id/sixtysix_percent_color_icon"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentLeft="true"
                    android:layout_gravity="center|center_vertical"
                    android:layout_margin="4dp"
                    android:background="@color/transparent"
                    android:contentDescription="icon"
                    android:src="@drawable/colored_circle"/>

                <ImageView
                    android:id="@+id/max_color_icon"
                    android:layout_width="32dp"
                    android:layout_height="32dp"
                    android:layout_alignParentLeft="true"
                    android:layout_gravity="center|center_vertical"
                    android:layout_margin="4dp"
                    android:background="@color/transparent"
                    android:contentDescription="icon"
                    android:src="@drawable/colored_circle"/>

            </LinearLayout>

            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="8dp"
                android:gravity="center"
                android:text="Carbonation (Vol CO2)"
                android:textColor="@color/title_color"
                android:textSize="20dp"/>

            <TextView
                android:id="@+id/style_carbonation_view"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:gravity="center"
                android:text="N / A"
                android:textColor="@color/text"
                android:textSize="16sp"/>

        </LinearLayout>

    </ScrollView>
</LinearLayout>


text:
package com.tle.webtests.framework;

import org.openqa.selenium.WebDriver;

public class WebDriverCheckout {
  private final WebDriver driver;

  public WebDriverCheckout(WebDriver webDriver) {
    this.driver = webDriver;
  }

  public WebDriver getDriver() {
    return driver;
  }
}


text:
package com.sage.cerberus.core.service;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

import com.sage.cerberus.coreAPI.RoleService;
import com.sage.cerberus.model.security.Role;

public class ConcreteRoleService implements RoleService {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

	@Override
	public Set<Role> findDefaultRolesForNewUser() {
		Set<Role> roles = new HashSet<>();

		Role userRole = (Role) sessionFactory.getCurrentSession().createCriteria(Role.class)
		.add(Restrictions.eq("name", "User"))
		.uniqueResult();
		roles.add(userRole);

		return roles;
	}

}


text:
from torch.utils.data import Dataset as D
import numpy as np

from .Protein import Protein
from src.admin.utils import format_bytes

class Dataset(D):
    def __init__(self, proteins, crop=True):
        super().__init__()
        if crop:
            proteins = self.crop(proteins)

        self.X = [np.concatenate([p.sequence, p.acc, p.ss3], 1) for p in proteins]
        self.Y = [p.contact_matrix * p.mask for p in proteins]
        self.masks = [p.mask for p in proteins]

    def __len__(self):
        return len(self.X)

    def crop(self, proteins):
        #max_len = 859 # 99th percentile
        max_len = 539 # 95th percentile
        #max_len = 429 # 90th percentile
        #max_len = 293 # 75th percentile
        proteins = list(filter(lambda x: len(x) <= max_len, proteins))
        return proteins

    def __getitem__(self, idx):
        x = self.X[idx]
        y = self.Y[idx]
        mask = self.masks[idx]
        return x, y, mask

    def shuffle(self):
        perm = np.random.permutation(len(self.X))
        self.X = [self.X[i] for i in perm]
        self.Y = [self.Y[i] for i in perm]
        self.masks = [self.masks[i] for i in perm]

    @property
    def max_length(self):
        try:
            return self._max_length
        except AttributeError:
            self._max_length = max(len(p) for p in self.X)
            return self._max_length

    @property
    def mean_length(self):
        try:
            return self._mean_length
        except AttributeError:
            self._mean_length = np.mean(list(len(p) for p in self.X))
            return self._mean_length

    @property
    def dim(self):
        try:
            return self._dim
        except AttributeError:
            self._dim = self.X[0].shape[-1]
            return self._dim

    @property
    def bytes(self):
        bytes_per_elt = 4
        mask_size = sum([np.prod(m.shape) * bytes_per_elt for m in self.masks])
        y_size = sum([np.prod(m.shape) * bytes_per_elt for m in self.Y])
        x_size = sum([np.prod(m.shape) * bytes_per_elt for m in self.X])
        b = mask_size + y_size + x_size
        return format_bytes(b)

    @classmethod
    def from_records(cls, records):
        proteins = [Protein.from_record(record) for record in records]
        return cls(proteins)


text:
"""Test cases for end-to-end testing.  Run with the server_tests script."""

import calendar
import datetime
import email
import email.header
import optparse
import os
import pytest
import re
import simplejson
import sys
import tempfile
import time
import unittest
import urlparse

from google.appengine.api import images

import config
from const import ROOT_URL, PERSON_STATUS_TEXT, NOTE_STATUS_TEXT
import download_feed
from model import *
from photo import MAX_IMAGE_DIMENSION
import remote_api
from resources import Resource, ResourceBundle
import reveal
import scrape
import setup_pf as setup
from test_pfif import text_diff
from text_query import TextQuery
import utils
from server_tests_base import ServerTestsBase

class ImportTests(ServerTestsBase):
    """Tests for CSV import page at /api/import."""
    def setUp(self):
        ServerTestsBase.setUp(self)
        config.set_for_repo(
            'haiti',
            api_action_logging=True)
        self.filename = None

    def tearDown(self):
        if self.filename:
            os.remove(self.filename)
        ServerTestsBase.tearDown(self)

    def _write_csv_file(self, content):
        # TODO(ryok): We should use StringIO instead of a file on disk. Update
        # scrape.py to support StringIO.
        fd, self.filename = tempfile.mkstemp()
        os.fdopen(fd, 'w').write('\n'.join(content))

    def test_import_no_csv(self):
        """Verifies an error message is shown when no CSV file is uploaded."""
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key')
        assert 'Please specify at least one CSV file.' in doc.text

    def test_import_invalid_authentication_key(self):
        """Verifies an error message is shown when auth key is invalid."""
        self._write_csv_file([
            'person_record_id,source_date,full_name',
            'test.google.com/person1,2013-02-26T09:10:00Z,_test_full_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='bad_key', content=open(self.filename))
        assert 'Missing or invalid authorization key' in doc.text

    def test_import_broken_csv(self):
        """Verifies an error message is shown when a broken CSV is imported."""
        self._write_csv_file([
            'person_record_id,source_date,\0full_name',  # contains null
            'test.google.com/person1,2013-02-26T09:10:00Z,_test_full_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'The CSV file is formatted incorrectly' in doc.text
        assert Person.all().count() == 0
        assert Note.all().count() == 0

    def test_import_one_person(self):
        """Verifies a Person entry is successfully imported."""
        self._write_csv_file([
            'person_record_id,source_date,full_name',
            'test.google.com/person1,2013-02-26T09:10:00Z,_test_full_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'Person records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert Person.all().count() == 1
        assert Note.all().count() == 0
        person = Person.all().get()
        assert person.record_id == 'test.google.com/person1'
        assert person.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        assert person.full_name == '_test_full_name'
        self.verify_api_log(ApiActionLog.WRITE, person_records=1)

    def test_import_one_note(self):
        """Verifies a Note entry is successfully imported."""
        person = Person(
            key_name='haiti:test.google.com/person1',
            repo='haiti',
            author_name='_test_author_name',
            full_name='_test_given_name _test_family_name',
            given_name='_test_given_name',
            family_name='_test_family_name',
            source_date=ServerTestsBase.TEST_DATETIME,
            entry_date=ServerTestsBase.TEST_DATETIME,
            latest_status='',
        )
        db.put(person)

        self._write_csv_file([
            'note_record_id,person_record_id,author_name,source_date,status',
            'test.google.com/note1,test.google.com/person1,' +
            '_test_author_name,2013-02-26T09:10:00Z,believed_alive',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))

        assert 'Note records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)

        assert Note.all().count() == 1
        note = Note.all().get()
        assert note.record_id == 'test.google.com/note1'
        assert note.person_record_id == 'test.google.com/person1'
        assert note.author_name == '_test_author_name'
        assert note.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        assert note.status == 'believed_alive'

        assert Person.all().count() == 1
        person = Person.all().get()
        assert person.latest_status == 'believed_alive'

        self.verify_api_log(ApiActionLog.WRITE, note_records=1)

    def test_import_only_digit_record_id(self):
        """Verifies that a Person entry is successfully imported even if the
        record_id just contains digits, and that the imported record_id is
        prefixed with the write domain associated with auth key."""
        self._write_csv_file([
            'person_record_id,source_date,full_name',
            '1,2013-02-26T09:10:00Z,_test_full_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'Person records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert Person.all().count() == 1
        assert Note.all().count() == 0
        person = Person.all().get()
        assert person.record_id == 'test.google.com/1'
        assert person.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        assert person.full_name == '_test_full_name'
        self.verify_api_log(ApiActionLog.WRITE, person_records=1)

    def test_import_domain_dont_match(self):
        """Verifies we reject a Person entry whose record_id domain does not
        match that of authentication key."""
        self._write_csv_file([
            'person_record_id,source_date,full_name',
            'different.google.com/person1,2013-02-26T09:10:00Z,_test_full_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'Person records Imported 0 of 1' in re.sub('\\s+', ' ', doc.text)
        assert 'Not in authorized domain' in doc.text
        assert Person.all().count() == 0
        assert Note.all().count() == 0
        self.verify_api_log(ApiActionLog.WRITE)

    def test_import_one_person_and_note_on_separate_rows(self):
        """Verifies a Note entry and a Person entry on separate rows are
        successfully imported."""
        self._write_csv_file([
            'person_record_id,full_name,source_date,note_record_id,author_name',
            'test.google.com/person1,_test_full_name,2013-02-26T09:10:00Z,,',
            'test.google.com/person1,,2013-02-26T09:10:00Z,' +
            'test.google.com/note1,_test_author_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'Person records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert 'Note records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert Person.all().count() == 1
        assert Note.all().count() == 1
        person = Person.all().get()
        assert person.record_id == 'test.google.com/person1'
        assert person.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        assert person.full_name == '_test_full_name'
        note = Note.all().get()
        assert note.record_id == 'test.google.com/note1'
        assert note.person_record_id == 'test.google.com/person1'
        assert note.author_name == '_test_author_name'
        assert note.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        self.verify_api_log(ApiActionLog.WRITE, person_records=1, note_records=1)

    def test_import_one_person_and_note_on_single_row(self):
        """Verifies a Note entry and a Person entry on a single row are
        successfully imported."""
        self._write_csv_file([
            'person_record_id,full_name,source_date,note_record_id,author_name',
            'test.google.com/person1,_test_full_name,2013-02-26T09:10:00Z,' +
            'test.google.com/note1,_test_author_name',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))
        assert 'Person records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert 'Note records Imported 1 of 1' in re.sub('\\s+', ' ', doc.text)
        assert Person.all().count() == 1
        assert Note.all().count() == 1
        person = Person.all().get()
        assert person.record_id == 'test.google.com/person1'
        assert person.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        assert person.full_name == '_test_full_name'
        note = Note.all().get()
        assert note.record_id == 'test.google.com/note1'
        assert note.person_record_id == 'test.google.com/person1'
        assert note.author_name == '_test_author_name'
        assert note.source_date == datetime.datetime(2013, 2, 26, 9, 10, 0)
        self.verify_api_log(ApiActionLog.WRITE, person_records=1, note_records=1)

    def test_import_note_for_non_existent_person(self):
        """Verifies a Note entry is not imported if it points to a non-existent
        person_record_id."""
        self._write_csv_file([
            'note_record_id,person_record_id,author_name,source_date,status',
            'test.google.com/note1,test.google.com/non_existent_person,' +
            '_test_author_name,2013-02-26T09:10:00Z,believed_alive',
            ])
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key', content=open(self.filename))

        assert 'Note records Imported 0 of 1' in re.sub('\\s+', ' ', doc.text)
        assert 'There is no person record with the person_record_id' in doc.text
        assert Note.all().count() == 0
        self.verify_api_log(ApiActionLog.WRITE)

    def test_import_xlsx(self):
        """Verifies an xlsx file import."""
        doc = self.go('/haiti/api/import')
        form = doc.last('form')
        doc = self.s.submit(form, key='test_key',
            content=open(self.get_test_filepath('persons.xlsx')))
        assert 'Person records Imported 3 of 3' in re.sub('\\s+', ' ', doc.text)
        assert Person.all().count() == 3
        person = Person.all().get()  # check the first Person
        assert person.record_id == 'test.google.com/12345'
        assert person.source_date == datetime.datetime(2013, 11, 12, 7, 26, 0)
        assert person.full_name == 'Mary Example'
        self.verify_api_log(ApiActionLog.WRITE, person_records=3, note_records=0)


text:
import paramiko
import itertools,string,crypt

PASSSIZE = 5
IPADDRESS = "127.0.0.1"
USERNAME = "vagrant"
SSHPORT=2222

# Run /vagrant/bin/pythonDependencies.bash to get all dependencies.
# Generates a password of containing only digits with a size of PASSSIZE

var = itertools.combinations(string.digits,PASSSIZE)

try:
    for i in var:
        passwd = ''.join(i)

        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())

        try:
            ssh.connect(IPADDRESS , port=SSHPORT, username=USERNAME, password=passwd)
            print "Connected successfully. Password = "+passwd
            break
        except paramiko.AuthenticationException, error:
            print "Incorrect password: "+passwd

        except socket.error, error:
            print error

        except paramiko.SSHException, error:
            print error
            print "Most probably this is caused by a missing host key"

        except Exception, error:
            print "Unknown error: "+error

        ssh.close()

except Exception,error :
    print error


text:
package org.gradle.launcher.daemon.server;

import org.gradle.api.Action;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.internal.concurrent.DefaultExecutorFactory;
import org.gradle.internal.id.UUIDGenerator;
import org.gradle.messaging.remote.Address;
import org.gradle.messaging.remote.ConnectionAcceptor;
import org.gradle.messaging.remote.internal.ConnectCompletion;
import org.gradle.messaging.remote.internal.IncomingConnector;
import org.gradle.messaging.remote.internal.inet.InetAddressFactory;
import org.gradle.messaging.remote.internal.inet.TcpIncomingConnector;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Opens a TCP connection for clients to connect to to communicate with a daemon.
 */
public class DaemonTcpServerConnector implements DaemonServerConnector {
    final private IncomingConnector incomingConnector;

    private boolean started;
    private boolean stopped;
    private final Lock lifecycleLock = new ReentrantLock();
    private ConnectionAcceptor acceptor;

    public DaemonTcpServerConnector() {
        this.incomingConnector = new TcpIncomingConnector(
                new DefaultExecutorFactory(),
                new InetAddressFactory(),
                new UUIDGenerator()
        );
    }

    public Address start(final IncomingConnectionHandler handler) {
        lifecycleLock.lock();
        try {
            if (stopped) {
                throw new IllegalStateException("server connector cannot be started as it is either stopping or has been stopped");
            }
            if (started) {
                throw new IllegalStateException("server connector cannot be started as it has already been started");
            }

            // Hold the lock until we actually start accepting connections for the case when stop is called from another
            // thread while we are in the middle here.

            Action<ConnectCompletion> connectEvent = new Action<ConnectCompletion>() {
                public void execute(ConnectCompletion completion) {
                    handler.handle(new SynchronizedDispatchConnection<Object>(completion.create(getClass().getClassLoader())));
                }
            };

            acceptor = incomingConnector.accept(connectEvent, false);
            started = true;
            return acceptor.getAddress();
        } finally {
            lifecycleLock.unlock();
        }
    }

    public void stop() {
        lifecycleLock.lock();
        try {
            stopped = true;
        } finally {
            lifecycleLock.unlock();
        }

        CompositeStoppable.stoppable(acceptor, incomingConnector).stop();
    }

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.ok2c.lightnio.impl.pool;

import java.net.SocketAddress;

import com.ok2c.lightnio.IOSession;
import com.ok2c.lightnio.pool.ManagedIOSession;

class BasicManagedIOSession implements ManagedIOSession {

    private final SessionPool<SocketAddress> pool;
    private final PoolEntry<SocketAddress> entry;

    private volatile boolean released;
    private volatile boolean reusable;

    public BasicManagedIOSession(
            final SessionPool<SocketAddress> pool,
            final PoolEntry<SocketAddress> entry) {
        super();
        this.pool = pool;
        this.entry = entry;
        this.released = false;
        this.reusable = true;
    }

    public void releaseSession() {
        if (this.released) {
            return;
        }
        this.released = true;
        IOSession iosession = this.entry.getIOSession();
        this.pool.release(this.entry, this.reusable && !iosession.isClosed());
    }

    public void abortSession() {
        if (this.released) {
            return;
        }
        this.released = true;
        IOSession iosession = this.entry.getIOSession();
        iosession.shutdown();
        this.pool.release(this.entry, false);
    }

    public IOSession getSession() {
        if (this.released) {
            return null;
        }
        return this.entry.getIOSession();
    }

    public Object getState() {
        if (this.released) {
            return null;
        }
        return this.entry.getState();
    }

    public void setState(final Object state) {
        if (this.released) {
            return;
        }
        this.entry.setState(state);
    }

    public boolean isReusable() {
        return this.reusable;
    }

    public void markNonReusable() {
        if (this.released) {
            return;
        }
        this.reusable = false;
    }

    public void markReusable() {
        if (this.released) {
            return;
        }
        this.reusable = true;
    }

    protected PoolEntry<SocketAddress> getEntry() {
        return this.entry;
    }

}


text:
package by.vorokhobko.chat;

import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test.
 *
 * @author Evgeny Vorokhobko (vorokhobko2011@yandex.ru).
 * @version 1.
 * @since 07.02.2019.
 */
public class ChatTest {
    /**
     * The class field.
     */
    private static final File LOG =  new File("d:/Programming/Java/Projects/log.txt");
    /**
     * The class field.
     */
    private static final File TEXT = new File("d:/Programming/Java/Projects/text.txt");
    /**
     * Test.
     */
    @Test
    public void whenEnterStopThenProgramWriteOnlyUserPhrase() {
        String input = "стоп\r\nhello\r\nbye";
        System.setIn(new ByteArrayInputStream(input.getBytes()));
        new Chat().workChat(TEXT, LOG);
        ArrayList<String> result = new ArrayList<>();
        ArrayList<String> example = new ArrayList<>(Arrays.asList("User: стоп", "User: hello", "User: bye"));
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(LOG), StandardCharsets.UTF_8))) {
            while (reader.ready()) {
                result.add(reader.readLine());
            }
            assertThat(example, is(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
// The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "DFImageFetching.h"

NS_ASSUME_NONNULL_BEGIN

/*! The PHImageRequestOptionsVersion value for requesting an image asset with or without adjustments, used by the version property. Default value is PHImageRequestOptionsVersionCurrent.
 @note Should be put into DFImageRequestOptions userInfo dictionary.
 */
extern NSString *const DFPhotosKitVersionKey;

/*! Image fetcher for Photos Kit framework. Supported resources: PHAsset, NSURL with scheme com.github.kean.photos-kit.
 @note Use methods of NSURL+DFPhotosKit category to construct URLs for PHAssets.
 */
NS_CLASS_AVAILABLE_IOS(8_0) @interface DFPhotosKitImageFetcher : NSObject <DFImageFetching>

@end

NS_ASSUME_NONNULL_END


text:
[![Systemic Filwer](./logo/Systemic-DNA-Code-filwer-256x256.png)](./logo/Systemic-DNA-Code-filwer-256x256.png)

# Filwer

[![Build Status](https://travis-ci.org/Adron/systemic-filwer.svg?branch=master)](https://travis-ci.org/Adron/systemic-filwer)

Systemic file watcher for managing inbound files.

Features:  (Rough draft of features)

 * Watches for all files and directories in file location X.
 * Watches for file(s) set in watcher-settings.json config file at location X.
 * Watches for file(s) set in watcher-settings.json config file at location specified in watcher-settings.json config file.
 * Reports to console what is going on with files in location X. (Prospecitvely add additional logging later)
 * Once file is discovered new (add & change occurs) file is placed in location Y.
 * Once file is discovered new (add & change occurs) file is copied to location as specified in the watcher-settings.json file.

### Design intent for *.json config files:

#### sitrep.json Description [here](docs/sitrep.json.md)

#### options.json Description [here](docs/options.json.md)


text:
import { SearchForm } from "~/components/search-form";
import type { _Props } from "./types";

export const Component: React.FC<_Props> = (props) => (
  <fieldset disabled={props.disabled}>
    <SearchForm
      className={`border-none ${
        props.disabled ? "cursor-not-allowed bg-gray-600" : "bg-gray-800"
      }`}
    />
  </fieldset>
);


text:
package http_server;

import java.io.IOException;

public interface RequestHandler {
	public void process(Request req) throws HTTPException, IOException;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.resourcemanager.dns.models;

import com.azure.core.annotation.Fluent;

/** An immutable client-side representation of a SOA (start of authority) record set in Azure DNS Zone. */
@Fluent
public interface SoaRecordSet extends DnsRecordSet {
    /** @return the SOA record in this record set */
    SoaRecord record();
}


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


text:
.class Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings$11;
.super Landroid/content/BroadcastReceiver;
.source "WifiApSettings.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;-><init>()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;

# direct methods
.method constructor <init>(Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;)V
    .locals 0

    iput-object p1, p0, Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings$11;->this$0:Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;

    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 1

    iget-object v0, p0, Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings$11;->this$0:Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;

    invoke-static {v0, p1, p2}, Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;->-wrap14(Lcom/samsung/android/settings/wifi/mobileap/WifiApSettings;Landroid/content/Context;Landroid/content/Intent;)V

    return-void
.end method


text:
package com.dafy.a.config;

import org.springframework.context.annotation.Configuration;

@Configuration
public class WebConfig {

}


text:
import Absolute from './components/Absolute'
import Box from './components/Box'
import Grid from './components/Grid'
import ScrollView from './components/ScrollView'
import Spacer from './components/Spacer'

import applyMultiplier from './utils/applyMultiplier'

export { Absolute, Box, Grid, ScrollView, Spacer, applyMultiplier }


text:
namespace boost {
namespace asio {

typedef thread_pool static_thread_pool;

} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_STATIC_THREAD_POOL_HPP


text:
package schemas

import (
	"github.com/graphql-go/graphql"
	"github.com/vsouza/democratic/resolvers"
)

var queryType = graphql.NewObject(
	graphql.ObjectConfig{
		Name: "Query",
		Fields: graphql.Fields{
			"user": &graphql.Field{
				Type: userType,
				Args: graphql.FieldConfigArgument{
					"id": &graphql.ArgumentConfig{
						Type: graphql.String,
					},
				},
				Resolve: resolvers.GetUserByID,
			},
		},
	})

var Schema, _ = graphql.NewSchema(
	graphql.SchemaConfig{
		Query: queryType,
	},
)


text: <!DOCTYPE html>


text:
<form name="editForm" role="form" novalidate ng-submit="vm.save()">

		<button type="button" class="close" data-dismiss="modal"
			aria-hidden="true" ng-click="vm.clear()">×</button>

{{vm.wizardTitleList[vm.wizardStep]}}

		<jhi-alert-error></jhi-alert-error>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-general.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-repair.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-new-line.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-assessments.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-excavations.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-new-constr.html'"></ng-include>

				<ng-include src="'app/entities/project/wizard-steps/project-wiz-right-of-way.html'"></ng-include>

		<button type="button" class="btn btn-default" data-dismiss="modal"
			ng-click="vm.clear()">
			 Cancel
		</button>
		<button type="button" ng-click="vm.back()"
			ng-disabled="editForm.$invalid || vm.isSaving"
			ng-hide="vm.wizardStep == 0" class="btn btn-default">
			 Back
		</button>
		<button type="button" ng-click="vm.next()"
			ng-disabled="editForm.$invalid || vm.isSaving"
			ng-hide="vm.wizardStep == vm.wizardMax"
			class="btn btn-primary">
			Next
		</button>
        <button type="submit"
        	ng-disabled="editForm.$invalid || vm.isSaving"
			ng-hide="vm.wizardStep != vm.wizardMax"
        	class="btn btn-primary">
             Save
        </button>

</form>


text:
(function (root, factory) {

  'use strict';

  // CommonJS module is defined
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = factory(require('jquery'));
  }
  // AMD module is defined
  else if (typeof define === 'function' && define.amd) {
    define(['jquery'], function ($) {
      return factory ($);
    });
  } else {
    factory(root.jQuery);
  }

}(this, function ($) {

  'use strict';
  // jshint laxcomma: true

 /* TYPEAHEAD PUBLIC CLASS DEFINITION
  * ================================= */

  var Typeahead = function (element, options) {
    this.$element = $(element);
    this.options = $.extend({}, $.fn.typeahead.defaults, options);
    this.matcher = this.options.matcher || this.matcher;
    this.sorter = this.options.sorter || this.sorter;
    this.select = this.options.select || this.select;
    this.autoSelect = typeof this.options.autoSelect == 'boolean' ? this.options.autoSelect : true;
    this.highlighter = this.options.highlighter || this.highlighter;
    this.render = this.options.render || this.render;
    this.updater = this.options.updater || this.updater;
    this.displayText = this.options.displayText || this.displayText;
    this.source = this.options.source;
    this.delay = this.options.delay;
    this.$menu = $(this.options.menu);
    this.$appendTo = this.options.appendTo ? $(this.options.appendTo) : null;
    this.shown = false;
    this.listen();
    this.showHintOnFocus = typeof this.options.showHintOnFocus == 'boolean' ? this.options.showHintOnFocus : false;
    this.afterSelect = this.options.afterSelect;
    this.addItem = false;
  };

  Typeahead.prototype = {

    constructor: Typeahead,

    select: function () {
      var val = this.$menu.find('.active').data('value');
      this.$element.data('active', val);
      if(this.autoSelect || val) {
        var newVal = this.updater(val);
        // Updater can be set to any random functions via "options" parameter in constructor above.
        // Add null check for cases when updater returns void or undefined.
        if (!newVal) {
          newVal = "";
        }
        this.$element
          .val(this.displayText(newVal) || newVal)
          .change();
        this.afterSelect(newVal);
      }
      return this.hide();
    },

    updater: function (item) {
      return item;
    },

    setSource: function (source) {
      this.source = source;
    },

    show: function () {
      var pos = $.extend({}, this.$element.position(), {
        height: this.$element[0].offsetHeight
      }), scrollHeight;

      scrollHeight = typeof this.options.scrollHeight == 'function' ?
          this.options.scrollHeight.call() :
          this.options.scrollHeight;

      var element;
      if (this.shown) {
        element = this.$menu;
      } else if (this.$appendTo) {
        element = this.$menu.appendTo(this.$appendTo);
      } else {
        element = this.$menu.insertAfter(this.$element);
      }
      element.css({
          top: pos.top + pos.height + scrollHeight
        , left: pos.left
        })
        .show();

      this.shown = true;
      return this;
    },

    hide: function () {
      this.$menu.hide();
      this.shown = false;
      return this;
    },

    lookup: function (query) {
      var items;
      if (typeof(query) != 'undefined' && query !== null) {
        this.query = query;
      } else {
        this.query = this.$element.val() ||  '';
      }

      if (this.query.length < this.options.minLength && !this.options.showHintOnFocus) {
        return this.shown ? this.hide() : this;
      }

      var worker = $.proxy(function() {

        if($.isFunction(this.source)) this.source(this.query, $.proxy(this.process, this));
        else if (this.source) {
          this.process(this.source);
        }
      }, this);

      clearTimeout(this.lookupWorker);
      this.lookupWorker = setTimeout(worker, this.delay);
    },

    process: function (items) {
      var that = this;

      items = $.grep(items, function (item) {
        return that.matcher(item);
      });

      items = this.sorter(items);

      if (!items.length && !this.options.addItem) {
        return this.shown ? this.hide() : this;
      }

      if (items.length > 0) {
        this.$element.data('active', items[0]);
      } else {
        this.$element.data('active', null);
      }

      // Add item
      if (this.options.addItem){
        items.push(this.options.addItem);
      }

      if (this.options.items == 'all') {
        return this.render(items).show();
      } else {
        return this.render(items.slice(0, this.options.items)).show();
      }
    },

    matcher: function (item) {
    var it = this.displayText(item);
      return ~it.toLowerCase().indexOf(this.query.toLowerCase());
    },

    sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item;

      while ((item = items.shift())) {
        var it = this.displayText(item);
        if (!it.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item);
        else if (~it.indexOf(this.query)) caseSensitive.push(item);
        else caseInsensitive.push(item);
      }

      return beginswith.concat(caseSensitive, caseInsensitive);
    },

    highlighter: function (item) {
          var html = $('

');
          var query = this.query;
          var i = item.toLowerCase().indexOf(query.toLowerCase());
          var len, leftPart, middlePart, rightPart, strong;
          len = query.length;
          if(len === 0){
              return html.text(item).html();
          }
          while (i > -1) {
              leftPart = item.substr(0, i);
              middlePart = item.substr(i, len);
              rightPart = item.substr(i + len);
              strong = $('').text(middlePart);
              html
                  .append(document.createTextNode(leftPart))
                  .append(strong);
              item = rightPart;
              i = item.toLowerCase().indexOf(query.toLowerCase());
          }
          return html.append(document.createTextNode(item)).html();
    },

    render: function (items) {
      var that = this;
      var self = this;
      var activeFound = false;
      var data = [];
      var _category = that.options.separator;

      $.each(items, function (key,value) {
        // inject separator
        if (key > 0 && value[_category] !== items[key - 1][_category]){
          data.push({
              __type: 'divider'
          });
        }

        // inject category header
        if (value[_category] && (key === 0 || value[_category] !== items[key - 1][_category])){
          data.push({
              __type: 'category',
              name: value[_category]
          });
        }
        data.push(value);
      });

      items = $(data).map(function (i, item) {

        if ((item.__type || false) == 'category'){
            return $(that.options.headerHtml).text(item.name)[0];
        }

        if ((item.__type || false) == 'divider'){
            return $(that.options.headerDivider)[0];
        }

        var text = self.displayText(item);
        i = $(that.options.item).data('value', item);
        i.find('a').html(that.highlighter(text, item));
        if (text == self.$element.val()) {
            i.addClass('active');
            self.$element.data('active', item);
            activeFound = true;
        }
        return i[0];
      });

      if (this.autoSelect && !activeFound) {
        items.filter(':not(.dropdown-header)').first().addClass('active');
        this.$element.data('active', items.first().data('value'));
      }
      this.$menu.html(items);
      return this;
    },

    displayText: function(item) {
      return typeof item !== 'undefined' && typeof item.name != 'undefined' && item.name || item;
    },

    next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next();

      if (!next.length) {
        next = $(this.$menu.find('li')[0]);
      }

      next.addClass('active');
    },

    prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev();

      if (!prev.length) {
        prev = this.$menu.find('li').last();
      }

      prev.addClass('active');
    },

    listen: function () {
      this.$element
        .on('focus',    $.proxy(this.focus, this))
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this));

      if (this.eventSupported('keydown')) {
        this.$element.on('keydown', $.proxy(this.keydown, this));
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
        .on('mouseleave', 'li', $.proxy(this.mouseleave, this));
    },

    destroy : function () {
      this.$element.data('typeahead',null);
      this.$element.data('active',null);
      this.$element
        .off('focus')
        .off('blur')
        .off('keypress')
        .off('keyup');

      if (this.eventSupported('keydown')) {
        this.$element.off('keydown');
      }

      this.$menu.remove();
    },

    eventSupported: function(eventName) {
      var isSupported = eventName in this.$element;
      if (!isSupported) {
        this.$element.setAttribute(eventName, 'return;');
        isSupported = typeof this.$element[eventName] === 'function';
      }
      return isSupported;
    },

    move: function (e) {
      if (!this.shown) return;

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault();
          break;

        case 38: // up arrow
          // with the shiftKey (this is actually the left parenthesis)
          if (e.shiftKey) return;
          e.preventDefault();
          this.prev();
          break;

        case 40: // down arrow
          // with the shiftKey (this is actually the right parenthesis)
          if (e.shiftKey) return;
          e.preventDefault();
          this.next();
          break;
      }
    },

    keydown: function (e) {
      this.suppressKeyPressRepeat = ~$.inArray(e.keyCode, [40,38,9,13,27]);
      if (!this.shown && e.keyCode == 40) {
        this.lookup();
      } else {
        this.move(e);
      }
    },

    keypress: function (e) {
      if (this.suppressKeyPressRepeat) return;
      this.move(e);
    },

    keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
        case 16: // shift
        case 17: // ctrl
        case 18: // alt
          break;

        case 9: // tab
        case 13: // enter
          if (!this.shown) return;
          this.select();
          break;

        case 27: // escape
          if (!this.shown) return;
          this.hide();
          break;
        default:
          this.lookup();
      }

      e.preventDefault();
   },

   focus: function (e) {
      if (!this.focused) {
        this.focused = true;
        if (this.options.showHintOnFocus) {
          this.lookup('');
        }
      }
    },

    blur: function (e) {
      this.focused = false;
      if (!this.mousedover && this.shown) this.hide();
    },

    click: function (e) {
      e.preventDefault();
      this.select();
      //this.$element.focus();
      this.hide();
    },

    mouseenter: function (e) {
      this.mousedover = true;
      this.$menu.find('.active').removeClass('active');
      $(e.currentTarget).addClass('active');
    },

    mouseleave: function (e) {
      this.mousedover = false;
      if (!this.focused && this.shown) this.hide();
    }

  };

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  var old = $.fn.typeahead;

  $.fn.typeahead = function (option) {
    var arg = arguments;
     if (typeof option == 'string' && option == 'getActive') {
        return this.data('active');
     }
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option;
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)));
      if (typeof option == 'string' && data[option]) {
        if (arg.length > 1) {
          data[option].apply(data, Array.prototype.slice.call(arg ,1));
        } else {
          data[option]();
        }
      }
    });
  };

  $.fn.typeahead.defaults = {
        source: [],
        items: 8,
        menu: '

',
        item: '

',
        minLength: 1,
        scrollHeight: 0,
        autoSelect: true,
        afterSelect: $.noop,
        addItem: false,
        delay: 0,
        separator: 'category',
        headerHtml: '

',
        headerDivider: '

'
  };

  $.fn.typeahead.Constructor = Typeahead;

 /* TYPEAHEAD NO CONFLICT
  * =================== */

  $.fn.typeahead.noConflict = function () {
    $.fn.typeahead = old;
    return this;
  };

 /* TYPEAHEAD DATA-API
  * ================== */

  $(document).on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
    var $this = $(this);
    if ($this.data('typeahead')) return;
    $this.typeahead($this.data());
  });

}));


text:
module Data.Codeword
  ( Codeword(..)
  , codeword
  ) where

import Data.CRC
import Data.Bits
import Data.Word

newtype Codeword = Codeword { getCodeword :: Word32 }

-- Takes the 21 bit data segment of a codeword and adds the CRC and parity
-- error correction codes
codeword :: Word32 -> Codeword
codeword x = Codeword $ shiftL fullCRC 1 .|. parityBit fullCRC
  where
    fullCRC = shiftL x crcLength .|. crc x