text:
<!DOCTYPE html>

        <title>Frontend - Visualizing Progression Tree to Root Out Cancer</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link href="css/bootstrap.min.css" rel="stylesheet">
        <link href="css/ripples.min.css" rel="stylesheet">
        <link href="css/material-wfont.min.css" rel="stylesheet">

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

QCRI - Visualizing Progression Tree to Root out Cancer

                            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

                            </button>
                            Home

About Project

Backend

Frontend

Frontend Documentation

Dataview Script

Data visualization box script

Graph Script

Script that deals with graphs

Node-link script

Graph node-linking script

Data Reduction script

Reduce the data to view it

Scatter-Plot script

Representing and dealing with scatter plots

Dataview script

							There was a typo, 'centroids' was mistakenly typed 'centeroid' at some parts, and correcting it might not be a safe option

For the documentation of the function 'each' refer to

								Visual Controls Options

                    			      Contains the values of the options that are used to control the visual behaviors of the node-link diagram

                    			       Defined clusters, nodes, links, and grah

                    			       Are meant to be just a sample of how to use and initialize the graph properly (refer to them to see how they are related to each other)

                    			Reduced Elements

                    			      Contains the information that will be used to represent each of the reduced node-link diagrams after the dimenionality reduction of the original one

                    			      It is nessacry to have a copy for each one even if they share the same attributes, because of the changes that happen to them in the visualization stage (such as branch selection, dragging,...etc)

                    			Reduction Functions

                    			      Are just functions that take care of calling the reduction functions with their proper settings. To reduce the call and avoid mistakes and inconsistency, it is better to keep them this way so that changes the settings occurs only at one place

								get_centroids() Function

                    			      A function that gets the data (centers and average grade values) from the HTML file and creates the original non-reduced clusters and graph structure

								jsonStr() Function

                    			      Not nesscary but added in cases of arrays just in case a browser fails to convert an array into a JSON object directly

								init_reduce() Function

                    			      Handles the dimensionality reduction of the original graph structure and creates a new graph for each reduction type

                    				For the details of how to properly initialize the graph to work with the node-link diagram refer to the example in the top of the script file.

								reconstruct() Function

                            			      Parameters:

                            			       centroids: An array of the centroids to which the graph will be drawn based on

										       links: An array of links that links the centroids

										       clusters: An array of the cluster set, is not used in the functionality of the function but is needed for the creation of the node-link diagram

										       graph: A reference to the graph that is to be reconstructed. Must be an existing graph

										       SVG ID: For the nodelink() function to be given to the created SVG

											Given the above parameters the function resets and recalculates the nodes and the links of edges of the graph, then creates a new node-link diagram with the specified ID.

								changeDR() Function

                            			      Parameters:

                            			       algorithm: The name of the algorithm to which the view should be switched to

										       reconstruct: A boolean variable that determines whether the graph should be reconstructed due to changes in the parameters or not

											Given the above parameters the function hides every SVG element in the view, the based on the specified algorithm it will show the SVG element that is associated with it. If the value of reconstruct was true, the function will call reconstruct() with the corresponding arguments.

								Normalized Array

                    			      Shows how to properly set the array that can be passed to a scatter plot

                    			      Also two examples on how to initialize a scatter plot are given but commented

                    			window.resize() Event Handler

                    			      Currently does not function, is meant to handle the changes in the sizes of the node-link diagram and scatter plots

                    			Features Array

                    			      Hold the data of the features that will be read from the HTML

                    			Selected Features

                    			      Hold the names of the selected features, both indicator and grade

                    				The rest of the AUTOCOMPLETE section is just some precedure to handle the autocomplete and selection prodecures

Coloring Section

                    					Custom Colors Object

                    					An object that has the attributes named after the corresponding color scaling types. Each attribute is an array of palletes, where each pallete is an array of colors.

Format { 'scale type 1' : [ ['color 1', 'color 2', ..], [..], .., [..] ], 'scale type 2' : [....] }

colorscale() Constructor

										Parameters:

                            			       domain: The minimum and the maximum values that will be scaled to match a color set

										       color set: An array of colors that will be used as the range of the scale

										Functions:

										       maps(): Maps a value that lies within the domain to and index to a color in the specified color set

										       clrScale variable: variable that will server as the global color scale

										       init_colorScales(): Creates HTML elements (divs, radio buttons, and SVG) that will represent the color scales and pallets. It also creates the events of the radio buttons and handles hiding all the scaling types except for the first one (in that case it is the sequential scaling)

Events Section

								kmeansUpdate.submit() Event Handler

								       init_colorScales(): Sends an AJAX request to the server to recalculate the K-means algorithm with a new number of clusters. Upon success, the it changes the attributes in the HTML element that holds the data of the graph, calls get_centroids() -documented previously- and init_reduce() -documented previously- to recalculate the whole thing

								       switch_opts_algos(), switch_opts_red(), switch_clr_scales() Functions: Are used to show and hide certain elements based on their specified targets (called through the proper event handlers in the HTML file)

								       window.load() Event Handler: Handles the opertains that should be executed once the page has been loaded

								       btn_plot.click()  Event Handler: Sends a request to the server to calculate a projection of data onto a branch. Upon success, the data will be displayed on a scatter plot based on the selected scatter plot

								        Parameters:

								         params: refer to the scatter script documentation

								         axis data: refer to the example of how to intialize a scatter plot to know the format of the axis data

									Note: changing the ID's of the divs in the HTML will require changing them accordingly in this function

								       visual-params-lable.click()  Event Handler: Only handles showing and hiding the Visual Parameters div

Bugs and Errors

									here is a bug in the server, it can only project the data for 'dataInit01' and 'dataInit02' indicator features, but not with the others

Graph Script

									To make it easier for the maintainer to debug any bug that happens with selecting a branch later on, the console.log() calls were not removed

									Vector3 and Vector2

									      Plain vector definitions, nothing fancy in them

									Cluster

Represents a cluster sent from the server

The data is a reference to the array of the points which the cluster contains</il>

The centroid is the value of the center of the cluster, should be an array of any length (N-dimensions)

The grade values is an object representing the grade values of this cluster for each grade feature

									Node

									      Refers to a cluster, but is the one used in the graph structure

									Weighted Edge

Represents an edge between two nodes (or clusters)

Is directed in structure (with respect to the naming of source and target), but the connection can be reversed anytime</il>

Has the weight, and holds the distance between the two nodes in their original n-dimensional space

Graph Structure

								Nodes and Edges

                    			      Array of nodes and edges for the graph (refer to their documentation for more information)

                    			Selection

                    			      An array of the indices of the selected nodes in the graph, represent a selected branch

                    			Threshold

                    			      The value that will be used to filter out some edges; if their weight is less than the threshold they will not be considered edges

								N-L Map

                    			      The node-link map, used as a lookup table for the connected edges

Is some sort of a hashmap to make retrieving data faster

JavaScript does not have an implementation of a hashmap, but its objects can serve as hashmaps due to their structure and the way they operate

Is formatted as follows { node key : [ [ [the index of a child, the weight of the edge], ... ], [ [the index of a parent, the weight of the edge], ... ] ], node key : ... }

                    			addNode() Function

                    			      Given a node, the function assigns a new index to it which is its index in the nodes array. Then it creates a new key in the nlMap which is going to be the index of that node

								findChildren() Function

                    			      Gets the list of children of a certain node from nlMap  given its index. Then the children are filtered after the weights of their edges are tested against the threshold, leaving only the ones that are greater than or equal to the threshold value

								findParents() Function

                    			      The same as findChildren() but works in the other direction

                    			findEdge() Function

                    			      Loops through the array of edges to find an edge between that node having the index of _source_index and the one having the index of _target_index. The indices are interchangable, it does not matter in which order they are passed. Should use nlMap instead of edges array

								Visited

                    			      An array of the previously visited nodes. It was made to avoid infinite loops that happen because of revisiting the same nodes multiple times

									The visited array must be reset after each call for any of the branch functions, but not inside the functions. Finding branchs is recursive, it can be defined and reset inside the functions but that will require some changes to them, having the list outside the function and reseting it independently is more convenient and safer

All Branch Functions (differences explained below)

									Parameters:

                            		       source index: The index of the node from which the function should start searching

                            		       target index: The index of the node which the function should stop when reached

                            			Given the source and the target, the function tries to find a set of nodes that link those two nodex. The functions use breadth-first search to find the nodes that make the branch. The functions were implemented first as depth-first but then BFS was found to be more approperiate, therefore, the implementation is not a good BFS but rather a DFS with one step before it.

                            		Functions:

                            		safeBranch()

                            		       Puts the children and the parents in one array and branches based on that (direction does not matter)

                            		branch()

                            		       Gets only the list of children (goes in one direction where the target is a child or a grandchild of the source)

                            		inverseBranch()

                            		       Gets only the list of parents (goes in one direction where the target is a parent or a grandparent of the source)

                            		Examples:

                            		Find the branch between A(source) and E(target)

A -> B -> C -> D -> E : branch() finds its way as it scans the children and E is a grandchild of A and can be reached by going in one direction. inverseBranch() will fail to find a path between A and E in this case

A <- B <- C <- D <- E : branch() will fail to find a path since E cannot be reached by a series of children from A. However, inverseBranch() will work fine

A -> B -> C <- D <- E : both branch() and inverseBranch() will fail in this case since the connection between A and E does not go in one direction

safeBranch() works for all of the three cases.

Node-link Script

    									Note: To make it easier for the maintainer to debug any bug that happens with selecting a branch later on, the console.log() calls were not removed

									ode_default_opts Object

									Holds the default options that are to be used in the nodelink() to customize the attributes of the elements

sizeScale() Function : scales the size passed to it according to its ratio from minSize to maxSize attributes

color_func Function : maps a certain attribute of a node to a color based on the value of colorScale. It is there for a default setting, but is not the one the actual one being used, it works if the colors of the nodes were not set manually

radius_func() Function : based on the size of the node (the number of elements its cluster contains), the function gives that node a propr radius to represent it. In fact it maps the area to work better with big numbers but the equation is rearranged to give the radius

									clear_selection() Function

									      resets the selection array of a graph, and resets the elements in an SVG to their normal settings (resets the visual representation of a selected branch)

Nodelink Structure

									Parameters:

graph: The graph which has the nodes and the edges to be visualized

clusters: An array of the clusters that correspond to the nodes of the graph

element ID: The array of the div where the SVG will be added

