text:
<?php

namespace Valdi\Validator;

use Valdi\ValidationException;
use Valdi\Validator;

/**
 * Validator for array data, be it maps or lists.
 */
abstract class AbstractArray implements ValidatorInterface
{

    /**
     * Holds the invalid values.
     */
    protected $invalidDetails;

    /**
     * Checks whether the given values are of the expected array data.
     *
     * @param mixed $values the potential array values to check
     * @param Validator $validator the validator to check with
     * @param array $rules the rules which the array data must fulfill
     *
     * @return boolean - true if all the $values are valid, else false with the invalid details set
     */
    abstract protected function isValidArray($values, Validator $validator, array $rules);

    /**
     * {@inheritdoc}
     */
    public function isValid($value, array $parameters)
    {
        if (count($parameters) !== 2) {
            throw new ValidationException('Expecting two parameters.');
        }
        if (!($parameters[0] instanceof Validator)) {
            throw new ValidationException('Expecting the first parameter to be an instance of a Validator.');
        }
        return in_array($value, ['', null], true) ||
            $this->isValidArray($value, $parameters[0], $parameters[1]);
    }
}


text:
package aima.test.core.unit.probability.bayes.approx;

import org.junit.Assert;
import org.junit.Test;

import aima.core.probability.ProbabilityModel;
import aima.core.probability.RandomVariable;
import aima.core.probability.bayes.BayesianNetwork;
import aima.core.probability.bayes.approx.PriorSample;
import aima.core.probability.bayes.approx.RejectionSampling;
import aima.core.probability.example.BayesNetExampleFactory;
import aima.core.probability.example.ExampleRV;
import aima.core.probability.proposition.AssignmentProposition;
import aima.core.util.MockRandomizer;

/**
 *
 * @author Ciaran O'Reilly
 * @author Ravi Mohan
 */
public class RejectionSamplingTest {

	public static final double DELTA_THRESHOLD = ProbabilityModel.DEFAULT_ROUNDING_THRESHOLD;

	@Test
	public void testPriorSample_basic() {

		BayesianNetwork bn = BayesNetExampleFactory
				.constructCloudySprinklerRainWetGrassNetwork();
		AssignmentProposition[] e = new AssignmentProposition[] { new AssignmentProposition(
				ExampleRV.SPRINKLER_RV, Boolean.TRUE) };
		MockRandomizer r = new MockRandomizer(new double[] { 0.1 });
		RejectionSampling rs = new RejectionSampling(new PriorSample(r));

		double[] estimate = rs.rejectionSampling(
				new RandomVariable[] { ExampleRV.RAIN_RV }, e, bn, 100)
				.getValues();

		Assert.assertArrayEquals(new double[] { 1.0, 0.0 }, estimate,
				DELTA_THRESHOLD);
	}

