text:
var util = require('util')
  , events = require('events')
  , http = require('http')
  , crypto = require('crypto')
  , Options = require('options')
  , WebSocket = require('./WebSocket')
  , Extensions = require('./Extensions')
  , PerMessageDeflate = require('./PerMessageDeflate')
  , tls = require('tls')
  , url = require('url');

/**
 * WebSocket Server implementation
 */

function WebSocketServer(options, callback) {
  if (this instanceof WebSocketServer === false) {
    return new WebSocketServer(options, callback);
  }

  events.EventEmitter.call(this);

  options = new Options({
    host: '0.0.0.0',
    port: null,
    server: null,
    verifyClient: null,
    handleProtocols: null,
    path: null,
    noServer: false,
    disableHixie: false,
    clientTracking: true,
    perMessageDeflate: true
  }).merge(options);

  if (!options.isDefinedAndNonNull('port') && !options.isDefinedAndNonNull('server') && !options.value.noServer) {
    throw new TypeError('`port` or a `server` must be provided');
  }

  var self = this;

  if (options.isDefinedAndNonNull('port')) {
    this._server = http.createServer(function (req, res) {
      var body = http.STATUS_CODES[426];
      res.writeHead(426, {
        'Content-Length': body.length,
        'Content-Type': 'text/plain'
      });
      res.end(body);
    });
    this._server.allowHalfOpen = false;
    this._server.listen(options.value.port, options.value.host, callback);
    this._closeServer = function() { if (self._server) self._server.close(); };
  }
  else if (options.value.server) {
    this._server = options.value.server;
    if (options.value.path) {
      // take note of the path, to avoid collisions when multiple websocket servers are
      // listening on the same http server
      if (this._server._webSocketPaths && options.value.server._webSocketPaths[options.value.path]) {
        throw new Error('two instances of WebSocketServer cannot listen on the same http server path');
      }
      if (typeof this._server._webSocketPaths !== 'object') {
        this._server._webSocketPaths = {};
      }
      this._server._webSocketPaths[options.value.path] = 1;
    }
  }
  if (this._server) this._server.once('listening', function() { self.emit('listening'); });

  if (typeof this._server != 'undefined') {
    this._server.on('error', function(error) {
      self.emit('error', error)
    });
    this._server.on('upgrade', function(req, socket, upgradeHead) {
      //copy upgradeHead to avoid retention of large slab buffers used in node core
      var head = new Buffer(upgradeHead.length);
      upgradeHead.copy(head);

      self.handleUpgrade(req, socket, head, function(client) {
        self.emit('connection'+req.url, client);
        self.emit('connection', client);
      });
    });
  }

  this.options = options.value;
  this.path = options.value.path;
  this.clients = [];
}

/**
 * Inherits from EventEmitter.
 */

util.inherits(WebSocketServer, events.EventEmitter);

/**
 * Immediately shuts down the connection.
 *
 * @api public
 */

WebSocketServer.prototype.close = function(callback) {
  // terminate all associated clients
  var error = null;
  try {
    for (var i = 0, l = this.clients.length; i < l; ++i) {
      this.clients[i].terminate();
    }
  }
  catch (e) {
    error = e;
  }

  // remove path descriptor, if any
  if (this.path && this._server._webSocketPaths) {
    delete this._server._webSocketPaths[this.path];
    if (Object.keys(this._server._webSocketPaths).length == 0) {
      delete this._server._webSocketPaths;
    }
  }

  // close the http server if it was internally created
  try {
    if (typeof this._closeServer !== 'undefined') {
      this._closeServer();
    }
  }
  finally {
    delete this._server;
  }
  if(callback)
    callback(error);
  else if(error)
    throw error;
}

/**
 * Handle a HTTP Upgrade request.
 *
 * @api public
 */

WebSocketServer.prototype.handleUpgrade = function(req, socket, upgradeHead, cb) {
  // check for wrong path
  if (this.options.path) {
    var u = url.parse(req.url);
    if (u && u.pathname !== this.options.path) return;
  }

  if (typeof req.headers.upgrade === 'undefined' || req.headers.upgrade.toLowerCase() !== 'websocket') {
    abortConnection(socket, 400, 'Bad Request');
    return;
  }

  if (req.headers['sec-websocket-key1']) handleHixieUpgrade.apply(this, arguments);
  else handleHybiUpgrade.apply(this, arguments);
}

module.exports = WebSocketServer;

/**
 * Entirely private apis,
 * which may or may not be bound to a sepcific WebSocket instance.
 */

function handleHybiUpgrade(req, socket, upgradeHead, cb) {
  // handle premature socket errors
  var errorHandler = function() {
    try { socket.destroy(); } catch (e) {}
  }
  socket.on('error', errorHandler);

  // verify key presence
  if (!req.headers['sec-websocket-key']) {
    abortConnection(socket, 400, 'Bad Request');
    return;
  }

  // verify version
  var version = parseInt(req.headers['sec-websocket-version']);
  if ([8, 13].indexOf(version) === -1) {
    abortConnection(socket, 400, 'Bad Request');
    return;
  }

  // verify protocol
  var protocols = req.headers['sec-websocket-protocol'];

  // verify client
  var origin = version < 13 ?
    req.headers['sec-websocket-origin'] :
    req.headers['origin'];

  // handle extensions offer
  var extensionsOffer = Extensions.parse(req.headers['sec-websocket-extensions']);

  // handler to call when the connection sequence completes
  var self = this;
  var completeHybiUpgrade2 = function(protocol) {

    // calc key
    var key = req.headers['sec-websocket-key'];
    var shasum = crypto.createHash('sha1');
    shasum.update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
    key = shasum.digest('base64');

    var headers = [
        'HTTP/1.1 101 Switching Protocols'
      , 'Upgrade: websocket'
      , 'Connection: Upgrade'
      , 'Sec-WebSocket-Accept: ' + key
    ];

    if (typeof protocol != 'undefined') {
      headers.push('Sec-WebSocket-Protocol: ' + protocol);
    }

    var extensions = {};
    try {
      extensions = acceptExtensions.call(self, extensionsOffer);
    } catch (err) {
      abortConnection(socket, 400, 'Bad Request');
      return;
    }

    if (Object.keys(extensions).length) {
      var serverExtensions = {};
      Object.keys(extensions).forEach(function(token) {
        serverExtensions[token] = [extensions[token].params]
      });
      headers.push('Sec-WebSocket-Extensions: ' + Extensions.format(serverExtensions));
    }

    // allows external modification/inspection of handshake headers
    self.emit('headers', headers);

    socket.setTimeout(0);
    socket.setNoDelay(true);
    try {
      socket.write(headers.concat('', '').join('\r\n'));
    }
    catch (e) {
      // if the upgrade write fails, shut the connection down hard
      try { socket.destroy(); } catch (e) {}
      return;
    }

    var client = new WebSocket([req, socket, upgradeHead], {
      protocolVersion: version,
      protocol: protocol,
      extensions: extensions
    });

    if (self.options.clientTracking) {
      self.clients.push(client);
      client.on('close', function() {
        var index = self.clients.indexOf(client);
        if (index != -1) {
          self.clients.splice(index, 1);
        }
      });
    }

    // signal upgrade complete
    socket.removeListener('error', errorHandler);
    cb(client);
  }

  // optionally call external protocol selection handler before
  // calling completeHybiUpgrade2
  var completeHybiUpgrade1 = function() {
    // choose from the sub-protocols
    if (typeof self.options.handleProtocols == 'function') {
        var protList = (protocols || "").split(/, */);
        var callbackCalled = false;
        var res = self.options.handleProtocols(protList, function(result, protocol) {
          callbackCalled = true;
          if (!result) abortConnection(socket, 401, 'Unauthorized');
          else completeHybiUpgrade2(protocol);
        });
        if (!callbackCalled) {
            // the handleProtocols handler never called our callback
            abortConnection(socket, 501, 'Could not process protocols');
        }
        return;
    } else {
        if (typeof protocols !== 'undefined') {
            completeHybiUpgrade2(protocols.split(/, */)[0]);
        }
        else {
            completeHybiUpgrade2();
        }
    }
  }

  // optionally call external client verification handler
  if (typeof this.options.verifyClient == 'function') {
    var info = {
      origin: origin,
      secure: typeof req.connection.authorized !== 'undefined' || typeof req.connection.encrypted !== 'undefined',
      req: req
    };
    if (this.options.verifyClient.length == 2) {
      this.options.verifyClient(info, function(result, code, name) {
        if (typeof code === 'undefined') code = 401;
        if (typeof name === 'undefined') name = http.STATUS_CODES[code];

        if (!result) abortConnection(socket, code, name);
        else completeHybiUpgrade1();
      });
      return;
    }
    else if (!this.options.verifyClient(info)) {
      abortConnection(socket, 401, 'Unauthorized');
      return;
    }
  }

  completeHybiUpgrade1();
}