SVG ID: The ID of the SVG that will be created

opts (options): A set of options that define the settings of the nodes (has to be in the same format as node_default_opts)

force: A boolean value that determines whether the diagram will rely on the default force-directed placement of the nodes (true) or the positions will be the same as the ones given by a dimensionality reduction algorithm

									Settings:

change_mode(): switches between the 'select' mode and the 'drag' mode

change_scale(): swicthes between radius scaling modes. If 'true', it applies the radius_fuc() of the given options

set_threshold(): filters the displayed edges based on the weight of that edge in graph

set_colors(): maps the value of a grade feature of each cluster into a color for the node that represents it

									Nodes and Labels

Note that the labels are drawn above the nodes, so that every label is above every other node. This makes it easier for the user to determine whether a node is covering a smaller one behind it or not, if that is not needed then they should be combined into one group ('g' element) to make manipulating them easier

									node_click() Event Handler

Handles selecting the nodes when the SVG has the attribute mode set to 'select'. Does not just do the selection visually, it calls the given graph to find a selection, then based on the result from the call of the function it selects the points.

										It uses safeBranch() to find the branch between two points, previously it used branch() then when it fails it also checks inverseBranch() to find another way. After utilizing safeBranch() the other case should not be included, unless the graph was mean to be directed.

node_drag() Behavior & Its Functions

    										refer to D3 Drag Behavior for detailed documentation of how it works

									force_start(): Event Handler

											The handler is only called once, that is when D3 starts to draw the elements. At that stage D3 assigns values to the positions of the nodes (d.{x, y}) and their links (d.{source, target}.{x,  y}). In the case of force-directed graph (force is set to be true), the handler does not forcefully set the value for D3, it leaves the value D3 assigned the way it is.

											In the case of not wanting a force-directed graph, the handler calls force.stop(), since there is no point in recalculating the positions again. However, with the force-directed graph, it lets D3 continue its caluclations.

									force_tick(): Event Handler

											A normal classic tick handler, it just repositions the nodes, edges, and labels based on their location if it was changed from the previous one.

									force_end(): Event Handler

											Pretty much the same as the force_tick() handler, but is to be called when either D3 stops changing the position of the points, or when the force.stop() function is called.

Zoom Behavior

											Refer to SVG Geometric Zooming Example

Bugs and Errors

After zooming, the nodes are both scaled and shifted based on the focal points. However, the tooltip does not go with that, therefore after scaling the position of the tooltip will not be the same as the hovered node.

											Failed attempt: using d3.mouse(this) inside the event handler for hovered event did not work.

											Suggested action: remove the focal point and always zoom into one certain point, in this case it is fairly to locate the new position of the node.

Sometimes after doing some work with the large scatter plots, the node-link SVG disappears either partially or entirely. The causes of the bug are unknown, and attempts to reporoduce it intentionally to find a scenario where this bug occurs failed

Suggestions

Instead of going through the hassle of trying to locate the hovered node and position the tooltip accordingly, it might be a good idea to have a small box in one of the corners, it serves as a tooltip but it doesn't move based on the node's position. The box might be draggable as well to make it more convenient to the user

Data Reduction Script

                					A setof function that are used to test the dimensionality reduction algorithms. They are generally some utility functions and can be used for any other purpose. The function each() is widely used across the scripts.

                					generate_normal_point() Function:

	                						Generates a point that will most likely form a normal distribution with the other points generated by that functions. The more the number of the calls of the function, the more normal the points are distributed

                					generta_conflicting() Function:

	                						Generates consecutive points that conflict with each other in some dimensions. The function does not generate a set of points, it generates one point with each call, but its static parameters ensure that some points will have the save value in some dimensions

                					loop() Function:

	                						Wraps the for loop, it is kind of obselete now but it was useful for some previous tests. Still exists in the script for future use

                					each() Function:

	                						A widely used function in almost every script file. It wraps the for loop but it loops through all the elements (loop() required setting the lower bounds and upper bounds of the loop). Makes the script more dynamic, shorter, and easily modifible but lacks in performance since it introduces a function call inside the body of the loop instead of just executing the instructions directly.

											It is better to replace the each() calls with normal 'for' loops for better performance.

                					generate_points() Function:

	                						Given a function that generates one point and the number of points that should be generated, the function then generates a set of points (each point is generated by a call to the function func() passed as an argument)

	                				The rest of the functions are just for displaying and outputting the values

Scatter-plot Script

	                				regression_params() Function:

	                						Calculates the slope (m) and the y-intercept (b) of the regression line equation for a set of points

	                				regression_points() Function:

	                						Gets the parameters of the line by calling regression_params(), then it calculates the starting and ending points of the regression line.

											The first point lies at x = 0, and by substituting in the line equation y = b. The other points is at x = _xLim, while y = (m * _xLim) + b

	                				merge_points() Function:

	                						As each point lies on a certain edge between two nodes, each point has its location relative to those two nodes. in order to deal with them, each point must be given a location relative to the starting and ending nodes only.
											For more information about the parameter t that is being used to calculate the new location refer to the documentation of "Dataview data" for branch_axis() Function

	                				scatter() Function:

	                						Plain D3 procedures, documentation embedded within the code

                    LICENSE - CONTACT


text:
/*jshint strict: false */
/*global ArangoServerState */

////////////////////////////////////////////////////////////////////////////////
/// @brief administration actions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2014, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var actions = require("org/arangodb/actions");

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_get_admin_server_role
/// @brief Get to know whether this server is a Coordinator or DB-Server
///
/// @RESTHEADER{GET /_admin/server/role, Return role of a server in a cluster}
///
/// @RESTDESCRIPTION
///
/// Returns the role of a server in a cluster.
/// The role is returned in the *role* attribute of the result.
/// Possible return values for *role* are:
/// - *COORDINATOR*: the server is a coordinator in a cluster
/// - *PRIMARY*: the server is a primary database server in a cluster
/// - *SECONDARY*: the server is a secondary database server in a cluster
/// - *UNDEFINED*: in a cluster, *UNDEFINED* is returned if the server role cannot be
///    determined. On a single server, *UNDEFINED* is the only possible return
///    value.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// Is returned in all cases.
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////