	@Test
	public void testRejectionSampling_AIMA3e_pg532() {
		// AIMA3e pg. 532

		BayesianNetwork bn = BayesNetExampleFactory
				.constructCloudySprinklerRainWetGrassNetwork();
		AssignmentProposition[] e = new AssignmentProposition[] { new AssignmentProposition(
				ExampleRV.SPRINKLER_RV, Boolean.TRUE) };

		// 400 required as 4 variables and 100 samples planned
		double[] ma = new double[400];
		for (int i = 0; i < ma.length; i += 4) {
			// Of the 100 that we generate, suppose
			// that 73 have Sprinkler = false and are rejected,
			if (i < (73 * 4)) {
				ma[i] = 0.5; // i.e Cloudy=true
				ma[i + 1] = 0.2; // i.e. Sprinkler=false
				ma[i + 2] = 0.5; // i.e. Rain=true
				ma[i + 3] = 0.1; // i.e. WetGrass=true
			} else {
				ma[i] = 0.5; // i.e Cloudy=true
				ma[i + 1] = 0.09; // i.e. Sprinkler=true
				// while 27 have Sprinkler = true; of the 27,
				// 8 have Rain = true
				if (i < ((73 + 8) * 4)) {
					ma[i + 2] = 0.5; // i.e. Rain=true
				} else {
					// and 19 have Rain = false.
					ma[i + 2] = 0.9; // i.e. Rain=false
				}

				ma[i + 3] = 0.1; // i.e. WetGrass=true
			}
		}
		MockRandomizer r = new MockRandomizer(ma);
		RejectionSampling rs = new RejectionSampling(new PriorSample(r));

		double[] estimate = rs.rejectionSampling(
				new RandomVariable[] { ExampleRV.RAIN_RV }, e, bn, 100)
				.getValues();

		Assert.assertArrayEquals(new double[] { 0.2962962962962963,
				0.7037037037037037 }, estimate, DELTA_THRESHOLD);
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System.Collections;
using UnityEngine;

public enum AnimationType {
    Linear,
    PingPong,
    Sin
}

[RequireComponent(typeof(Renderer))]
public class SharedTextureAnimator : GameObjectBehavior {
    public float scrollSpeed = 0.7f;
    public bool animateX = false;
    public bool animateY = true;
    public bool useSharedMaterial = true; // using the sharedMaterial allows batching
    public AnimationType animationType = AnimationType.Linear;

    private Material mat; // material cache

    private void Start() {
        if (useSharedMaterial)
            mat = renderer.sharedMaterial;
        else
            mat = renderer.material;
    }

    private void Update() {
        float offset = 0.0f;

        // calculate the offset based on the chosen type
        switch (animationType) {
            case AnimationType.Linear:
                offset = Time.time * scrollSpeed % 1;
                break;

            case AnimationType.PingPong:
                offset = Mathf.PingPong(Time.time * scrollSpeed, 1);
                break;

            case AnimationType.Sin:
                offset = Mathf.Sin(Time.time * scrollSpeed);
                break;
        }

        if (animateX && animateY)
            mat.mainTextureOffset = new Vector2(offset, offset);
        else if (animateX)
            mat.mainTextureOffset = new Vector2(offset, 0);
        else if (animateY)
            mat.mainTextureOffset = new Vector2(0, offset);
    }
}


text:
package com.gigigo.orchextra.domain.abstractions.foreground;

public interface ForegroundTasksManager {

  void startForegroundTasks();

  void finalizeForegroundTasks();
}


text:
require 'rubygems' if RUBY_VERSION < '1.9.0' && Puppet.features.rubygems?
require 'aws-sdk-core' if Puppet.features.aws?

Puppet::Type.type(:s3synced_file).provide(:posix) do
  confine :feature => :aws
  confine :feature => :posix
  include Puppet::Util::POSIX
  include Puppet::Util::Warnings
  require 'etc'

  def create
    begin
      s3 = Aws::S3::Client.new(
        access_key_id: @resource[:access_key_id],
        secret_access_key: @resource[:secret_access_key],
        region: @resource[:region]
      )

      if File.exists?(@resource[:name])
        s3.get_object(
          bucket: @resource[:bucket],
          key: @resource[:key],
          if_modified_since: File.mtime(@resource[:name]),
          response_target: @resource[:name]
        )
      else
        s3.get_object(
          bucket: @resource[:bucket],
          key: @resource[:key],
          response_target: @resource[:name]
        )
      end

      # Make sure the mode is correct
      if @resource[:mode] != nil
        should_mode = @resource.should(:mode)
        unless self.mode == should_mode
            self.mode = should_mode
        end
      end
      if @resource[:owner] != nil
        should_owner = name2uid(@resource.should(:owner))
        unless self.owner == should_owner
            self.owner = should_owner
        end
      end
      if @resource[:group] != nil
        should_group = name2gid(@resource.should(:group))
        unless self.group == should_group
            self.group = should_group
        end
      end

    rescue Aws::S3::Errors::ServiceError => e
      if e.context.http_response.status_code == 304
        info("Not modified on S3")
      else
        self.fail "Could not download s3 file. Status: #{e.context.http_response.status_code}"
      end
    rescue => e
      self.fail "Could not download s3 file: #{e.message}"
    end
  end

  def destroy
      File.unlink(@resource[:name])
  end

  def exists?
    if "#{@resource[:ensure]}" == 'present'
      false
    else
      File.exists?(@resource[:name])
    end
  end

  #copyed from file resource type from puppet main types
  def mode
    if stat = resource.stat
      return (stat.mode & 007777).to_s(8)
    else
      return :absent
    end
  end

  def mode=(value)
    begin
      File.chmod(value.to_i(8), resource[:name])
    rescue => detail
      error = Puppet::Error.new("failed to set mode #{mode} on #{resource[:name]}: #{detail.message}")
      error.set_backtrace detail.backtrace
      raise error
    end
  end

  # Determine if the user is valid, and if so, return the UID
  def name2uid(value)
    Integer(value) rescue uid(value) || false
  end

  def name2gid(value)
    Integer(value) rescue gid(value) || false
  end

  def owner
    unless stat = resource.stat
      return :absent
    end
    currentvalue = stat.uid
    # On OS X, files that are owned by -2 get returned as really
    # large UIDs instead of negative ones.  This isn't a Ruby bug,
    # it's an OS X bug, since it shows up in perl, too.
    if currentvalue > Puppet[:maximum_uid].to_i
      self.warning "Apparently using negative UID (#{currentvalue}) on a platform that does not consistently handle them"
      currentvalue = :silly
    end
    currentvalue
  end

  def owner=(should)
    method = :chown
    begin
      File.send(method, should, nil, resource[:name])
    rescue => detail
      raise Puppet::Error, "Failed to set owner to '#{should}': #{detail}"
    end
  end

  def group
    return :absent unless stat = resource.stat
    currentvalue = stat.gid

    # On OS X, files that are owned by -2 get returned as really
    # large GIDs instead of negative ones.  This isn't a Ruby bug,
    # it's an OS X bug, since it shows up in perl, too.
    if currentvalue > Puppet[:maximum_uid].to_i
      self.warning "Apparently using negative GID (#{currentvalue}) on a platform that does not consistently handle them"
      currentvalue = :silly
    end
    currentvalue
  end

  def group=(should)
    method = :chown
    begin
      File.send(method, nil, should, resource[:name])
    rescue => detail
      raise Puppet::Error, "Failed to set group to '#{should}': #{detail}"
    end
  end

end


text:
"""
build_lib_ic.py
Copyright 2016 Adam Greig
Licensed under the MIT licence, see LICENSE file for details.

Generate symbols for generic black-box ICs etc.

Symbols configuration:
Each symbol is defined by a .yaml file in the same path that the .lib file
should be placed. Each file contains the following keys:
designator: optional, default "IC", the default reference designator
footprint: optional, an associated footprint to autofill
datasheet: optional, a URL or path to a datasheet
ordercodes: optional, list of (supplier, code) for supplier order codes
description: description of the part, placed in the .dcm file
pins: list of lists of left and right pin groups
          (blocks of related pins with a space in-between).
      Each group contains a list of tuples of:
          (pin name, pin number, electrical type).
      Number and name may be given as a string or an integer.
      Electrical type must be a string out of:
          in, out, bidi, tri, passive, unspec, pwrin, pwrout,
          oc, od, oe, os, nc.
      These correspond to input, output, bidirectional, tristate, passive,
          unspecified, power_input, power_output, open_collector,
          open_emitter, and not_connected. They should be given as strings.

"""

from __future__ import print_function, division

import os
import sys
import yaml
import fnmatch
import argparse

pin_types = {
    "in": "I",
    "out": "O",
    "bidi": "B",
    "tri": "T",
    "passive": "P",
    "unspec": "U",
    "pwrin": "W",
    "pwrout": "w",
    "oc": "C",
    "od": "C",
    "oe": "E",
    "os": "E",
    "nc": "N",
}

def geometry(conf):
    # width is twice the width required to accommodate the longest name
    longest_name = max(max(max(len(pin[0]) for pin in grp) for grp in side)
                       for side in conf['pins'])
    width = 2 * (longest_name + 1) * 50
    width += width % 200

    # height is the maximum required on either side
    if len(conf['pins']) != 2:
        raise RuntimeError("IC schematic symbols must list pins on exactly "
                           "two sides.")
    left_pins = sum(len(x) for x in conf['pins'][0])
    right_pins = sum(len(x) for x in conf['pins'][1])
    left_groups = len(conf['pins'][0])
    right_groups = len(conf['pins'][1])

    height = 100 * max(
        left_pins + left_groups - 1, right_pins + right_groups - 1)

    # height must be an odd multiple of 0.1" or the grid breaks
    if (height // 100) % 2 == 0:
        height += 100

    # Pin length based on maximum pin number length
    longest_num = max(max(max(len(str(pin[1])) for pin in grp) for grp in side)
                      for side in conf['pins'])
    length = max(100, longest_num*50)
    # Ensure pins will align to a 100mil grid by making the part wider
    if length % 100 != 0:
        width += 100

    return width, height, length, left_groups

def fields(conf):
    width, height, _, lgroups = geometry(conf)
    field_x = -width//2
    field_y = height//2 + 50
    out = []

    # Designator at top
    out.append("F0 \"{}\" {} {} 50 H V L CNN".format(
        conf.get('designator', 'IC'), field_x, field_y))

    # Value/name at bottom
    out.append("F1 \"{}\" {} {} 50 H V L CNN".format(
        conf['name'], field_x, -field_y))

    # Either specify a footprint or just set its size, position, invisibility
    if "footprint" in conf:
        out.append("F2 \"{}\" {} {} 50 H I L CNN".format(
            conf['footprint'], field_x, -field_y-100))
    else:
        out.append("F2 \"\" {} {} 50 H I L CNN".format(field_x, -field_y-100))

    # Specify a datasheet if given
    if "datasheet" in conf:
        out.append("F3 \"{}\" {} {} 50 H I L CNN".format(
            conf['datasheet'], field_x, -field_y-200))
    else:
        out.append("F3 \"\" {} {} 50 H I L CNN".format(field_x, -field_y-200))

    # Order codes
    for idx, (supplier, code) in enumerate(conf.get("ordercodes", [])):
        out.append("F{} \"{}\" {} {} 50 H I L CNN \"{}\"".format(
            idx+4, code, field_x, -field_y-(300+idx*100), supplier))

    return out

def draw_pins(groups, x0, y0, direction, length):
    out = []
    pin_x = x0
    pin_y = y0
    for group in groups:
        for (name, num, t) in group:
            out.append("X {} {} {} {} {} {} 50 50 0 0 {}".format(
                name, num, pin_x, pin_y, length, direction, pin_types[t]))
            pin_y -= 100
        pin_y -= 100
    return out

def draw(conf):
    width, height, length, lgroups = geometry(conf)
    out = []
    out.append("DRAW")

    # Containing box
    out.append("S {} {} {} {} 0 1 0 f".format(
        -width//2, height//2, width//2, -height//2))

    # Pins
    x0 = -width//2 - length
    y0 = height//2 - 50
    out += draw_pins(conf['pins'][0], x0, y0, "R", length)
    out += draw_pins(conf['pins'][1], -x0, y0, "L", length)

    out.append("ENDDRAW")
    return out

def library(conf):
    out = []

    out.append("EESchema-LIBRARY Version 2.3")
    out.append("#encoding utf-8")
    out.append("#\n# {}\n#".format(conf['name']))
    out.append("DEF {} {} 0 40 Y Y 1 F N".format(
        conf['name'], conf.get('designator', 'IC')))

    out += fields(conf)
    out += draw(conf)

    out.append("ENDDEF\n#\n#End Library\n")
    return "\n".join(out)

def documentation(conf):
    out = []
    out.append("EESchema-DOCLIB  Version 2.0")
    out.append("$CMP {}".format(conf['name']))
    out.append("D {}".format(conf['description']))
    out.append("$ENDCMP\n")
    return "\n".join(out)

def load_items(libpath):
    config = {}
    for dirpath, dirnames, files in os.walk(libpath):
        dirnames.sort()
        files.sort()
        for fn in fnmatch.filter(files, "*.yaml"):
            path = os.path.join(dirpath, fn)
            with open(path) as f:
                item = yaml.safe_load(f)
                item["path"] = dirpath
                config[item["name"]] = item
    return config

def main(libpath, verify=False, verbose=False):
    config = load_items(libpath)
    for name, conf in config.items():
        conf['name'] = name
        path = os.path.join(conf.get("path", ""), name.lower()+".lib")
        dcmpath = os.path.splitext(path)[0] + ".dcm"

        lib = library(conf)
        dcm = documentation(conf)

        if verify and verbose:
            print("Verifying", path)

        # Check if anything has changed
        if os.path.isfile(path):
            with open(path) as f:
                oldlib = f.read()
            if os.path.isfile(dcmpath):
                with open(dcmpath) as f:
                    olddcm = f.read()
                if lib == oldlib and dcm == olddcm:
                    continue

        # If so, either verification failed or write the new files
        if verify:
            return False
        else:
            with open(path, "w") as f:
                f.write(lib)
            with open(dcmpath, "w") as f:
                f.write(dcm)

    # If we finished and didn't return yet, verification has succeeded
    if verify:
        return True

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("libpath", type=str, help=
                        "Path to libraries to process")
    parser.add_argument("--verify", action="store_true", help=
                        "Verify libraries are up to date")
    parser.add_argument("--verbose", action="store_true", help=
                        "Print out every library verified")
    args = vars(parser.parse_args())
    result = main(**args)
    if args['verify']:
        if result:
            print("OK: all libs up-to-date.")
            sys.exit(0)
        else:
            print("Error: libs not up-to-date.", file=sys.stderr)
            sys.exit(1)


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

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/tab_item_title"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:drawableTop="@drawable/groups_icon"
            android:gravity="center_horizontal"
            android:padding="5dp"
            android:singleLine="true"
            android:text="TabItem"
            android:textColor="@color/main_botton_text_color"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/tab_item_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginEnd="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/unread_count_bg"
            android:gravity="center"
            android:lines="1"
            android:textColor="#FFFFFF"
            android:textSize="11sp"
            android:visibility="gone" />
    </FrameLayout>

</LinearLayout>


text:
""" Creating model on lists of datasets

"""
from .world import world, setup_module, teardown_module
from . import create_source_steps as source_create
from . import create_dataset_steps as dataset_create
from . import create_model_steps as model_create
from . import create_multimodel_steps as multimodel_create
from . import compare_predictions_steps as compare_pred

class TestMultimodel(object):

    def setup(self):
        """
            Debug information
        """
        print("\n-------------------\nTests in: %s\n" % __name__)

    def teardown(self):
        """
            Debug information
        """
        print("\nEnd of tests in: %s\n-------------------\n" % __name__)

    def test_scenario1(self):
        """
            Scenario: Successfully creating a model from a dataset list:
                Given I create a data source uploading a "<data>" file
                And I wait until the source is ready less than <time_1> secs
                And I create a dataset
                And I wait until the dataset is ready less than <time_2> secs
                And I store the dataset id in a list
                And I create a dataset
                And I wait until the dataset is ready less than <time_3> secs
                And I store the dataset id in a list
                Then I create a model from a dataset list
                And I wait until the model is ready less than <time_4> secs
                And I check the model stems from the original dataset list

                Examples:
                | data                | time_1  | time_2 | time_3 |  time_4 |
                | ../data/iris.csv | 10      | 10     | 10     |  10
        """
        print(self.test_scenario1.__doc__)
        examples = [
            ['data/iris.csv', '10', '10', '10', '10']]
        for example in examples:
            print("\nTesting with:\n", example)
            source_create.i_upload_a_file(self, example[0])
            source_create.the_source_is_finished(self, example[1])
            dataset_create.i_create_a_dataset(self)
            dataset_create.the_dataset_is_finished_in_less_than(self, example[2])
            multimodel_create.i_store_dataset_id(self)
            dataset_create.i_create_a_dataset(self)
            dataset_create.the_dataset_is_finished_in_less_than(self, example[3])
            multimodel_create.i_store_dataset_id(self)
            model_create.i_create_a_model_from_dataset_list(self)
            model_create.the_model_is_finished_in_less_than(self, example[4])
            multimodel_create.i_check_model_datasets_and_datasets_ids(self)

    def test_scenario2(self):
        """
            Scenario: Successfully creating a model from a dataset list and predicting with it using median:
                Given I create a data source uploading a "<data>" file
                And I wait until the source is ready less than <time_1> secs
                And I create a dataset
                And I wait until the dataset is ready less than <time_2> secs
                And I create a model
                And I wait until the model is ready less than <time_3> secs
                And I create a local multi model
                When I create a local multimodel batch prediction using median for <input_data>
                Then the local prediction is <prediction>

                Examples:
                | data                | time_1  | time_2 | time_3 |  input_data | prediction
                | ../data/grades.csv | 10      | 10     | 10     |  {'Tutorial': 99.47, 'Midterm': 53.12, 'TakeHome': 87.96} | 50
        """
        print(self.test_scenario2.__doc__)
        examples = [
            ['data/grades.csv', '30', '30', '30', '{"Tutorial": 99.47, "Midterm": 53.12, "TakeHome": 87.96}', 63.33]]
        for example in examples:
            print("\nTesting with:\n", example)
            source_create.i_upload_a_file(self, example[0])
            source_create.the_source_is_finished(self, example[1])
            dataset_create.i_create_a_dataset(self)
            dataset_create.the_dataset_is_finished_in_less_than(self, example[2])
            model_create.i_create_a_model(self)
            model_create.the_model_is_finished_in_less_than(self, example[3])
            world.list_of_models = [world.model]
            compare_pred.i_create_a_local_multi_model(self)
            compare_pred.i_create_a_local_mm_median_batch_prediction(self, example[4])
            compare_pred.the_local_prediction_is(self, example[5])


text:
<!--
  ~ Copyright 2013, The Sporting Exchange Limited
  - Copyright 2014, Simon Matić Langford
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

	<parent>
		<groupId>uk.co.exemel.disco</groupId>
		<artifactId>disco-test</artifactId>
		<version>3.3-SNAPSHOT</version>
	</parent>

	<modelVersion>4.0.0</modelVersion>
	<artifactId>disco-test-utils</artifactId>
	<packaging>jar</packaging>
	<name>disco-test-utils</name>

	<dependencies>
        <dependency>
            <groupId>jtidy</groupId>
            <artifactId>jtidy</artifactId>
            <version>4aug2000r7-dev</version>
        </dependency>
        <dependency>
            <groupId>commons-jxpath</groupId>
            <artifactId>commons-jxpath</artifactId>
            <version>1.3</version>
        </dependency>

		<dependency>
			<groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>${json.version}</version>
        </dependency>

		<dependency>
			<groupId>com.sun</groupId>
			<artifactId>tools</artifactId>
			<scope>system</scope>
			<systemPath>${java.home}/../lib/tools.jar</systemPath>
            <version>${java.version}</version>
		</dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

		<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

		<dependency>
		    <groupId>xerces</groupId>
		    <artifactId>xercesImpl</artifactId>
		</dependency>

		<dependency>
		    <groupId>xalan</groupId>
		    <artifactId>xalan</artifactId>
		</dependency>

		<dependency>
    		<groupId>${project.groupId}</groupId>
		  	<artifactId>client-idd</artifactId>
		  	<version>${project.version}</version>
    	</dependency>

    	<dependency>
    		<groupId>commons-io</groupId>
		  	<artifactId>commons-io</artifactId>
		  	<version>${commons.io.version}</version>
    	</dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>${testng.version}</version>
        </dependency>

        <!--TODO: Consider XMLUnit to compare XML?-->
        <!--<dependency>-->
            <!--<groupId>xmlunit</groupId>-->
            <!--<artifactId>xmlunit</artifactId>-->
            <!--<version>1.5</version>-->
        <!--</dependency>-->

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>${mockito-core.version}</version>
        </dependency>

	</dependencies>
</project>


text:
let { writeFile } = require('fs').promises
let { join } = require('path')
let mkdirp = require('mkdirp')

module.exports = async function processImport(check, output) {
  if (!check.import) {
    return
  }

  let loader = ''
  for (let i in check.import) {
    let imports = `${check.import[i]}`
    let list = check.import[i].replace(/}|{/g, '').trim()

    if (check.import[i] === '*') {
      imports = `${check.import[i]} as all`
      list = `all`
    }

    loader +=
      `import ${imports} from ${JSON.stringify(i)}\n` + `console.log(${list})\n`
  }
  await mkdirp(output)
  let entry = join(output, 'index.js')
  await writeFile(entry, loader)
  check.files = entry
}


text:
#include <mrpt/maps/CColouredPointsMap.h>
#include <mrpt/maps/CSimplePointsMap.h>
#include <mrpt/ros1bridge/point_cloud2.h>
#include <mrpt/ros1bridge/time.h>
#include <mrpt/version.h>
#include <ros/console.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/PointField.h>

using namespace mrpt::maps;

static bool check_field(
	const sensor_msgs::PointField& input_field, std::string check_name,
	const sensor_msgs::PointField** output)
{
	bool coherence_error = false;
	if (input_field.name == check_name)
	{
		if (input_field.datatype != sensor_msgs::PointField::FLOAT32 &&
			input_field.datatype != sensor_msgs::PointField::FLOAT64 &&
			input_field.datatype != sensor_msgs::PointField::UINT16 &&
			input_field.datatype != sensor_msgs::PointField::UINT8)
		{
			*output = nullptr;
			coherence_error = true;
		}
		else
		{
			*output = &input_field;
		}
	}
	return coherence_error;
}

static void get_float_from_field(
	const sensor_msgs::PointField* field, const unsigned char* data,
	float& output)
{
	if (field != nullptr)
	{
		if (field->datatype == sensor_msgs::PointField::FLOAT32)
			output = *(reinterpret_cast<const float*>(&data[field->offset]));
		else
			output = (float)(*(
				reinterpret_cast<const double*>(&data[field->offset])));
	}
	else
		output = 0.0;
}
static void get_uint16_from_field(
	const sensor_msgs::PointField* field, const unsigned char* data,
	uint16_t& output)
{
	if (field != nullptr)
	{
		if (field->datatype == sensor_msgs::PointField::UINT16)
			output = *(reinterpret_cast<const uint16_t*>(&data[field->offset]));
		else if (field->datatype == sensor_msgs::PointField::UINT8)
			output = *(reinterpret_cast<const uint8_t*>(&data[field->offset]));
	}
	else
		output = 0;
}

std::set<std::string> mrpt::ros1bridge::extractFields(
	const sensor_msgs::PointCloud2& msg)
{
	std::set<std::string> lst;
	for (const auto& f : msg.fields)
		lst.insert(f.name);
	return lst;
}

/** Convert sensor_msgs/PointCloud2 -> mrpt::slam::CSimplePointsMap
 *
 * \return true on sucessful conversion, false on any error.
 */
bool mrpt::ros1bridge::fromROS(
	const sensor_msgs::PointCloud2& msg, CSimplePointsMap& obj)
{
	// Copy point data
	unsigned int num_points = msg.width * msg.height;
	obj.clear();
	obj.reserve(num_points);

	bool incompatible = false;
	const sensor_msgs::PointField *x_field = nullptr, *y_field = nullptr,
								  *z_field = nullptr;

	for (unsigned int i = 0; i < msg.fields.size() && !incompatible; i++)
	{
		incompatible |= check_field(msg.fields[i], "x", &x_field);
		incompatible |= check_field(msg.fields[i], "y", &y_field);
		incompatible |= check_field(msg.fields[i], "z", &z_field);
	}

	if (incompatible || (!x_field || !y_field || !z_field)) return false;

	// If not, memcpy each group of contiguous fields separately
	for (unsigned int row = 0; row < msg.height; ++row)
	{
		const unsigned char* row_data = &msg.data[row * msg.row_step];
		for (uint32_t col = 0; col < msg.width; ++col)
		{
			const unsigned char* msg_data = row_data + col * msg.point_step;

			float x, y, z;
			get_float_from_field(x_field, msg_data, x);
			get_float_from_field(y_field, msg_data, y);
			get_float_from_field(z_field, msg_data, z);
			obj.insertPoint(x, y, z);
		}
	}

	return true;
}

bool mrpt::ros1bridge::fromROS(
	const sensor_msgs::PointCloud2& msg, CPointsMapXYZI& obj)
{
	// Copy point data
	unsigned int num_points = msg.width * msg.height;
	obj.clear();
	obj.reserve(num_points);

	bool incompatible = false;
	const sensor_msgs::PointField *x_field = nullptr, *y_field = nullptr,
								  *z_field = nullptr, *i_field = nullptr;

	for (unsigned int i = 0; i < msg.fields.size() && !incompatible; i++)
	{
		incompatible |= check_field(msg.fields[i], "x", &x_field);
		incompatible |= check_field(msg.fields[i], "y", &y_field);
		incompatible |= check_field(msg.fields[i], "z", &z_field);
		incompatible |= check_field(msg.fields[i], "intensity", &i_field);
	}

	if (incompatible || (!x_field || !y_field || !z_field || !i_field))
		return false;

	// If not, memcpy each group of contiguous fields separately
	for (unsigned int row = 0; row < msg.height; ++row)
	{
		const unsigned char* row_data = &msg.data[row * msg.row_step];
		for (uint32_t col = 0; col < msg.width; ++col)
		{
			const unsigned char* msg_data = row_data + col * msg.point_step;

			float x, y, z, i;
			get_float_from_field(x_field, msg_data, x);
			get_float_from_field(y_field, msg_data, y);
			get_float_from_field(z_field, msg_data, z);
			get_float_from_field(i_field, msg_data, i);
			obj.insertPoint(x, y, z);

			obj.setPointIntensity(obj.size() - 1, i / 255.0);
		}
	}
	return true;
}

bool mrpt::ros1bridge::toROS(
	const CSimplePointsMap& obj, const std_msgs::Header& msg_header,
	sensor_msgs::PointCloud2& msg)
{
	msg.header = msg_header;

	// 2D structure of the point cloud. If the cloud is unordered, height is
	//  1 and width is the length of the point cloud.
	msg.height = 1;
	msg.width = obj.size();

	std::array<std::string, 3> names = {"x", "y", "z"};
	std::array<size_t, 3> offsets = {0, sizeof(float) * 1, sizeof(float) * 2};

	msg.fields.resize(3);
	for (size_t i = 0; i < 3; i++)
	{
		auto& f = msg.fields.at(i);

		f.count = 1;
		f.offset = offsets[i];
		f.datatype = sensor_msgs::PointField::FLOAT32;
		f.name = names[i];
	}

#if MRPT_IS_BIG_ENDIAN
	msg.is_bigendian = true;
#else
	msg.is_bigendian = false;
#endif

	msg.point_step = sizeof(float) * 3;
	msg.row_step = msg.width * msg.point_step;

	// data:
	msg.data.resize(msg.row_step * msg.height);

	const auto& xs = obj.getPointsBufferRef_x();
	const auto& ys = obj.getPointsBufferRef_y();
	const auto& zs = obj.getPointsBufferRef_z();

	float* pointDest = reinterpret_cast<float*>(msg.data.data());
	for (size_t i = 0; i < xs.size(); i++)
	{
		*pointDest++ = xs[i];
		*pointDest++ = ys[i];
		*pointDest++ = zs[i];
	}

	return true;
}

bool mrpt::ros1bridge::toROS(
	const CPointsMapXYZI& obj, const std_msgs::Header& msg_header,
	sensor_msgs::PointCloud2& msg)
{
	msg.header = msg_header;

	// 2D structure of the point cloud. If the cloud is unordered, height is
	//  1 and width is the length of the point cloud.
	msg.height = 1;
	msg.width = obj.size();

	std::array<std::string, 4> names = {"x", "y", "z", "intensity"};
	std::array<size_t, 4> offsets = {
		0, sizeof(float) * 1, sizeof(float) * 2, sizeof(float) * 3};

	msg.fields.resize(4);
	for (size_t i = 0; i < 4; i++)
	{
		auto& f = msg.fields.at(i);

		f.count = 1;
		f.offset = offsets[i];
		f.datatype = sensor_msgs::PointField::FLOAT32;
		f.name = names[i];
	}

#if MRPT_IS_BIG_ENDIAN
	msg.is_bigendian = true;
#else
	msg.is_bigendian = false;
#endif

	msg.point_step = sizeof(float) * 4;
	msg.row_step = msg.width * msg.point_step;

	// data:
	msg.data.resize(msg.row_step * msg.height);

	const auto& xs = obj.getPointsBufferRef_x();
	const auto& ys = obj.getPointsBufferRef_y();
	const auto& zs = obj.getPointsBufferRef_z();
	const auto& Is = obj.getPointsBufferRef_intensity();

	float* pointDest = reinterpret_cast<float*>(msg.data.data());
	for (size_t i = 0; i < xs.size(); i++)
	{
		*pointDest++ = xs[i];
		*pointDest++ = ys[i];
		*pointDest++ = zs[i];
		*pointDest++ = Is[i];
	}

	return true;
}

/** Convert sensor_msgs/PointCloud2 -> mrpt::obs::CObservationRotatingScan */
bool mrpt::ros1bridge::fromROS(
	const sensor_msgs::PointCloud2& msg,
	mrpt::obs::CObservationRotatingScan& obj,
	const mrpt::poses::CPose3D& sensorPoseOnRobot,
	unsigned int num_azimuth_divisions)
{
	// Copy point data
	obj.timestamp = mrpt::ros1bridge::fromROS(msg.header.stamp);

	bool incompatible = false;
	const sensor_msgs::PointField *x_field = nullptr, *y_field = nullptr,
								  *z_field = nullptr, *i_field = nullptr,
								  *ring_field = nullptr;

	for (unsigned int i = 0; i < msg.fields.size() && !incompatible; i++)
	{
		incompatible |= check_field(msg.fields[i], "x", &x_field);
		incompatible |= check_field(msg.fields[i], "y", &y_field);
		incompatible |= check_field(msg.fields[i], "z", &z_field);
		incompatible |= check_field(msg.fields[i], "ring", &ring_field);
		check_field(msg.fields[i], "intensity", &i_field);
	}

	if (incompatible || (!x_field || !y_field || !z_field || !ring_field))
		return false;

	// 1st: go through the scan and find ring count:
	uint16_t ring_min = 0, ring_max = 0;

	for (unsigned int row = 0; row < msg.height; ++row)
	{
		const unsigned char* row_data = &msg.data[row * msg.row_step];
		for (uint32_t col = 0; col < msg.width; ++col)
		{
			const unsigned char* msg_data = row_data + col * msg.point_step;
			uint16_t ring_id = 0;
			get_uint16_from_field(ring_field, msg_data, ring_id);

			mrpt::keep_min(ring_min, ring_id);
			mrpt::keep_max(ring_max, ring_id);
		}
	}
	ASSERT_NOT_EQUAL_(ring_min, ring_max);

	obj.rowCount = ring_max - ring_min + 1;
	obj.columnCount = num_azimuth_divisions;

	obj.rangeImage.resize(obj.rowCount, obj.columnCount);
	obj.rangeImage.fill(0);

	// Default unit: 1cm
	if (obj.rangeResolution == 0) obj.rangeResolution = 1e-2;

	if (i_field)
	{
		obj.intensityImage.resize(obj.rowCount, obj.columnCount);
		obj.intensityImage.fill(0);
	}
	else
		obj.intensityImage.resize(0, 0);

	// If not, memcpy each group of contiguous fields separately
	for (unsigned int row = 0; row < msg.height; ++row)
	{
		const unsigned char* row_data = &msg.data[row * msg.row_step];
		for (uint32_t col = 0; col < msg.width; ++col)
		{
			const unsigned char* msg_data = row_data + col * msg.point_step;

			float x, y, z;
			uint16_t ring_id = 0;
			get_float_from_field(x_field, msg_data, x);
			get_float_from_field(y_field, msg_data, y);
			get_float_from_field(z_field, msg_data, z);
			get_uint16_from_field(ring_field, msg_data, ring_id);

			const mrpt::math::TPoint3D localPt =
				sensorPoseOnRobot.inverseComposePoint(
					mrpt::math::TPoint3D(x, y, z));
			const double azimuth = std::atan2(localPt.y, localPt.x);

			const auto az_idx = lround(
				(num_azimuth_divisions - 1) * (azimuth + M_PI) / (2 * M_PI));
			ASSERT_GE_(az_idx, 0);
			ASSERT_LE_(az_idx, num_azimuth_divisions - 1);

			// Store in matrix form:
			obj.rangeImage(ring_id, az_idx) =
				lround(localPt.norm() / obj.rangeResolution);

			if (i_field)
			{
				float intensity;
				get_float_from_field(i_field, msg_data, intensity);
				ASSERT_LE_(intensity, 255.0f);
				obj.intensityImage(ring_id, az_idx) = lround(intensity);
			}
		}
	}
	return true;
}


text:
#ifndef _CInputMenu_
#define _CInputMenu_

#include "CTMenu.h"
/** @brief Menu that work with IP adress. Contains input field and two buttons.*/
class CInputIPMenu :public CTMenu{
public:
                            CInputIPMenu ( const int, const int, const string &);
    /** Returning IP adress which it gets from user. */
    string                  getInput ( void ) const {return m_IPadress;};
    bool                    changeTextLine(const int, const string &);

protected:
    string                  m_IPadress; /**< Correct Ip adress which user wrote.*/
    int                     m_ScanX; /**< X position where input field starts.*/
    int                     m_ScanY; /**< Y position where input field starts.*/
    TButton                 m_ButtonBack; /**< Back button. */
    bool                    m_ButtonBackA; /**< If button Back is selected. */

    void                    print   ( void );
    int                     control ( void );
    void                    printBorder( const int, const int);

};

#endif


text:
module Refinery
  module Images
    module Validators
      autoload :ImageSizeValidator, 'refinery/images/validators/image_size_validator'
      autoload :ImageUpdateValidator, 'refinery/images/validators/image_update_validator'
    end
  end
end


text:
package ch.heigvd.amt.amtproject.services.dao;

import ch.heigvd.amt.amtproject.entities.Application;
import ch.heigvd.amt.amtproject.entities.EndUser;
import java.util.List;
import javax.ejb.Local;

@Local
public interface EndUserDAOLocal extends IGenericDAO<EndUser, Long>{

    List<EndUser> getEndUserList(Application app);

    List<EndUser> findByAppAndPage(Application app, int pageize, int pageIndex);

    EndUser findByAppAndUserId(Application app, String userId);

}


text:
'use strict';

var should = require('should');
var players = require("../components/players");
var middleware = require('./middleware');

describe('The middleware module', function () {

	describe('When intercepting player unique identifier', function () {

		var identifier = 'anything';
		var world = 'catland';
		var mockPlayer = { name: 'Juan', email: 'juan@gmail.com' };
		var mockRequest = { params: { worldId: world } };
		var next = function () { };
		var mockError = { err: 'mock error' };
		var mockResponse = {
			statusCode: undefined,
			jsonObject: undefined,
			status: function (code) { this.statusCode = code; return this; },
			json: function (obj) { this.jsonObject = obj; return this; }
		};
		var originalFunction;

		beforeEach(function (done) {
			originalFunction = players.findByAnyUniqueIdentifier;
			done();
		});

		afterEach(function (done) {
			unmock();
			done();
		});

		it('it adds the results from the components/players module as a parameter', function (done) {
			mockPlayersWhenGivenToReturn(world, identifier, mockPlayer);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, function () {
				mockPlayer.should.be.equal(mockRequest.player);
				done();
			}, identifier);
		});

		it('if no player is found, sends status code 404', function (done) {
			mockPlayersWhenGivenToReturn(world, identifier, null);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, next, identifier);
			(404).should.be.equal(mockResponse.statusCode);
			done();
		});

		it('if no player is found, returns a json object with error message', function (done) {
			mockPlayersWhenGivenToReturn(world, identifier, null);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, next, identifier);
			should.exist(mockResponse.jsonObject);
			mockResponse.jsonObject.message.should.equal("PLAYER with identifier '" + identifier + "' does not exist.");
			done();
		});

		it('it does not call the next interceptor if no player is found', function (done) {
			mockPlayersWhenGivenToReturn(world, identifier, null);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, function () {
				should.fail();
			}, identifier);
			done();
		});

		it('if an error happens during the database call, sends status code 500', function (done) {
			mockPlayersToGiveError(world, identifier, mockError);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, next, identifier);
			(500).should.be.equal(mockResponse.statusCode);
			done();
		});

		it('if an error happens during the database call, returns a json object with the error message and the error object', function (done) {
			mockPlayersToGiveError(world, identifier, mockError);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, next, identifier);
			should.exist(mockResponse.jsonObject);
			mockResponse.jsonObject.message.should.equal('An unexpected application error has occured.');
			mockResponse.jsonObject.err.should.equal(mockError);
			done();
		});

		it('if an error happens during the database call, it does not call the next interceptor', function (done) {
			mockPlayersToGiveError(world, identifier, mockError);

			middleware.playerUniqueIdentifierInterceptor('player')(mockRequest, mockResponse, function () {
				should.fail();
			}, identifier);
			done();
		});

		var unmock = function () {
			players.findByAnyUniqueIdentifier = originalFunction;
		}

		var mockPlayersWhenGivenToReturn = function (expectedWorldId, expectedIdentifier, result) {
			players.findByAnyUniqueIdentifier = function (worldId, identifier, success, fail) {
				identifier.should.be.equal(expectedIdentifier);
				worldId.should.be.equal(expectedWorldId);
				success(result);
			};
		}

		var mockPlayersToGiveError = function (expectedWorldId, expectedIdentifier, error) {
			players.findByAnyUniqueIdentifier = function (worldId, identifier, success, fail) {
				identifier.should.be.equal(expectedIdentifier);
				worldId.should.be.equal(expectedWorldId);
				fail(error);
			};
		}
	});
});