function handleHixieUpgrade(req, socket, upgradeHead, cb) {
  // handle premature socket errors
  var errorHandler = function() {
    try { socket.destroy(); } catch (e) {}
  }
  socket.on('error', errorHandler);

  // bail if options prevent hixie
  if (this.options.disableHixie) {
    abortConnection(socket, 401, 'Hixie support disabled');
    return;
  }

  // verify key presence
  if (!req.headers['sec-websocket-key2']) {
    abortConnection(socket, 400, 'Bad Request');
    return;
  }

  var origin = req.headers['origin']
    , self = this;

  // setup handshake completion to run after client has been verified
  var onClientVerified = function() {
    var wshost;
    if (!req.headers['x-forwarded-host'])
        wshost = req.headers.host;
    else
        wshost = req.headers['x-forwarded-host'];
    var location = ((req.headers['x-forwarded-proto'] === 'https' || socket.encrypted) ? 'wss' : 'ws') + '://' + wshost + req.url
      , protocol = req.headers['sec-websocket-protocol'];

    // handshake completion code to run once nonce has been successfully retrieved
    var completeHandshake = function(nonce, rest) {
      // calculate key
      var k1 = req.headers['sec-websocket-key1']
        , k2 = req.headers['sec-websocket-key2']
        , md5 = crypto.createHash('md5');

      [k1, k2].forEach(function (k) {
        var n = parseInt(k.replace(/[^\d]/g, ''))
          , spaces = k.replace(/[^ ]/g, '').length;
        if (spaces === 0 || n % spaces !== 0){
          abortConnection(socket, 400, 'Bad Request');
          return;
        }
        n /= spaces;
        md5.update(String.fromCharCode(
          n >> 24 & 0xFF,
          n >> 16 & 0xFF,
          n >> 8  & 0xFF,
          n       & 0xFF));
      });
      md5.update(nonce.toString('binary'));

      var headers = [
          'HTTP/1.1 101 Switching Protocols'
        , 'Upgrade: WebSocket'
        , 'Connection: Upgrade'
        , 'Sec-WebSocket-Location: ' + location
      ];
      if (typeof protocol != 'undefined') headers.push('Sec-WebSocket-Protocol: ' + protocol);
      if (typeof origin != 'undefined') headers.push('Sec-WebSocket-Origin: ' + origin);

      socket.setTimeout(0);
      socket.setNoDelay(true);
      try {
        // merge header and hash buffer
        var headerBuffer = new Buffer(headers.concat('', '').join('\r\n'));
        var hashBuffer = new Buffer(md5.digest('binary'), 'binary');
        var handshakeBuffer = new Buffer(headerBuffer.length + hashBuffer.length);
        headerBuffer.copy(handshakeBuffer, 0);
        hashBuffer.copy(handshakeBuffer, headerBuffer.length);

        // do a single write, which - upon success - causes a new client websocket to be setup
        socket.write(handshakeBuffer, 'binary', function(err) {
          if (err) return; // do not create client if an error happens
          var client = new WebSocket([req, socket, rest], {
            protocolVersion: 'hixie-76',
            protocol: protocol
          });
          if (self.options.clientTracking) {
            self.clients.push(client);
            client.on('close', function() {
              var index = self.clients.indexOf(client);
              if (index != -1) {
                self.clients.splice(index, 1);
              }
            });
          }

          // signal upgrade complete
          socket.removeListener('error', errorHandler);
          cb(client);
        });
      }
      catch (e) {
        try { socket.destroy(); } catch (e) {}
        return;
      }
    }

    // retrieve nonce
    var nonceLength = 8;
    if (upgradeHead && upgradeHead.length >= nonceLength) {
      var nonce = upgradeHead.slice(0, nonceLength);
      var rest = upgradeHead.length > nonceLength ? upgradeHead.slice(nonceLength) : null;
      completeHandshake.call(self, nonce, rest);
    }
    else {
      // nonce not present in upgradeHead, so we must wait for enough data
      // data to arrive before continuing
      var nonce = new Buffer(nonceLength);
      upgradeHead.copy(nonce, 0);
      var received = upgradeHead.length;
      var rest = null;
      var handler = function (data) {
        var toRead = Math.min(data.length, nonceLength - received);
        if (toRead === 0) return;
        data.copy(nonce, received, 0, toRead);
        received += toRead;
        if (received == nonceLength) {
          socket.removeListener('data', handler);
          if (toRead < data.length) rest = data.slice(toRead);
          completeHandshake.call(self, nonce, rest);
        }
      }
      socket.on('data', handler);
    }
  }

  // verify client
  if (typeof this.options.verifyClient == 'function') {
    var info = {
      origin: origin,
      secure: typeof req.connection.authorized !== 'undefined' || typeof req.connection.encrypted !== 'undefined',
      req: req
    };
    if (this.options.verifyClient.length == 2) {
      var self = this;
      this.options.verifyClient(info, function(result, code, name) {
        if (typeof code === 'undefined') code = 401;
        if (typeof name === 'undefined') name = http.STATUS_CODES[code];

        if (!result) abortConnection(socket, code, name);
        else onClientVerified.apply(self);
      });
      return;
    }
    else if (!this.options.verifyClient(info)) {
      abortConnection(socket, 401, 'Unauthorized');
      return;
    }
  }

  // no client verification required
  onClientVerified();
}

function acceptExtensions(offer) {
  var extensions = {};
  var options = this.options.perMessageDeflate;
  if (options && offer[PerMessageDeflate.extensionName]) {
    var perMessageDeflate = new PerMessageDeflate(options !== true ? options : {}, true);
    perMessageDeflate.accept(offer[PerMessageDeflate.extensionName]);
    extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
  }
  return extensions;
}

function abortConnection(socket, code, name) {
  try {
    var response = [
      'HTTP/1.1 ' + code + ' ' + name,
      'Content-type: text/html'
    ];
    socket.write(response.concat('', '').join('\r\n'));
  }
  catch (e) { /* ignore errors - we've aborted this connection */ }
  finally {
    // ensure that an early aborted connection is shut down completely
    try { socket.destroy(); } catch (e) {}
  }
}


text:
package io.fabric8.openshift.api.model.config.v1;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.fabric8.kubernetes.api.model.Container;
import io.fabric8.kubernetes.api.model.IntOrString;
import io.fabric8.kubernetes.api.model.KubernetesResource;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.LocalObjectReference;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.ObjectReference;
import io.fabric8.kubernetes.api.model.PersistentVolumeClaim;
import io.fabric8.kubernetes.api.model.PodTemplateSpec;
import io.fabric8.kubernetes.api.model.ResourceRequirements;
import io.sundr.builder.annotations.Buildable;
import io.sundr.builder.annotations.BuildableReference;
import lombok.EqualsAndHashCode;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

@JsonDeserialize(using = com.fasterxml.jackson.databind.JsonDeserializer.None.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
    "apiVersion",
    "kind",
    "metadata",
    "networkType"
})
@ToString
@EqualsAndHashCode
@Setter
@Accessors(prefix = {
    "_",
    ""
})
@Buildable(editableEnabled = false, validationEnabled = false, generateBuilderPackage = false, lazyCollectionInitEnabled = false, builderPackage = "io.fabric8.kubernetes.api.builder", refs = {
    @BuildableReference(ObjectMeta.class),
    @BuildableReference(LabelSelector.class),
    @BuildableReference(Container.class),
    @BuildableReference(PodTemplateSpec.class),
    @BuildableReference(ResourceRequirements.class),
    @BuildableReference(IntOrString.class),
    @BuildableReference(ObjectReference.class),
    @BuildableReference(LocalObjectReference.class),
    @BuildableReference(PersistentVolumeClaim.class)
})
public class NetworkMigration implements KubernetesResource
{

    @JsonProperty("networkType")
    private String networkType;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    /**
     * No args constructor for use in serialization
     *
     */
    public NetworkMigration() {
    }

    /**
     *
     * @param networkType
     */
    public NetworkMigration(String networkType) {
        super();
        this.networkType = networkType;
    }

    @JsonProperty("networkType")
    public String getNetworkType() {
        return networkType;
    }