actions.defineHttp({
  url : "_admin/server/role",
  prefix : false,

  callback : function (req, res) {
    actions.resultOk(req, res, actions.HTTP_OK, { role: ArangoServerState.role() });
  }
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|/// @startDocuBlock\\|// --SECTION--\\|/// @\\}"
// End:

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Laraflock\Skeleton\Providers;

use Illuminate\Support\ServiceProvider as BaseServiceProvider;

class ServiceProvider extends BaseServiceProvider
{
    /**
     * {@inheritDoc}
     */
    public function boot()
    {

    }

    /**
     * {@inheritDoc}
     */
    public function register()
    {

    }
}


text:
package com.google.code.beanmatchers;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.emptyArray;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ArrayTypeBasedValueGeneratorTest {

  @InjectMocks
  private TypeBasedValueGenerator unitUnderTest;

  @Mock
  private TypeBasedValueGenerator valueGeneratorMock;

  @BeforeMethod
  public void setUp() {
    unitUnderTest = new ArrayTypeBasedValueGenerator();
    initMocks(this);
  }

  @Test
  public void canCreateArray() {
    // given
    when(valueGeneratorMock.generate(Integer.TYPE)).thenReturn(4);

    // when
    int[] value = unitUnderTest.generate(int[].class);

    // then
    assertThat(value, is(notNullValue()));
  }

  @Test
  public void arrayShouldHaveAtLeastOneElement() {
    // given
    when(valueGeneratorMock.generate(String.class)).thenReturn("test");

    // when
    String[] value = unitUnderTest.generate(String[].class);

    // then
    assertThat(value, is(not(emptyArray())));
    assertThat(value[0], is("test"));
  }
}


text:
from ironicclient.tests.functional import base

class IronicClientHelp(base.FunctionalTestBase):
    """Test for python-ironicclient help messages."""

    def test_ironic_help(self):
        """Check Ironic client main help message contents."""
        caption = ("Command-line interface to the "
                   "OpenStack Bare Metal Provisioning API.")
        subcommands = {
            'bash-completion',
            'chassis-create',
            'chassis-delete',
            'chassis-list',
            'chassis-node-list',
            'chassis-show',
            'chassis-update',
            'driver-list',
            'driver-properties',
            'driver-show',
            'driver-vendor-passthru',
            'help',
            'node-create',
            'node-delete',
            'node-get-boot-device',
            'node-get-console',
            'node-get-supported-boot-devices',
            'node-list',
            'node-port-list',
            'node-set-boot-device',
            'node-set-console-mode',
            'node-set-maintenance',
            'node-set-power-state',
            'node-set-provision-state',
            'node-show',
            'node-show-states',
            'node-update',
            'node-validate',
            'node-vendor-passthru',
            'port-create',
            'port-delete',
            'port-list',
            'port-show',
            'port-update'
        }

        output = self._ironic('help', flags='', params='')

        self.assertIn(caption, output)
        for string in subcommands:
            self.assertIn(string, output)


text:
vagrant-box
===========

Vagrant configuration with puppet provisioning


text:
class CreateReproductionTypes < ActiveRecord::Migration
  def self.up
    create_table :reproduction_types, :options => 'ENGINE=MyISAM, CHARACTER SET=utf8 COLLATE=utf8_general_ci' do |t|
      t.column :title, :string, :limit => 30, :null => false
    end
    ReproductionType.create :title => 'No limit'
    ReproductionType.create :title => 'Prohibited'
    ReproductionType.create :title => 'Credit required'
    ReproductionType.create :title => 'Contact copyright holder'
  end

  def self.down
    drop_table :reproduction_types
  end
end


text:
var test = require('tape');
var Poller = require('../index');

test('throws without url', function(t) {
  t.plan(1);
  t.throws(function() {
    var poller = new Poller({
      // uh oh... no url
    }, /url is a required option/);
  });
});

test('defaults to 1 minute interval', function(t) {
  t.plan(1);
  var poller = new Poller({
    url: 'http://example.com'
  });
  t.equals(poller.options.interval, 60000);
});


text:
class JavaClass extends Dva {
    @Override
    void justFun(int $this$justFun, String j) {
        System.out.println(j);
        System.out.println($this$justFun);
    }
}


text:
var express = require('express');
var bodyParser = require('body-parser');
var _ = require('underscore');
var SofiaTree = require('../');
// A micro REST search service to benchmark SofiaTree performance against lineal search
// ------------------------------------------------------------------------------------

// var agent = require('webkit-devtools-agent');
// agent.start();

// create application/json parser
var jsonParser = bodyParser.json({limit: '5mb'})

function randomPositive(max){

	return Math.floor((Math.random() * max) + 1);
}

function randomSub(w){

	return w.substring(0,randomPositive(w.length));
}

//Just To compare performance
function linealSearch(st,dict){
	var t = process.hrtime();

	var term= st.toLowerCase();

	var	matches=_.filter(dict,function(word){
		return word.indexOf(term) === 0;
	});

	t = process.hrtime(t);
	console.log("  %d results found on %d s and %d ms using lineal search", matches.length, t[0], t[1] / 1e6);
	return matches;
}

// Global
var server = express();

// It takes first argument as the listening port, defaults to 8000
var port=process.argv[2] || 8000;

//Provide sane defaults to avoid errors on empty dictionary searches
var dictionary=[];

var sofiaTree= new SofiaTree();

server.post('/dictionary/',jsonParser, function (req, res) {

	if (!req.body)
		return res.sendStatus(400)

	dictionary= e=_.uniq(req.body,true);
	//Reset whole tree on each new dictionary submission to reset cache
	sofiaTree= new SofiaTree();

	dictionary.forEach(function(word){
		sofiaTree.insert(word);
	},server);

	//print the just generated tree
	// console.log(sofiaTree.getCompletions(''));
    res.writeHead(200, { 'content-type': 'application/json' });
    res.write(JSON.stringify({ status: "ok" }));
    console.log("Dictionary loaded with " + dictionary.length + " entries [" + dictionary[0] + ",... ...," + dictionary[dictionary.length -1] + "]" );

    res.end();
});

server.get('/search/:term/:limit?',function (req, res) {

	console.log("Searching for '"+ req.params.term + "' ...");
	// Comment this to compare perfomance betwen SofiaTree and linealSearch

	linealSearch(req.params.term.toLowerCase(),dictionary);

	if(req.params.limit){
		var t = process.hrtime();
		var result=sofiaTree.getCompletions(req.params.term, parseInt(req.params.limit));
		t = process.hrtime(t);
		console.log("  %d results found on %d s and %d ms using SofiaTree (limited)", result.length, t[0], t[1] / 1e6);
	}

	var t = process.hrtime();
	var result=sofiaTree.getCompletions(req.params.term);
	t = process.hrtime(t);
	console.log("  %d results found on %d s and %d ms using SofiaTree", result.length, t[0], t[1] / 1e6);

	res.writeHead(200, { 'content-type': 'application/json' });
	res.write(JSON.stringify(result));

	res.end();
});

server.get('/gentests/:max',function (req, res) {

	console.log("Generating "+ req.params.max + " tests");

	var BASE_URL="curl 'http://127.0.0.1:" + port +"/search/"
	var result=[];
	var i;
	var randomWord;

	if(dictionary && dictionary.length)
		for(i=0; i < req.params.max; i++){
			randomWord=dictionary[randomPositive(dictionary.length)];
			result.push(BASE_URL + randomSub(randomWord)  + "'")
			console.log(BASE_URL + randomSub(randomWord)  + "'")
		}

	res.writeHead(200, { 'content-type': 'application/json' });
	res.write(JSON.stringify(result));
	res.end();
});

server.listen(port);
console.log("Server started at port " + port + "...")


text:
export interface Options {
    cwd: string;
}
/**
 * Interface for `<jspm_packages>/.dependencies.json`.
 */
export interface DependenciesJson {
    [index: string]: {
        deps: {
            [index: string]: string;
        };
        peerDeps: {
            [index: string]: string;
        };
    };
}
/**
 * Browser field overrides like NPM.
 */
export declare type Browser = string | Overrides;
/**
 * Override map for file lookups.
 */
export interface Overrides {
    [dependency: string]: string;
}
export interface JspmPackageJson {
    name: string;
    main: string;
    version?: string;
    typings?: string;
    browser?: Browser;
    browserTypings?: Browser;
    directories?: {
        baseURL: string;
        packages?: string;
    };
    configFiles?: ConfigFiles;
    dependencies?: {
        [index: string]: string;
    };
    peerDependencies?: {
        [index: string]: string;
    };
    devDependencie?: {
        [index: string]: string;
    };
    overrides?: {
        [index: string]: any;
    };
}
/**
 * Interface for the resolved JSPM config.
 */
export interface JspmConfig {
    getDependencyTree(moduleName: string): any;
}
export interface ConfigFiles {
    jspm: string;
    'jspm:browser': string;
    'jspm:dev': string;
    'jspm:node': string;
}
export interface Configs {
    jspm?: any;
    browser?: any;
    dev?: any;
    node?: any;
}
export interface JspmProjectInfo {
    jspmPackageJson: JspmPackageJson;
    jspmConfigs: Configs;
    dependenciesJson?: DependenciesJson;
}
export interface PathMap {
    [prefix: string]: string;
}
/**
 * Module name maps to package name.
 */
export interface ModuleMap {
    [moduleName: string]: string;
}
export interface PackageMap {
    [versionedName: string]: {
        map: ModuleMap;
    };
}
export interface DependencyInfo {
    paths: PathMap;
    map: ModuleMap;
    packages: PackageMap;
}
export interface DependencyBranch {
    [moduleName: string]: DependencyTree;
}
export interface DependencyTree {
    path: string;
    map?: DependencyBranch;
}


text:
package io.undertow.websockets.jsr;

import io.undertow.servlet.api.InstanceFactory;
import io.undertow.servlet.api.InstanceHandle;

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

import javax.websocket.Extension;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

/**
 * Server default container configurator.
 * <p>
 * This API is stupid, because it has no way to attach deployment specific context.
 *
 * @author Stuart Douglas
 */
public class DefaultContainerConfigurator extends ServerEndpointConfig.Configurator {

    public static final DefaultContainerConfigurator INSTANCE = new DefaultContainerConfigurator();

    /**
     * thread local hacks to work around a horrible horrible broken API
     */
    private static final ThreadLocal<InstanceFactory<?>> currentInstanceFactory = new ThreadLocal<>();
    private static final ThreadLocal<InstanceHandle<?>> currentInstanceHandle = new ThreadLocal<>();

    @Override
    public String getNegotiatedSubprotocol(final List<String> supported, final List<String> requested) {
        for(String proto : requested) {
            if(supported.contains(proto)) {
                return proto;
            }
        }
        return "";
    }

    @Override
    public List<Extension> getNegotiatedExtensions(final List<Extension> installed, final List<Extension> requested) {
        final List<Extension> ret = new ArrayList<>();
        for (Extension req : requested) {
            for (Extension extension : installed) {
                if (extension.getName().equals(req.getName())) {
                    ret.add(req);
                    break;
                }
            }
        }
        return ret;
    }

    @Override
    public boolean checkOrigin(final String originHeaderValue) {
        //we can't actually do anything here, because have have absolutely no context.
        return true;
    }

    @Override
    public void modifyHandshake(final ServerEndpointConfig sec, final HandshakeRequest request, final HandshakeResponse response) {
    }

    @Override
    public <T> T getEndpointInstance(final Class<T> endpointClass) throws InstantiationException {
        InstanceFactory<?> factory = currentInstanceFactory.get();
        if(factory != null) {
            InstanceHandle<?> instance = factory.createInstance();
            currentInstanceHandle.set(instance);
            return (T) instance.getInstance();
        }
        try {
            return endpointClass.newInstance();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    static void setCurrentInstanceFactory(InstanceFactory<?> factory) {
         currentInstanceFactory.set(factory);
    }

    static InstanceHandle<?> clearCurrentInstanceFactory() {
        currentInstanceFactory.remove();
        InstanceHandle<?> handle = currentInstanceHandle.get();
        currentInstanceHandle.remove();
        return handle;
    }
}


text:
"""Memoize the data produced by slow operations into Google storage.

Caches computations described in terms of command lines and inputs directories
or files, which yield a set of output file.
"""

# Done first to setup python2 module path.
import toolchain_env

import hashlib
import logging
import os
import platform
import shutil
import sys

import directory_storage
import file_tools
import gsd_storage
import hashing_tools
import log_tools
import working_directory

class Once(object):
  """Class to memoize slow operations."""

  def __init__(self, storage, use_cached_results=True, cache_results=True,
               print_url=None, check_call=None):
    """Constructor.

    Args:
      storage: An storage layer to read/write from (GSDStorage).
      use_cached_results: Flag indicating that cached computation results
                          should be used when possible.
      cache_results: Flag that indicates if successful computations should be
                     written to the cache.
      print_url: Function that accepts an URL for printing the build result,
                 or None.
      check_call: A testing hook for allowing build commands to be intercepted.
                  Same interface as subprocess.check_call.
    """
    if check_call is None:
      check_call = log_tools.CheckCall
    self._storage = storage
    self._directory_storage = directory_storage.DirectoryStorageAdapter(storage)
    self._use_cached_results = use_cached_results
    self._cache_results = cache_results
    self._print_url = print_url
    self._check_call = check_call

  def KeyForOutput(self, package, output_hash):
    """Compute the key to store a give output in the data-store.

    Args:
      package: Package name.
      output_hash: Stable hash of the package output.
    Returns:
      Key that this instance of the package output should be stored/retrieved.
    """
    return 'object/%s_%s.tgz' % (package, output_hash)

  def KeyForBuildSignature(self, build_signature):
    """Compute the key to store a computation result in the data-store.

    Args:
      build_signature: Stable hash of the computation.
    Returns:
      Key that this instance of the computation result should be
      stored/retrieved.
    """
    return 'computed/%s.txt' % build_signature

  def WriteOutputFromHash(self, package, out_hash, output):
    """Write output from the cache.

    Args:
      package: Package name (for tgz name).
      out_hash: Hash of desired output.
      output: Output path.
    Returns:
      URL from which output was obtained if successful, or None if not.
    """
    key = self.KeyForOutput(package, out_hash)
    url = self._directory_storage.GetDirectory(key, output)
    if not url:
      logging.debug('Failed to retrieve %s' % key)
      return None
    if hashing_tools.StableHashPath(output) != out_hash:
      logging.warning('Object does not match expected hash, '
                      'has hashing method changed?')
      return None
    return url

  def PrintDownloadURL(self, url):
    """Print download URL if function was provided in the constructor.

    Args:
      urls: A list of urls to print.
    """
    if self._print_url is not None:
      self._print_url(url)

  def WriteResultToCache(self, package, build_signature, output):
    """Cache a computed result by key.

    Also prints URLs when appropriate.
    Args:
      package: Package name (for tgz name).
      build_signature: The input hash of the computation.
      output: A path containing the output of the computation.
    """
    if not self._cache_results:
      return
    out_hash = hashing_tools.StableHashPath(output)
    try:
      output_key = self.KeyForOutput(package, out_hash)
      # Try to get an existing copy in a temporary directory.
      wd = working_directory.TemporaryWorkingDirectory()
      with wd as work_dir:
        temp_output = os.path.join(work_dir, 'out')
        url = self._directory_storage.GetDirectory(output_key, temp_output)
        if url is None:
          # Isn't present. Cache the computed result instead.
          url = self._directory_storage.PutDirectory(output, output_key)
          logging.info('Computed fresh result and cached it.')
        else:
          # Cached version is present. Replace the current output with that.
          file_tools.RemoveDirectoryIfPresent(output)
          shutil.move(temp_output, output)
          logging.info(
              'Recomputed result matches cached value, '
              'using cached value instead.')
      # Upload an entry mapping from computation input to output hash.
      self._storage.PutData(
          out_hash, self.KeyForBuildSignature(build_signature))
      self.PrintDownloadURL(url)
    except gsd_storage.GSDStorageError:
      logging.info('Failed to cache result.')
      raise

  def ReadMemoizedResultFromCache(self, package, build_signature, output):
    """Read a cached result (if it exists) from the cache.

    Also prints URLs when appropriate.
    Args:
      package: Package name (for tgz name).
      build_signature: Build signature of the computation.
      output: Output path.
    Returns:
      Boolean indicating successful retrieval.
    """
    # Check if its in the cache.
    if self._use_cached_results:
      out_hash = self._storage.GetData(
          self.KeyForBuildSignature(build_signature))
      if out_hash is not None:
        url = self.WriteOutputFromHash(package, out_hash, output)
        if url is not None:
          logging.info('Retrieved cached result.')
          self.PrintDownloadURL(url)
          return True
    return False

  def Run(self, package, inputs, output, commands, unpack_commands=None,
          hashed_inputs=None, working_dir=None):
    """Run an operation once, possibly hitting cache.

    Args:
      package: Name of the computation/module.
      inputs: A dict of names mapped to files that are inputs.
      output: An output directory.
      commands: A list of command.Command objects to run.
      unpack_commands: A list of command.Command object to run before computing
                       the build hash. Or None.
      hashed_inputs: An alternate dict of inputs to use for hashing and after
                     the packing stage (or None).
      working_dir: Working directory to use, or None for a temp dir.
    """
    if working_dir is None:
      wdm = working_directory.TemporaryWorkingDirectory()
    else:
      wdm = working_directory.FixedWorkingDirectory(working_dir)

    # Cleanup destination.
    file_tools.RemoveDirectoryIfPresent(output)
    os.mkdir(output)

    with wdm as work_dir:
      # Optionally unpack before hashing.
      if unpack_commands is not None:
        for command in unpack_commands:
          command.Invoke(check_call=self._check_call, package=package,
                         cwd=work_dir, inputs=inputs, output=output)

      # Use an alternate input set from here on.
      if hashed_inputs is not None:
        inputs = hashed_inputs

      # Compute the build signature with modified inputs.
      build_signature = self.BuildSignature(
          package, inputs=inputs, commands=commands)

      # We're done if it's in the cache.
      if self.ReadMemoizedResultFromCache(package, build_signature, output):
        return
      for command in commands:
        command.Invoke(check_call=self._check_call, package=package,
                       cwd=work_dir, inputs=inputs, output=output,
                       build_signature=build_signature)

    self.WriteResultToCache(package, build_signature, output)

  def SystemSummary(self):
    """Gather a string describing intrinsic properties of the current machine.

    Ideally this would capture anything relevant about the current machine that
    would cause build output to vary (other than build recipe + inputs).
    """
    # Note there is no attempt to canonicalize these values.  If two
    # machines that would in fact produce identical builds differ in
    # these values, it just means that a superfluous build will be
    # done once to get the mapping from new input hash to preexisting
    # output hash into the cache.
    assert len(sys.platform) != 0, len(platform.machine()) != 0
    items = [
        ('platform', sys.platform),
        ('machine', platform.machine()),
        ]
    return str(items)

  def BuildSignature(self, package, inputs, commands):
    """Compute a total checksum for a computation.

    The computed hash includes system properties, inputs, and the commands run.
    Args:
      package: The name of the package computed.
      inputs: A dict of names -> files/directories to be included in the
              inputs set.
      commands: A list of command.Command objects describing the commands run
                for this computation.
    Returns:
      A hex formatted sha1 to use as a computation key.
    """
    h = hashlib.sha1()
    h.update('package:' + package)
    h.update('summary:' + self.SystemSummary())
    for command in commands:
      h.update('command:')
      h.update(str(command))
    for key in sorted(inputs.keys()):
      h.update('item_name:' + key + '\x00')
      h.update('item:' + hashing_tools.StableHashPath(inputs[key]))
    return h.hexdigest()


text:
endpoints=(sizes regions images "account/keys")
for i in "${endpoints[@]}"; do
    url=`printf "https://api.digitalocean.com/v2/%s" $i`
    curl -X "GET" -H "Authorization: Bearer $DO_API_TOKEN" $url | python -mjson.tool
done


text:
bool trainableParameters(CMT::Trainable::Parameters* params, std::string key, MEX::Input::Getter value) {
    if(key == "verbosity") {
        params->verbosity = value;
        return true;
    }

    if(key == "maxIter") {
        params->maxIter = value;
        return true;
    }

    if(key == "threshold") {
        params->threshold = value;
        return true;
    }

    if(key == "numGrad") {
        params->numGrad = value;
        return true;
    }

    if(key == "batchSize") {
        params->batchSize = value;
        return true;
    }

    if(key == "cbIter") {
        params->cbIter = value;
        return true;
    }

    if(key == "valIter") {
        params->valIter = value;
        return true;
    }

    if(key == "valLookAhead") {
        params->valLookAhead = value;
        return true;
    }

    return false;
}

bool trainableParse(CMT::Trainable* obj, std::string cmd, const MEX::Output& output, const MEX::Input& input) {

    // Methods
    if(cmd == "initialize") {
        obj->initialize(input[0], input[1]);
        return true;
    }

    if(cmd == "checkGradient") {
        if(input.has(2)) {
            CMT::Trainable::Parameters params;

            if(input.has(3)){
                params = input.toStruct<CMT::Trainable::Parameters>(3, &trainableParameters);
            }

            output[0] = obj->checkGradient(input[0], input[1], input[2], params);
            return true;
        }

        output[0] = obj->checkGradient(input[0], input[1]);
        return true;
    }

    if(cmd == "checkPerformance") {
        if(input.has(2)) {
            CMT::Trainable::Parameters params;

            if(input.has(3)){
                params = input.toStruct<CMT::Trainable::Parameters>(3, &trainableParameters);
            }

            output[0] = obj->checkPerformance(input[0], input[1], input[2], params);
            return true;
        }

        output[0] = obj->checkPerformance(input[0], input[1]);
        return true;
    }

    if(cmd == "fisherInformation") {
        CMT::Trainable::Parameters params;

        if(input.has(2)){
            params = input.toStruct<CMT::Trainable::Parameters>(2, &trainableParameters);
        }

        output[0] = obj->fisherInformation(input[0], input[1], params);
        return true;
    }

    // Superclass
    return conditionaldistributionParse(obj, cmd, output, input);
}


text:
// uci.cpp

// includes

#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include "board.h"
#include "engine.h"
#include "move.h"
#include "move_do.h"
#include "move_legal.h"
#include "option.h"
#include "parse.h"
#include "line.h"
#include "uci.h"
#include "util.h"

// constants

static const bool UseDebug = false;

static const int StringSize = 4096;

// variables

uci_t Uci[1];

// prototypes

static bool uci_is_ok      (const uci_t * uci);

static int  parse_bestmove (uci_t * uci, const char string[]);
static void parse_id       (uci_t * uci, const char string[]);
static int  parse_info     (uci_t * uci, const char string[]);
static void parse_option   (uci_t * uci, const char string[]);
static void parse_score    (uci_t * uci, const char string[]);

static int  mate_score     (int dist);

// functions

// uci_is_ok()

static bool uci_is_ok(const uci_t * uci) {

   if (uci == NULL) return false;
   if (uci->engine == NULL) return false;
   if (uci->option_nb < 0 || uci->option_nb >= OptionNb) return false;

   return true;
}

// uci_open()

void uci_open(uci_t * uci, engine_t * engine) {

   char string[StringSize];
   int event;

   ASSERT(uci!=NULL);
   ASSERT(engine!=NULL);

   // init

   uci->engine = engine;

   uci->name = NULL;
   my_string_set(&uci->name,"<empty>");
   uci->author = NULL;
   my_string_set(&uci->author,"<empty>");
   uci->option_nb = 0;

   uci->ready_nb = 0;
   uci->searching = 0;
   uci->pending_nb = 0;

   board_start(uci->board);
   uci_clear(uci);

   // send "uci" and wait for "uciok"

   engine_send(uci->engine,"uci");

   do {
      engine_get(uci->engine,string,StringSize);
      event = uci_parse(uci,string);
   } while ((event & EVENT_UCI) == 0);
}

// uci_close()

void uci_close(uci_t * uci) {

   int i;
   option_t * opt;

   ASSERT(uci_is_ok(uci));

   engine_close(uci->engine);

   uci->engine = NULL;
   my_string_clear(&uci->name);
   my_string_clear(&uci->author);

   for (i = 0; i < uci->option_nb; i++) {
      opt = &uci->option[i];
      my_string_clear(&opt->name);
      my_string_clear(&opt->value);
   }

   uci->option_nb = 0;
}

// uci_clear()

void uci_clear(uci_t * uci) {

   ASSERT(uci_is_ok(uci));

   ASSERT(!uci->searching);

   uci->best_move = MoveNone;
   uci->ponder_move = MoveNone;

   uci->score = 0;
   uci->depth = 0;
   uci->sel_depth = 0;
   line_clear(uci->pv);

   uci->best_score = 0;
   uci->best_depth = 0;
   uci->best_sel_depth = 0;
   line_clear(uci->best_pv);

   uci->node_nb = 0;
   uci->time = 0.0;
   uci->speed = 0.0;
   uci->cpu = 0.0;
   uci->hash = 0.0;
   line_clear(uci->current_line);

   uci->root_move = MoveNone;
   uci->root_move_pos = 0;
   uci->root_move_nb = board_mobility(uci->board);
}

// uci_send_isready()

void uci_send_isready(uci_t * uci) {

   ASSERT(uci!=NULL);

   engine_send(uci->engine,"isready");
   uci->ready_nb++;
}

// uci_send_isready_sync()

void uci_send_isready_sync(uci_t * uci) {

   char string[StringSize];
   int event;

   ASSERT(uci_is_ok(uci));

   // send "isready" and wait for "readyok"

   uci_send_isready(uci);

   do {
      engine_get(uci->engine,string,StringSize);
      event = uci_parse(uci,string);
   } while ((event & EVENT_READY) == 0);
}

// uci_send_stop()

void uci_send_stop(uci_t * uci) {

   ASSERT(uci_is_ok(uci));

   ASSERT(uci->searching);
   ASSERT(uci->pending_nb>=1);

   engine_send(Engine,"stop");
   uci->searching = false;
}

// uci_send_stop_sync()

void uci_send_stop_sync(uci_t * uci) {

   char string[StringSize];
   int event;

   ASSERT(uci_is_ok(uci));

   ASSERT(uci->searching);
   ASSERT(uci->pending_nb>=1);

   // send "stop" and wait for "bestmove"

   uci_send_stop(uci);

   do {
      engine_get(uci->engine,string,StringSize);
      event = uci_parse(uci,string);
   } while ((event & EVENT_STOP) == 0);
}

// uci_send_ucinewgame()

void uci_send_ucinewgame(uci_t * uci) {

   ASSERT(uci!=NULL);

   if (option_get_int("UCIVersion") >= 2) {
      engine_send(uci->engine,"ucinewgame");
   }
}

// uci_option_exist()

bool uci_option_exist(uci_t * uci, const char option[]) {

   int i;
   option_t * opt;

   ASSERT(uci_is_ok(uci));
   ASSERT(option!=NULL);

   // scan options

   for (i = 0; i < uci->option_nb; i++) {
      opt = &uci->option[i];
      if (my_string_case_equal(opt->name,option)) return true;
   }

   return false;
}

// uci_send_option()

void uci_send_option(uci_t * uci, const char option[], const char format[], ...) {

   va_list arg_list;
   char value[StringSize];
   int i;
   option_t * opt;

   ASSERT(uci_is_ok(uci));
   ASSERT(option!=NULL);
   ASSERT(format!=NULL);

   // format

   va_start(arg_list,format);
   vsprintf(value,format,arg_list);
   va_end(arg_list);

   if (UseDebug) my_log("POLYGLOT OPTION %s VALUE %s\n",option,value);

   // scan options

   for (i = 0; i < uci->option_nb; i++) {

      opt = &uci->option[i];

      if (my_string_case_equal(opt->name,option) && !my_string_equal(opt->value,value)) {
         engine_send(uci->engine,"setoption name %s value %s",option,value);
         my_string_set(&opt->value,value);
      }
   }
}

// uci_parse()

int uci_parse(uci_t * uci, const char string[]) {

   int event;
   parse_t parse[1];
   char command[StringSize];
   char argument[StringSize];

   ASSERT(uci_is_ok(uci));
   ASSERT(string!=NULL);

   // init

   event = EVENT_NONE;

   // parse

   parse_open(parse,string);

   if (parse_get_word(parse,command,StringSize)) {

      parse_get_string(parse,argument,StringSize);
      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" ARGUMENT \"%s\"\n",command,argument);

      if (false) {

      } else if (my_string_equal(command,"bestmove")) {

         // search end

         ASSERT(uci->pending_nb>0);

         if (uci->searching && uci->pending_nb == 1) {

            // current search

            uci->searching = false;
            uci->pending_nb--;

            event = parse_bestmove(uci,argument); // updates uci->best_move and uci->ponder_move

         } else {

            // obsolete search

            if (uci->pending_nb > 0) {
               uci->pending_nb--;
               if (uci->pending_nb == 0) event = EVENT_STOP;
            }
         }

      } else if (my_string_equal(command,"id")) {

         parse_id(uci,argument);

      } else if (my_string_equal(command,"info")) {

         // search information

         if (uci->searching && uci->pending_nb == 1) { // current search
            event = parse_info(uci,argument);
         }

      } else if (my_string_equal(command,"option")) {

         parse_option(uci,argument);

      } else if (my_string_equal(command,"readyok")) {

         // engine is ready

         ASSERT(uci->ready_nb>0);

         if (uci->ready_nb > 0) {
            uci->ready_nb--;
            if (uci->ready_nb == 0) event = EVENT_READY;
         }

      } else if (my_string_equal(command,"uciok")) {

         event = EVENT_UCI;

      } else {

         if (UseDebug) my_log("POLYGLOT unknown command \"%s\"\n",command);
      }
   }

   parse_close(parse);

   return event;
}

// parse_bestmove()

static int parse_bestmove(uci_t * uci, const char string[]) {

   parse_t parse[1];
   char command[StringSize];
   char option[StringSize];
   char argument[StringSize];
   board_t board[1];

   ASSERT(uci_is_ok(uci));
   ASSERT(string!=NULL);

   // init

   strcpy(command,"bestmove");

   parse_open(parse,string);
   parse_add_keyword(parse,"ponder");

   // bestmove

   if (!parse_get_string(parse,argument,StringSize)) {
      my_fatal("parse_bestmove(): missing argument\n");
   }

   uci->best_move = move_from_can(argument,uci->board);
   if (uci->best_move == MoveNone) my_fatal("parse_bestmove(): not a move \"%s\"\n",argument);

   ASSERT(uci->best_move!=MoveNone);
   ASSERT(move_is_legal(uci->best_move,uci->board));

   // loop

   while (parse_get_word(parse,option,StringSize)) {

      parse_get_string(parse,argument,StringSize);

      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" OPTION \"%s\" ARGUMENT \"%s\"\n",command,option,argument);

      if (false) {

      } else if (my_string_equal(option,"ponder")) {

         ASSERT(!my_string_empty(argument));

         board_copy(board,uci->board);
         move_do(board,uci->best_move);

         uci->ponder_move = move_from_can(argument,board);
         // if (uci->ponder_move == MoveNone) my_fatal("parse_bestmove(): not a move \"%s\"\n",argument);

         ASSERT(uci->ponder_move!=MoveNone);
         ASSERT(move_is_legal(uci->ponder_move,board));

      } else {

         my_log("POLYGLOT unknown option \"%s\" for command \"%s\"\n",option,command);
      }
   }

   parse_close(parse);

   return EVENT_MOVE;
}

// parse_id()

static void parse_id(uci_t * uci, const char string[]) {

   parse_t parse[1];
   char command[StringSize];
   char option[StringSize];
   char argument[StringSize];

   ASSERT(uci!=NULL);
   ASSERT(string!=NULL);

   // init

   strcpy(command,"id");

   parse_open(parse,string);
   parse_add_keyword(parse,"author");
   parse_add_keyword(parse,"name");

   // loop

   while (parse_get_word(parse,option,StringSize)) {

      parse_get_string(parse,argument,StringSize);
      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" OPTION \"%s\" ARGUMENT \"%s\"\n",command,option,argument);

      if (false) {
      } else if (my_string_equal(option,"author")) {
         ASSERT(!my_string_empty(argument));
         my_string_set(&uci->author,argument);
      } else if (my_string_equal(option,"name")) {
         ASSERT(!my_string_empty(argument));
         my_string_set(&uci->name,argument);
      } else {
         my_log("POLYGLOT unknown option \"%s\" for command \"%s\"\n",option,command);
      }
   }

   parse_close(parse);

   if (UseDebug) my_log("POLYGLOT engine name \"%s\" author \"%s\"\n",uci->name,uci->author);
}

// parse_info()

static int parse_info(uci_t * uci, const char string[]) {

   int event;
   parse_t parse[1];
   char command[StringSize];
   char option[StringSize];
   char argument[StringSize];
   int n;
   sint64 ln;

   ASSERT(uci_is_ok(uci));
   ASSERT(string!=NULL);

   // init

   event = EVENT_NONE;

   strcpy(command,"info");

   parse_open(parse,string);
   parse_add_keyword(parse,"cpuload");
   parse_add_keyword(parse,"currline");
   parse_add_keyword(parse,"currmove");
   parse_add_keyword(parse,"currmovenumber");
   parse_add_keyword(parse,"depth");
   parse_add_keyword(parse,"hashfull");
   parse_add_keyword(parse,"multipv");
   parse_add_keyword(parse,"nodes");
   parse_add_keyword(parse,"nps");
   parse_add_keyword(parse,"pv");
   parse_add_keyword(parse,"refutation");
   parse_add_keyword(parse,"score");
   parse_add_keyword(parse,"seldepth");
   parse_add_keyword(parse,"string");
   parse_add_keyword(parse,"tbhits");
   parse_add_keyword(parse,"time");

   // loop

   while (parse_get_word(parse,option,StringSize)) {

      parse_get_string(parse,argument,StringSize);

      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" OPTION \"%s\" ARGUMENT \"%s\"\n",command,option,argument);

      if (false) {

      } else if (my_string_equal(option,"cpuload")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=0);

         if (n >= 0) uci->cpu = double(n) / 1000.0;

      } else if (my_string_equal(option,"currline")) {

         ASSERT(!my_string_empty(argument));

         line_from_can(uci->current_line,uci->board,argument,LineSize);

      } else if (my_string_equal(option,"currmove")) {

         ASSERT(!my_string_empty(argument));

         uci->root_move = move_from_can(argument,uci->board);
         ASSERT(uci->root_move!=MoveNone);

      } else if (my_string_equal(option,"currmovenumber")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=1&&n<=uci->root_move_nb);

         if (n >= 1 && n <= uci->root_move_nb) {
            uci->root_move_pos = n - 1;
            ASSERT(uci->root_move_pos>=0&&uci->root_move_pos<uci->root_move_nb);
         }

      } else if (my_string_equal(option,"depth")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=1);

         if (n >= 0) {
            if (n > uci->depth) event |= EVENT_DEPTH;
            uci->depth = n;
         }

      } else if (my_string_equal(option,"hashfull")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=0);

         if (n >= 0) uci->hash = double(n) / 1000.0;

      } else if (my_string_equal(option,"multipv")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=1);

      } else if (my_string_equal(option,"nodes")) {

         ASSERT(!my_string_empty(argument));

         ln = my_atoll(argument);
         ASSERT(ln>=0);

         if (ln >= 0) uci->node_nb = ln;

      } else if (my_string_equal(option,"nps")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=0);

         if (n >= 0) uci->speed = double(n);

      } else if (my_string_equal(option,"pv")) {

         ASSERT(!my_string_empty(argument));

         line_from_can(uci->pv,uci->board,argument,LineSize);
         event |= EVENT_PV;

      } else if (my_string_equal(option,"refutation")) {

         ASSERT(!my_string_empty(argument));

         line_from_can(uci->pv,uci->board,argument,LineSize);

      } else if (my_string_equal(option,"score")) {

         ASSERT(!my_string_empty(argument));

         parse_score(uci,argument);

      } else if (my_string_equal(option,"seldepth")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=0);

         if (n >= 0) uci->sel_depth = n;

      } else if (my_string_equal(option,"string")) {

         // TODO: argument to EOS

         ASSERT(!my_string_empty(argument));

      } else if (my_string_equal(option,"tbhits")) {

         ASSERT(!my_string_empty(argument));

         ln = my_atoll(argument);
         ASSERT(ln>=0);

      } else if (my_string_equal(option,"time")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n>=0);

         if (n >= 0) uci->time = double(n) / 1000.0;

      } else {

         my_log("POLYGLOT unknown option \"%s\" for command \"%s\"\n",option,command);
      }
   }

   parse_close(parse);

   // update display

   if ((event & EVENT_PV) != 0) {
      uci->best_score = uci->score;
      uci->best_depth = uci->depth;
      uci->best_sel_depth = uci->sel_depth;
      line_copy(uci->best_pv,uci->pv);
   }

   return event;
}