text:
package controllers.api;

import java.util.Date;
import java.util.List;

import jobs.UpdateDocumentCommentCountJob;
import models.Category;
import models.Discussion;
import models.DiscussionDocument;
import models.Document;
import models.User;
import models.Vote;
import play.data.validation.Required;
import play.mvc.With;
import controllers.AppController;
import controllers.web.Auth;

@With(ApiController.class)
public class Discussions extends AppController {

    public static void create(@Required Discussion discussion, Document document) {
        if (!validation.hasErrors()) {
            User me = getMe();
            discussion.content = discussion.content.trim();
            discussion.user = me;
            if (discussion.validateAndSave()) {
                if (document.id != null) {
                    DiscussionDocument discussionDocument = new DiscussionDocument(discussion, document, me);
                    if (discussionDocument.validateAndSave()) {
                        discussion.updateDocumentCountAndSave(true);
                        document.updateDiscussionCountAndSave(true);
                    }
                }
                renderJSON(discussion);
            }
        }
    }

    public static void delete(long id) {
        checkAuthenticity();
        User me = Auth.getMe();
        Discussion discussion = Discussion.findById(id);
        notFoundIfNull(discussion);
        if (discussion.user.id == me.id) {
            Vote.deleteAllForDiscussion(discussion.id);
            discussion.delete();
            renderJSON(true);
        } else {
            unauthorized();
        }
    }