    @JsonProperty("networkType")
    public void setNetworkType(String networkType) {
        this.networkType = networkType;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

redpajama_set_name: RedPajamaGithub


text:
macro    (pileRelativePath
          pile_relative_path__output
          pile_relative_path__reference
          pile_relative_path__input)

	set(pile_relative_path__result )

	# get a list from path components
	string (REGEX REPLACE
		"[/\\]"
		";"
		pile_relative_path__reference_l
		"${pile_relative_path__reference}")
 	string (REGEX REPLACE
		"[/\\]"
		";"
		pile_relative_path__input_l
		"${pile_relative_path__input}")

	# get lengths
	list (LENGTH
		  pile_relative_path__reference_l
		  pile_relative_path__reference_c)
	list (LENGTH
		  pile_relative_path__input_l
		  pile_relative_path__input_c)

	# common parts
	set (pile_relative_path__i 0)
	set (pile_relative_path__ok ON)
	while (pile_relative_path__ok AND
	       pile_relative_path__i LESS pile_relative_path__input_c AND
		   pile_relative_path__i LESS pile_relative_path__reference_c)

		# get the components at this index
		list (GET pile_relative_path__reference_l ${pile_relative_path__i}
		      pile_relative_path__reference_crt)
		list (GET pile_relative_path__input_l ${pile_relative_path__i}
		      pile_relative_path__input_crt)

		# if they are not the same break the loop
		if (NOT "${pile_relative_path__reference_crt}" STREQUAL "${pile_relative_path__input_crt}")
			set (pile_relative_path__ok OFF)
		else ()
			# next one
			math (EXPR
				pile_relative_path__i
				"${pile_relative_path__i} + 1")
		endif()
	endwhile()

	# pile_relative_path__i has the index of first mismatch
	# and the number of common components
	set (pile_relative_path__common ${pile_relative_path__i})

	# add ../../.. things
	while (pile_relative_path__i LESS pile_relative_path__input_c)

		if (pile_relative_path__result)
			set (pile_relative_path__result
				"../${pile_relative_path__result}")
		else ()
			set (pile_relative_path__result "..")
		endif()

		# next one
		math (EXPR
			pile_relative_path__i
			"${pile_relative_path__i} + 1")
	endwhile()

    # If enabled, this would generate relative paths that start with ./
	#if (pile_relative_path__result)
	#	set (pile_relative_path__result "${pile_relative_path__result}")
	#else ()
	#	set (pile_relative_path__result ".")
	#endif()

	set (pile_relative_path__i ${pile_relative_path__common})
	while (pile_relative_path__i LESS pile_relative_path__reference_c)

		# get the components at this index
		list (GET pile_relative_path__reference_l ${pile_relative_path__i}
		      pile_relative_path__reference_crt)

		if (pile_relative_path__result)
			set (pile_relative_path__result
					"${pile_relative_path__result}/${pile_relative_path__reference_crt}")
		else ()
			set (pile_relative_path__result
					"${pile_relative_path__reference_crt}")
		endif()

		# next one
		math (EXPR
			pile_relative_path__i
			"${pile_relative_path__i} + 1")
	endwhile()

	set (${pile_relative_path__output} "${pile_relative_path__result}")

endmacro ()

# ============================================================================


text:
/**
 * Module dependencies.
 */

var utils = require('../../../utils')
  , eyes = require('eyes')
  , async = require('async')
  , _ = require('lodash');

var EventEmitter = require('events').EventEmitter;

var Warehouse = require('../../../warehouse');
var Container = require('../../../container');

var HR = require('./hr');
/*

  Quarry.io - Workforce
  ---------------------

  Looks after a collection of workers for a stack

  There are departments:

    reception       (fixed)
    switchboard     (fixed)

    router          (fixed but re-routable)
    warehouse

  Every workforce gets at least one of these

  The fixed workers do one job on the network

  The warehouse workers are the variable network element

  The routers the the breadboard of the network (the wires are real!)

*/

module.exports = function(options){

  if(!options){
    throw new Error('Workforce requires some options');
  }

  /*

    hire workers is the initial provision of workers at the start

  */
  if(!options.database){
    throw new Error('Job List requires a database');
  }

  var database = options.database;

  var container = Container.new('workforce').id(options.id);

  var hr = HR({
    id:options.id
  })

  var workforce = _.extend({
    container:container,

    /*

      this gets the initial workforce loaded from whatever
      function has been passed in to provide it

    */
    prepare:function(done){

      var self = this;

      this.emit('hire_workforce', function(error, initialstaff){

        if(initialstaff.find('building').count()<=0){
          throw new Error('a workforce needs at least one building to operate');
        }

        if(initialstaff.find('worker').count()<=0){
          throw new Error('a workforce needs at least one worker to operate');
        }

        container.append(initialstaff);

        /*

          inject the worker configuration from the system config

          the user can change this later but this is the starting point

        */

        initialstaff
          .find('janitor')
          .attr('config', options.janitorconfig)

        initialstaff
          .find('worker')
          .attr('config', options.workerconfig)

        /*

          now get the workforce uploaded to the deployment db

        */
        database
          .append(container)
          .title('Appending workforce to deployment database')
          .ship(function(){
            done();
          })

      })

      return this;
    },

    /*

      this gets all of the workers started using whatever function
      has been provided to do so

    */
    start_work:function(done){

      var self = this;
      /*

        get the workers booted and ready

      */
      async.forEach(container.find('building').containers(), function(building, nextbuilding){

        /*

          for each building we boot a janitor and then get the workers started

        */
        async.series([

          /*

            get the Janitor in before we get workers to arrive

          */
          function(next){

            async.forEach(building.find('janitor').containers(), function(janitor, nextjanitor){

              self.emit('start_janitor', {
                janitor:janitor,
                building:building
              }, function(error, status){

                hr.add_janitor(janitor);
                nextjanitor();
              })

            }, next)
          },

          /*

            loop each worker and get them started

          */
          function(next){
            async.forEach(building.find('worker').containers(), function(worker, nextworker){

              self.emit('start_worker', {
                worker:worker,
                building:building
              }, function(error, status){

                hr.add_worker(worker);
                nextworker();
              })

            }, next)
          }
        ], nextbuilding)

      }, done)
    }

  }, options)

  _.extend(workforce, EventEmitter.prototype);

  return workforce;
}


text:
"""
Created on Sun Sep 17 09:27:31 2017

@author: dariocorral
"""

import pandas as pd
from datetime import timedelta
from tickers import Tickers
from hourOffset import Hour

class Candles(object):
    """
    OANDA Historical Rates ready to use with Pandas
    """

    def __init__(self):

        self.__hour = Hour()
        self.__tickers = Tickers()

    def dataframe(self,periods, granularity,sundayCandle, *ticker):
        """
        OANDA Historical Rates

        :param periods: number of periods
        :type: int

        :paramm granularity: OANDA timeframes:
                  "S5" - 5 seconds
                  "S10" - 10 seconds
                  "S15" - 15 seconds
                  "S30" - 30 seconds
                  "M1" - 1 minute
                  "M2" - 2 minutes
                  "M3" - 3 minutes
                  "M4" - 4 minutes
                  "M5" - 5 minutes
                  "M10" - 10 minutes
                  "M15" - 15 minutes
                  "M30" - 30 minutes
                  "H1" - 1 hour
                  "H2" - 2 hours
                  "H3" - 3 hours
                  "H4" - 4 hours
                  "H6" - 6 hours
                  "H8" - 8 hours
                  "H12" - 12 hours
                  "D" - 1 Day
                  "W" - 1 Week
                  "M" - 1 Month
        :type: string

        :param sundayCandle: True -> Sunday Candles included
                             False -> No Sunday Candles
        :type : bool

        :param ticker: required instruments format OANDA API
        :type: str, tuple or list

        :return: dataFrame object

        """
        #Define empty dataframe
        df = pd.DataFrame()

        for instr in ticker:

            histRates =  self.__tickers._oanda_api.get_history(count =
                              int(periods * 1.2), instrument= instr,
                              candleFormat = 'midpoint',granularity= granularity,
                              dailyAlignment= (self.__hour.hour_offset_calculate(
                                                  6 ,
                                               self.__hour.offset_NY_GMT)),
                              weeklyAlignment='Monday')

            #From dict to dataframe
            histRates = histRates.get('candles')
            histRates = pd.DataFrame.from_dict(histRates)
            histRates['ticker'] = instr
            histRates['time'] = pd.to_datetime(histRates['time'])

            #Apply GMT_hours_offset to local time
            histRates['time'] += timedelta(hours =
                             self.__hour.offset_local_GMT)
            histRates.set_index ('time', inplace = True)

            #Sunday candle filter
            if sundayCandle == False:

                histRates['Weekday'] = histRates.index.weekday
                histRates = histRates.loc[histRates['Weekday'] != 6]
                histRates = histRates.tail(periods)

            else:

                histRates = histRates.tail(periods)

            #Daily and weekly granularity in date format without hours
            if granularity == 'D' or granularity == 'W':

                histRates.index = histRates.index.date

            #Columns definition
            histRates= histRates[['ticker','openMid','highMid','lowMid',
                                  'closeMid','volume','complete']]

            histRates.columns = ('ticker','open','high','low','close','volume',
                    'complete')

            df = df.append(histRates)

        return df


text:
<?php

//matriz mapa / contas / ajeitamento.

include('minimap.php');

$template = <<<THEVERYENDOFYOU

	{{topnav}}

Use os botões de direção para se movimentar:

$minimap
Ver Mapa Completo

<form action="index.php?do=move" method="post">

<input name="north" type="submit" value="Norte" />

<input name="west" type="submit" value="Oeste" /><input name="east" type="submit" value="Leste" />

<input name="south" type="submit" style="width:53px" value="Sul" />

</form>

Latitude: {{latitude}}

Longitude: {{longitude}}

{{pergaminho}}	{{diamante}}

Seu browser não suporta frames.

Atualizar Histórico.

{{currenttown}}
Viajar Para:

{{townslist}}

{{forumslink}}
{{adminlink}}
Funções com Jogadores:

Realizar uma Troca

Realizar um Duelo

Funções nas Cidades:

Enviar Ryou

Enviar Item

Acessar o Banco

Outras Funções:

Visualizar Personagem

Rank

Chat

Mudar Senha

Sair

Ajuda

{{pmsnovas}}

Ler Minhas Mensagens

Enviar uma Mensagem

THEVERYENDOFYOU;
?>


text:
package ContactsSQL;

require Exporter;
@ISA       = qw(Exporter);
@EXPORT    = qw(getContactsSQL);
@EXPORT_OK = qw(getContactsSQL);

use strict;
use lib "..","../..";

sub getContactsSQL {
    my (%params) = @_;

    my $assoc_id         = $params{'associd'}          || 0;
    my $club_id          = $params{'clubid'}           || 0;
    my $getregistrations = $params{'getregistrations'} || 0;
    my $getpayments      = $params{'getpayments'}      || 0;
    my $getprimary       = $params{'getprimary'}       || 0;
    my $getClearances 	 = $params{'getclearances'}       || 0;
    my $sql = '';

    #if getting a list of any sort, an assoc should always be provided.
    if ($assoc_id or $club_id or $getregistrations or $getpayments or $getprimary) {
        $sql .= q[SELECT * FROM tblContacts WHERE 1=1];
        $sql .= q[ AND intAssocID=?]         if $assoc_id > 0;
        $sql .= q[ AND intClubID=?]; #clubid needed even if 0.
        $sql .= q[ AND intFnPayments=?]      if $getpayments;
        $sql .= q[ AND intFnRegistrations=?] if $getregistrations;
        $sql .= q[ AND intPrimaryContact=?]  if $getprimary;
       	$sql .= q[ AND intFnClearances=?]  if $getClearances;
	 $sql .= q[ ORDER BY intContactID];
    }
    else {
        $sql .= qq[SELECT * FROM tblContacts WHERE intContactID=? LIMIT 1];
    }
    return $sql;
}

1;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Splash" parent="android:Theme">
    <item name="android:windowBackground">@drawable/splash</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
  </style>

  <style name="Theme.Main" parent="android:Theme">
  <item name="android:windowBackground">@drawable/img_background</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:editTextColor">@color/black_color</item>
    <item name="android:textColorPrimary">@color/black_color</item>
  </style>
</resources>


text:
<?php

namespace Google\Service\ShoppingContent;

class DatafeedFormat extends \Google\Model
{
  /**
   * @var string
   */
  public $columnDelimiter;
  /**
   * @var string
   */
  public $fileEncoding;
  /**
   * @var string
   */
  public $quotingMode;

  /**
   * @param string
   */
  public function setColumnDelimiter($columnDelimiter)
  {
    $this->columnDelimiter = $columnDelimiter;
  }
  /**
   * @return string
   */
  public function getColumnDelimiter()
  {
    return $this->columnDelimiter;
  }
  /**
   * @param string
   */
  public function setFileEncoding($fileEncoding)
  {
    $this->fileEncoding = $fileEncoding;
  }
  /**
   * @return string
   */
  public function getFileEncoding()
  {
    return $this->fileEncoding;
  }
  /**
   * @param string
   */
  public function setQuotingMode($quotingMode)
  {
    $this->quotingMode = $quotingMode;
  }
  /**
   * @return string
   */
  public function getQuotingMode()
  {
    return $this->quotingMode;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DatafeedFormat::class, 'Google_Service_ShoppingContent_DatafeedFormat');


text:
iframe {
  width: 100%;
  background-color: transparent;
  border: none; }


text:
package org.apereo.cas.support.saml.web.idp.profile.slo;

import org.apereo.cas.authentication.principal.WebApplicationService;
import org.apereo.cas.logout.slo.DefaultSingleLogoutServiceLogoutUrlBuilder;
import org.apereo.cas.logout.slo.SingleLogoutUrl;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.ServicesManager;
import org.apereo.cas.support.saml.services.SamlRegisteredService;
import org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade;
import org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.web.UrlValidator;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.saml2.metadata.SingleLogoutService;

import java.util.Collection;

/**
 * This is {@link SamlIdPSingleLogoutServiceLogoutUrlBuilder}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
@Slf4j
public class SamlIdPSingleLogoutServiceLogoutUrlBuilder extends DefaultSingleLogoutServiceLogoutUrlBuilder {
    /**
     * Property to indicate the binding for the saml logout profile.
     */
    public static final String PROPERTY_NAME_SINGLE_LOGOUT_BINDING = "singleLogoutSamlBinding";

    /**
     * The Services manager.
     */
    protected final ServicesManager servicesManager;

    /**
     * The Saml registered service caching metadata resolver.
     */
    protected final SamlRegisteredServiceCachingMetadataResolver samlRegisteredServiceCachingMetadataResolver;

    public SamlIdPSingleLogoutServiceLogoutUrlBuilder(final ServicesManager servicesManager,
                                                      final SamlRegisteredServiceCachingMetadataResolver resolver,
                                                      final UrlValidator urlValidator) {
        super(urlValidator);
        this.servicesManager = servicesManager;
        this.samlRegisteredServiceCachingMetadataResolver = resolver;
    }

    @Override
    public Collection<SingleLogoutUrl> determineLogoutUrl(final RegisteredService registeredService,
                                                          final WebApplicationService singleLogoutService) {
        try {
            if (registeredService instanceof SamlRegisteredService) {
                val location = buildLogoutUrl(registeredService, singleLogoutService);
                if (location != null) {
                    LOGGER.debug("Final logout URL built for [{}] is [{}]", registeredService, location);
                    return CollectionUtils.wrap(location);
                }
            }
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        LOGGER.debug("Service [{}] is not a SAML service, or its logout url could not be determined", registeredService);
        return super.determineLogoutUrl(registeredService, singleLogoutService);
    }

    private SingleLogoutUrl buildLogoutUrl(final RegisteredService registeredService, final WebApplicationService singleLogoutService) {
        LOGGER.trace("Building logout url for SAML service [{}]", registeredService);

        val entityID = singleLogoutService.getId();
        LOGGER.trace("Located entity id [{}]", entityID);

        val samlRegisteredService = (SamlRegisteredService) registeredService;
        val adaptorRes = SamlRegisteredServiceServiceProviderMetadataFacade.get(samlRegisteredServiceCachingMetadataResolver, samlRegisteredService, entityID);
        if (adaptorRes.isEmpty()) {
            LOGGER.warn("Cannot find metadata linked to [{}]", entityID);
            return null;
        }
        val adaptor = adaptorRes.get();

        var sloService = adaptor.getSingleLogoutService(SAMLConstants.SAML2_POST_BINDING_URI);
        if (sloService != null) {
            return finalizeSingleLogoutUrl(sloService, samlRegisteredService);
        }
        sloService = adaptor.getSingleLogoutService(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        if (sloService != null) {
            return finalizeSingleLogoutUrl(sloService, samlRegisteredService);
        }
        sloService = adaptor.getSingleLogoutService(SAMLConstants.SAML2_SOAP11_BINDING_URI);
        if (sloService != null) {
            return finalizeSingleLogoutUrl(sloService, samlRegisteredService);
        }
        LOGGER.warn("Cannot find SLO service in metadata for entity id [{}]", entityID);
        return null;
    }

    private static SingleLogoutUrl finalizeSingleLogoutUrl(final SingleLogoutService sloService, final SamlRegisteredService service) {
        val location = StringUtils.isBlank(sloService.getResponseLocation()) ? sloService.getLocation() : sloService.getResponseLocation();
        val url = new SingleLogoutUrl(location, service.getLogoutType());
        url.getProperties().put(PROPERTY_NAME_SINGLE_LOGOUT_BINDING, sloService.getBinding());
        return url;
    }
}


text:
"""
    Biothings Test Helpers

    There are two types of test classes that provide utilities to
    three types of test cases, developed in the standalone apps.

    The two types of test classes are:
        BiothingsWebTest, which targets a running web server.
        BiothingsWebAppTest, which targets a web server config file.

    To further illustrate, for any biothings web applications, it
    typically conforms to the following architectures:

    Layer 3: A web server that implements the behaviors defined below.
    Layer 2: A config file that defines how to serve data from ES.
    Layer 1: An Elasticsearch server with data.

    And for the two types of test classes, to explain their differences
    in the context of the layered design described above:
        BiothingsWebTest targets an existing Layer 3 endpoint.
        BiothingsWebAppTest targets layer 2 and runs its own layer 3.
        Note no utility is provided to directly talk to layer 1.

    The above discussed the python structures provided as programming
    utilities, on the other hand, there are three types of use cases,
    or testing objectives:
        L3 Data test, which is aimed to test the data integrity of an API.
            It subclasses BiothingsWebTest and ensures all layers working.
            The data has to reside in elasticsearch already.
        L3 Feature test, which is aimed to test the API implementation.
            It makes sure the settings in config file is reflected.
            These tests work on production data and require constant
            updates to keep the test cases in sync with the actual data.
            These test cases subclass BiothingsWebTest as well and asl
            require existing production data in elasticsearch.
        L2 Feature test, doing basically the same things as above but uses
            a small set of data that it ingests into elasticsearch.
            This is a lightweight test for development and automated testings
            for each new commit. It comes with data it will ingest in ES
            and does not require any existing data setup to run.

    To illustrate the differences in a chart:
    +--------------+---------------------+-----------------+-------------+---------------------------+
    | Objectives   | Class               | Test Target     | ES Has Data | Automated Testing Trigger |
    +--------------+---------------------+-----------------+-------------+---------------------------+
    | L3 Data Test | BiothingsWebTest    | A Running API   | Yes         | Data Release              |
    +--------------+---------------------+-----------------+-------------+---------------------------+
    | L3 Feature T.| BiothingsWebTest    | A Running API   | Yes         | Data Release & New Commit |
    +--------------+---------------------+-----------------+-------------+---------------------------+
    | L2 Feature T.| BiothingsWebAppTest | A config module | No*         | New Commit                |
    +--------------+---------------------+-----------------+-------------+---------------------------+
    * For L2 Feature Test, data is defined in the test cases and will be automatically ingested into
      Elasticsearch at the start of the testing and get deleted after testing finishes. The other
      two types of testing require existing production data on the corresponding ES servers.

    In development, it is certainly possible for a particular test case
    to fall under multiple test types, then the developer can use proper
    inheritance structures to avoid repeating the specific test case.

    In terms of naming conventions, sometimes the L3 tests are grouped
    together and called remote tests, as they mostly target remote servers.
    And the L2 tests are called local tests, as they starts a local server.

    L3 Envs:

    TEST_SCHEME
    TEST_PREFIX
    TEST_HOST
    TEST_CONF

    L2 Envs:

    TEST_KEEPDATA
    < Config Module Override >

"""
import glob
import inspect
import json
import os
from functools import partial
from typing import Optional, Union

import pytest
import requests
import urllib3
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

from biothings.utils.common import traverse
from biothings.web.launcher import BiothingsAPI
from biothings.web.settings import configs
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase

class BiothingsWebTest:
    # relative path parsing configuration
    scheme = 'http'
    prefix = 'v1'
    host = ''

    def request(self, path, method='GET', expect=200, **kwargs):
        """
        Use requests library to make an HTTP request.
        Ensure path is translated to an absolute path.
        Conveniently check if status code is as expected.
        """
        url = self.get_url(path)
        res = requests.request(method, url, **kwargs)
        assert res.status_code == expect, res.text

        return res

    def get_url(self, path):
        """
        Try best effort to get a full url to make a request.
        Return an absolute url when class var 'host' is defined.
        If not, return a path relative to the host root.
        """
        scheme = os.getenv("TEST_SCHEME", self.scheme)
        prefix = os.getenv("TEST_PREFIX", self.prefix).strip('/')
        host = os.getenv("TEST_HOST", self.host).strip('/')

        # already an absolute path
        if path.lower().startswith(("http://", "https://")):
            return path

        # path standardization
        if not path.startswith('/'):
            if prefix:  # append prefix
                path = '/'.join((prefix, path))
            path = '/' + path

        # host standardization
        if host:
            path = f"{scheme}://{host}{path}"

        return path

    def query(self, method='GET', endpoint='query', hits=True, data=None, json=None, **kwargs):
        """
        Make a query and assert positive hits by default.
        Assert zero hit when hits is set to False.
        """

        if method == 'GET':
            res = self.request(
                endpoint, params=kwargs,
                data=data, json=json).json()

            assert bool(res.get('hits')) == hits
            return res

        if method == 'POST':
            res = self.request(
                endpoint, method=method,
                params=kwargs, data=data,
                json=json).json()

            for item in res:  # list
                if "_id" not in item:
                    _hits = False
                    break
            else:
                _hits = bool(res)
            assert _hits is hits
            return res

        raise ValueError('Invalid Request Method.')

    @staticmethod
    def msgpack_ok(packed_bytes):
        """ Load msgpack into a dict """
        try:
            import msgpack
        except ImportError:
            pytest.skip('Msgpack is not installed.')
        try:
            dic = msgpack.unpackb(packed_bytes)
        except BaseException:  # pylint: disable=bare-except
            assert False, 'Not a valid Msgpack binary.'
        return dic

    @staticmethod
    def value_in_result(value, result: Union[dict, list], key: str,
                        case_insensitive: bool = False) -> bool:
        """
        Check if value is in result at specific key

        Elasticsearch does not care if a field has one or more values (arrays),
        so you may get a search with multiple values in one field.
        You were expecting a result of type T but now you have a List[T] which
        is bad.
        In testing, usually any one element in the list eq. to the value you're
        looking for, you don't really care which.
        This helper function checks if the value is at a key, regardless
        of the details of nesting, so you can just do this:
            assert self.value_in_result(value, result, 'where.it.should.be')

        Caveats:
        case_insensitive only calls .lower() and does not care about locale/
        unicode/anything

        Args:
            value: value to look for
            result: dict or list of input, most likely from the APIs
            key: dot delimited key notation
            case_insensitive: for str comparisons, invoke .lower() first
        Returns:
            boolean indicating whether the value is found at the key
        Raises:
            TypeError: when case_insensitive set to true on unsupported types
        """
        res_at_key = []
        if case_insensitive:
            try:
                value = value.lower()
            except Exception:
                raise TypeError("failed to invoke method .lower()")
        for k, v in traverse(result, leaf_node=True):
            if k == key:
                if case_insensitive:
                    try:
                        v = v.lower()
                    except Exception:
                        raise TypeError("failed to invoke method .lower()")
                res_at_key.append(v)
        return value in res_at_key

class BiothingsWebAppTest(BiothingsWebTest, AsyncHTTPTestCase):
    """
        Starts the tornado application to run tests locally.
        Need a config.py under the test class folder.
    """
    TEST_DATA_DIR_NAME: Optional[str] = None  # set sub-dir name

    @pytest.fixture(scope="class", autouse=True)
    def _setup_elasticsearch(self):
        # Author: Zhongchao Qian
        # https://github.com/biothings/biothings.api/pull/135

        if not self.TEST_DATA_DIR_NAME:
            yield  # do no setup and yield control to pytest
            return

        s = requests.Session()
        s.mount('http://',
                adapter=requests.adapters.HTTPAdapter(
                    max_retries=urllib3.Retry(total=5, backoff_factor=3.0)
                ))  # values seem reasonable
        es_host = 'http://' + self.config.ES_HOST

        server_info = s.get(es_host).json()
        version_info = tuple(int(v) for v
                             in server_info['version']['number'].split('.'))
        if version_info[0] < 6 or version_info[0] == 6 and version_info[1] < 8:
            pytest.exit("Tests need to be running on ES6.8+")

        indices = []  # for cleanup later
        data_dir_path = os.path.dirname(inspect.getfile(type(self)))
        data_dir_path = os.path.join(data_dir_path, 'test_data')
        data_dir_path = os.path.join(data_dir_path, self.TEST_DATA_DIR_NAME)
        glob_json_pattern = os.path.join(data_dir_path, '*.json')
        # wrap around in try-finally so the index is guaranteed to be
        err_flag = False
        try:
            # TODO No match seems to cause illegible error
            for index_mapping_path in glob.glob(glob_json_pattern):
                index_name = os.path.basename(index_mapping_path)
                index_name = os.path.splitext(index_name)[0]
                indices.append(index_name)
                r = s.head(f'{es_host}/{index_name}')
                if r.status_code != 404:
                    if os.environ.get('TEST_KEEPDATA'):
                        continue
                    raise RuntimeError(f"{index_name} already exists!")
                with open(index_mapping_path, 'r') as f:
                    mapping = json.load(f)
                data_path = os.path.join(data_dir_path, index_name + '.ndjson')
                with open(data_path, 'r') as f:
                    bulk_data = f.read()
                if version_info[0] == 6:
                    r = s.put(f'{es_host}/{index_name}', json=mapping,
                              params={'include_type_name': 'false'})
                elif version_info[0] > 6:
                    r = s.put(f'{es_host}/{index_name}', json=mapping)
                else:
                    raise RuntimeError("This shouldn't have happened")
                r.raise_for_status()
                if version_info[0] < 8:
                    r = s.post(f'{es_host}/{index_name}/_doc/_bulk',
                            data=bulk_data,
                            headers={'Content-type': 'application/x-ndjson'})
                elif version_info[0] >= 8:
                    r = s.post(f'{es_host}/{index_name}/_bulk',
                            data=bulk_data,
                            headers={'Content-type': 'application/x-ndjson'})
                else:
                    raise RuntimeError("This shouldn't have happened")
                r.raise_for_status()
                s.post(f'{es_host}/{index_name}/_refresh')
            yield
        except Exception as e:
            err_msg = str(e)
            err_flag = True
        finally:
            if not os.environ.get('TEST_KEEPDATA'):
                for index_name in indices:
                    s.delete(f'{es_host}/{index_name}')
            if err_flag:
                pytest.exit("Error setting up ES for tests:", err_msg)

    @property
    def config(self):
        if not hasattr(self, '_config'):
            conf = os.getenv("TEST_CONF", 'config.py')
            base = os.path.dirname(inspect.getfile(type(self)))
            file = os.path.join(base, conf)
            self._config = configs.load(file)
        return self._config

    # override
    def get_new_ioloop(self):
        return IOLoop.current()

    # override
    def get_app(self):
        prefix = self.config.APP_PREFIX
        version = self.config.APP_VERSION
        self.prefix = f'{prefix}/{version}'
        return BiothingsAPI.get_app(self.config)

    # override
    def request(self, path, method="GET", expect=200, **kwargs):

        url = self.get_url(path)

        func = partial(requests.request, method, url, **kwargs)
        res = self.io_loop.run_sync(
            lambda: self.io_loop.run_in_executor(None, func))

        assert res.status_code == expect, res.text
        return res

    # override
    def get_url(self, path):

        path = BiothingsWebTest.get_url(self, path)
        return AsyncHTTPTestCase.get_url(self, path)

# Compatibility
BiothingsTestCase = BiothingsWebAppTest
BiothingsDataTest = BiothingsWebTest


text:
/**
 * Default config for Feature Flags
 * If not provided, values from here will be used
 */

exports = module.exports = {
	// Anything given to a user at level X will
	// be implicitly granted to users at level > X
	// You can disable this by TODO
	// Possibly add 'all' and 'anon' levels?
	levels: {
		anon: 0,
		login: 1,
		paid: 2,
		admin: 999
	},
	// TODO: A way to say 'only at this level'
	locals: {
		anon: {},
		login: {
			userSettings: true,
			upgradePitch: true
		},
		paid: {
			upgradePitch: false
		},
		admin: {
			adminPanel: true
		},
		// Also can add locals by level
		1: {
			addComment: true
		}
	},
	// Routes configured here will be overwritten by requireLevel calls
	routes: {
		'/': {
			anon: true
		},
		'/login': {
			anon: true,
			login: false
		}
	},
	// These are the defaults
	// Only include these if you want something different
	settings: {
		// The HTTP error code to respond with when
		//   the user requests a page they don't have access to
		respCode: 403,
		// For security reasons, it may be a better idea to 404 admin urls
		adminRespCode: 404,
		// requireLevel calls don't overwrite the config above.
		configRoutesPriority: false
	}
};


text:
package org.assertj.core.api;

import static org.assertj.core.api.BDDAssertions.then;

import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Stream;

import org.assertj.core.groups.Properties;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

@DisplayName("EntryPoint assertions extractProperty method")
class EntryPointAssertions_extractProperties_Test extends EntryPointAssertionsBaseTest {

  @ParameterizedTest
  @MethodSource("extractPropertiesFunctions")
  void should_create_Properties(Function<String, Properties<Object>> extractPropertiesFunction) {
    // GIVEN
    String property = "name";
    // WHEN
    Properties<Object> properties = extractPropertiesFunction.apply(property);
    // THEN
    then(properties).extracting("propertyName")
                    .isEqualTo(property);
  }

  private static Stream<Function<String, Properties<Object>>> extractPropertiesFunctions() {
    return Stream.of(Assertions::extractProperty, BDDAssertions::extractProperty, withAssertions::extractProperty);
  }

  @ParameterizedTest
  @MethodSource("extractTypedPropertiesFunctions")
  void should_create_strongly_typed_Properties(BiFunction<String, Class<String>, Properties<String>> extractTypedPropertiesFunction) {
    // GIVEN
    String property = "name";
    // WHEN
    Properties<String> properties = extractTypedPropertiesFunction.apply(property, String.class);
    // THEN
    then(properties).extracting("propertyName")
                    .isEqualTo(property);
  }

  private static Stream<BiFunction<String, Class<String>, Properties<String>>> extractTypedPropertiesFunctions() {
    return Stream.of(Assertions::extractProperty, BDDAssertions::extractProperty, withAssertions::extractProperty);
  }

}


text:
package edu.ucsb.cs.partitioning.lsh;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.hadoop.filecache.DistributedCache;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Reader;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

/**
 * This class reads in documents of the format [docid word1 word2 ...] and
 * produce an lsh minhash signature to each of them "l" times using a list of
 * minHashTables.
 *
 * @author Maha
 */
public class LshMapper extends MapReduceBase implements
		Mapper<LongWritable, Text, IntArrayWritable, LongWritable> {

	CounterWritable docCount = new CounterWritable();
	private LongWritable lng = new LongWritable();
	private IntArrayWritable keySig = new IntArrayWritable();
	private int l;
	private LshTable lsh = new LshTable();

	@Override
	public void configure(JobConf job) {
		l = job.getInt(LshPartitionMain.L_PROPERTY, LshPartitionMain.L_VALUE);
		try {
			Path[] localFiles = DistributedCache.getLocalCacheFiles(job);
			// System.out.println("local:" + localFiles[0].getName());
			// FileSystem fs = localFiles[0].getFileSystem(job);
			FileSystem fs = FileSystem.get(job);
			// Reader reader = new SequenceFile.Reader(fs, localFiles[0], job);
			Reader reader = new SequenceFile.Reader(fs, new Path("lshfile"), job);
			reader.next(lsh);
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void map(LongWritable unused, Text idwordsBag,
			OutputCollector<IntArrayWritable, LongWritable> output, Reporter report)
			throws IOException {
		StringTokenizer tkz = new StringTokenizer(idwordsBag.toString(), " ");
		docCount.docid = Long.parseLong(tkz.nextToken()); // document id
		while (tkz.hasMoreTokens()) {
			String word = tkz.nextToken();
			lng.set(Long.parseLong(word));
			docCount.addFeature(lng);
		}
		ArrayList<int[]> signatures = lsh.getSignatures(docCount);
		lng.set(docCount.docid);
		System.out.println("Num sigs: " + signatures.size());
		for (int i = 0; i < l; i++) {
			keySig.setArray(signatures.get(i));
			output.collect(keySig, lng);
		}
	}
}


text:
__version__=''' $Id: genreference.py 2385 2004-06-17 15:26:05Z rgbecker $ '''
__doc__ = """
This module contains the script for building the reference.
"""
def run(verbose=None, outDir=None):
    import os, sys, shutil
    from reportlab.tools.docco import yaml2pdf
    from reportlab.lib.utils import _RL_DIR
    if verbose is None: verbose=('-s' not in sys.argv)
    yaml2pdf.run('reference.yml','reference.pdf')
    if verbose: print 'Saved reference.pdf'
    docdir = os.path.join(_RL_DIR,'docs')
    if outDir: docDir = outDir
    destfn = docdir + os.sep + 'reference.pdf'
    shutil.copyfile('reference.pdf', destfn)
    if verbose: print 'copied to %s' % destfn

def makeSuite():
    "standard test harness support - run self as separate process"
    from reportlab.test.utils import ScriptThatMakesFileTest
    return ScriptThatMakesFileTest('../docs/reference', 'genreference.py', 'reference.pdf')

if __name__=='__main__':
    run()


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Harsha Ashok</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Harsha Ashok

                        Portfolio

                        Experience

                        About Me

                        Contact

Welcome To My Page!

HARSHA ASHOK

                More

Portfolio

Lorem ipsum dolor sit amet consectetur.

Round Icons

Graphic Design

Startup Framework

Website Design

Treehouse

Website Design

Golden

Website Design

Escape

Website Design

Dreams

Website Design

Experience

Timeline

July 2015 - Present

Software Engineer, Intuit

                                            Part of development team as a backend engineer for Quickbooks Online Payroll.

Developer on backend APIs for QBO Services.

 JAN 2015 - MAY 2015

Engineering Intern - Master's Level, Symantec Corp.

Part of development team for Symantec's Endpoint Protection and Management System(EPMP).

Developer on backend APIs for EPMP Services.

JUN 2014 - AUG 2014

Software Engineering Intern, Intuit Docstoc

Full Stack Development for Intuit Docstoc using .NET MVC framework, C#, MySQL, js, etc.

Engaged in Intuit's flagship Lean StartIn program; Developed an OCR receipt capture system for Mint.com

Aug 2013 - May 2015

Master's in Computer Science, University of Southern California

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

Sep 2012 - Jul 2013

Software Engineer, Philips TPVision

Development and design of connectivity & multimedia features for Philips Smart TVs.

Development of Opera browser's customized plugin and implementation in product.

XXX xx

XXXX

xx?!

About Me

Lorem ipsum dolor sit amet consectetur.

Harsha Ashok

Software Engineer

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut eaque, laboriosam veritatis, quos non quis ad perspiciatis, totam corporis ea, alias ut unde.

Contact Us

Lorem ipsum dolor sit amet consectetur.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © Your Website 2014

Privacy Policy

Terms of Use

Project Name

Lorem ipsum dolor sit amet consectetur.

Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!

                                Want these icons in this portfolio item sample?You can download 60 of them for free, courtesy of RoundIcons.com, or you can purchase the 1500 icon set here.

Date: July 2014

Client: Round Icons

Category: Graphic Design

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Heading

Lorem ipsum dolor sit amet consectetur.

Startup Framework is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.

You can preview Startup Framework here.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Treehouse is a free PSD web template built by Mathavan Jaya. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by Mathavan Jaya. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Escape is a free PSD web template built by Mathavan Jaya. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>

Project Name

Lorem ipsum dolor sit amet consectetur.

Dreams is a free PSD web template built by Mathavan Jaya. Dreams is a modern one page web template designed for almost any purpose. It's a beautiful template that's designed with the Bootstrap framework in mind.

You can download the PSD template in this portfolio sample item at FreebiesXpress.com.

                            <button type="button" class="btn btn-primary" data-dismiss="modal"> Close Project</button>


text:
require 'test_helper'

class BreadsControllerTest < ActionController::TestCase
  setup do
    @bread = breads(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:breads)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create bread" do
    assert_difference('Bread.count') do
      post :create, bread: { descripcion: @bread.descripcion, precio: @bread.precio, tipo: @bread.tipo }
    end

    assert_redirected_to bread_path(assigns(:bread))
  end

  test "should show bread" do
    get :show, id: @bread
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @bread
    assert_response :success
  end

  test "should update bread" do
    patch :update, id: @bread, bread: { descripcion: @bread.descripcion, precio: @bread.precio, tipo: @bread.tipo }
    assert_redirected_to bread_path(assigns(:bread))
  end

  test "should destroy bread" do
    assert_difference('Bread.count', -1) do
      delete :destroy, id: @bread
    end

    assert_redirected_to breads_path
  end
end


text:
package org.diirt.vtype.next;

import java.time.Instant;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;

/**
 *
 * @author carcassi
 */
public class VDoubleTest {

    @Test
    public void testCreate() {
        Alarm alarm = Alarm.create(AlarmSeverity.MINOR, "LOW");
        Time time = Time.create(Instant.ofEpochSecond(1354719441, 521786982));
        VDouble value = VDouble.create(1.0, alarm, time, Display.none());
        assertThat(value.getValue(), equalTo(1.0));
        assertThat(value.getAlarm(), equalTo(alarm));
        assertThat(value.getTime(), equalTo(time));
        assertThat(value.toString(), equalTo("VDouble[1.0 ,MINOR(LOW), 2012-12-05T14:57:21.521786982Z]"));
    }

}


text:
struct Graphics;
struct Sprite;

struct NumberSprite {
   // Ex. " 3" in white text.
   static NumberSprite HUDNumber(Graphics& graphics, int number, int num_digits)
      { return NumberSprite(graphics, number, num_digits, WHITE, NONE); }

   // Ex. "-30" in red text.
   static NumberSprite DamageNumber(Graphics& graphics, int number)
      { return NumberSprite(graphics, number, 0, RED, MINUS); }

   // Ex. "+128" in white text.
   static NumberSprite ExperienceNumber(Graphics& graphics, int number)
      { return NumberSprite(graphics, number, 0, WHITE, PLUS); }

   void draw(Graphics& graphics, units::Game x, units::Game y);
   void drawCentered(Graphics& graphics, units::Game x, units::Game y)
      { draw(graphics, x - width() / 2, y - height() / 2); }

  private:
   enum ColorType {
      RED,
      WHITE
   };
   enum OperatorType {
      PLUS,
      MINUS,
      NONE,
   };
   // if num_digits is 0, we don't care how much space it takes up.
   NumberSprite(Graphics& graphics, int number, int num_digits, ColorType color, OperatorType op);

   units::Game width() const { return units::kHalfTile * reversed_glyphs_.size(); }
   units::Game height() const { return units::kHalfTile; }

   units::Game padding_;
   std::vector<boost::shared_ptr<Sprite> > reversed_glyphs_;
};

#endif // NUMBER_SPRITE_H_


text:
/* eslint-disable */

/**
* LICENSE MIT
* (C) Daniel Zelisko
* http://github.com/danielzzz/node-ping
*
* A poor man's ping for node.js
* It uses UDP_scanning (as node is not able to generate iCPM packets)
* http://en.wikipedia.org/wiki/Port_scanner#UDP_scanning
* it may not work correct for hosts that silently drop UDP traffic on their firewall
* you need at pcap version 0.1.9 or higher
*
*/

var sys = require("util"),
pcap = require('pcap');

var addr = process.argv[3] || 'localhost';
setInterval(function() {probe(addr)}, 1000);

function probe(addr) {
    sys.puts('sending a probe to ' + addr);
    var dgram = require('dgram');
    var message = new Buffer("Some bytes");
    var client = dgram.createSocket("udp4");
    client.send(message, 0, message.length, 21111, addr);
    client.close();
}

// create a pcap session
pcap_session = pcap.createSession(process.argv[2] || 'eth0', "");

// listen for packets, decode them, and feed the simple printer
pcap_session.addListener('packet', function (raw_packet) {
    var packet = pcap.decode.packet(raw_packet);
    if (packet.link && packet.link.ip && packet.link.ip.saddr==addr) {
        packet.link && packet.link.ip && sys.puts(packet.link.ip.saddr + " is alive");
    }
});

//-------- example ------------------------


text:
package net.glowstone.net.codec;

import java.io.IOException;

import net.glowstone.msg.Message;

import org.jboss.netty.buffer.ChannelBuffer;

public abstract class MessageCodec<T extends Message> {

    private final Class<T> clazz;
    private final int opcode;

    public MessageCodec(Class<T> clazz, int opcode) {
        this.clazz = clazz;
        this.opcode = opcode;
    }

    public final Class<T> getType() {
        return clazz;
    }

    public final int getOpcode() {
        return opcode;
    }

    public abstract ChannelBuffer encode(T message) throws IOException;

    public abstract T decode(ChannelBuffer buffer) throws IOException;

}


text:
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from builtins import *

from github import ApiError

from commitsan.github import github, GITHUB_BLOB_URL_TMPL
from commitsan.worker import job

CONTRIBUTING_FILENAME = 'CONTRIBUTING.md'

def output(*args, **kwargs):
    kwargs.setdefault('file', sys.stderr)
    print(*args, **kwargs)

@job()
def post_status(repo, commit, context, description, state='pending', **kwargs):
    endpoint = github.repos(repo).statuses(commit)
    if 'target_url' not in kwargs:
        kwargs['target_url'] = (GITHUB_BLOB_URL_TMPL
                                .format(filename=CONTRIBUTING_FILENAME,
                                        **locals()))
    output('Posting to {repo}: state of {commit} set to {state}: '
           '{context} ({description})'
           .format(**dict(kwargs, **locals())))
    endpoint.post(context='commitsan/{}'.format(context),
                  description=description, state=state, **kwargs)

def report_issue(repo, commit, context, description, fatal=False):
    post_status.delay(repo, commit, context, description,
                      state='failure' if fatal else 'pending')


text:
namespace syncer {

ModelTypeConnectorProxy::ModelTypeConnectorProxy(
    const scoped_refptr<base::SequencedTaskRunner>& task_runner,
    const base::WeakPtr<ModelTypeConnector>& model_type_connector)
    : task_runner_(task_runner), model_type_connector_(model_type_connector) {}

ModelTypeConnectorProxy::~ModelTypeConnectorProxy() {}

void ModelTypeConnectorProxy::ConnectType(
    ModelType type,
    std::unique_ptr<ActivationContext> activation_context) {
  task_runner_->PostTask(
      FROM_HERE,
      base::Bind(&ModelTypeConnector::ConnectType, model_type_connector_, type,
                 base::Passed(&activation_context)));
}

void ModelTypeConnectorProxy::DisconnectType(ModelType type) {
  task_runner_->PostTask(FROM_HERE,
                         base::Bind(&ModelTypeConnector::DisconnectType,
                                    model_type_connector_, type));
}

}  // namespace syncer


text:
static size_t next_power_of_two(size_t const v);

void * set(ArrayList * const list, size_t const ix, void * const x) {
  assert(list != NULL);
  assert(ix < list->size);
  void * deleted = list->get(list->data, ix);
  list->set(list->data, ix, x);
  return deleted;
}

void * get(const ArrayList * const list, size_t const ix) {
  assert(list != NULL);
  assert(ix < list->size);
  return list->get(list->data, ix);
}

void add(ArrayList * const list, void * const x) {
  add_at(list, list->size, x);
}

void add_at(ArrayList * const list, size_t const ix, void * const x) {
  assert(list != NULL);
  assert(ix <= list->size);

  if (list->size >= list->capacity) {
    list->capacity *= 2;
    list->data = realloc(list->data, list->capacity * list->element_size);
    assert(list->data != NULL);
  }

  if (ix < list->size)
    memmove(list->offset(list->data, ix+1),
	    list->offset(list->data, ix),
	    (list->size-ix) * list->element_size);

  list->set(list->data, ix, x);
  list->size++;
}

void add_all(ArrayList * const list, void * const xs, size_t const len) {
  add_all_at(list, list->size, xs, len);
}

void add_all_at(ArrayList * const list, size_t const ix, void * const xs, size_t const len) {
  assert(list != NULL);
  assert(xs != NULL);
  assert(ix <= list->size);

  if (list->size + len > list->capacity) {
    list->capacity = next_power_of_two(list->size + len);
    list->data = realloc(list->data, list->capacity * list->element_size);
    assert(list->data != NULL);
  }

  if (ix < list->size)
    memmove(list->offset(list->data, ix+len),
	    list->offset(list->data, ix),
	    (list->size-ix) * list->element_size);

  memcpy(list->offset(list->data, ix), xs, len * list->element_size);
  list->size += len;
}

void * remove_elem(ArrayList * const list, void * const x, EqFun equals) {
  assert(list != NULL);
  assert(equals != NULL);

  size_t ix;
  bool found = index_of(list, x, &ix, equals);

  if (found) {
    void * deleted = list->get(list->data, ix);
    remove_at(list, ix);
    list->size--;
    return deleted;
  }

  return NULL;
}

void * remove_at(ArrayList * const list, size_t const ix) {
  assert(list != NULL);
  assert(ix < list->size);

  void * deleted = list->get(list->data, ix);

  memmove(list->offset(list->data, ix),
	  list->offset(list->data, ix+1),
	  (list->size-ix) * list->element_size);

  list->size--;

  return deleted;
}

void ensure_capacity(ArrayList * const list, size_t const min_capacity) {
  assert(list != NULL);

  if (list->capacity < min_capacity) {
    list->capacity = next_power_of_two(min_capacity);
    list->data = realloc(list->data, list->capacity * list->element_size);
    assert(list->data != NULL);
  }
}

bool is_empty(const ArrayList * const list) {
  assert(list != NULL);
  return list->size == 0;
}

bool contains(const ArrayList * const list, const void * const x, EqFun equals) {
  assert(list != NULL);
  assert(equals != NULL);
  size_t u;
  return index_of(list, x, &u, equals);
}

bool index_of(const ArrayList * const list, const void * const x, size_t * out, EqFun equals) {
  assert(list != NULL);
  assert(out != NULL);
  assert(equals != NULL);

  for (size_t i = 0; i < list->size; i++) {
    if (equals(x, list->get(list->data, i))) {
      *out = i;
      return true;
    }
  }
  return false;
}

void to_array(const ArrayList * const list, void * const out) {
  assert(list != NULL);
  assert(out != NULL);

  for (size_t i = 0; i < list->size; i++)
    list->set(out, i, list->get(list->data, i));
}

static size_t next_power_of_two(size_t v) {
  v--;
  v |= v >> 1;
  v |= v >> 2;
  v |= v >> 4;
  v |= v >> 8;
  v |= v >> 16;
  v |= v >> 32;
  v++;
  return v;
}


text:
$LOAD_PATH.unshift File.expand_path(File.dirname(__FILE__) + '/../lib/')

begin
  require 'debugger'
  require 'debugger-pry'
rescue LoadError
  # The two requires will fail on Ruby 1.8, but we don't particularly care
end


text:
var Expression = function(obj){
	// initialize internal variables
	this.identifier = obj.identifier;
	this.arrayIndices = obj.index;
	this.const = obj.const;
};

// can be overwrited
Expression.prototype.getCode = function(){
	var indices = this.arrayIndices?this.arrayIndices.getCode():'';
	if(this.isConstant())
		return this.const;
	return this.identifier.getCode()+indices;
};
Expression.prototype.isConstant = function(){
	return this.const !== undefined;
}

Expression.constant = function(cons){
	return new Expression({const:cons});
}

module.exports = Expression;


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('estoque', '0007_docmovstq_numero'),
    ]

    operations = [
        migrations.AlterField(
            model_name='docmovstq',
            name='usuario',
            field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL, verbose_name='usuário'),
        ),
    ]


text:
require_relative "../../../../spec_helper"

describe "Crowbar::Client::Command::Node::Reboot" do
  include_context "command_context"

  it_behaves_like "a command class", true do
    subject do
      ::Crowbar::Client::Command::Node::Reboot.new(
        stdin,
        stdout,
        stderr
      )
    end
  end
end


text:
'use strict';

const _ = require('underscore');

const ipc = require('electron').ipcRenderer;
const dialog = require('electron').remote.dialog;
const BrowserWindow = require('electron').remote.BrowserWindow;

const transfers = require('../../../db').transfers;

const transfersList = $('#transfersList');
const transfersModal = $('#transfersModal');

$(document).ready(() => {

  transfers.loadDatabase((err) => {

    transfers.find({}, function (err, docs) {

      if (docs.length > 0) {

        _.each(docs, function (doc) {
          transfersList.append(`

                ${doc.name}
                <button class="btn btn-danger btn-xs pull-right" onclick="removeRecord('${doc._id}', '${doc.name}')">x</button>

                Цена: ${doc.price}р.

          `);
        });
      } else {

        transfersList.html('
Тарифы не найдены.
');
      }
    });
  });

  $('form#addTransfer').submit(function (event) {

    event.preventDefault();

    const name = $('#name').val();
    const price = $('#price').val();

    transfers.loadDatabase((err) => {
      transfers.insert({
        name: name,
        price: price
      }, function (err, newDoc) {
        BrowserWindow.getFocusedWindow().reload();
      });
    });

    transfersModal.modal('hide');

    this.reset();

    return false;
  });
});

function removeRecord (id, name) {
  dialog.showMessageBox(BrowserWindow.getFocusedWindow(), {
    message: `Удалить "${name}" ?`,
    buttons: ["OK", "Отменить"]
  }, function (index) {
    if (index === 0) {
      transfers.loadDatabase((err) => {
        transfers.remove({ _id: id }, {}, function (err, numRemoved) {
          if (err)
            console.log(err);
          else
            $('#'+id).remove();
        });
      });
    }
  });
};


text:
import Ember from 'ember';

export default Ember.Component.extend({

    change: function() {
        if (!this.get('inputCheckbox.checked')) {
            if(!confirm('Are you sure that you want to uncheck this?')) {
                this.set('inputCheckbox.checked', true);
            }
        }
        return false;
    }
});


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="cache-control" content="no-cache" />

  <link rel="shortcut icon" href="/webOPACClient/images/SBD.ico" />

            <link rel="stylesheet" href="/webOPACClient/jsp/common/infoguide.css"  type="text/css" />

  <title>

      Online-Katalog der Städtischen Bibliotheken Dresden

  </title>

        Online-Katalog der Städtischen Bibliotheken Dresden

      Diese Seite verwendet Cookies.

         Weitere Informationen.

Suche

Merkliste

Konto

Kontostand

Benutzerdaten

Sucheinstellungen

		Benutzernummer 123456
		Abmelden

			   Hilfe

Neu im Bestand

<form id="AdvancedSearchForm" method="post" action="/webOPACClient/search.do">
<input type="hidden" name="methodToCall" value="submit" />
<input type="hidden" name="searchCategories[0]" value="-1" />

<input type="hidden" name="searchString[1]" value="" />

<input type="hidden" name="searchString[2]" value="" />

<input type="hidden" name="searchString[3]" value="" />

<input type="hidden" name="searchString[4]" value="" />

<input type="hidden" name="CSId" value="1234" />
<input type="hidden" name="searchHistory" value="" />
<input type="text" name="searchString[0]" value="" id="f1" />

<input type="submit" class="dbutton" id="submitSearch" name="submitSearch" value="Suchen" />
</form>

              Ausleihen
               (0)

				        Übersicht

               Gemahnte Medien

               Rückgeforderte Medien

				       Verlängerte Medien

				       Fernleihen

	  	       Bestellungen
		          (0)

  		       Vormerkungen
        		  (0)

  		       Gebühren
        		   (0,00 EUR)

Ausleihen

       		Nr.
       		Titel, Verfasser
	        Leihfrist, Zweigstelle

      		  Konto entält keine <Ausleihen>.

      weitere Optionen

Liste ausgeben

    drucken

	  |
    speichern

 <form id="UserAccountForm" method="post" action="/webOPACClient/userAccount.do">
 <input type="hidden" name="methodToCall" value="showaccount" />
 <input type="hidden" name="CSId" value="12345" />

      E-Mail

    <input type="text" name="email" value="123456" id="email" />

      Betreff

    <input type="text" name="subject" value="" id="subject" />

    versenden

 </form>

Benutzerkonto

    			Ausweis gültig bis

    			11.11.2017

Vormerk- / Bestellgebühr

Bei der Durchführung einer Vormerkung / Bestellung wird Ihr Bibliothekskonto sofort mit der anfallenden Gebühr von 1.00 Euro belastet.
Weitere 0.20 Euro Rückversandgebühr fallen ggf. bei der Rückgabe des Mediums an.

Vormerkung stornieren

Vormerkungen können Sie telefonisch oder persönlich in allen Bibliotheken unseres Netzes stornieren lassen, sofern das Medium nicht bereits auf dem Transportweg ist. Bei einer Stornierung wird auch die Vormerkgebühr wieder aus Ihrem Bibliothekskonto gelöscht.

Service

Benachrichtigungen über abholbare Vorbestellungen und Erinnerungen an das Ende der Leihfrist werden auch als E-Mail oder SMS verschickt.

Möchten Sie diesen Service nutzen, dann tragen Sie bitte IhreE-Mail-Adresse oder Ihre Handy-Nummer in Ihre Nutzerdaten ein. Wählen Sie im 'Konto' > 'Benutzerdaten' > 'Stammdaten' > 'Adressdaten'. Dort steht Ihnen auch ein Hinweistext zur Verfügung.

		Bitte melden Sie sich beim Verlassen des Kataloges von Ihrem Bibliothekskonto ab!
		Jetzt abmelden.

	  Copyright © 2014. Alle Rechte vorbehalten.


text:
package com.bbva.arq.devops.ae.mirrorgate.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.verify;

import com.bbva.arq.devops.ae.mirrorgate.model.Build;
import com.bbva.arq.devops.ae.mirrorgate.model.Event;
import com.bbva.arq.devops.ae.mirrorgate.model.EventType;
import com.bbva.arq.devops.ae.mirrorgate.repository.EventRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class EventServiceTest {

    @Mock
    private EventRepository eventRepository;

    private EventServiceImpl eventService;

    @Before
    public void init() {
        eventService = new EventServiceImpl(eventRepository);
    }

    @Captor ArgumentCaptor<Event> captor;

    @Test
    public void test() {

        final Build build = createBuild();

        eventService.saveEvent(build, EventType.BUILD);

        verify(eventRepository).save(captor.capture());

        assertEquals(EventType.BUILD, captor.getValue().getEventType());
        assertEquals(build.getId(), captor.getValue().getCollectionId());
        assertNotNull(captor.getValue().getTimestamp());
    }

    private Build createBuild() {
        return new Build();
    }

}


text:
if (typeof define !== 'function') { var define = require('amdefine')(module) }

define(['jquery'], function ($) {

    "use strict";

    var AjaxCacheManager = function (options) {
        this.setOptions(options);
    };

    AjaxCacheManager.prototype = {
        options : {
            cache_container: null,
        },
        setOptions : function (options) {
            this.options = $.extend({}, this.options, options);
            this.init();
        },
        init : function () {
            this._htmlCache = [];
        },
        clear : function () {
            this._htmlCache = [];
        },
        load: function(url, callback) {
            var _self = this;

            if (_self.options.cache_container === null && typeof callback === 'undefined') {
                throw "No cache container or callback is set.";
            }

            if (_self.get(url) === null) {
                if (_self.options.cache_container !== null) {
                    $(_self.options.cache_container).html("Loading...");
                }
                $.get(url, function(data) {
                    _self.cache(url, data);

                    _self._updateContainer(url, callback);
                    _self._updateCallback(url, callback);
                });
            } else {
                _self._updateContainer(url, callback);
                _self._updateCallback(url, callback);
            }
        },
        cache: function (url, html) {
            this._htmlCache[url] = html;
            this._lastUrl = url;
        },
        get: function (url) {
            this._lastUrl = url;

            if (typeof this._htmlCache[url] === 'undefined') {
                return null;
            }
            return this._htmlCache[url];
        },
        changeContainer: function(containerSelector) {
            _self.options.cache_container = containerSelector;
        },
        _updateContainer: function(url, callback) {
            var _self = this;

            if (_self.options.cache_container === null) {
                return;
            }
            var containerHTML = _self.get(url);
            $(_self.options.cache_container).html(containerHTML);
        },
        _updateCallback: function(url, callback) {
            var html = this.get(url);

            if (typeof callback !== 'undefined') {
                callback(html);
            }
        }
    };

    return AjaxCacheManager;
});


text:
<?xml version="1.0"?>
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">

<document>

    <title>Solr Version Control System</title>

      <title>Overview</title>

        The Solr source code resides in the Apache Subversion (SVN) repository.
        The command-line SVN client can be obtained here or as an optional package for cygwin.
        The TortoiseSVN GUI client for Windows can be obtained here. There
        are also SVN plugins available for older versions of Eclipse and
        IntelliJ IDEA that don't have subversion support already included.

Here is some more text.  It contains a link.

Text Here

</document>


text:
Project : Analysis and comparison of Twitter networks of students across different universities.

report.pdf has the summary of our findings.

My team member's repo : https://github.com/hpandya2/CS579_Project


text:
extern "C" int PClownCarExecute(dEn_c *clown);
extern "C" void PClownCarAfterCreate(dEn_c *clown, u32);
extern "C" int PClownCarDraw(dEn_c *clown);
extern "C" void PClownCarMove(dEn_c *clown);

const char* PCCarcNameList [] = {
	"koopaJr_clown_ply",
	NULL
};

int CConDraw(dEn_c *clown) {
	// setup cannon model
	clown->matrix.translation(clown->pos.x, clown->pos.y + 8.0, clown->pos.z-100.0);
	short newrotz = -0x2000;
	short newroty = ((clown->rot.y * 0x4000) / 0x800) - 0x4000;
	short newrotx;
	if (clown->rot.x < 0x8000) {
		newrotx = -clown->rot.x;
	}
	else {
		newrotx = clown->rot.x;
	}
	// OSReport("Angle?: %x, %x", clown->rot.y, newroty);
	clown->matrix.applyRotationYXZ(&clown->rot.x, &newroty, &newrotz);

	cModel->setDrawMatrix(clown->matrix);
	Vec sc = {0.25f, 0.5f, 0.25f};
	cModel->setScale(&sc);
	cModel->calcWorld(false);

	cModel->scheduleForDrawing();

	return PClownCarDraw(clown);
	// run normal clown function
}
extern dStateBase_c JrClownEndDemoState;
extern dStateBase_c JrClownDemoWaitState;
extern dStateBase_c ClownDemoWaitState;

int CConExecute(dEn_c *clown) {
	// A REALLY TERRIBLE HACK.
	float saveX = clown->pos.x;
	float saveY = clown->pos.y;

	int ret = PClownCarExecute(clown);

	dStateBase_c *state = clown->acState.getCurrentState();
	if (state == &JrClownEndDemoState || state == &JrClownDemoWaitState || state == &ClownDemoWaitState) {
		clown->pos.x = saveX;
		clown->pos.y = saveY;
		clown->speed.x = 0.0f;
		clown->speed.y = 0.0f;
	}
	return ret;
}

void CCafterCreate(dEn_c *clown, u32 param) {

	clown->scale.x *= 1.25;
	clown->scale.y *= 1.25;
	clown->scale.z *= 1.25;

	// setup the model
	nw4r::g3d::ResFile resFile;

	cAllocator->link(-1, GameHeaps[0], 0, 0x20);

	resFile.data = getResource("koopaJr_clown_ply", "g3d/cannon.brres");
	nw4r::g3d::ResMdl mdl = resFile.GetResMdl("Cannon");
	cModel->setup(mdl, cAllocator, 0x224, 1, 0);
	SetupTextures_MapObj(cModel, 0);

	cAllocator->unlink();

	// Original AfterCreate
	PClownCarAfterCreate(clown, param);

	int playerCount = 0;
	for (int i = 0; i < 4; i++)
		if (Player_Active[i])
			playerCount++;

	if ((clown->settings & 0xF) != 0) {
		int playerID = (clown->settings & 0xF) - 1;
		if (playerID >= playerCount)
			clown->Delete(1);
	}
}

void CConExecuteMove(dEn_c *clown) {

	u8 player = cPlayerOccupying->which_player;
	// OSReport("Angle = %x, %x, %x", (GetSpecificPlayerActor(player))->rot.y, (GetSpecificPlayerActor(player))->rot.x, (GetSpecificPlayerActor(player))->rot.z);
	// OSReport("Clown = %x, %x, %x", (clown)->rot.y, (clown)->rot.x, (clown)->rot.z);

	Vec tempPos;

	u32 buttonPushed = Remocon_GetPressed(GetRemoconMng()->controllers[cPlayerOccupying->which_player]);
	if (buttonPushed & 0x0100) {

		if (cTimer > 90) {
			if (clown->direction == 0) { // Going right
				tempPos = (Vec){clown->pos.x + 32.0f, clown->pos.y + 32.0f, 3564.0f};
				dStageActor_c *spawned = CreateActor(657, 0, tempPos, 0, 0);
				spawned->speed.x = 5.0;
			}
			else {
				tempPos = (Vec){clown->pos.x - 32.0f, clown->pos.y + 32.0f, 3564.0f};
				dStageActor_c *spawned = CreateActor(657, 0, tempPos, 0, 0);
				spawned->speed.x = -5.0;
			}

			S16Vec nullRot = {0,0,0};
			Vec efScale = {0.1f, 0.1f, 0.1f};
			SpawnEffect("Wm_en_killervanish", 0, &tempPos, &nullRot, &efScale);
			nw4r::snd::SoundHandle handle;
			PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_OBJ_HOUDAI_S_SHOT, 1);

		cTimer = 0;
		}
	}

	cTimer++;

	ClassWithCameraInfo *cwci = ClassWithCameraInfo::instance;
	float leftBound = cwci->screenLeft + 12.0f;
	float rightBound = (cwci->screenLeft + cwci->screenWidth) - 12.0f;
	if (clown->pos.x < leftBound)
		clown->pos.x = leftBound;
	if (clown->pos.x > rightBound)
		clown->pos.x = rightBound;

	// run normal move
	PClownCarMove(clown);
}

extern "C" m3d::mdl_c *__ct__Q23m3d5mdl_cFv(m3d::mdl_c *mdl);
extern "C" mHeapAllocator_c *__ct__16mHeapAllocator_cFv(mHeapAllocator_c *al);
extern "C" dEn_c *__ct__20daJrClownForPlayer_cFv(dEn_c *clown);

dEn_c *newClownCtor(dEn_c *clown) {
	__ct__20daJrClownForPlayer_cFv(clown);
	__ct__16mHeapAllocator_cFv(cAllocator);
	__ct__Q23m3d5mdl_cFv(cModel);
	return clown;
}

extern "C" void __dt__Q23m3d5mdl_cFv(m3d::mdl_c *mdl, u32 willDelete);
extern "C" void __dt__16mHeapAllocator_cFv(mHeapAllocator_c *al, u32 willDelete);
extern "C" void __dt__20daJrClownForPlayer_cFv(dEn_c *clown, u32 willDelete);

extern "C" u32 sAllocatorFunc__FrmHeap;

void newClownDtor(dEn_c *clown, u32 willDelete) {
	void **al = (void **)(((u32)clown) + 0x524);
	if (*al != &sAllocatorFunc__FrmHeap) {
		OSReport("oh no! bad allocator %p\n", *al);
		*al = &sAllocatorFunc__FrmHeap;
	}

	__dt__Q23m3d5mdl_cFv(cModel, 0xFFFFFFFF);
	__dt__16mHeapAllocator_cFv(cAllocator, 0xFFFFFFFF);
	__dt__20daJrClownForPlayer_cFv(clown, willDelete);
}

extern "C" void JrClownForPlayer_playAccelSound() {
	nw4r::snd::SoundHandle handle;
	PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_PLY_CROWN_ACC, 1);
}

// Below is the projectile used byt eh clown car - Replaces WM_PAKKUN

class daClownShot : public dEn_c {
	int onCreate();
	int onExecute();
	int onDraw();

	mHeapAllocator_c allocator;
	nw4r::g3d::ResFile resFile;
	m3d::mdl_c bodyModel;

	mEf::es2 effect;
	static daClownShot *build();

	void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther);
};

void daClownShot::playerCollision(ActivePhysics *apThis, ActivePhysics *apOther) { }

daClownShot *daClownShot::build() {
	void *buffer = AllocFromGameHeap1(sizeof(daClownShot));
	return new(buffer) daClownShot;
}

int daClownShot::onCreate() {
	allocator.link(-1, GameHeaps[0], 0, 0x20);
	this->resFile.data = getResource("koopaJr_clown_ply", "g3d/houdai_ball.brres");
	nw4r::g3d::ResMdl mdl = this->resFile.GetResMdl("houdai_ball");
	bodyModel.setup(mdl, &allocator, 0x224, 1, 0);
	allocator.unlink();

	ActivePhysics::Info GreatBalls;

	GreatBalls.xDistToCenter = 0.0;
	GreatBalls.yDistToCenter = 0.0;
	GreatBalls.xDistToEdge = 8.0;
	GreatBalls.yDistToEdge = 7.0;

	GreatBalls.category1 = 0x3;
	GreatBalls.category2 = 0x0;
	GreatBalls.bitfield1 = 0x6F;
	GreatBalls.bitfield2 = 0xffbafffe;
	GreatBalls.unkShort1C = 0;
	GreatBalls.callback = &dEn_c::collisionCallback;

	this->aPhysics.initWithStruct(this, &GreatBalls);
	this->aPhysics.addToList();

	// These fucking rects do something for the tile rect
	spriteSomeRectX = 8.0f;
	spriteSomeRectY = 8.0f;
	_320 = 0.0f;
	_324 = 0.0f;

	u32 flags = SENSOR_BREAK_BRICK | SENSOR_BREAK_BLOCK | SENSOR_80000000;
	static const lineSensor_s below(flags, 12<<12, 4<<12, 0<<12);
	static const pointSensor_s above(flags, 0<<12, 12<<12);
	static const lineSensor_s adjacent(flags, 6<<12, 9<<12, 6<<12);

	collMgr.init(this, &below, &above, &adjacent);
	collMgr.calculateBelowCollisionWithSmokeEffect();

	this->speed.y = 4.0;
	this->y_speed_inc = -0.1875;

	this->onExecute();
	return true;
}

int daClownShot::onDraw() {
	matrix.translation(this->pos.x, this->pos.y, this->pos.z);

	matrix.applyRotationYXZ(&this->rot.x, &this->rot.y, &this->rot.z);

	bodyModel.setDrawMatrix(matrix);
	bodyModel.setScale(&scale);
	bodyModel.calcWorld(true);

	bodyModel.scheduleForDrawing();
	return true;
}

int daClownShot::onExecute() {
	HandleXSpeed();
	HandleYSpeed();
	doSpriteMovement();

	collMgr.calculateBelowCollisionWithSmokeEffect();
	collMgr.calculateAboveCollision(0);
	collMgr.calculateAdjacentCollision();
	if (collMgr.outputMaybe) {
		S16Vec nullRot = {0,0,0};
		Vec oneVec = {1.0f, 1.0f, 1.0f};
		SpawnEffect("Wm_en_burst_m", 0, &pos, &nullRot, &oneVec);
		nw4r::snd::SoundHandle handle;
		PlaySoundWithFunctionB4(SoundRelatedClass, &handle, SE_OBJ_TARU_BREAK, 1);
		Delete(1);
		return true;
	}

	S16Vec nullRot = {0,0,0};
	Vec efScale = {0.7f, 0.7f, 0.7f};
	effect.spawn("Wm_en_killersmoke", 0, &pos, &nullRot, &efScale);

	float rect[] = {0.0, 0.0, 8.0, 8.0};
	int ret = this->outOfZone(this->pos, (float*)&rect, this->currentZoneID);
	if(ret) {
		this->Delete(1);
	}

	return true;
}

// This is for making clown shots able to kill other shit

extern "C" bool Amp_NewPreSpriteCollision(ActivePhysics *apThis, ActivePhysics *apOther) {
	// apThis = amp, apOther = other thing
	dEn_c *amp = (dEn_c*)apThis->owner;

	if (apOther->info.category2 == 9) {
		if (amp->collisionCat9_RollingObject(apThis, apOther))
			return true;
	} else if (apOther->owner->name == WM_PAKKUN) {
		amp->killByDieFall(apOther->owner);
		return true;
	}

	return false;
}

extern "C" void KazanRock_Explode(void *kazanRock);
extern "C" void KazanRock_OriginalCollisionCallback(ActivePhysics *apThis, ActivePhysics *apOther);
extern "C" void KazanRock_CollisionCallback(ActivePhysics *apThis, ActivePhysics *apOther) {
	if (apOther->owner->name == WM_PAKKUN) {
		apThis->someFlagByte |= 2;
		KazanRock_Explode(apThis->owner);
	} else {
		KazanRock_OriginalCollisionCallback(apThis, apOther);
	}
}


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

namespace Dealership.CommandHandlers
{
    public class UserNotLoggedCommandHandler : CommandHandlerBase
    {
        private const string UserNotLogged = "You are not logged! Please login first!";

        private readonly IUserProvider userProvider;

        public UserNotLoggedCommandHandler(IUserProvider userProvider)
        {
            this.userProvider = userProvider;
        }

        protected override bool CanHandle(ICommand command)
        {
            return command.Name != "RegisterUser" && command.Name != "Login" && this.userProvider.LoggedUser == null;
        }

        protected override string ProccessCommandInternal(ICommand command)
        {
            return UserNotLogged;
        }
    }
}