// parse_option()

static void parse_option(uci_t * uci, const char string[]) {

   option_t * opt;
   parse_t parse[1];
   char command[StringSize];
   char option[StringSize];
   char argument[StringSize];

   ASSERT(uci!=NULL);
   ASSERT(string!=NULL);

   // init

   strcpy(command,"option");

   if (uci->option_nb >= OptionNb) return;

   opt = &uci->option[uci->option_nb];
   uci->option_nb++;

   opt->name = NULL;
   my_string_set(&opt->name,"<empty>");

   opt->value = NULL;
   my_string_set(&opt->value,"<empty>");

   parse_open(parse,string);
   parse_add_keyword(parse,"default");
   parse_add_keyword(parse,"max");
   parse_add_keyword(parse,"min");
   parse_add_keyword(parse,"name");
   parse_add_keyword(parse,"type");
   parse_add_keyword(parse,"var");

   // loop

   while (parse_get_word(parse,option,StringSize)) {

      parse_get_string(parse,argument,StringSize);
      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" OPTION \"%s\" ARGUMENT \"%s\"\n",command,option,argument);

      if (false) {

      } else if (my_string_equal(option,"default")) {

         // ASSERT(!my_string_empty(argument)); // HACK for Pepito

         if (!my_string_empty(argument)) {
            my_string_set(&opt->value,argument);
         }

      } else if (my_string_equal(option,"max")) {

         ASSERT(!my_string_empty(argument));

      } else if (my_string_equal(option,"min")) {

         ASSERT(!my_string_empty(argument));

      } else if (my_string_equal(option,"name")) {

         ASSERT(!my_string_empty(argument));

         if (!my_string_empty(argument)) {
            my_string_set(&opt->name,argument);
         }

      } else if (my_string_equal(option,"type")) {

         ASSERT(!my_string_empty(argument));

      } else if (my_string_equal(option,"var")) {

         ASSERT(!my_string_empty(argument));

      } else {

         my_log("POLYGLOT unknown option \"%s\" for command \"%s\"\n",option,command);
      }
   }

   parse_close(parse);

   if (UseDebug) my_log("POLYGLOT option name \"%s\" value \"%s\"\n",opt->name,opt->value);
}