    public static void list(String keyword, long categoryId, String order, Integer page) {
        List<Document> documents = Document.search(keyword, categoryId, order, page);
        renderJSON(documents);
    }

    public static void markAsViewed(long id) {
        checkAuthenticity();
        Discussion discussion = Discussion.findById(id);
        if (discussion != null) {
            String sessionKey = String.format("lastDiscussionViewed", id);

            if (session.get(sessionKey) != null) {
                if (session.get(sessionKey) != discussion.id.toString()) {
                    discussion.increaseViewCountAndSave();
                    session.put(sessionKey, discussion.id);
                }
            } else {
                discussion.increaseViewCountAndSave();
                session.put(sessionKey, new Date().getTime());
            }
        } else {
            notFound();
        }
        ok();
    }

    public static void update(long id, @Required Discussion discussion) {
        checkAuthenticity();
        User me = Auth.getMe();
        Discussion check = Discussion.findById(id);
        notFoundIfNull(check);
        if (check.user.id == me.id) {
            if (!validation.hasErrors()) {
                check.title = discussion.title;
                check.category = discussion.category;
                check.content = discussion.content;
                check.tags = discussion.tags;
                check.user = me;
                discussion = check;
                if (discussion.validateAndSave()) {
                    renderJSON(discussion);
                }
            }
        } else {
            unauthorized();
        }
    }
}


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

namespace System.ServiceModel
{
    internal class InvocationOptions<TProxy> where TProxy : class
    {
        public Func<TProxy, Task<object>> AsynchronousInvocation { get; set; }
        public Func<TProxy, object> SynchronousInvocation { get; set; }
        public System.Threading.CancellationToken CancellationToken { get; set; }
    }
}


text:
package de.uniulm.omi.cloudiator.sword.service;

import de.uniulm.omi.cloudiator.sword.domain.Pricing;

public interface PricingService {
    /**
     * Retrieves an {@link Iterable} of the pricing that the cloud provider uses.
     *
     * @return the pricing offered.
     */
    Iterable<Pricing> listPricing();
}


text:
package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;
import java.util.List;

import static java.util.Arrays.asList;

public class P1_FunctionalInterfaces {
    /*
     see https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html

     => functional interfaces have one abstract method, default methods are not abstract

     example:
     */

    @FunctionalInterface//compile checks if requirement of one abstract method is met
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;
    }

    @FunctionalInterface
    public interface Whatever<V> {
        V aMethod();//one abstract method

        //impl method
        default List<V> anotherMethod() {
            return asList(aMethod(), aMethod());
        }
    }

    //two abstract methods
    public interface NotAFunctionalInterface<V> {
        V aMethod();
        List<V> anotherMethod();
    }

    /*
    Functional interfaces can be implemented and used the classic way:
     */
    class Md5HashFunction implements HashFunction {
        @Override
        public byte[] hash(final String input) throws Exception {
            return MessageDigest.getInstance("MD5").digest(input.getBytes());
        }
    }

    class ClassicMd5HashFunctionUser {
        void demo() throws Exception {
            final HashFunction hashFunction = new Md5HashFunction();
            final byte[] bytes = hashFunction.hash("hello");
        }
    }

    class AnonymousClassHashFunctionUser {
        void demo() throws Exception {
            final HashFunction hashFunction = new HashFunction() {
                @Override
                public byte[] hash(final String input) throws Exception {
                    return MessageDigest.getInstance("SHA1").digest(input.getBytes());
                }
            };
            final byte[] bytes = hashFunction.hash("hello");
        }
    }

    /** Java 8 enables to use lambda functions: */

    static class LambdaHashFunctionUser {
        void demo() throws Exception {
            final HashFunction hashFunction = (final String input) -> MessageDigest.getInstance("SHA1").digest(input.getBytes());
            final byte[] bytes = hashFunction.hash("hello");
        }
    }

    static class UseInferenceAndConvention {
        void demo() throws Exception {
            final HashFunction hashFunction = input -> MessageDigest.getInstance("SHA12").digest(input.getBytes());
            final byte[] bytes = hashFunction.hash("hello");
        }
    }

    static class Blocks {
        void demo() throws Exception {
            final HashFunction hashFunction = input -> {//parenthesis
                final MessageDigest sha12 = MessageDigest.getInstance("SHA12");
                return sha12.digest(input.getBytes());//return statement
            };
            final byte[] bytes = hashFunction.hash("hello");
        }
    }

    static class MultipleParameters {
        interface Op {
            long calculate(final long first, final long second);
        }

        void demo() throws Exception {
            final Op addition = (left, right) -> left + right;
        }
    }
}


text:
from subprocess import Popen,PIPE
import re
import time
import sqlite3

CONCURRENCY_ALLOWED = 30
OUTDATE_TIME = 86400

# initializing database
db = sqlite3.connect("/tmp/ddos.db3")
c = db.cursor()
#
try:
    c.execute("CREATE TABLE ddos (ip text unique,date integer);")
except:
    print "database exists"

# blocking ips has more than CONCURRENCY_ALLOWED connections
pipe = Popen("netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n > /tmp/ddos.txt", shell=True,bufsize=1024,stdout=PIPE).stdout
ddos = pipe.read()
ddos = open("/tmp/ddos.txt").read()
ct = re.compile(r"(\S+)\s+(\S+).*\n").findall(ddos)

for count,ip in ct:
    if int(count)>CONCURRENCY_ALLOWED and (ip != "127.0.0.1") and (not ip.startswith("192.168")):
        out = Popen("iptables -I INPUT -s %s -j DROP"%ip,shell=True,bufsize=1024,stdout=PIPE).stdout
        print "blocking %s for %s visits" % (ip,count)
        #c.execute('REPLACE INTO ddos VALUES (?,?)',(ip,int(time.time())))
        time.sleep(0.1)

db.commit()

# unblocking outdated blockings
c.execute("SELECT * FROM ddos")
ddos = c.fetchall()

for ip,date in ddos:
    if date + OUTDATE_TIME < time.time():
        c.execute("DELETE FROM ddos WHERE ip=?",(ip,))
        print "unblocking %s" % ip
        out = Popen("iptables -D INPUT -s %s -j DROP"%ip,shell=True,
                     bufsize=1024,stdout=PIPE).stdout
        time.sleep(0.1)

db.commit()


text:
package com.sap.dcode.usingmaf.ui.main;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.sap.dcode.usingmaf.services.AppSettings;
import com.sap.dcode.util.TraceLog;
import com.sap.maf.tools.logon.core.LogonCore;
import com.sap.maf.tools.logon.core.LogonCoreContext;
import com.sap.maf.tools.logon.core.LogonCoreException;
import com.sap.maf.tools.logon.logonui.api.LogonListener;
import com.sap.maf.tools.logon.logonui.api.LogonUIFacade;
import com.sap.maf.tools.logon.manager.LogonContext;
import com.sap.maf.tools.logon.manager.LogonManager.LogonManagerException;

public class MAFLogonActivity extends Activity implements LogonListener {
	private final String TAG = MAFLogonActivity.class.getSimpleName();
	private LogonUIFacade mLogonUIFacade;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//TODO 1-1 COMPLETE onCreate in MAFLogonActivity ***************************************************
	}

	@Override
	public void objectFromSecureStoreForKey() {

	}

	@Override
	public void onApplicationSettingsUpdated() {

	}

	@Override
	public void onBackendPasswordChanged(boolean arg0) {

	}

	@Override
	public void onLogonFinished(String message, boolean isSuccess,
			LogonContext lgContext) {
		//TODO 1-3 COMPLETE onLogonFinished in MAFLogonActivity ***************************************************

	}

	@Override
	public void onSecureStorePasswordChanged(boolean arg0, String arg1) {

	}

	@Override
	public void onUserDeleted() {

	}

	@Override
	public void registrationInfo() {

	}

	private void showLogonScreen() {
		//TODO 1-2 COMPLETE showLogonScreen in MAFLogonActivity ***************************************************
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.showLogonScreen();
	}

	@Override
	public void onRefreshCertificate(boolean arg0, String arg1) {
	}

}


text:
/*
 * Stack.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <boost/foreach.hpp>
#include "Stack.h"
#include "../Hypothesis.h"
#include "../Manager.h"
#include "../../Scores.h"
#include "../../HypothesisColl.h"

using namespace std;

namespace Moses2
{

namespace NSNormal
{

Stack::Stack(const Manager &mgr) :
  HypothesisColl(mgr)
{
  // TODO Auto-generated constructor stub

}

Stack::~Stack()
{
  // TODO Auto-generated destructor stub
}

}
}


text:
<?php
/*
|--------------------------------------------------------------------------
| Extension Bootstrap
|--------------------------------------------------------------------------
|
| To use extension, please register each class with their individual factories
| examples are show below:
|
| Override Built-in Platform
|
|
*/

use Faker\PlatformFactory;
use Faker\Components\Engine\Common\Formatter\FormatterFactory;
use Faker\Components\Engine\Common\TypeRepository;
use Faker\Locale\LocaleFactory;
use Doctrine\DBAL\Types\Type;

/*
|--------------------------------------------------------------------------
| Doctrine Platforms
|--------------------------------------------------------------------------
|
| To include new platforms must tell Faker\\PlatformFactory what the new or overriden
| extensions are.
|
|
| Override Built-in Platform (mysql):
|
|   PlatformFactory::registerExtension('mysql','Faker\\Components\\Extension\\Doctrine\\Platforms\\MySqlPlatform');
|
| Include New MyPlatform:
|
| PlatformFactory::registerExtension('myplatform','Faker\\Components\\Extension\\Doctrine\\Platforms\\MyPlatform');
|
*/

    PlatformFactory::registerExtension('mysql','Faker\\Extension\\Doctrine\\Platforms\\MySqlPlatform');

/*
|--------------------------------------------------------------------------
| Doctrine Column Types
|--------------------------------------------------------------------------
|
| To include new column types use the Doctine Type Static Factory
| You don't need to add these types to a platform, Faker pull them directly.
|
|  Add new Column types (mysql):
|
|  //Type::addType('point', 'Geo\Types\Point');
|
*/

   //Type::addType('point', 'Geo\Types\Point');