// parse_score()

static void parse_score(uci_t * uci, const char string[]) {

   parse_t parse[1];
   char command[StringSize];
   char option[StringSize];
   char argument[StringSize];
   int n;

   ASSERT(uci_is_ok(uci));
   ASSERT(string!=NULL);

   // init

   strcpy(command,"score");

   parse_open(parse,string);
   parse_add_keyword(parse,"cp");
   parse_add_keyword(parse,"lowerbound");
   parse_add_keyword(parse,"mate");
   parse_add_keyword(parse,"upperbound");

   // loop

   while (parse_get_word(parse,option,StringSize)) {

      parse_get_string(parse,argument,StringSize);

      if (UseDebug) my_log("POLYGLOT COMMAND \"%s\" OPTION \"%s\" ARGUMENT \"%s\"\n",command,option,argument);

      if (false) {

      } else if (my_string_equal(option,"cp")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);

         uci->score = n;

      } else if (my_string_equal(option,"lowerbound")) {

         ASSERT(my_string_empty(argument));

      } else if (my_string_equal(option,"mate")) {

         ASSERT(!my_string_empty(argument));

         n = atoi(argument);
         ASSERT(n!=0);

         uci->score = mate_score(n);

      } else if (my_string_equal(option,"upperbound")) {

         ASSERT(my_string_empty(argument));

      } else {

         my_log("POLYGLOT unknown option \"%s\" for command \"%s\"\n",option,command);
      }
   }

   parse_close(parse);
}