/*
|--------------------------------------------------------------------------
| Faker DataTypes
|--------------------------------------------------------------------------
|
| To Add a new datatype a it must be registered, and the object
| are extending from base Type.
|
| You may also override built in types using the same key.
|
| Example:
|
| TypeRepository::registerExtension('vector','Faker\\Extension\\Faker\\Type\\Vector');
*/

 //TypeRepository::registerExtension('vector','Faker\\Extension\\Faker\\Type\\Vector');
 TypeRepository::registerExtension('rental.return','Faker\\Extension\\Faker\\Type\\RentalReturn');
 TypeRepository::registerExtension('password','Faker\\Extension\\Faker\\Type\\Password');

/*
|--------------------------------------------------------------------------
| Faker Formatters
|--------------------------------------------------------------------------
|
| Register a new formatter, which control how data is written to the writter.
|
| FormatterFactory::registerExtension('mongo','Faker\\Components\\Extension\\Faker\\Formatter\\Mongo');
|
*/

  //FormatterFactory::registerExtension('mongo','Faker\\Components\\Extension\\Faker\\Formatter\\Mongo');

/*
|--------------------------------------------------------------------------
| Faker Locales
|--------------------------------------------------------------------------
|
| Register a new Locale, which provide locale specific text to the generators.
|
| LocaleFactory::registerExtension('french','Faker\\Components\\Extension\\Locale\\FrenchLocale');
|
*/

  //LocaleFactory::registerExtension('french','Faker\\Components\\Extension\\Locale\\FrenchLocale');

/* End of File */


text:
package com.streamsets.pipeline.stage.processor.listpivot;

import com.streamsets.pipeline.api.ConfigDef;
import com.streamsets.pipeline.api.ConfigGroups;
import com.streamsets.pipeline.api.FieldSelectorModel;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Processor;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.ValueChooserModel;
import com.streamsets.pipeline.config.OnStagePreConditionFailure;
import com.streamsets.pipeline.config.OnStagePreConditionFailureChooserValues;
import com.streamsets.pipeline.configurablestage.DProcessor;

@StageDef(
    version=1,
    label="List Pivoter",
    description = "Produce new records for each element of a list",
    icon="pivoter.png",
    upgrader = ListPivotProcessorUpgrader.class,
    onlineHelpRefUrl = "index.html#Processors/ListPivoter.html#task_dn1_k13_qw"
)
@ConfigGroups(Groups.class)
@GenerateResourceBundle
public class ListPivotDProcessor extends DProcessor {

  @ConfigDef(
      required = true,
      group = "PIVOT",
      type = ConfigDef.Type.MODEL,
      defaultValue = "",
      label = "List To Pivot",
      description = "Path to List-type field that will be exploded into multiple records.",
      displayPosition = 10
  )
  @FieldSelectorModel(singleValued = true)
  public String listPath;

  @ConfigDef(
      required = true,
      group = "PIVOT",
      type = ConfigDef.Type.BOOLEAN,
      defaultValue = "true",
      label = "Copy All Fields",
      description = "Copy all fields (including the original list) to each resulting record. " +
          "If this is not set, then the pivoted value is set as the root field of the record.",
      displayPosition = 20
  )
  public boolean copyFields;

  @ConfigDef(
      required = false,
      group = "PIVOT",
      type = ConfigDef.Type.STRING,
      defaultValue = "",
      dependsOn = "copyFields",
      triggeredByValue = "true",
      label = "Pivoted Items Path",
      description = "Path in the new record where the pivoted list items are written to. Each record will contain one" +
          "item from the original list at this path. If this is not specified, the path of the original list is used. " +
          "If there is data at this field path, it will be overwritten.",
      displayPosition = 30
  )
  public String newPath;

  @ConfigDef(
      required = true,
      type = ConfigDef.Type.MODEL,
      defaultValue = "TO_ERROR",
      label = "Field Does Not Exist",
      description="Action for data that does not contain the specified fields",
      displayPosition = 40,
      group = "PIVOT"
  )
  @ValueChooserModel(OnStagePreConditionFailureChooserValues.class)
  public OnStagePreConditionFailure onStagePreConditionFailure;

  @Override
  protected Processor createProcessor() {
    return new ListPivotProcessor(
        listPath,
        newPath,
        copyFields,
        onStagePreConditionFailure
    );
  }
}


text:
class IngramMicro::SalesOrderSubmission < IngramMicro::BaseElement
  DEFAULTS = {
    customer: nil,
    sales_order_shipment_information: nil,
    credit_card_information: nil,
    sales_order_header: nil,
    detail: nil,
    line_items: [],
    customer_id: nil,
    business_name: nil,
    carrier_name: nil,
    purchase_order_information: nil
  }.freeze

  def defaults
    DEFAULTS
  end

  def initialize(options={})
    super
    @element[:customer] ||= IngramMicro::Customer.new
    @element[:sales_order_shipment_information] ||= IngramMicro::SalesOrderShipmentInformation.new
    @element[:credit_card_information] ||= IngramMicro::CreditCardInformation.new
    @element[:sales_order_header] ||= IngramMicro::SalesOrderHeader.new
    @element[:detail] ||= IngramMicro::Detail.new({line_items: @element[:line_items]})
  end

  def build(builder)
    builder.send('header') do
      builder.send 'customer-id', @element[:customer_id]
      builder.send 'business-name', @element[:business_name]
      builder.send 'carrier-name', @element[:carrier_name]
      builder.send('customer-information') do
        @element[:customer].build(builder)
      end
      builder.send('shipment-information') do
        @element[:sales_order_shipment_information].build(builder)
      end
      if @element[:purchase_order_information]
        builder.send('purchase-order-information') do
          @element[:purchase_order_information].build(builder)
        end
      end
      builder.send('credit-card-information') do
        @element[:credit_card_information].build(builder)
      end
      builder.send('order-header') do
        @element[:sales_order_header].build(builder)
      end
    end
    builder.send('detail') do
      @element[:detail].build(builder)
    end
  end

  def valid?
    true
  end
end


text:
package com.example.refreashtabview.fragment;

import android.support.v4.app.Fragment;
import android.widget.AbsListView;

public abstract class ScrollTabHolderFragment extends Fragment implements ScrollTabHolder {

	private int fragmentId;

	protected ScrollTabHolder scrollTabHolder;

	public void setScrollTabHolder(ScrollTabHolder scrollTabHolder) {
		this.scrollTabHolder = scrollTabHolder;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount,
			int pagePosition) {
		// nothing
	}

	@Override
	public void onHeaderScroll(boolean isRefreashing, int value, int pagePosition) {

	}

	public int getFragmentId() {
		return fragmentId;
	}

	public void setFragmentId(int fragmentId) {
		this.fragmentId = fragmentId;
	}
}


text:
import {Component, OnInit} from '@angular/core';
import {RouterLink} from '@angular/router-deprecated';

import {BibleService} from './bible.service';
import {BookComponent} from './book.component';

@Component({
	templateUrl: 'bible.component.html',
    providers: [BibleService],
    directives: [BookComponent, RouterLink],
	styleUrls: [ 'bible.css' ],
	moduleId: 'app/bible/'
})
export class BibleComponent implements OnInit {
	books: any;
	groups: any[];

    constructor(private _service: BibleService) {
	}

	ngOnInit() {
		this.books = this._service.getBooks()
		this.groups = []
		var group
		for (var book of this.books.nt) {
			var fullGroupName = book.group + book.subGroup
			if (!group || group.fullName != fullGroupName) {
				group = { name: book.group, fullName: fullGroupName, books: [] }
				this.groups.push(group)
			}
			group.books.push(book)
		}

		//this._service.getBooks()
		//	.subscribe(books => this.books = books);
	}
}


text:
import { assert } from "chai";

import { Options, run, Status } from "../../src/runner";

const customRulesOptions: Options = {
    config: "./test/config/tslint-custom-rules.json",
    exclude: [],
    files: ["src/test.ts"],
    format: "prose",
    rulesDirectory: "./test/files/custom-rules",
};

describe("Runner Tests", () => {
    it("outputs absolute path with --outputAbsolutePaths", async () => {
        const { status, stdout, stderr } = await runLint({
            ...customRulesOptions,
            outputAbsolutePaths: true,
        });
        assert.equal(status, 2);
        // match either a path starting with `/` or something like `C:`
        assert.isTrue(/ERROR: (\/|\w:)/.test(stdout));
        assert.equal(stderr, "");
    });

    it("outputs relative path without --outputAbsolutePaths", async () => {
        const { status, stdout, stderr } = await runLint(customRulesOptions);
        assert.equal(status, 2);
        assert.include(stdout, "ERROR: src/");
        assert.equal(stderr, "");
    });
});

async function runLint(
    options: Options,
): Promise<{ status: Status; stdout: string; stderr: string }> {
    let stdout = "";
    let stderr = "";
    const status = await run(options, {
        log(m) {
            stdout += m;
        },
        error(m) {
            stderr += m;
        },
    });
    return { status, stdout, stderr };
}


text:
static void check() {
  // In 1.34, there's no parameterless constructor; in 1.36, there's
  // only a parameterless constructor
  auto options =
      std::make_shared<grpc::experimental::TlsChannelCredentialsOptions>(nullptr);
  options->set_server_verification_option(
      grpc_tls_server_verification_option::GRPC_TLS_SERVER_VERIFICATION);
}

int main(int argc, const char** argv) {
  check();
  return 0;
}


text:
#ifndef SEAFILE_CLIENT_OPEN_LOCAL_FILE_HELPER_H
#define SEAFILE_CLIENT_OPEN_LOCAL_FILE_HELPER_H

extern "C" {

struct _CcnetClient;

}

/**
 * Helper class to handle open local file request
 */
class OpenLocalHelper
{
public:
    static OpenLocalHelper* instance();

    void openLocalFile(const char* url);

    void handleOpenLocalFromCommandLine(const char *url);

    void checkPendingOpenLocalRequest();

private:
    static OpenLocalHelper* singleton_;

    OpenLocalHelper();

    void messageBox(const QString& msg);

    bool connectToCcnetDaemon();

    void sendOpenLocalFileMessage(const char *url);

    _CcnetClient *sync_client_;

    char *url_;
};

#endif // SEAFILE_CLIENT_OPEN_LOCAL_FILE_HELPER_H


text:
from test import test_support
import types
import unittest

class FuncAttrsTest(unittest.TestCase):
    def setUp(self):
        class F:
            def a(self):
                pass
        def b():
            return 3
        self.f = F
        self.fi = F()
        self.b = b

    def cannot_set_attr(self, obj, name, value, exceptions):
        if not test_support.check_impl_detail():
            exceptions = (TypeError, AttributeError)
        # Helper method for other tests.
        try:
            setattr(obj, name, value)
        except exceptions:
            pass
        else:
            self.fail("shouldn't be able to set %s to %r" % (name, value))
        try:
            delattr(obj, name)
        except exceptions:
            pass
        else:
            self.fail("shouldn't be able to del %s" % name)

class FunctionPropertiesTest(FuncAttrsTest):
    # Include the external setUp method that is common to all tests
    def test_module(self):
        self.assertEqual(self.b.__module__, __name__)

    def test_dir_includes_correct_attrs(self):
        self.b.known_attr = 7
        self.assertIn('known_attr', dir(self.b),
                        "set attributes not in dir listing of method")
        # Test on underlying function object of method
        self.f.a.im_func.known_attr = 7
        self.assertIn('known_attr', dir(self.f.a),
                        "set attribute on unbound method implementation in "
                        "class not in dir")
        self.assertIn('known_attr', dir(self.fi.a),
                        "set attribute on unbound method implementations, "
                        "should show up in next dir")

    def test_duplicate_function_equality(self):
        # Body of `duplicate' is the exact same as self.b
        def duplicate():
            'my docstring'
            return 3
        self.assertNotEqual(self.b, duplicate)

    def test_copying_func_code(self):
        def test(): pass
        self.assertEqual(test(), None)
        test.func_code = self.b.func_code
        self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily

    def test_func_globals(self):
        self.assertIs(self.b.func_globals, globals())
        self.cannot_set_attr(self.b, 'func_globals', 2, TypeError)

    def test_func_closure(self):
        a = 12
        def f(): print a
        c = f.func_closure
        self.assertIsInstance(c, tuple)
        self.assertEqual(len(c), 1)
        # don't have a type object handy
        self.assertEqual(c[0].__class__.__name__, "cell")
        self.cannot_set_attr(f, "func_closure", c, TypeError)

    def test_empty_cell(self):
        def f(): print a
        try:
            f.func_closure[0].cell_contents
        except ValueError:
            pass
        else:
            self.fail("shouldn't be able to read an empty cell")
        a = 12

    def test_func_name(self):
        self.assertEqual(self.b.__name__, 'b')
        self.assertEqual(self.b.func_name, 'b')
        self.b.__name__ = 'c'
        self.assertEqual(self.b.__name__, 'c')
        self.assertEqual(self.b.func_name, 'c')
        self.b.func_name = 'd'
        self.assertEqual(self.b.__name__, 'd')
        self.assertEqual(self.b.func_name, 'd')
        # __name__ and func_name must be a string
        self.cannot_set_attr(self.b, '__name__', 7, TypeError)
        self.cannot_set_attr(self.b, 'func_name', 7, TypeError)
        # __name__ must be available when in restricted mode. Exec will raise
        # AttributeError if __name__ is not available on f.
        s = """def f(): pass\nf.__name__"""
        exec s in {'__builtins__': {}}
        # Test on methods, too
        self.assertEqual(self.f.a.__name__, 'a')
        self.assertEqual(self.fi.a.__name__, 'a')
        self.cannot_set_attr(self.f.a, "__name__", 'a', AttributeError)
        self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)

    def test_func_code(self):
        num_one, num_two = 7, 8
        def a(): pass
        def b(): return 12
        def c(): return num_one
        def d(): return num_two
        def e(): return num_one, num_two
        for func in [a, b, c, d, e]:
            self.assertEqual(type(func.func_code), types.CodeType)
        self.assertEqual(c(), 7)
        self.assertEqual(d(), 8)
        d.func_code = c.func_code
        self.assertEqual(c.func_code, d.func_code)
        self.assertEqual(c(), 7)
        # self.assertEqual(d(), 7)
        try:
            b.func_code = c.func_code
        except ValueError:
            pass
        else:
            self.fail("func_code with different numbers of free vars should "
                      "not be possible")
        try:
            e.func_code = d.func_code
        except ValueError:
            pass
        else:
            self.fail("func_code with different numbers of free vars should "
                      "not be possible")

    def test_blank_func_defaults(self):
        self.assertEqual(self.b.func_defaults, None)
        del self.b.func_defaults
        self.assertEqual(self.b.func_defaults, None)

    def test_func_default_args(self):
        def first_func(a, b):
            return a+b
        def second_func(a=1, b=2):
            return a+b
        self.assertEqual(first_func.func_defaults, None)
        self.assertEqual(second_func.func_defaults, (1, 2))
        first_func.func_defaults = (1, 2)
        self.assertEqual(first_func.func_defaults, (1, 2))
        self.assertEqual(first_func(), 3)
        self.assertEqual(first_func(3), 5)
        self.assertEqual(first_func(3, 5), 8)
        del second_func.func_defaults
        self.assertEqual(second_func.func_defaults, None)
        try:
            second_func()
        except TypeError:
            pass
        else:
            self.fail("func_defaults does not update; deleting it does not "
                      "remove requirement")

class InstancemethodAttrTest(FuncAttrsTest):
    def test_im_class(self):
        self.assertEqual(self.f.a.im_class, self.f)
        self.assertEqual(self.fi.a.im_class, self.f)
        self.cannot_set_attr(self.f.a, "im_class", self.f, TypeError)
        self.cannot_set_attr(self.fi.a, "im_class", self.f, TypeError)

    def test_im_func(self):
        self.f.b = self.b
        self.assertEqual(self.f.b.im_func, self.b)
        self.assertEqual(self.fi.b.im_func, self.b)
        self.cannot_set_attr(self.f.b, "im_func", self.b, TypeError)
        self.cannot_set_attr(self.fi.b, "im_func", self.b, TypeError)

    def test_im_self(self):
        self.assertEqual(self.f.a.im_self, None)
        self.assertEqual(self.fi.a.im_self, self.fi)
        self.cannot_set_attr(self.f.a, "im_self", None, TypeError)
        self.cannot_set_attr(self.fi.a, "im_self", self.fi, TypeError)

    def test_im_func_non_method(self):
        # Behavior should be the same when a method is added via an attr
        # assignment
        self.f.id = types.MethodType(id, None, self.f)
        self.assertEqual(self.fi.id(), id(self.fi))
        self.assertNotEqual(self.fi.id(), id(self.f))
        # Test usage
        try:
            self.f.id.unknown_attr
        except AttributeError:
            pass
        else:
            self.fail("using unknown attributes should raise AttributeError")
        # Test assignment and deletion
        self.cannot_set_attr(self.f.id, 'unknown_attr', 2, AttributeError)
        self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)

    def test_implicit_method_properties(self):
        self.f.a.im_func.known_attr = 7
        self.assertEqual(self.f.a.known_attr, 7)
        self.assertEqual(self.fi.a.known_attr, 7)

class ArbitraryFunctionAttrTest(FuncAttrsTest):
    def test_set_attr(self):
        # setting attributes only works on function objects
        self.b.known_attr = 7
        self.assertEqual(self.b.known_attr, 7)
        for func in [self.f.a, self.fi.a]:
            try:
                func.known_attr = 7
            except AttributeError:
                pass
            else:
                self.fail("setting attributes on methods should raise error")

    def test_delete_unknown_attr(self):
        try:
            del self.b.unknown_attr
        except AttributeError:
            pass
        else:
            self.fail("deleting unknown attribute should raise TypeError")

    def test_setting_attrs_duplicates(self):
        try:
            self.f.a.klass = self.f
        except AttributeError:
            pass
        else:
            self.fail("setting arbitrary attribute in unbound function "
                      " should raise AttributeError")
        self.f.a.im_func.klass = self.f
        for method in [self.f.a, self.fi.a, self.fi.a.im_func]:
            self.assertEqual(method.klass, self.f)

    def test_unset_attr(self):
        for func in [self.b, self.f.a, self.fi.a]:
            try:
                func.non_existent_attr
            except AttributeError:
                pass
            else:
                self.fail("using unknown attributes should raise "
                          "AttributeError")

class FunctionDictsTest(FuncAttrsTest):
    def test_setting_dict_to_invalid(self):
        self.cannot_set_attr(self.b, '__dict__', None, TypeError)
        self.cannot_set_attr(self.b, 'func_dict', None, TypeError)
        from UserDict import UserDict
        d = UserDict({'known_attr': 7})
        self.cannot_set_attr(self.f.a.im_func, '__dict__', d, TypeError)
        self.cannot_set_attr(self.fi.a.im_func, '__dict__', d, TypeError)

    def test_setting_dict_to_valid(self):
        d = {'known_attr': 7}
        self.b.__dict__ = d
        # Setting dict is only possible on the underlying function objects
        self.f.a.im_func.__dict__ = d
        # Test assignment
        self.assertIs(d, self.b.__dict__)
        self.assertIs(d, self.b.func_dict)
        # ... and on all the different ways of referencing the method's func
        self.assertIs(d, self.f.a.im_func.__dict__)
        self.assertIs(d, self.f.a.__dict__)
        self.assertIs(d, self.fi.a.im_func.__dict__)
        self.assertIs(d, self.fi.a.__dict__)
        # Test value
        self.assertEqual(self.b.known_attr, 7)
        self.assertEqual(self.b.__dict__['known_attr'], 7)
        self.assertEqual(self.b.func_dict['known_attr'], 7)
        # ... and again, on all the different method's names
        self.assertEqual(self.f.a.im_func.known_attr, 7)
        self.assertEqual(self.f.a.known_attr, 7)
        self.assertEqual(self.fi.a.im_func.known_attr, 7)
        self.assertEqual(self.fi.a.known_attr, 7)

    def test_delete_func_dict(self):
        try:
            del self.b.__dict__
        except (AttributeError, TypeError):
            pass
        else:
            self.fail("deleting function dictionary should raise TypeError")
        try:
            del self.b.func_dict
        except (AttributeError, TypeError):
            pass
        else:
            self.fail("deleting function dictionary should raise TypeError")

    def test_unassigned_dict(self):
        self.assertEqual(self.b.__dict__, {})

    def test_func_as_dict_key(self):
        value = "Some string"
        d = {}
        d[self.b] = value
        self.assertEqual(d[self.b], value)

class FunctionDocstringTest(FuncAttrsTest):
    def test_set_docstring_attr(self):
        self.assertEqual(self.b.__doc__, None)
        self.assertEqual(self.b.func_doc, None)
        docstr = "A test method that does nothing"
        self.b.__doc__ = self.f.a.im_func.__doc__ = docstr
        self.assertEqual(self.b.__doc__, docstr)
        self.assertEqual(self.b.func_doc, docstr)
        self.assertEqual(self.f.a.__doc__, docstr)
        self.assertEqual(self.fi.a.__doc__, docstr)
        self.cannot_set_attr(self.f.a, "__doc__", docstr, AttributeError)
        self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)

    def test_delete_docstring(self):
        self.b.__doc__ = "The docstring"
        del self.b.__doc__
        self.assertEqual(self.b.__doc__, None)
        self.assertEqual(self.b.func_doc, None)
        self.b.func_doc = "The docstring"
        del self.b.func_doc
        self.assertEqual(self.b.__doc__, None)
        self.assertEqual(self.b.func_doc, None)