// mate_score()

static int mate_score(int dist) {

   ASSERT(dist!=0);

   if (false) {
   } else if (dist > 0) {
      return +option_get_int("MateScore") - (+dist) * 2 + 1;
   } else if (dist < 0) {
      return -option_get_int("MateScore") + (-dist) * 2;
   }

   return 0;
}

// end of uci.cpp


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:ns1="urn:oasis:names:tc:xliff:document:1.2">
    <!-- From: file:/tmp/aar_gen_tmp3462974426155758594/tmp-deduplicated/blaze-out/gcc-4.X.Y-crosstool-v18-hybrid-grtev4-k8-opt/genfiles/java/com/google/android/gmscore/integ/client/common/res/values-nb/strings.xml -->
    <eat-comment/>
    <string msgid="9089562800660647919" name="common_google_play_services_unknown_issue">"<ns1:g id="APP_NAME">%1$s</ns1:g> har problemer med Google Play-tjenester. Hvis problemet vedvarer, kan du ta kontakt med utvikleren for å få hjelp."</string>
</resources>


text:
namespace printing {

namespace mojom {
enum class PrinterType;
}

extern const char kDummyPrinterName[];
const int kTestPrinterDpi = 600;

// Creates a print ticket with some default values. Based on ticket creation in
// chrome/browser/resources/print_preview/native_layer.js.
base::Value::Dict GetPrintTicket(mojom::PrinterType type);

}  // namespace printing

#endif  // CHROME_BROWSER_PRINTING_PRINT_TEST_UTILS_H_


text:
module ActiveRecord

  # TODO
  module CurrentUser

    def self.included(base) #:nodoc:
      base.alias_method_chain :touch,  :current_user
      base.alias_method_chain :create, :current_user
      base.alias_method_chain :update, :current_user

      base.class_inheritable_accessor :current_user_class_name, :instance_writer => false
      base.current_user_class_name = 'User'
    end

    private

      def touch_with_current_user(timestamp_attribute = nil, current_user_attribute = nil) #:nodoc:
        if current_user_class_name && (current = current_user_class_name.constantize.current)
          if current_user_attribute
            send("#{attribute}=", current)
          else
            self.updator = current if respond_to?(:updator)
          end
        end
        touch_without_current_user(timestamp_attribute)
      end

      def create_with_current_user #:nodoc:
        if current_user_class_name && (current = current_user_class_name.constantize.current)
          self.creator = current if respond_to?(:creator) && creator.nil?
          self.updator = current if respond_to?(:updator) && updator.nil?
        end
        create_without_current_user
      end

      def update_with_current_user(*args) #:nodoc:
        if current_user_class_name && (current = current_user_class_name.constantize.current) && (!partial_updates? || changed?)
          self.updator = current if respond_to?(:updator)
        end
        update_without_current_user(*args)
      end

  end

end


text:
define(["require", "exports", '../metadata/index', './metadata', './metadata', './container'], function (require, exports, _index, _metadata, _metadata_1, _container) {
    exports.Registration = _metadata_1.Registration;
    exports.TransientRegistration = _metadata_1.TransientRegistration;
    exports.SingletonRegistration = _metadata_1.SingletonRegistration;
    exports.Resolver = _metadata_1.Resolver;
    exports.Lazy = _metadata_1.Lazy;
    exports.All = _metadata_1.All;
    exports.Optional = _metadata_1.Optional;
    exports.Parent = _metadata_1.Parent;
    exports.Factory = _metadata_1.Factory;
    exports.Container = _container.Container;
    function inject() {
        var rest = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            rest[_i - 0] = arguments[_i];
        }
        return function (target) {
            target.inject = rest;
            return target;
        };
    }
    exports.inject = inject;
    function transient(key) {
        return function (target) {
            _index.Metadata.on(target).add(new _metadata.TransientRegistration(key));
            return target;
        };
    }
    exports.transient = transient;
    function singleton(keyOrRegisterInChild, registerInChild) {
        if (registerInChild === void 0) { registerInChild = false; }
        return function (target) {
            _index.Metadata.on(target).add(new _metadata.SingletonRegistration(keyOrRegisterInChild, registerInChild));
            return target;
        };
    }
    exports.singleton = singleton;
    _index.Decorators.configure.parameterizedDecorator('inject', inject);
    _index.Decorators.configure.parameterizedDecorator('transient', transient);
    _index.Decorators.configure.parameterizedDecorator('singleton', singleton);
});


text:
namespace Marten.Linq.Parsing.Methods
{
    internal class PhraseSearch: FullTextSearchMethodCallParser
    {
        public PhraseSearch() : base(nameof(LinqExtensions.PhraseSearch), FullTextSearchFunction.phraseto_tsquery)
        {
        }
    }
}