class StaticMethodAttrsTest(unittest.TestCase):
    def test_func_attribute(self):
        def f():
            pass

        c = classmethod(f)
        self.assertTrue(c.__func__ is f)

        s = staticmethod(f)
        self.assertTrue(s.__func__ is f)

def test_main():
    test_support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest,
                              ArbitraryFunctionAttrTest, FunctionDictsTest,
                              FunctionDocstringTest,
                              StaticMethodAttrsTest)

if __name__ == "__main__":
    test_main()


text:
package org.elasticsearch.test.integration.versioning;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.integration.AbstractNodesTests;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.nullValue;

/**
 *
 */
@Test
public class ConcurrentDocumentOperationTests extends AbstractNodesTests {

    @AfterMethod
    public void closeNodes() {
        closeAllNodes();
    }

    @Test
    public void concurrentOperationOnSameDocTest() throws Exception {
        // start 5 nodes
        Node[] nodes = new Node[5];
        for (int i = 0; i < nodes.length; i++) {
            nodes[i] = startNode(Integer.toString(i));
        }

        logger.info("--> create an index with 1 shard and max replicas based on nodes");
        nodes[0].client().admin().indices().prepareCreate("test")
                .setSettings(settingsBuilder().put("number_of_shards", 1).put("number_of_replicas", nodes.length - 1))
                .execute().actionGet();

        logger.info("execute concurrent updates on the same doc");
        int numberOfUpdates = 100;
        final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
        final CountDownLatch latch = new CountDownLatch(numberOfUpdates);
        for (int i = 0; i < numberOfUpdates; i++) {
            nodes[0].client().prepareIndex("test", "type1", "1").setSource("field1", i).execute(new ActionListener<IndexResponse>() {
                @Override
                public void onResponse(IndexResponse response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Throwable e) {
                    e.printStackTrace();
                    failure.set(e);
                    latch.countDown();
                }
            });
        }

        latch.await();

        assertThat(failure.get(), nullValue());

        nodes[0].client().admin().indices().prepareRefresh().execute().actionGet();

        logger.info("done indexing, check all have the same field value");
        Map masterSource = nodes[0].client().prepareGet("test", "type1", "1").execute().actionGet().sourceAsMap();
        for (int i = 0; i < (nodes.length * 5); i++) {
            assertThat(nodes[0].client().prepareGet("test", "type1", "1").execute().actionGet().sourceAsMap(), equalTo(masterSource));
        }
    }
}


text:
@interface FlickrResponseData : NSObject

@property (nonatomic, readonly) NSInteger page;
@property (nonatomic, readonly) NSInteger totalPages;
@property (nonatomic, readonly) NSInteger pageSize;
@property (nonatomic, readonly) NSArray* photos;

+(instancetype) responseDataFromDictionary:(NSDictionary*) flickrResponse;

@end


text:
myAppModule.factory('userSession', ['$http', function($http) {
  var factory = {}

  factory.user = null;

  factory.checkSession = function() {
    if (factory.user == null) {
      return $http.get('/sessions/fetch');
    } else {
      return factory.user;
    }
  }

  return factory;
}]);


text:
package mta.catsfeeder.persistence;

import mta.catsfeeder.model.User;

/**
 * Created by Aleosha on 14/02/2015.
 */
public interface IUserDao extends IAbstractDao<User>{
    User getUser(String username, String password);

    User createUser(String username, String password, String email);

    User getByEmail(String email);

    User getByUsername(String recipient);
}


text:
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var dssumpw = require( './dssumpw.native.js' );
var ndarray = require( './ndarray.native.js' );

// MAIN //

setReadOnly( dssumpw, 'ndarray', ndarray );

// EXPORTS //

module.exports = dssumpw;


text:
/*
 * Copyright (c) 2002-2015, the original author or authors.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *
 * http://www.opensource.org/licenses/bsd-license.php
 */
package jline;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import jline.internal.TerminalLineSettings;

/**
 * Representation of the input terminal for a platform.
 *
 * @author Marc Prud'hommeaux
 * @author Jason Dillon
 * @since 2.0
 */
public interface Terminal
{
    void init() throws Exception;

    void restore() throws Exception;

    void reset() throws Exception;

    boolean isSupported();

    int getWidth();

    int getHeight();

    boolean isAnsiSupported();

    TerminalLineSettings getSettings();

    /**
     * When ANSI is not natively handled, the output will have to be wrapped.
     */
    OutputStream wrapOutIfNeeded(OutputStream out);

    /**
     * When using native support, return the InputStream to use for reading characters
     * else return the input stream passed as a parameter.
     *
     * @since 2.6
     */
    InputStream wrapInIfNeeded(InputStream in) throws IOException;

    /**
     * For terminals that don't wrap when character is written in last column,
     * only when the next character is written.
     * These are the ones that have 'am' and 'xn' termcap attributes (xterm and
     * rxvt flavors falls under that category)
     */
    boolean hasWeirdWrap();

    boolean isEchoEnabled();

    void setEchoEnabled(boolean enabled);

    String getOutputEncoding();

}


text:
'use strict';

/**
 * Module dependencies
 */
var specsPolicy = require('../policies/specs.server.policy'),
  specs = require('../controllers/specs.server.controller');

module.exports = function (app) {
  // Specs Routes
  app.route('/api/specs').all(specsPolicy.isAllowed)
    .get(specs.list)
    .post(specs.create);

  app.route('/api/specs/:specId').all(specsPolicy.isAllowed)
    .get(specs.read)
    .put(specs.update)
    .delete(specs.delete);

  app.route('/api/specs/:specId/swagger').get(specs.readSwagger);

  app.route('/api/specs/:specId/dredd').post(specs.testSwagger);

  // Finish by binding the Spec middleware
  app.param('specId', specs.specByID);
};


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="FullscreenTheme" parent="android:Theme.NoTitleBar">
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">@style/ButtonBar</item>
        <item name="metaButtonBarButtonStyle">@style/ButtonBarButton</item>
    </style>

    <style name="ButtonBar">
        <item name="android:paddingLeft">2dp</item>
        <item name="android:paddingTop">5dp</item>
        <item name="android:paddingRight">2dp</item>
        <item name="android:paddingBottom">0dp</item>
        <item name="android:background">@android:drawable/bottom_bar</item>
    </style>

    <style name="ButtonBarButton" />

    <style name="textLCARS_large" parent="android:TextAppearance.Large">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">@color/lcars_orange</item>
        <item name="android:textAlignment">gravity</item>
        <item name="android:fontFamily">fonts/lcarsgtj3.ttf</item>
    </style>

</resources>


text:
from netforce.model import Model, fields, get_model

class BarcodeReturnRM(Model):
    _name = "barcode.return.rm"
    _transient = True
    _fields = {
        "location_to_id": fields.Many2One("stock.location", "To Location", condition=[["type", "=", "internal"]]),
        "production_id": fields.Many2One("production.order", "Production Order", condition=[["state", "=", "in_progress"]]),
        "location_from_id": fields.Many2One("stock.location", "From Location"),
        "journal_id": fields.Many2One("stock.journal", "Stock Journal"),
        "lines": fields.One2Many("barcode.return.rm.line", "wizard_id", "Lines"),
        "state": fields.Selection([["pending", "Pending"], ["done", "Completed"]], "Status", required=True),
    }

    _defaults = {
        "state": "done",
    }

    def onchange_production(self, context={}):
        data = context["data"]
        order_id = data["production_id"]
        order = get_model("production.order").browse(order_id)
        data["location_from_id"] = order.production_location_id.id
        return data

    def fill_products(self, ids, context={}):
        obj = self.browse(ids)[0]
        order = obj.production_id
        found = False
        for comp in order.components:
            if comp.qty_issued <= 0.01:
                continue
            vals = {
                "wizard_id": obj.id,
                "product_id": comp.product_id.id,
                "lot_id": comp.lot_id.id,
                "qty": comp.qty_issued,
                "uom_id": comp.uom_id.id,
            }
            get_model("barcode.return.rm.line").create(vals)
            found = True
        if not found:
            raise Exception("No products to return")

    def clear(self, ids, context={}):
        obj = self.browse(ids)[0]
        vals = {
            "production_id": None,
            "location_from_id": None,
            "lines": [("delete_all",)],
        }
        obj.write(vals)

    def validate(self, ids, context={}):
        obj = self.browse(ids)[0]
        if not obj.lines:
            raise Exception("Product list is empty")
        pick_vals = {
            "type": "in",
            "related_id": "production.order,%d" % obj.production_id.id,
            "journal_id": obj.journal_id.id,
            "lines": [],
        }
        for line in obj.lines:
            line_vals = {
                "product_id": line.product_id.id,
                "qty": line.qty,
                "uom_id": line.uom_id.id,
                "lot_id": line.lot_id.id,
                "location_from_id": obj.location_from_id.id,
                "location_to_id": obj.location_to_id.id,
            }
            pick_vals["lines"].append(("create", line_vals))
        pick_id = get_model("stock.picking").create(pick_vals, context={"pick_type": "in"})
        if obj.state == "done":
            get_model("stock.picking").set_done([pick_id])
        elif obj.state == "pending":
            get_model("stock.picking").pending([pick_id])
        pick = get_model("stock.picking").browse(pick_id)
        obj.clear()
        return {
            "flash": "Goods receipt %s created successfully" % pick.number,
            "focus_field": "production_id",
        }

BarcodeReturnRM.register()


text:
/**
 * "First, solve the problem. Then, write the code. -John Johnson"
 * "Or use Vangav M"
 * www.vangav.com
 * */

/**
 * MIT License
 *
 * Copyright (c) 2016 Vangav
 *
 * 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.
 * */

/**
 * Community
 * Facebook Group: Vangav Open Source - Backend
 *   fb.com/groups/575834775932682/
 * Facebook Page: Vangav
 *   fb.com/vangav.f
 *
 * Third party communities for Vangav Backend
 *   - play framework
 *   - cassandra
 *   - datastax
 *
 * Tag your question online (e.g.: stack overflow, etc ...) with
 *   #vangav_backend
 *   to easier find questions/answers online
 * */

package com.vangav.backend.security.authentication.facebook;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.vangav.backend.networks.rest_client.RestResponseJson;

/**
 * @author mustapha
 * fb.com/mustapha.abdallah
 */
/**
 * ResponseFacebookAuth: JSON class representing Facebook's authentication
 *                         response
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseFacebookAuth extends RestResponseJson {

  @Override
  @JsonIgnore
  protected String getName () throws Exception {

    return "FacebookAuth";
  }

  @Override
  @JsonIgnore
  protected ResponseFacebookAuth getThis () throws Exception {

    return this;
  }

  /**
   * id: the Facebook app's ID (i.e.: your app's Facebook ID, provided by
   *       Facebook for each registered app; mobile app, web app, etc ...)
   */
  @JsonProperty
  public String id;
}