text:
define([
	'require',
	'num/num',
	"engine/rendering/drawcallbacks/idrawcallback",
	"engine/rendering/image",
	"engine/rendering/drawcallback",
	"physics/jello"
], function(require, num, IDrawCallback, Image, DrawCallback, Jello) {
    var Vector2 = require('num/num').Vector2,
        AABB = require('physics/jello').AABB;

	var firefly1x1 = Image.get("firefly1x1.png");
	var firefly2x2 = Image.get("firefly2x2.png");

	return IDrawCallback.subclass({
		draw: function(entity, renderer) {
			if(!entity.fireflyImage) {
				if(!firefly1x1.data || !firefly2x2.data) return;
				entity.fireflyImage = Math.random() < 0.5 ? firefly1x1 : firefly2x2;
			}

			var imageData = entity.fireflyImage.data;

			// define source rectangle
			var sourceX = 0;
			var sourceY = 0;
			var sourceWidth = imageData.width;
			var sourceHeight = imageData.height;

			// define destination aabb
			var worldMiddlePoint = entity.getBody().getDerivedPosition();
			// scale extend down to meet the source's extent in screen coordinates
			var worldExtent = new Vector2(
				sourceWidth * env.renderer.singlePixelExtent.x,
				sourceHeight * env.renderer.singlePixelExtent.y
			);
			var aabb = new AABB(
				worldMiddlePoint.sub(worldExtent.divFloat(2)),
				worldMiddlePoint.add(worldExtent.divFloat(2))
			);

			return renderer.drawImageOnWorldAABB(imageData, aabb, sourceX, sourceY, sourceWidth, sourceHeight);
		}
	});

});


text:
int main(int argc, char *argv[]) {
  try {
    using namespace kaldi;
    typedef kaldi::int32 int32;

    const char *usage =
        "Transform GMM means with linear or affine transform\n"
        "Usage:  gmm-transform-means <transform-matrix> <model-in> "
        "<model-out>\n"
        "e.g.: gmm-transform-means 2.mat 2.mdl 3.mdl\n";

    bool binary = true;  // write in binary if true.

    ParseOptions po(usage);
    po.Register("binary", &binary, "Write output in binary mode");

    po.Read(argc, argv);

    if (po.NumArgs() != 3) {
      po.PrintUsage();
      exit(1);
    }

    std::string mat_rxfilename = po.GetArg(1),
                model_in_rxfilename = po.GetArg(2),
                model_out_wxfilename = po.GetArg(3);

    Matrix<BaseFloat> mat;
    ReadKaldiObject(mat_rxfilename, &mat);

    AmDiagGmm am_gmm;
    TransitionModel trans_model;
    {
      bool binary_read;
      Input ki(model_in_rxfilename, &binary_read);
      trans_model.Read(ki.Stream(), binary_read);
      am_gmm.Read(ki.Stream(), binary_read);
    }

    int32 dim = am_gmm.Dim();
    if (mat.NumRows() != dim)
      KALDI_ERR << "Transform matrix has " << mat.NumRows()
                << " rows but "
                   "model has dimension " << am_gmm.Dim();
    if (mat.NumCols() != dim && mat.NumCols() != dim + 1)
      KALDI_ERR << "Transform matrix has " << mat.NumCols()
                << " columns but "
                   "model has dimension " << am_gmm.Dim()
                << " (neither a linear nor an "
                   "affine transform";

    for (int32 i = 0; i < am_gmm.NumPdfs(); i++) {
      DiagGmm &gmm = am_gmm.GetPdf(i);

      Matrix<BaseFloat> means;
      gmm.GetMeans(&means);
      Matrix<BaseFloat> new_means(means.NumRows(), means.NumCols());
      if (mat.NumCols() == dim) {  // linear case
        // Right-multiply means by mat^T (equivalent to left-multiplying each
        // row by mat).
        new_means.AddMatMat(1.0, means, kNoTrans, mat, kTrans, 0.0);
      } else {  // affine case
        Matrix<BaseFloat> means_ext(means.NumRows(), means.NumCols() + 1);
        means_ext.Set(1.0);  // set all elems to 1.0
        SubMatrix<BaseFloat> means_part(means_ext, 0, means.NumRows(), 0,
                                        means.NumCols());
        means_part.CopyFromMat(means);  // copy old part...
        new_means.AddMatMat(1.0, means_ext, kNoTrans, mat, kTrans, 0.0);
      }
      gmm.SetMeans(new_means);
      gmm.ComputeGconsts();
    }

    {
      Output ko(model_out_wxfilename, binary);
      trans_model.Write(ko.Stream(), binary);
      am_gmm.Write(ko.Stream(), binary);
    }
    KALDI_LOG << "Written model to " << model_out_wxfilename;
    return 0;
  } catch (const std::exception &e) {
    std::cerr << e.what() << '\n';
    return -1;
  }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Splicer.Renderer
{
    public static class NativeMethods
    {
        [DllImport("Kernel32.dll", EntryPoint = "RtlMoveMemory")]
        internal static extern void CopyMemory(IntPtr Destination, IntPtr Source,
                                               [MarshalAs(UnmanagedType.U4)] uint Length);
    }
}


text:
<?php

namespace ReceiptValidator\iTunes;

use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\GuzzleException;
use InvalidArgumentException;
use ReceiptValidator\RunTimeException;

class Validator
{
    const ENDPOINT_SANDBOX = 'https://sandbox.itunes.apple.com';
    const ENDPOINT_PRODUCTION = 'https://buy.itunes.apple.com';

    /**
     * endpoint url.
     *
     * @var string
     */
    protected $endpoint;

    /**
     * Whether to exclude old transactions.
     *
     * @var bool
     */
    protected $exclude_old_transactions = false;

    /**
     * itunes receipt data, in base64 format.
     *
     * @var string|null
     */
    protected $receipt_data;

    /**
     * The shared secret is a unique code to receive your In-App Purchase receipts.
     * Without a shared secret, you will not be able to test or offer your automatically
     * renewable In-App Purchase subscriptions.
     *
     * @var string|null
     */
    protected $shared_secret;

    /**
     * Guzzle http client.
     *
     * @var HttpClient
     */
    protected $client;

    /**
     * request options.
     *
     * @var array
     */
    protected $request_options = [];

    /**
     * Validator constructor.
     *
     * @param string $endpoint
     *
     * @throws InvalidArgumentException
     */
    public function __construct(string $endpoint = self::ENDPOINT_PRODUCTION)
    {
        $this->setEndpoint($endpoint);
    }

    /**
     * Get receipt data.
     *
     * @return string|null
     */
    public function getReceiptData(): ?string
    {
        return $this->receipt_data;
    }

    /**
     * Set receipt data, either in base64, or in json.
     *
     * @param string|null $receipt_data
     *
     * @return $this
     */
    public function setReceiptData(?string $receipt_data = null): self
    {
        if (strpos($receipt_data, '{') !== false) {
            $this->receipt_data = base64_encode($receipt_data);
        } else {
            $this->receipt_data = $receipt_data;
        }

        return $this;
    }

    /**
     * @return string|null
     */
    public function getSharedSecret(): ?string
    {
        return $this->shared_secret;
    }

    /**
     * @param string|null $shared_secret
     *
     * @return $this
     */
    public function setSharedSecret(?string $shared_secret = null): self
    {
        $this->shared_secret = $shared_secret;

        return $this;
    }

    /**
     * get endpoint.
     *
     * @return string
     */
    public function getEndpoint(): string
    {
        return $this->endpoint;
    }

    /**
     * @param string $endpoint
     *
     * @throws InvalidArgumentException
     *
     * @return $this
     */
    public function setEndpoint(string $endpoint): self
    {
        if ($endpoint !== self::ENDPOINT_PRODUCTION && $endpoint !== self::ENDPOINT_SANDBOX) {
            throw new InvalidArgumentException("Invalid endpoint '{$endpoint}'");
        }
        $this->endpoint = $endpoint;

        return $this;
    }

    /**
     * Get exclude old transactions.
     *
     * @return bool
     */
    public function getExcludeOldTransactions(): bool
    {
        return $this->exclude_old_transactions;
    }

    /**
     * Set exclude old transactions.
     *
     * @param bool $exclude
     *
     * @return Validator
     */
    public function setExcludeOldTransactions(bool $exclude): self
    {
        $this->exclude_old_transactions = $exclude;

        return $this;
    }

    /**
     * Get Client Request Options.
     *
     * @return array
     */
    public function getRequestOptions(): array
    {
        return $this->request_options;
    }

    /**
     * Set Client Options.
     *
     * @param array $request_options
     *
     * @return Validator
     */
    public function setRequestOptions(array $request_options): self
    {
        $this->request_options = $request_options;

        return $this;
    }

    /**
     * Get Guzzle client config.
     *
     * @return array
     */
    protected function getClientConfig(): array
    {
        $base_uri = ['base_uri' => $this->endpoint];

        return array_merge($this->request_options, $base_uri);
    }

    /**
     * Returns the Guzzle client.
     *
     * @return HttpClient
     */
    protected function getClient(): HttpClient
    {
        if ($this->client === null) {
            $this->client = new HttpClient($this->getClientConfig());
        }

        return $this->client;
    }

    /**
     * Prepare request data (json).
     *
     * @return string
     */
    protected function prepareRequestData(): string
    {
        $request = [
            'receipt-data'             => $this->getReceiptData(),
            'exclude-old-transactions' => $this->getExcludeOldTransactions(),
        ];

        if ($this->shared_secret !== null) {
            $request['password'] = $this->shared_secret;
        }

        return json_encode($request);
    }

    /**
     * @param null|string $receipt_data
     * @param null|string $shared_secret
     *
     * @throws RunTimeException
     * @throws GuzzleException
     *
     * @return ResponseInterface
     */
    public function validate(?string $receipt_data = null, ?string $shared_secret = null): ResponseInterface
    {
        if ($receipt_data !== null) {
            $this->setReceiptData($receipt_data);
        }

        if ($shared_secret !== null) {
            $this->setSharedSecret($shared_secret);
        }

        $client = $this->getClient();

        return $this->sendRequestUsingClient($client);
    }

    /**
     * @param HttpClient $client
     *
     * @throws RunTimeException
     * @throws GuzzleException
     *
     * @return ProductionResponse|SandboxResponse
     */
    private function sendRequestUsingClient(HttpClient $client)
    {
        $baseUri = (string) $client->getConfig('base_uri');

        $httpResponse = $client->request('POST', '/verifyReceipt', ['body' => $this->prepareRequestData()]);

        if ($httpResponse->getStatusCode() !== 200) {
            throw new RunTimeException('Unable to get response from itunes server');
        }

        $decodedBody = json_decode($httpResponse->getBody(), true);

        if ($baseUri === self::ENDPOINT_PRODUCTION) {
            $response = new ProductionResponse($decodedBody);

            // on a 21007 error, retry the request in the sandbox environment
            // these are receipts from the Apple review team
            if ($response->getResultCode() === ResponseInterface::RESULT_SANDBOX_RECEIPT_SENT_TO_PRODUCTION) {
                $config = array_merge($this->getClientConfig(), ['base_uri' => self::ENDPOINT_SANDBOX]);
                $client = new HttpClient($config);

                return $this->sendRequestUsingClient($client);
            }
        } else {
            $response = new SandboxResponse($decodedBody);
        }

        return $response;
    }
}


text:
module Poodle
  module ActionView
    # This module creates Bootstrap wrappers around basic View Tags
    module ThemeHelper
      # theme_fa_icon('plus')
      #
      # theme_fa_icon('plus', 'lg')
      #
      def theme_fa_icon(icon_text, size="")
        size_class = %w{lg 2x 3x 4x 5x}.include?(size.strip) ? " fa-#{size.strip}" : ""
        ""
      end

      # theme_button_text('New Project')
      #  New Project
      def theme_button_text(text)
        " #{text}"
      end

      # theme_button is used to create poodle like buttons which has built in classes and icons
      # e.g:
      #   theme_button('New Project', 'plus', new_admin_project_path)
      # The above is equivalent to
      #   link_to raw(" New Project"), new_admin_project_path, :class=>"btn btn-primary pull-right ml-5", :remote=>true
      # And produces the following html
      #    New Project
      def theme_button(text, icon, url, options={})
        options.reverse_merge!(
          method: :get,
          remote: true,
          btn_type: :primary,
          btn_size: :md,
          classes: "pull-right ml-5 mb-5",
          data: {}
        )
        display_content = raw(theme_fa_icon(icon)+theme_button_text(text))
        link_to(display_content, url, :class=>"btn btn-#{options[:btn_type]} btn-#{options[:btn_size]} #{options[:classes]}", :remote=>options[:remote], method: options[:method], data: options[:data])
      end

      # Example
      #   theme_edit_button(edit_admin_project_path(@project))
      # is equivalent to:
      # ---------------------------
      # link_to raw(" Edit"), edit_admin_project_path(@project), :class=>"btn btn-default btn-xs pull-right ml-10", :remote=>true %>
      def theme_edit_button(url, options={})
        options.reverse_merge!(
          text: "Edit",
          icon: "edit",
          method: :get,
          remote: true,
          btn_type: :default,
          btn_size: :xs,
          classes: "pull-right ml-10"
        )
        theme_button(options[:text], options[:icon], url, options)
      end

      # Example
      #   theme_delete_button(admin_project_path(@project))
      # is equivalent to:
      # ---------------------------
      # link_to raw(" Delete"), admin_project_path(@project), method: :delete, data: { confirm: 'Are you sure?' }, :class=>"btn btn-danger btn-xs pull-right", :remote=>true
      def theme_delete_button(url, options={})
        options.reverse_merge!(
          text: "Delete",
          icon: "trash",
          method: :delete,
          remote: true,
          btn_type: :danger,
          btn_size: :xs,
          classes: "pull-right ml-10",
          data: { confirm: 'Are you sure?' }
        )
        theme_button(options[:text], options[:icon], url, options)
      end

      # theme_heading(heading)
      # theme_heading(heading, icon='cog')
      #

      #
Manage Projects

      #

      def theme_heading(heading, icon='')
        content_tag :div, class: "row mb-10" do
          content_tag :div, class: "fs-22 col-sm-12" do
            raw((icon ? theme_fa_icon(icon, 'lg') : "") + " #{heading}")
          end
        end
      end

      # theme_search_form is a helper to create a form to filter the results by entering a search query
      def theme_search_form(cls, url, method=:get, remote=true, text="Search!", placeholder="Search ...")
        form_for cls.new, :url => url,
              :method => method, :remote=>remote,
              :html=>{:class=>"pull-right", :style=>"margin-bottom:0px;"} do |f|
          content_tag :div, class: "input-group" do
            text_field_tag('query','', :class => 'form-control', :placeholder => placeholder) +
            content_tag(:span, class: "input-group-btn") do
              button_tag(type: 'submit', class: "btn btn-default") do
                raw(theme_fa_icon('search') +
                content_tag(:span, class: "btn-text") do
                  " " + text
                end)
              end
            end
          end
        end
      end

      def theme_drop_down(collection, method_name, **options)
        options.reverse_merge!(
          scope: :admin
        )
        content_tag(:div, class: "btn-group mt-10 mb-10", style: "width:100%;") do
          button_tag(type: 'button', :class => "btn btn-default btn-block dropdown-toggle", "data-toggle" => "dropdown") do
            raw("Choose a Project" + content_tag(:span, "", class: "caret"))
          end +
          content_tag(:ul, class: "dropdown-menu", role: "menu") do
            li_array = []
            collection.each do |item|
              li_array << content_tag(:li) do
                url = main_app.url_for([options[:scope], item])
                link_to item.send(method_name), url, :remote => true
              end
            end
            raw(li_array.join(" ")) +
            content_tag(:li, link_to_next_page(collection, 'Next Page', :remote => true)) +
            content_tag(:li, link_to_previous_page(collection, 'Previous Page', :remote => true))
          end
        end
      end

      def clear_tag(height=nil)
        height_class = height ? " cl-#{height}" : ""
        content_tag(:div, "", class: "clearfix#{height_class}")
      end

      # Example
      #   theme_paginate(@projects)
      #
      # is equivalent to:
      # ---------------------------
      #

      # <% if @projects.any? %>
      #    <%= content_tag :div, :class=>"pull-right" do %>
      #      <%= paginate @projects, :remote => true %>
      #    <% end %>
      # <% end %>
      #

      # ---------------------------
      def theme_paginate(collection)
        return "" if collection.empty?
        clear_tag(10) +
        content_tag(:div, :class=>"pull-right") do
          paginate(collection, :remote => true)
        end +
        clear_tag(10)
      end

      # Example
      #   theme_panel_message("No Results found")
      #
      # is equivalent to:
      # ---------------------------
      #

      #   "No Results found"
      #

      def theme_panel_message(message)
        content_tag(:div, class: "panel panel-default panel-message text-color-grey p-80 text-align-center", style: "height:200px;") do
          raw(message)
        end
      end

      # Example
      #   theme_panel_title("Team Members")
      #
      # is equivalent to:
      # ---------------------------
      #
Team Members

      def theme_panel_title(title, classes="")
        content_tag(:h3, title, class: "panel-title #{classes}")
      end

      # Example
      #   theme_item_title(project.name, admin_project_path(project))
      #
      # is equivalent to:
      # ---------------------------
      #  <%= link_to project.name, admin_project_path(project), :remote=>true, :class=>"text-color-blue fs-16" %>
      def theme_item_title(title, url, classes = "text-color-blue fs-16", remote=true)
        link_to(title, url, :remote=>remote, :class=>classes)
      end

      # Example
      #   theme_item_sub_title(project.client.name)
      #
      # is equivalent to:
      # ---------------------------
      #
<%= project.client.name if project.client %>

      def theme_item_sub_title(text, classes = "text-color-red fs-14")
        content_tag(:div, text, class: classes)
      end

      # Example
      #   theme_item_description(project.client.name, 120)
      #
      # is equivalent to:
      # ---------------------------
      #
<%= project.client.description %>

      def theme_item_description(text, limit=120, classes = "text-color-grey fs-12")
        description = scrap_word(text, limit)
        content_tag(:div, description, class: classes)
      end

      def theme_detail_box(collection, **options)
        options.reverse_merge!(
          show_partial: "show",
          new_partial: "form",
          edit_partial: "form",
          index_partial: "show",
        )
        case params[:action]
        when "show"
          render partial: options[:show_partial]
        when "new"
          render partial: options[:new_partial]
        when "edit"
          render partial: options[:edit_partial]
        when "index"
          collection.empty? ? (theme_panel_message(I18n.translate("forms.no_results"))) : render(partial: options[:index_partial])
        else
          theme_panel_message(I18n.translate("forms.no_results"))
        end
      end

      # Example
      #   theme_more_widget(object, data_columns=[:id, :created_at, :updated_at], super_admin = true)
      # is equivalent to:
      # ---------------------------
      # <% if @current_user.is_super_admin? %>
      #  <%= render :partial => "widgets/more_details", :locals=>{
      #                        :data_model => @project,
      #                        :data_columns => [:id, :created_at, :updated_at],
      #                        :heading => "Technical Details",
      #                        :display_footer => false} %>
      # <% end %>
      def theme_more_widget(object, **options)
        options.reverse_merge!(
          data_columns: [:id, :created_at, :updated_at],
          super_admin: false,
          heading: "Technical Details"
        )
        display = options[:super_admin] ? @current_user.is_super_admin? : true
        render(:partial => "widgets/more_details",
                    :locals=>{:data_model => object,
                              :data_columns => options[:data_columns],
                              :heading => options[:heading],
                              :display_footer => false}) if display
      end

      # Example
      #   theme_panel_heading(@project.name)
      # is equivalent to:
      # ---------------------------
      #
<%= @project.name %>

      def theme_panel_heading(text, classes="fs-24 text-color-green")
        content_tag(:div, text, class: classes)
      end

      # Example
      #   theme_panel_sub_heading(@project.name, admin_client_path(@project.client))
      # is equivalent to:
      # ---------------------------
      # link_to(@project.client.name, admin_client_path(@project.client), class: "fs-16 text-color-red")
      def theme_panel_sub_heading(text, url, classes="fs-16 text-color-red")
        link_to(text, url, class: classes)
      end

      # Example
      #   theme_panel_description(@project.pretty_url, "fs-14")
      #   theme_panel_description(@project.description, "fs-14 mt-10")
      # is equivalent to:
      # ---------------------------
      #
<%= @project.pretty_url %>

      #
<%= @project.description %>

      def theme_panel_description(text, classes="fs-14")
        content_tag(:div, text, class: classes)
      end

    end
  end
end