text:
The schema defines the following properties:

## `names` (translations, required)

## `category` (string, enum, required)

This element must be one of the following enum values:

* `Evolutionary stones`
* `Repels`
* `Fossils`
* `Flutes`
* `Shards`
* `Held items`
* `Escape items`
* `Escape Rope`
* `Exchangeable items`
* `Valuable items`
* `Battle items`
* `Bottle Caps`
* `Legendary artifacts`
* `Honey`
* `Scents`
* `Nectars`
* `Potions`
* `Status condition healing items`
* `Revives`
* `PP-restoring items`
* `Vitamins`
* `Wings`
* `Drinks`
* `Herbal medicine`
* `Ability Capsule`
* `Berries`
* `Mulch`
* `Apricorns`
* `Poké Balls`
* `Decorations`
* `Accessoiries`
* `Backdrops`
* `Props`
* `Décor`
* `Clothing`
* `Fashion items`
* `Mail`
* `Key Items`
* `Event items`
* `Wood boxes`
* `Time Flute`
* `Pass Orbs`
* `Wonder Launcher items`
* `Rotom Powers`

## `descriptions` (array, required)

The object is an array with all elements of the type `object`.

The array object has the following properties:

### `games` (games, required)

### `translations` (translations, required)

Additional restrictions:

* Minimum items: `1`

## `prices` (array, required)

The object is an array with all elements of the type `object`.

The array object has the following properties:

### `games` (games, required)

### `buying` (integer, required)

Additional restrictions:

* Maximum: `60000`

### `selling` (integer, required)

Additional restrictions:

* Maximum: `60000`

## `pockets` (array, required)

The object is an array with all elements of the type `object`.

The array object has the following properties:

### `pocket` (pocket, required)

### `generations` (array, required)

The object is an array with all elements of the type `generation`.

## `effects` (array, required)

The object is an array with all elements of the type `effect`.

## `fling_power` (integer, required)

Additional restrictions:

* Maximum: `150`

---

# Sub Schemas

The schema defines the following additional types:

## `effect` (object)

Properties of the `effect` object:

### `condition` (string, enum, required)

This element must be one of the following enum values:

* `During Battle`
* `Outside of Battle`
* `Always`

### `target` (string, enum, required)

This element must be one of the following enum values:

* `Single Pokemon`
* `Single Pokemon > Single Move`
* `Single Pokemon > All Moves`
* `Team`
* `Trainer`

### `triggers_evolution` (boolean)

### `move_changes` (array)

The object is an array with all elements of the type `object`.

The array object has the following properties:

#### `field` (string, enum, required)

This element must be one of the following enum values:

* `max_pp`
* `pp`

#### `change_by_percent` (integer)

Additional restrictions:

* Minimum: `-100`
* Maximum: `160`

#### `change_by` (integer)

Additional restrictions:

* Minimum: `-10000`
* Maximum: `10000`

#### `change_by_max` (integer)

Additional restrictions:

* Minimum: `-10000`
* Maximum: `10000`

Additional restrictions:

* Minimum items: `1`

### `pokemon_changes` (array)

The object is an array with all elements of the type `object`.

The array object has the following properties:

#### `field` (string, enum, required)

This element must be one of the following enum values:

* `current_hp`
* `status_condition`
* `ev_hp`
* `ev_atk`
* `ev_def`
* `ev_sp_def`
* `ev_sp_atk`
* `ev_speed`
* `level`
* `atk`
* `def`
* `sp_atk`
* `sp_def`
* `speed`
* `accuracy`
* `critical_hit`
* `stat_reduction`

#### `change_by_percent` (integer)

Additional restrictions:

* Minimum: `-100`
* Maximum: `100`

#### `revive` (boolean)

#### `change_by` (integer)

Additional restrictions:

* Minimum: `-10000`
* Maximum: `10000`

#### `change` (string, enum)

This element must be one of the following enum values:

* `remove`
* `immune_for_5_turns`

#### `conditions` (array)

The object is an array with all elements of the type `string`.

Additional restrictions:

* Minimum items: `1`

Additional restrictions:

* Minimum items: `1`

## `games` (array)

## `pocket` (string)

## `generation` (integer)

## `translations` (object)

Properties of the `translations` object:

### `cz` (string)

### `dk` (string)

### `fr` (string)

### `de` (string, required)

### `gr` (string)

### `it` (string)

### `pl` (string)

### `tr` (string)

### `en` (string, required)

### `jp` (string)

### `es` (string)


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>GetDoubles Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache Lucene.Net 2.4.0 Class Library API

ExtendedFieldCacheImpl.GetDoubles Method

Overload List

        public virtual double[] GetDoubles(IndexReader,string);

        public virtual double[] GetDoubles(IndexReader,string,DoubleParser);

See Also

        ExtendedFieldCacheImpl Class | Lucene.Net.Search Namespace

Generated from assembly Lucene.Net [2.4.0.2]

redpajama_set_name: RedPajamaGithub


text:
import socket
import json

def talk_to_server(user_utterance):
	reply = ""

	with open('config.json') as config_file:
		data = json.load(config_file)
		serv_addr = data["server_address"]
		port = data["port"]

	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	server_address = (serv_addr, port)
	sock.connect(server_address)

	try:
		sock.sendall(user_utterance + '\n')

		while "\n" not in reply:
			data = sock.recv(16)
			if len(data) <= 0:
				print("something went wrong")
				break

			reply += data
	except:
		print("problem communicating with server")

	sock.close()

	return reply


text:
@interface XXCalculatorViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>

@end


text:
/* eslint-disable */

'use strict';

/*::
import type { Fragment, ReaderFragment } from 'relay-runtime';
type getFragmentIdentifierTest1NestedUserFragment$fragmentType = any;
import type { FragmentType } from "relay-runtime";
declare export opaque type getFragmentIdentifierTest1UsersFragment$fragmentType: FragmentType;
export type getFragmentIdentifierTest1UsersFragment$data = $ReadOnlyArray<{|
  +id: string,
  +name: ?string,
  +profile_picture: ?{|
    +uri: ?string,
  |},
  +$fragmentSpreads: getFragmentIdentifierTest1NestedUserFragment$fragmentType,
  +$fragmentType: getFragmentIdentifierTest1UsersFragment$fragmentType,
|}>;
export type getFragmentIdentifierTest1UsersFragment$key = $ReadOnlyArray<{
  +$data?: getFragmentIdentifierTest1UsersFragment$data,
  +$fragmentSpreads: getFragmentIdentifierTest1UsersFragment$fragmentType,
  ...
}>;
*/

var node/*: ReaderFragment*/ = {
  "argumentDefinitions": [
    {
      "kind": "RootArgument",
      "name": "scale"
    }
  ],
  "kind": "Fragment",
  "metadata": {
    "plural": true
  },
  "name": "getFragmentIdentifierTest1UsersFragment",
  "selections": [
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "id",
      "storageKey": null
    },
    {
      "alias": null,
      "args": null,
      "kind": "ScalarField",
      "name": "name",
      "storageKey": null
    },
    {
      "alias": null,
      "args": [
        {
          "kind": "Variable",
          "name": "scale",
          "variableName": "scale"
        }
      ],
      "concreteType": "Image",
      "kind": "LinkedField",
      "name": "profile_picture",
      "plural": false,
      "selections": [
        {
          "alias": null,
          "args": null,
          "kind": "ScalarField",
          "name": "uri",
          "storageKey": null
        }
      ],
      "storageKey": null
    },
    {
      "args": null,
      "kind": "FragmentSpread",
      "name": "getFragmentIdentifierTest1NestedUserFragment"
    }
  ],
  "type": "User",
  "abstractKey": null
};

if (__DEV__) {
  (node/*: any*/).hash = "91093197aa73a4d03537ace3e1561d6e";
}

module.exports = ((node/*: any*/)/*: Fragment<
  getFragmentIdentifierTest1UsersFragment$fragmentType,
  getFragmentIdentifierTest1UsersFragment$data,
>*/);


text:
from kombu import Exchange, Queue

## debug switch
debug=True

## manually set the domain
domain = '<%= @rabbitdomain %>'

## queue to monitor
watch_q = '<%= @rabbit_q %>'

## names of the scripts
workername='<%= @workername %>'
monitorname='<%= @monitorname %>'

## controller info
openstack_controller='<%= @controller %>'
rabbit_host='amqp://<%= @rabbitcreds %>@'+ openstack_controller +'//'

## not used, callback wont daemonize
worker_log_file="/tmp/%s.log" % workername
monitor_log_file="/tmp/%s.log" % monitorname

## used to check status
worker_pid_file="/tmp/%s.pid" % workername
monitor_pid_file="/tmp/%s.pid" % monitorname

task_exchange = Exchange('nova', type='topic', durable=False)
worker_queues = [Queue(watch_q + '_hipri', task_exchange, routing_key=watch_q + '_hipri'),
               Queue(watch_q + '_midpri', task_exchange, routing_key=watch_q + '_midpri'),
               Queue(watch_q + '_lopri', task_exchange, routing_key=watch_q + '_lopri')]
monitor_queues = [Queue('notifications.info', task_exchange, durable=False, routing_key='notifications.info')]

priority_to_routing_key = {'high': watch_q + '_hipri',
                           'mid': watch_q + '_midpri',
                           'low': watch_q + '_lopri'}

# list of events to listen for,
## for now, any compute related
## full list: https://wiki.openstack.org/wiki/SystemUsageData
## examples: http://paste.openstack.org/show/54140/
compute_events = [
        'compute.instance.create.end',
        'compute.instance.create.error',
        'compute.instance.create.start',
        'compute.instance.create_ip.end',
        'compute.instance.create_ip.start',
        'compute.instance.delete.end',
        'compute.instance.delete.start',
        'compute.instance.delete_ip.end',
        'compute.instance.delete_ip.start',
        'compute.instance.exists',
        'compute.instance.exists.verified.old',
        'compute.instance.finish_resize.end',
        'compute.instance.finish_resize.start',
        'compute.instance.live_migration.post.dest.end',
        'compute.instance.live_migration.post.dest.start',
        'compute.instance.live_migration.pre.end',
        'compute.instance.live_migration.pre.start',
        'compute.instance.live_migration._post.end',
        'compute.instance.live_migration._post.start',
        'compute.instance.power_off.end',
        'compute.instance.power_off.start',
        'compute.instance.power_on.end',
        'compute.instance.power_on.start',
        'compute.instance.reboot.end',
        'compute.instance.reboot.start',
        'compute.instance.rebuild.end',
        'compute.instance.rebuild.start',
        'compute.instance.rescue.end',
        'compute.instance.rescue.start',
        'compute.instance.resize.confirm.end',
        'compute.instance.resize.confirm.start',
        'compute.instance.resize.end',
        'compute.instance.resize.prep.end',
        'compute.instance.resize.prep.start',
        'compute.instance.resize.revert.end',
        'compute.instance.resize.revert.start',
        'compute.instance.resize.start',
        'compute.instance.resume',
        'compute.instance.shutdown.end',
        'compute.instance.shutdown.start',
        'compute.instance.snapshot.end',
        'compute.instance.snapshot.start',
        'compute.instance.suspend',
        'compute.instance.unrescue.end',
        'compute.instance.unrescue.start',
        'compute.instance.update',
        'compute.instance.volume.attach',
        'compute.instance.volume.detach'
]


text:
class CreateResponses < ActiveRecord::Migration
  def change
    create_table :responses do |t|
      t.integer :plan_id
      t.integer :requirement_id
      t.integer :label_id
      t.text :value

      t.timestamps
    end
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	/**
	 * Array para guardar todas las variables de la pagina
	 * @var array
	 */
	private $variables;

	/**
	 * Array para guardar exclusivamente los values del formulario
	 * @var array
	 */
	public $form_data;

	/**
	 * Constructor de clase
	 * Se encarga de hacer el load de los modulos necesarios
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();

		$this->load->library(array('form_validation', 'session', 'email' ));
		$this->load->helper(array('url', 'form'));
		$this->load->model('Login_model');
		$this->load->model('Emails_model');
		$this->form_data = new stdClass();//Instancio una clase vacia para evitar el warning "Creating default object from empty value"
		$this->variables['action'] = site_url('login/validate_credentials');
		$this->_initialize_fields();
	}

	/**
	 * Funcion que se carga por default al invocar al controlador sin especificar la URL completa
	 * @return void
	 */
	public function index()
	{
		$this->load->view('login/save', $this->variables);
	}

	/**
	 * Funcion que valida usuario y contraseña
	 * @return void
	 */
	public function validate_credentials()
	{
		$this->_set_rules();
		if($this->form_validation->run() == FALSE)//@TODO Validar si el usuario esta activo
		{
			$this->variables['message'] = '
' . validation_errors() . '
';
			$this->load->view('login/save', $this->variables);
		}
		else
		{
			$user = ($this->_get_post());
			$response = $this->Login_model->validate($user);
			if($response!=NULL)
			{
				$data = array(
						'userName' 		=> $this->input->post('userName'),
				        'idUser'        => $response['user']['idUser'],
						'token'			=> $response['token'],
						'idDiner'		=> $response['diners'][0]['idDiner'],
						'dinerName'		=> $response['diners'][0]['name'],
						'is_logged_in' 	=> true,
						'role'			=> $response['user']['role']
				);
				$this->session->set_userdata($data);
				redirect('home');
			}
			else
			{
				$this->variables['message'] = '
Nombre de usuario/contraseña incorrectos.
';
				$this->load->view('login/save', $this->variables);
			}
		}
	}

	/**
	 * Funcion que deslogea al usuario eliminando sus datos de la session
	 * @return		void
	 */
	public function logout()
	{
		$this->session->sess_destroy();
		$this->index();
	}

	/**
	 * Funcion que le envia una nueva contraseña al usuario a su mail
	 * @return		void
	 */
	public function forgot_password()
	{
		$this->variables['action'] = site_url('login/forgot_password');
		$this->_set_rules_forgot_password();
		$html_ok = '
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>';
		$html_error = '
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>';
		$html_close = '
';
		if($this->form_validation->run() == FALSE)
		{
			$this->variables['message'] = validation_errors();
			$this->variables['message'] = $this->variables['message'] != '' ? $html_error . $this->variables['message'] . $html_close : '';
		}
		else
		{
			$password = ($this->_get_post_forgot_password());
			if(($this->Login_model->reset_password($password))!=NULL)
			{
				$this->variables['message'] = $html_ok . 'Se envió un mail con su contraseña!' . $html_close;
			}
			else
			{
				$this->variables['message'] = $html_error . '¡Ups! Ocurrió un error' . $html_close;
			}
		}
		$this->load->view('login/reset_password', $this->variables);
	}

	/**
	 * Obtiene los datos del post y los devuelve en forma de objeto
	 * @return		object		$user
	 */
	private function _get_post()
	{
		$user 			= new stdClass();
		$user->userName = $this->input->post('userName');
		$user->password	= $this->input->post('password');
		return $user;
	}

	/**
	 * Obtiene los datos del post y los devuelve en forma de objeto
	 * @return		object		$password
	 */
	private function _get_post_forgot_password()
	{
		$password 				= new stdClass();
		$password->userName 	= $this->input->post('userName');
		$password->newPassword	= $this->_generate_password();
		return $password;
	}

	/**
	 * Funcion que inicializa las variables de los campos del formulario para la edición
	 * @return void
	 */
	private function _initialize_fields()
	{
		$this->variables['message'] = '';
		$this->form_data->userName 	= '';
		$this->form_data->password 	= '';
	}

	/**
	 * Funcion que setea las reglas de validacion del formulario y sus mensajes de errores
	 * @return void
	 */
	private function _set_rules()
	{
		$this->form_validation->set_message('required', 'Complete {field}.');
		$this->form_validation->set_rules('userName', 'Nombre de usuario/Email', 'required');
		$this->form_validation->set_rules('password', 'Contraseña', 'trim|required');
	}

	/**
	 * Funcion que setea las reglas de validacion del formulario y sus mensajes de errores
	 * @return void
	 */
	private function _set_rules_forgot_password()
	{
		$this->form_validation->set_rules('userName', 'Email', 'required|valid_email');
	}

	/**
	 * Función que genera una contraseña en forma aleatorio
	 * @param    $chars_min largo minimo (opcional, default 6)
	 * @param    $chars_max largo máximo (opcional, default 8)
	 * @param    $use_upper_case boolean para indicar si se usan mayúsuculas (opcional, default false)
	 * @param    $include_numbers boolean para indicar si se usan numeros (opcional, default false)
	 * @param    $include_special_chars boolean para indicar si se usan caracteres especiales (opcional, default false)
	 * @return    string containing a random password
	 */
	private function _generate_password($chars_min=6, $chars_max=8, $use_upper_case=false, $include_numbers=false, $include_special_chars=false)
	{
		$length = rand($chars_min, $chars_max);
		$selection = 'aeuoyibcdfghjklmnpqrstvwxz';
		if($include_numbers)
			$selection .= "1234567890";
			if($include_special_chars)
				$selection .= "!@\"#$%&[]{}?|";
				$password = "";
				for($i=0; $i<$length; $i++) {
					$current_letter = $use_upper_case ? (rand(0,1) ? strtoupper($selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))]) : $selection[(rand() % strlen($selection))];
					$password .=  $current_letter;
				}
				return $password;
	}

	/**
	 * Función que envia un mail a un destinatario con su contraseña
	 * @param    $to 		string destinatario
	 * @param    $password 	string password
	 */
	private function _send_mail($to, $password)
  	{
		return true;
	}
}


text:
"""
Implements the empirical cumulative distribution function given an array
of observations.

"""

import numpy as np

class ECDF:
    """
    One-dimensional empirical distribution function given a vector of
    observations.

    Parameters
    ----------
    observations : array_like
        An array of observations

    Attributes
    ----------
    observations : see Parameters

    """

    def __init__(self, observations):
        self.observations = np.asarray(observations)

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        m = "Empirical CDF:\n  - number of observations: {n}"
        return m.format(n=self.observations.size)

    def __call__(self, x):
        """
        Evaluates the ecdf at x

        Parameters
        ----------
        x : scalar(float)
            The x at which the ecdf is evaluated

        Returns
        -------
        scalar(float)
            Fraction of the sample less than x

        """
        def f(a):
            return np.mean(self.observations <= a)
        vf = np.frompyfunc(f, 1, 1)
        return vf(x).astype(float)


text:
        Email Address
        Actions

          {{::user.email_address}}
          Admin
          Invited

            <button type="button" class="btn btn-sm btn-primary dropdown-toggle" data-toggle="dropdown">

            </button>

 Resend Invite Email

 {{user.is_invite ? 'Revoke Invite' : 'Remove User' }}

                 {{vm.hasAdminRole(user)? 'Add Admin Role' : 'Remove Admin Role' }}

          No users were found.

        {{vm.pageSummary}}

 2">


text:
/* global markdown, hljs, mermaid, impress, document, window */

( function( document, window ) {
    "use strict";

    var preInit = function() {
        if ( window.markdown ) {

            // Unlike the other extras, Markdown.js doesn't by default do anything in
            // particular. We do it ourselves here.
            // In addition, we use "-----" as a delimiter for new slide.

            // Query all .markdown elements and translate to HTML
            var markdownDivs = document.querySelectorAll( ".markdown" );
            for ( var idx = 0; idx < markdownDivs.length; idx++ ) {
              var element = markdownDivs[ idx ];

              var slides = element.textContent.split( /^-----$/m );
              var i = slides.length - 1;
              element.innerHTML = markdown.toHTML( slides[ i ] );

              // If there's an id, unset it for last, and all other, elements,
              // and then set it for the first.
              var id = null;
              if ( element.id ) {
                id = element.id;
                element.id = "";
              }
              i--;
              while ( i >= 0 ) {
                var newElement = element.cloneNode( false );
                newElement.innerHTML = markdown.toHTML( slides[ i ] );
                element.parentNode.insertBefore( newElement, element );
                element = newElement;
                i--;
              }
              if ( id !== null ) {
                element.id = id;
              }
            }
        } // Markdown

        if ( window.hljs ) {
            hljs.initHighlightingOnLoad();
        }

        if ( window.mermaid ) {
            mermaid.initialize( { startOnLoad:true } );
        }
    };

    // Register the plugin to be called in pre-init phase
    // Note: Markdown.js should run early/first, because it creates new div elements.
    // So add this with a lower-than-default weight.
    impress.addPreInitPlugin( preInit, 1 );

} )( document, window );


text:
using System;

namespace SevenZip
{
	public interface ISetDecoderProperties
	{
		void SetDecoderProperties(byte[] properties);
	}
}


text:
package v1

import (
	"context"

	"google.golang.org/grpc"

	"go-common/library/net/rpc/warden"
)

const AppID = "live.daoanchor"

type Client struct {
	DaoAnchorClient
}

// NewClient new anchor grpc client
func NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) (*Client, error) {
	client := warden.NewClient(cfg, opts...)
	conn, err := client.Dial(context.Background(), "discovery://default/"+AppID)
	if err != nil {
		return nil, err
	}
	cli := &Client{}
	cli.DaoAnchorClient = NewDaoAnchorClient(conn)
	return cli, nil
}


text:
import * as moment from "moment";

/**
 * @class
 * Initializes a new instance of the SpellingTokenSuggestion class.
 * @constructor
 * @member {string} suggestion
 * @member {number} [score]
 * @member {string} [pingUrlSuffix]
 */
export interface SpellingTokenSuggestion {
  suggestion: string;
  readonly score?: number;
  readonly pingUrlSuffix?: string;
}

/**
 * @class
 * Initializes a new instance of the SpellingFlaggedToken class.
 * @constructor
 * @member {number} offset
 * @member {string} token
 * @member {string} type Possible values include: 'UnknownToken',
 * 'RepeatedToken'. Default value: 'UnknownToken' .
 * @member {array} [suggestions]
 * @member {string} [pingUrlSuffix]
 */
export interface SpellingFlaggedToken {
  offset: number;
  token: string;
  type: string;
  readonly suggestions?: SpellingTokenSuggestion[];
  readonly pingUrlSuffix?: string;
}

/**
 * @class
 * Initializes a new instance of the ResponseBase class.
 * @constructor
 * @member {string} _type Polymorphic Discriminator
 */
export interface ResponseBase {
  _type: string;
}

/**
 * @class
 * Initializes a new instance of the Identifiable class.
 * @constructor
 * Defines the identity of a resource.
 *
 * @member {string} [id] A String identifier.
 */
export interface Identifiable extends ResponseBase {
  readonly id?: string;
}

/**
 * @class
 * Initializes a new instance of the Response class.
 * @constructor
 * Defines a response. All schemas that could be returned at the root of a
 * response should inherit from this
 *
 */
export interface Response extends Identifiable {
}

/**
 * @class
 * Initializes a new instance of the Answer class.
 * @constructor
 */
export interface Answer extends Response {
}

/**
 * @class
 * Initializes a new instance of the SpellCheck class.
 * @constructor
 * @member {array} flaggedTokens
 */
export interface SpellCheck extends Answer {
  flaggedTokens: SpellingFlaggedToken[];
}

/**
 * @class
 * Initializes a new instance of the ErrorModel class.
 * @constructor
 * Defines the error that occurred.
 *
 * @member {string} code The error code that identifies the category of error.
 * Possible values include: 'None', 'ServerError', 'InvalidRequest',
 * 'RateLimitExceeded', 'InvalidAuthorization', 'InsufficientAuthorization'.
 * Default value: 'None' .
 * @member {string} [subCode] The error code that further helps to identify the
 * error. Possible values include: 'UnexpectedError', 'ResourceError',
 * 'NotImplemented', 'ParameterMissing', 'ParameterInvalidValue',
 * 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing',
 * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired'
 * @member {string} message A description of the error.
 * @member {string} [moreDetails] A description that provides additional
 * information about the error.
 * @member {string} [parameter] The parameter in the request that caused the
 * error.
 * @member {string} [value] The parameter's value in the request that was not
 * valid.
 */
export interface ErrorModel {
  code: string;
  readonly subCode?: string;
  message: string;
  readonly moreDetails?: string;
  readonly parameter?: string;
  readonly value?: string;
}

/**
 * @class
 * Initializes a new instance of the ErrorResponse class.
 * @constructor
 * The top-level response that represents a failed request.
 *
 * @member {array} errors A list of errors that describe the reasons why the
 * request failed.
 */
export interface ErrorResponse extends Response {
  errors: ErrorModel[];
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>

        <service
            android:name=".MessageListWidgetService"
            android:enabled="true"
            android:permission="android.permission.BIND_REMOTEVIEWS" />

    </application>
</manifest>


text:
<?php
require_once('config.inc.php');
// start new session or get current session
// basically looks for cookie or creates one
session_start();

// determines if user is logged in
function isLoggedIn() {
	return (isset($_SESSION['id']) && $_SESSION['can_login']);
}

// determines if session is expired
function isExpired() {
	return (time() - $_SESSION['time'] > SESSION_MAX_LENGTH);
}

// we do this every 'action' the user performs
function updateLastReq() {
	$_SESSION['time'] = time();
}
?>


text:
package org.jclouds.dynect.v3.domain.rdata;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.beans.ConstructorProperties;
import java.util.Map;

import com.google.common.collect.ForwardingMap;
import com.google.common.collect.ImmutableMap;

/**
 * Corresponds to the binary representation of the {@code SOA} (Start of Authority) RData
 *
 *
Example

 *
 *

 * SOAData rdata = SOAData.builder()
 *                        .rname("foo.com.")
 *                        .mname("admin.foo.com.")
 *                        .serial(1)
 *                        .refresh(3600)
 *                        .retry(600)
 *                        .expire(604800)
 *                        .minimum(60).build()
 *

 *
 * @see RFC 1035
 */
public class SOAData extends ForwardingMap<String, Object> {
   private final String mname;
   private final String rname;
   private final int serial;
   private final int refresh;
   private final int retry;
   private final int expire;
   private final int minimum;

   @ConstructorProperties({ "mname", "rname", "serial", "refresh", "retry", "expire", "minimum" })
   private SOAData(String mname, String rname, int serial, int refresh, int retry,
         int expire, int minimum) {
      this.mname = checkNotNull(mname, "mname");
      this.rname = checkNotNull(rname, "rname of %s", mname);
      checkArgument(serial >= 0, "serial of %s must be unsigned", mname);
      this.serial = serial;
      checkArgument(refresh >= 0, "refresh of %s must be unsigned", mname);
      this.refresh = refresh;
      checkArgument(retry >= 0, "retry of %s must be unsigned", mname);
      this.retry = retry;
      checkArgument(expire >= 0, "expire of %s must be unsigned", mname);
      this.expire = expire;
      checkArgument(minimum >= 0, "minimum of %s must be unsigned", mname);
      this.minimum = minimum;
      this.delegate = ImmutableMap.<String, Object> builder()
            .put("mname", checkNotNull(mname, "mname"))
            .put("rname", checkNotNull(rname, "rname of %s", mname))
            .put("serial", checkNotNull(serial, "serial of %s", mname))
            .put("refresh", checkNotNull(refresh, "refresh of %s", mname))
            .put("retry", checkNotNull(retry, "retry of %s", mname))
            .put("expire", checkNotNull(expire, "expire of %s", mname))
            .put("minimum", checkNotNull(minimum, "minimum of %s", mname)).build();
   }

   /**
    * domain-name of the name server that was the original or primary source of
    * data for this zone
    */
   public String getMname() {
      return mname;
   }

   /**
    * domain-name which specifies the mailbox of the person responsible for this
    * zone.
    */
   public String getRname() {
      return rname;
   }

   /**
    * version number of the original copy of the zone.
    */
   public int getSerial() {
      return serial;
   }

   /**
    * time interval before the zone should be refreshed
    */
   public int getRefresh() {
      return refresh;
   }

   /**
    * time interval that should elapse before a failed refresh should be retried
    */
   public int getRetry() {
      return retry;
   }

   /**
    * time value that specifies the upper limit on the time interval that can
    * elapse before the zone is no longer authoritative.
    */
   public int getExpire() {
      return expire;
   }

   /**
    * minimum TTL field that should be exported with any RR from this zone.
    */
   public int getMinimum() {
      return minimum;
   }

   private final transient ImmutableMap<String, Object> delegate;

   protected Map<String, Object> delegate() {
      return delegate;
   }

   public static SOAData.Builder builder() {
      return new Builder();
   }

   public SOAData.Builder toBuilder() {
      return builder().from(this);
   }

   public static final class Builder {
      private String mname;
      private String rname;
      private int serial = -1;
      private int refresh = -1;
      private int retry = -1;
      private int expire = -1;
      private int minimum = -1;

      /**
       * @see SOAData#getMname()
       */
      public SOAData.Builder mname(String mname) {
         this.mname = mname;
         return this;
      }

      /**
       * @see SOAData#getRname()
       */
      public SOAData.Builder rname(String rname) {
         this.rname = rname;
         return this;
      }

      /**
       * @see SOAData#getSerial()
       */
      public SOAData.Builder serial(int serial) {
         this.serial = serial;
         return this;
      }

      /**
       * @see SOAData#getRefresh()
       */
      public SOAData.Builder refresh(int refresh) {
         this.refresh = refresh;
         return this;
      }

      /**
       * @see SOAData#getRetry()
       */
      public SOAData.Builder retry(int retry) {
         this.retry = retry;
         return this;
      }

      /**
       * @see SOAData#getExpire()
       */
      public SOAData.Builder expire(int expire) {
         this.expire = expire;
         return this;
      }

      /**
       * @see SOAData#getMinimum()
       */
      public SOAData.Builder minimum(int minimum) {
         this.minimum = minimum;
         return this;
      }

      public SOAData build() {
         return new SOAData(mname, rname, serial, refresh, retry, expire, minimum);
      }

      public SOAData.Builder from(SOAData in) {
         return this.mname(in.getMname()).rname(in.getRname()).serial(in.getSerial()).refresh(in.getRefresh())
               .expire(in.getExpire()).minimum(in.getMinimum());
      }
   }
}


text:
package com.longcoding.moon.helpers;

import com.google.common.collect.Lists;
import com.longcoding.moon.configs.APIExposeSpecConfig;
import com.longcoding.moon.exceptions.ExceptionType;
import com.longcoding.moon.exceptions.GeneralException;
import com.longcoding.moon.models.apis.TransformData;
import com.longcoding.moon.models.cluster.ApiSync;
import com.longcoding.moon.models.ehcache.ApiInfo;
import com.longcoding.moon.models.ehcache.ServiceInfo;
import com.longcoding.moon.models.enumeration.*;
import com.longcoding.moon.services.sync.SyncService;
import com.longcoding.moon.models.ehcache.ServiceRoutingInfo;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * A class for loading all API specification information into the cache along with application loading.
 * Regardless of cluster mode, it is loaded based on application-apis.yml by default.
 * If an exception occurs, make sure that the configuration file is not corrupted.
 * If you use the cluster mode, you do not need to load the configuration file every time.
 *
 * @author longcoding
 */

@Slf4j
@Component
@EnableConfigurationProperties(APIExposeSpecConfig.class)
public class APIExposeSpecLoader implements InitializingBean {

    @Autowired
    APIExposeSpecConfig apiExposeSpecConfig;

    @Autowired
    APIExposeSpecification apiExposeSpecification;

    @Autowired
    SyncService syncService;

    @Value("${moon.service.ip-acl-enable}")
    Boolean enableIpAcl;

    @Value("${moon.service.cluster.enable}")
    Boolean enableCluster;

    @Autowired
    IClusterRepository clusterRepository;

    @Override
    public void afterPropertiesSet() throws Exception {

        // Whether to use IP-ACLs.
        // Set in application.yml.
        APIExposeSpecification.setIsEnabledIpAcl(enableIpAcl);

        // In cluster mode, the API information stored in the persistence layer is fetched and stored in the cache.
        if (enableCluster) {
            try {
                log.info("Loading Service Information");
                clusterRepository.getAllServiceInfo()
                        .forEach(serviceInfo -> {
                            apiExposeSpecification.getServiceInfoCache().put(serviceInfo.getServiceId(), serviceInfo);

                            String servicePath = serviceInfo.getServicePath().startsWith("/")? serviceInfo.getServicePath().substring(1) : serviceInfo.getServicePath();
                            apiExposeSpecification.getServiceTypeCache().put(servicePath, new ServiceRoutingInfo(serviceInfo.getServiceId(), serviceInfo.getRoutingType()));
                        });

                log.info("Loading API Spec Information");
                clusterRepository.getAllApiInfo()
                        .forEach(apiInfo -> syncService.syncApiInfoToCache(new ApiSync(SyncType.CREATE, apiInfo)));
            } catch (Exception ex) {
                throw new GeneralException(ExceptionType.E_1203_FAIL_CLUSTER_SYNC, ex);
            }
        }

        // Whether to load the api specification information in the configuration file.
        // There is no need to load each time.
        if ( !apiExposeSpecConfig.isInitEnable() ) return ;

        // Loads the service information in the configuration file into the cache.
        try {
            //Enroll Service expose
            apiExposeSpecConfig.getServices().forEach(service -> {

                RoutingType serviceRoutingType = service.isOnlyPassRequestWithoutTransform()? RoutingType.SKIP_API_TRANSFORM : RoutingType.API_TRANSFER;
                String servicePath = service.getServicePath().startsWith("/")? service.getServicePath().substring(1) : service.getServicePath();
                apiExposeSpecification.getServiceTypeCache().put(servicePath, new ServiceRoutingInfo(service.getServiceId(), serviceRoutingType));

                ServiceInfo serviceInfo = ServiceInfo.builder()
                        .serviceId(service.getServiceId())
                        .serviceName(service.getServiceName())
                        .minutelyCapacity(String.valueOf(service.getServiceMinutelyCapacity()))
                        .dailyCapacity(String.valueOf(service.getServiceDailyCapacity()))
                        .servicePath(service.getServicePath())
                        .outboundServiceHost(service.getOutboundServiceHost())
                        .routingType(serviceRoutingType)
                        .build();
                apiExposeSpecification.getServiceInfoCache().put(service.getServiceId(), serviceInfo);

                if (enableCluster) clusterRepository.setServiceInfo(serviceInfo);
            });
        } catch (Exception ex) {
            throw new GeneralException(ExceptionType.E_1200_FAIL_SERVICE_INFO_CONFIGURATION_INIT, ex);
        }

         // Loads the api specification information in the configuration file into the cache.
        try {
            //Enroll API expose
            apiExposeSpecConfig.getServices().forEach(service -> {
                if (Objects.isNull(service.getApis())) return ;
                service.getApis().forEach(apiSpec -> {

                    ConcurrentHashMap<String, Boolean> headers = new ConcurrentHashMap<>();
                    apiSpec.getHeader().forEach(header -> headers.put(header.toLowerCase(), false));
                    apiSpec.getHeaderRequired().forEach(requiredHeader -> headers.replace(requiredHeader.toLowerCase(), true));

                    ConcurrentHashMap<String, Boolean> queryParams = new ConcurrentHashMap<>();
                    apiSpec.getQueryParam().forEach(param -> queryParams.put(param.toLowerCase(), false));
                    apiSpec.getQueryParamRequired().forEach(requiredParam -> queryParams.replace(requiredParam.toLowerCase(), true));

                    List<TransformData> transformRequests = Lists.newArrayList();
                    Map<String, String[]> transformRequest = apiSpec.getTransform();
                    if (Objects.nonNull(transformRequest)) {
                        transformRequest.forEach((targetKey, transformPoint) -> {
                            TransformData transformData = TransformData.builder()
                                    .targetKey(targetKey.toLowerCase())
                                    .currentPoint(TransformType.of(transformPoint[0]))
                                    .targetPoint(TransformType.of(transformPoint[1]))
                                    .newKeyName(transformPoint.length > 2? transformPoint[2]:targetKey.toLowerCase())
                                    .build();
                            transformRequests.add(transformData);
                        });
                    }

                    ApiInfo apiInfo = ApiInfo.builder()
                            .apiId(apiSpec.getApiId())
                            .apiName(apiSpec.getApiName())
                            .serviceId(service.getServiceId())
                            .headers(headers)
                            .queryParams(queryParams)
                            .inboundURL(apiSpec.getInboundUrl().toLowerCase())
                            .outboundURL(apiSpec.getOutboundUrl().toLowerCase())
                            .inboundMethod(apiSpec.getMethod())
                            .outboundMethod(apiSpec.getMethod())
                            .protocol(apiSpec.getProtocol().stream().map(ProtocolType::of).collect(Collectors.toList()))
                            .isOpenApi(true)
                            .transformData(transformRequests)
                            .build();

                    apiExposeSpecification.getApiInfoCache().put(apiSpec.getApiId(), apiInfo);

                    if (enableCluster) clusterRepository.setApiInfo(apiInfo);
                });
            });

            /*
             * Enroll API Routing URL
             * Loads the api path information in the configuration file into the cache.
             * path is made to pattern for regex operations.
             */
            apiExposeSpecConfig.getServices().forEach(service -> {
                if (Objects.isNull(service.getApis())) return ;
                service.getApis().forEach(apiSpec -> {

                    String routingUrl = apiSpec.getInboundUrl();
                    String routingPathInRegex = HttpHelper.getRoutingRegex(routingUrl);

                    String servicePath = (service.getServicePath().startsWith("/"))? service.getServicePath() : "/" + service.getServicePath();
                    Pattern routingUrlInRegex = Pattern.compile(servicePath + routingPathInRegex);

                    apiExposeSpecification.getRoutingPathCache(MethodType.of(apiSpec.getMethod())).put(apiSpec.getApiId(), routingUrlInRegex);

                });
            });
        } catch (Exception ex) {
            throw new GeneralException(ExceptionType.E_1201_FAIL_API_INFO_CONFIGURATION_INIT, ex);
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Markdown Files — My sample book</title>

  <link href="_static/styles/theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link href="_static/styles/pydata-sphinx-theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">

  <link rel="stylesheet"
    href="_static/vendor/fontawesome/5.13.0/css/all.min.css">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
  <link rel="preload" as="font" type="font/woff2" crossorigin
    href="_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">

    <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
    <link rel="stylesheet" href="_static/styles/sphinx-book-theme.css?digest=5115cc725059bd94278eecd172e13a965bf8f5a9" type="text/css" />
    <link rel="stylesheet" type="text/css" href="_static/togglebutton.css" />
    <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
    <link rel="stylesheet" type="text/css" href="_static/mystnb.css" />
    <link rel="stylesheet" type="text/css" href="_static/sphinx-thebe.css" />
    <link rel="stylesheet" type="text/css" href="_static/design-style.b7bb847fb20b106c3d81b95245e65545.min.css" />

  <link rel="preload" as="script" href="_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf">

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Content with notebooks" href="notebooks.html" />
    <link rel="prev" title="Welcome to your Jupyter Book" href="intro.html" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="docsearch:language" content="None">

<input type="checkbox" class="sidebar-toggle" name="__navigation" id="__navigation" aria-label="Toggle navigation sidebar">

Toggle navigation sidebar

<input type="checkbox" class="sidebar-toggle" name="__page-toc" id="__page-toc" aria-label="Toggle in-page Table of Contents">

Toggle in-page Table of Contents

My sample book

<form class="bd-search d-flex align-items-center" action="search.html" method="get">

  <input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>

                    Welcome to your Jupyter Book

   Markdown Files

   Content with notebooks

   Notebooks with MyST Markdown

            Powered by Jupyter Book

<button onclick="toggleFullScreen()"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="bottom"
title="Fullscreen mode"
>

</button>

  <button class="headerbtn menu-dropdown__trigger"
      aria-label="Source repositories">

  </button>

repository

open issue

  <button class="headerbtn menu-dropdown__trigger"
      aria-label="Download this page">

  </button>

.md

<button onclick="printPdf(this)"
  class="headerbtn"
  data-toggle="tooltip"
data-placement="left"
title="Print to PDF"
>

.pdf
</button>

         Contents

   What is MyST?

   Sample Roles and Directives

   Citations

   Learn more

Markdown Files

 Contents

   What is MyST?

   Sample Roles and Directives

   Citations

   Learn more

Markdown Files#

Whether you write your book's content in Jupyter Notebooks (.ipynb) or
in regular markdown files (.md), you'll write in the same flavor of markdown
called MyST Markdown.
This is a simple file to help you get started and show off some syntax.

What is MyST?#

MyST stands for "Markedly Structured Text". It
is a slight variation on a flavor of markdown called "CommonMark" markdown,
with small syntax extensions to allow you to write roles and directives
in the Sphinx ecosystem.

For more about MyST, see the MyST Markdown Overview.

Sample Roles and Directives#

Roles and directives are two of the most powerful tools in Jupyter Book. They
are kind of like functions, but written in a markup language. They both
serve a similar purpose, but roles are written in one line, whereas
directives span many lines. They both accept different kinds of inputs,
and what they do with those inputs depends on the specific role or directive
that is being called.

Here is a "note" directive:

Note

Here is a note

It will be rendered in a special box when you build your book.

Here is an inline directive to refer to a document: Notebooks with MyST Markdown.

Citations#

You can also cite references that are stored in a bibtex file. For example,
the following syntax: {cite}`holdgraf_evidence_2014` will render like
this: [HdHPK14].

Moreover, you can insert a bibliography into your page with this syntax:
The {bibliography} directive must be used for all the {cite} roles to
render properly.
For example, if the references for your book are stored in references.bib,
then the bibliography is inserted with:

HdHPK14

Christopher Ramsay Holdgraf, Wendy de Heer, Brian N. Pasley, and Robert T. Knight. Evidence for Predictive Coding in Human Auditory Cortex. In International Conference on Cognitive Neuroscience. Brisbane, Australia, Australia, 2014. Frontiers in Neuroscience.

Learn more#

This is just a simple starter to get you started.
You can learn a lot more at jupyterbook.org.

previous

Welcome to your Jupyter Book

next

Content with notebooks

    By The Jupyter Book Community

      © Copyright 2022.


text:
class Book < ActiveRecord::Base
  validates :title, :price, :in_stock, presence: true
  validates :price, :in_stock, numericality: true
  acts_as_cartable :title => "title", :price => "price", :thumb_image_url => "image.thumb.url", :in_stock => "in_stock"
  mount_uploader :image, ImageBookUploader

  def in_stock?
    self.in_stock > 0 ? true : false
  end

end


text:
/***************************************************************************/
/*                                                                         */
/*  ftotval.c                                                              */
/*                                                                         */
/*    FreeType API for validating OpenType tables (body).                  */
/*                                                                         */
/*  Copyright 2004, 2006, 2008, 2010, 2013 by                              */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

#include "ft2build.h"
#include FT_INTERNAL_DEBUG_H

#include FT_INTERNAL_OBJECTS_H
#include FT_SERVICE_OPENTYPE_VALIDATE_H
#include FT_OPENTYPE_VALIDATE_H

  /* documentation is in ftotval.h */

  FT_EXPORT_DEF( FT_Error )
  FT_OpenType_Validate( FT_Face    face,
                        FT_UInt    validation_flags,
                        FT_Bytes  *BASE_table,
                        FT_Bytes  *GDEF_table,
                        FT_Bytes  *GPOS_table,
                        FT_Bytes  *GSUB_table,
                        FT_Bytes  *JSTF_table )
  {
    FT_Service_OTvalidate  service;
    FT_Error               error;

    if ( !face )
    {
      error = FT_THROW( Invalid_Face_Handle );
      goto Exit;
    }

    if ( !( BASE_table &&
            GDEF_table &&
            GPOS_table &&
            GSUB_table &&
            JSTF_table ) )
    {
      error = FT_THROW( Invalid_Argument );
      goto Exit;
    }

    FT_FACE_FIND_GLOBAL_SERVICE( face, service, OPENTYPE_VALIDATE );

    if ( service )
      error = service->validate( face,
                                 validation_flags,
                                 BASE_table,
                                 GDEF_table,
                                 GPOS_table,
                                 GSUB_table,
                                 JSTF_table );
    else
      error = FT_THROW( Unimplemented_Feature );

  Exit:
    return error;
  }

  FT_EXPORT_DEF( void )
  FT_OpenType_Free( FT_Face   face,
                    FT_Bytes  table )
  {
    FT_Memory  memory;

    if ( !face )
      return;

    memory = FT_FACE_MEMORY( face );

    FT_FREE( table );
  }

/* END */


text:
SDLVideoStreamingFormat Class Reference

Section Contents

protocol

codec

-initWithCodec:protocol:

Overview

An available format for video streaming in projection applications

      protocol

Protocol type, see VideoStreamingProtocol

Required

Objective-C

@property (readwrite, strong, nonatomic)
    SDLVideoStreamingProtocol _Nonnull protocol;

Swift

var `</span><span class="nv">protocol</span><span class="p">`: SDLVideoStreamingProtocol { get set }

      codec

Codec type, see VideoStreamingCodec

Required

Objective-C

@property (readwrite, strong, nonatomic) SDLVideoStreamingCodec _Nonnull codec;

Swift

var codec: SDLVideoStreamingCodec { get set }

      -initWithCodec:protocol:

Undocumented

Objective-C

- (instancetype)initWithCodec:(SDLVideoStreamingCodec)codec protocol:(SDLVideoStreamingProtocol)protocol;

Swift

init(codec: SDLVideoStreamingCodec, protocol: SDLVideoStreamingProtocol)


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function loadEvents(isRefreshing) {
        getCurrentPosition().then(function(_results) {
            console.log("I got here");
            Ti.API.info("_results " + JSON.stringify(_results, null, 2));
            var coordinates = [];
            if ("Simulator" != Ti.Platform.model) {
                coordinates.push(_results.location.longitude);
                coordinates.push(_results.location.latitude);
            } else {
                coordinates.push(-77.0240199);
                coordinates.push(38.920055);
            }
            var events = Alloy.Collections.instance("event");
            var whereParams = {
                coordinates: {
                    $nearSphere: coordinates,
                    $maxDistance: .00126
                }
            };
            events.reset();
            events.fetch({
                data: {
                    per_page: 30,
                    where: JSON.stringify(whereParams)
                },
                success: function() {
                    var rows = [];
                    events.forEach(function(e) {
                        var newRow = Alloy.createController("eventTableRow", {
                            eventModel: e
                        }).getView();
                        rows.push(newRow);
                    });
                    isRefreshing && $.refreshControl.hide();
                    $.tableView.data = rows;
                },
                error: function() {
                    isRefreshing && $.refreshControl.hide();
                    alert("Error fetching events, please try again");
                }
            });
        }, function(error) {
            alert(JSON.stringify(error));
        });
    }
    function showCreateEvent() {
        var win = Alloy.createController("createNewEvent", {
            parent: $
        }).getView();
        Alloy.Globals.tabgroup.activeTab.openWindow(win);
    }
    function onPullToRefresh() {
        loadEvents(true);
    }
    function getCurrentPosition() {
        var Q = require("q");
        var deferred = Q.defer();
        if (Ti.Geolocation.locationServicesEnabled) {
            Ti.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_NEAREST_TEN_METERS;
            Ti.Geolocation.distanceFilter = 10;
            Titanium.Geolocation.getCurrentPosition(function(e) {
                if (e.error) deferred.reject(e.error); else {
                    Ti.API.info(e.coords);
                    deferred.resolve({
                        location: {
                            longitude: e.coords.longitude,
                            latitude: e.coords.latitude
                        }
                    });
                }
            });
        } else deferred.reject({
            message: "Locaction services is disabled"
        });
        return deferred.promise;
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "home";
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.rootWindow = Ti.UI.createWindow({
        navTintColor: "white",
        backgroundColor: "#ffffff",
        barColor: "#2C82C9",
        titleAttributes: {
            color: "white",
            font: {
                fontFamily: "SourceSansPro-Bold",
                fontSize: 19
            }
        },
        translucent: "false",
        width: Ti.UI.FILL,
        heigth: Ti.UI.FILL,
        id: "rootWindow",
        title: "Feed"
    });
    $.__views.rootWindow && $.addTopLevelView($.__views.rootWindow);
    $.__views.rightNavButton = Ti.UI.createButton({
        width: Ti.UI.FILL,
        height: Ti.UI.FILL,
        tintColor: "white",
        color: "white",
        font: {
            fontFamily: "SourceSansPro-Bold",
            fontSize: 17
        },
        id: "rightNavButton",
        title: "Add",
        style: Titanium.UI.iPhone.SystemButtonStyle.PLAIN
    });
    $.__views.rootWindow.rightNavButton = $.__views.rightNavButton;
    $.__views.tableView = Ti.UI.createTableView({
        id: "tableView"
    });
    $.__views.refreshControl = Alloy.createWidget("nl.fokkezb.pullToRefresh", "widget", {
        id: "refreshControl",
        children: [ $.__views.tableView ],
        __parentSymbol: $.__views.rootWindow
    });
    $.__views.refreshControl.setParent($.__views.rootWindow);
    onPullToRefresh ? $.__views.refreshControl.on("release", onPullToRefresh) : __defers["$.__views.refreshControl!release!onPullToRefresh"] = true;
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    require("utilities");
    $.rightNavButton.addEventListener("click", showCreateEvent);
    $.initialize = function() {
        loadEvents(false);
    };
    __defers["$.__views.refreshControl!release!onPullToRefresh"] && $.__views.refreshControl.on("release", onPullToRefresh);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
<Record>
<Term>Protein-Energy Malnutrition</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<SemanticType>Pathologic Function</SemanticType>
<ParentTerm>Protein Deficiency</ParentTerm>
<ClassificationPath>Nutritional and Metabolic Diseases/Nutrition Disorders/Malnutrition/Deficiency Diseases/Protein Deficiency/Protein-Energy Malnutrition</ClassificationPath>
<BroaderTerm>Malnutrition</BroaderTerm>
<BroaderTerm>Protein-Energy Malnutrition</BroaderTerm>
<BroaderTerm>Nutritional and Metabolic Diseases</BroaderTerm>
<BroaderTerm>Nutrition Disorders</BroaderTerm>
<BroaderTerm>Protein Deficiency</BroaderTerm>
<BroaderTerm>Deficiency Diseases</BroaderTerm>
<ChildTerm>Kwashiorkor</ChildTerm>
<Synonym>Protein-Energy Malnutrition</Synonym>
<Synonym>Protein Energy Malnutrition</Synonym>
<Synonym>Protein-Calorie Malnutrition</Synonym>
<Synonym>Protein Calorie Malnutrition</Synonym>
<Synonym>Marasmus</Synonym>
<Description>The lack of sufficient energy or protein to meet the body's metabolic demands, as a result of either an inadequate dietary intake of protein, intake of poor quality dietary protein, increased demands due to disease, or increased nutrient losses.</Description>
<Source>MeSH</Source>
</Record>


text:
<?php

namespace Hubzero\Console\Exception;

class InvalidPropertyException extends \InvalidArgumentException implements ExceptionInterface
{
}


text:
package filter

import (
	"github.com/fitstar/falcore"
	"net/http"
	"sync"
	"time"
)

type UpstreamEntry struct {
	Upstream *Upstream
	Weight   int
}

// An UpstreamPool is a list of upstream servers which are considered
// functionally equivalent.  The pool will round-robin the requests to the servers.
type UpstreamPool struct {
	pool         []*UpstreamEntry
	rr_count     int
	ping_count   int64
	Name         string
	nextUpstream chan *UpstreamEntry
	shutdown     chan int
	weightMutex  *sync.RWMutex
	pinger       *time.Ticker
}

// The config consists of a map of the servers in the pool in the format host_or_ip:port
// where port is optional and defaults to 80.  The map value is an int with the weight
// only 0 and 1 are supported weights (0 disables a server and 1 enables it)
func NewUpstreamPool(name string, upstreams []*UpstreamEntry) *UpstreamPool {
	up := new(UpstreamPool)
	up.Name = name
	up.nextUpstream = make(chan *UpstreamEntry)
	up.weightMutex = new(sync.RWMutex)
	up.shutdown = make(chan int)
	up.pinger = time.NewTicker(3 * time.Second) // 3s
	up.pool = upstreams

	go up.nextServer()
	go up.pingUpstreams()

	return up
}

func (up UpstreamPool) Next() *UpstreamEntry {
	// TODO check in case all are down that we timeout
	return <-up.nextUpstream
}

// Logs the current status of the pool
func (up UpstreamPool) LogStatus() {
	weightsBuffer := make([]int, len(up.pool))
	// loop and save the weights so we don't lock for logging
	up.weightMutex.RLock()
	for i, ue := range up.pool {
		weightsBuffer[i] = ue.Weight
	}
	up.weightMutex.RUnlock()
	// Now do the logging
	for i, ue := range up.pool {
		falcore.Info("Upstream %v: %v:%v\t%v", up.Name, ue.Upstream.Transport.host, ue.Upstream.Transport.port, weightsBuffer[i])
	}
}

func (up UpstreamPool) FilterRequest(req *falcore.Request) (res *http.Response) {
	if len(up.pool) < 1 {
		return falcore.StringResponse(req.HttpRequest, 503, nil, "Service Unavailable\n")
	}

	ue := up.Next()
	res = ue.Upstream.FilterRequest(req)
	if req.CurrentStage.Status == 2 {
		// this gets set by the upstream for errors
		// so mark this upstream as down
		up.updateUpstream(ue, 0)
		up.LogStatus()
	}
	return
}

func (up UpstreamPool) updateUpstream(ue *UpstreamEntry, wgt int) {
	up.weightMutex.Lock()
	ue.Weight = wgt
	up.weightMutex.Unlock()
}

// This should only be called if the upstream pool is no longer active or this may deadlock
func (up UpstreamPool) Shutdown() {
	// ping and nextServer
	close(up.shutdown)

	// make sure we hit the shutdown code in the nextServer goroutine
	up.Next()
}

func (up UpstreamPool) nextServer() {
	// Don't start up if there are no entries
	if len(up.pool) < 1 {
		return
	}

	loopCount := 0
	for {
		next := up.rr_count % len(up.pool)
		up.weightMutex.RLock()
		wgt := up.pool[next].Weight
		up.weightMutex.RUnlock()
		// just return a down host if we've gone through the list twice and nothing is up
		// be sure to never return negative wgt hosts
		if (wgt > 0 || (loopCount > 2*len(up.pool))) && wgt >= 0 {
			loopCount = 0
			select {
			case <-up.shutdown:
				return
			case up.nextUpstream <- up.pool[next]:
			}
		} else {
			loopCount++
		}
		up.rr_count++
	}
}

func (up UpstreamPool) pingUpstreams() {
	pingable := true
	for pingable {
		select {
		case <-up.shutdown:
			return
		case <-up.pinger.C:
			gotone := false
			for i, ups := range up.pool {
				if ups.Upstream.PingPath != "" {
					go up.pingUpstream(ups, i)
					gotone = true
				}
			}
			if !gotone {
				pingable = false
			}
		}
	}
	falcore.Warn("Stopping ping for %v", up.Name)
}

func (up UpstreamPool) pingUpstream(ups *UpstreamEntry, index int) {
	isUp, ok := ups.Upstream.ping()
	up.weightMutex.RLock()
	wgt := ups.Weight
	up.weightMutex.RUnlock()
	// change in status
	if ok && (wgt > 0) != isUp {
		if isUp {
			up.updateUpstream(ups, 1)
		} else {
			up.updateUpstream(ups, 0)
		}
		up.LogStatus()
	}
}


text:
package com.dremio.exec.planner.sql.handlers.refresh;

import static com.dremio.exec.store.metadatarefresh.MetadataRefreshExecConstants.METADATA_STORAGE_PLUGIN_NAME;
import static com.dremio.io.file.Path.SEPARATOR;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.dremio.connector.ConnectorException;
import com.dremio.connector.metadata.BytesOutput;
import com.dremio.connector.metadata.DatasetSplit;
import com.dremio.connector.metadata.PartitionChunk;
import com.dremio.connector.metadata.PartitionChunkListing;
import com.dremio.connector.metadata.PartitionValue;
import com.dremio.exec.planner.physical.PlannerSettings;
import com.dremio.exec.planner.physical.Prel;
import com.dremio.exec.planner.physical.PrelUtil;
import com.dremio.exec.planner.sql.handlers.SqlHandlerConfig;
import com.dremio.exec.planner.sql.parser.SqlRefreshDataset;
import com.dremio.exec.store.DatasetRetrievalOptions;
import com.dremio.exec.store.PartitionChunkListingImpl;
import com.dremio.exec.store.dfs.FileSelection;
import com.dremio.exec.store.dfs.FileSystemPlugin;
import com.dremio.exec.store.iceberg.model.IcebergCommandType;
import com.dremio.exec.store.metadatarefresh.dirlisting.DirListingInvocationPrel;
import com.dremio.service.namespace.dataset.proto.DatasetConfig;
import com.dremio.service.namespace.dataset.proto.DatasetType;
import com.dremio.service.namespace.dirlist.proto.DirListInputSplitProto;
import com.dremio.service.namespace.file.proto.FileType;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

/**
 * Builds plan for filesystems in case of incremental and partial refresh.
 */
public class FileSystemRefreshIncrementalPlanBuilder extends FileSystemFullRefreshPlanBuilder implements SupportPartialRefresh {

  private final boolean isPartialRefresh;
  private PartitionChunk inputPartitionChunk;

  public FileSystemRefreshIncrementalPlanBuilder(SqlHandlerConfig config, SqlRefreshDataset sqlNode, UnlimitedSplitsMetadataProvider metadataProvider) {
    super(config, sqlNode, metadataProvider);
    logger.debug("Doing a filesystem incremental refresh on dataset. Dataset's full path is {}", datasetPath);
    isPartialRefresh = sqlNode.isPartialRefresh();
    icebergCommandType = IcebergCommandType.INCREMENTAL_METADATA_REFRESH;
  }

  @Override
  protected DatasetConfig setupDatasetConfig() {
    datasetFileType = FileType.PARQUET;
    //TODO: currently in the final table we write iceberg as the format of the dataset but we expect
    // all operators to have a parquet as the file type. So forcefully setting file type as parquet.
    DatasetConfig datasetConfig =  metadataProvider.getDatasetConfig();
    datasetConfig.getPhysicalDataset().getFormatSettings().setType(FileType.PARQUET);
    checkAndUpdateIsFileDataset();
    return datasetConfig;
  }

  @Override
  public PartitionChunkListing listPartitionChunks(DatasetRetrievalOptions datasetRetrievalOptions) throws ConnectorException {
    DirListInputSplitProto.DirListInputSplit dirListInputSplit;

    if (isPartialRefresh) {
      List<String> operatingPath = generatePathsForPartialRefresh();
      dirListInputSplit = DirListInputSplitProto.DirListInputSplit.newBuilder()
        .setRootPath(datasetPath.toString())
        .setOperatingPath(operatingPath.get(0))
        .setReadSignature(Long.MAX_VALUE).setIsFile(super.isFileDataset)
        .build();
    } else {
      dirListInputSplit = DirListInputSplitProto.DirListInputSplit.newBuilder()
        .setRootPath(datasetPath.toString())
        .setOperatingPath(datasetPath.toString())
        .setReadSignature(Long.MAX_VALUE).setIsFile(super.isFileDataset)
        .build();
    }
    DatasetSplit split = DatasetSplit.of(Collections.emptyList(), 1, 1, dirListInputSplit::writeTo);
    PartitionChunkListingImpl partitionChunkListing = new PartitionChunkListingImpl();
    partitionChunkListing.put(Collections.emptyList(), split);
    partitionChunkListing.computePartitionChunks();
    return partitionChunkListing;
  }

  @Override
  public Prel getDataFileListingPrel() {
    final FileSystemPlugin<?> metaStoragePlugin = config.getContext().getCatalogService().getSource(METADATA_STORAGE_PLUGIN_NAME);
    List<String> paths = isPartialRefresh ? generatePathsForPartialRefresh() : Collections.emptyList();

    return new DirListingInvocationPrel(cluster, cluster.getPlanner().emptyTraitSet().plus(Prel.PHYSICAL),
      table, storagePluginId, refreshExecTableMetadata,
      1.0d, metaStoragePlugin, metadataProvider.getTableUUId(), isPartialRefresh, metadataProvider, paths, x -> getRowCountEstimates("DirList"), ImmutableList.of());
  }

  public Prel getDirListToFooterReadExchange(Prel child) {
    return getHashToRandomExchangePrel(child);
  }

  @Override
  protected void checkAndUpdateIsFileDataset() {
    isFileDataset = DatasetType.PHYSICAL_DATASET_SOURCE_FILE.equals(metadataProvider.getDatasetConfig().getType());
  }

  public List<String> generatePathsForPartialRefresh() {
    RefreshDatasetValidator validator = new FileSystemPartitionValidator(metadataProvider);
    validator.validate(sqlNode);

    //Validated input partition chunks
    inputPartitionChunk = PartitionChunk.of(
      validator.getPartitionValues(),
      /* TODO */ ImmutableList.of(), BytesOutput.NONE);

    List<PartitionValue> partitionValues = inputPartitionChunk.getPartitionValues();

    List<String> partitionPaths = new ArrayList<>();
    partitionPaths.addAll(Arrays.asList(datasetPath.toString().split(SEPARATOR)));

    partitionValues.stream().forEach(x -> {
      String partition_path = ((PartitionValue.StringPartitionValue) x).getValue();
      partitionPaths.add(partition_path);
    });

    return Collections.singletonList(FileSelection.getPathBasedOnFullPath(partitionPaths).toString());
  }

  @Override
  public double getRowCountEstimates(String type) {
    Preconditions.checkState(datasetConfig != null, "Unexpected state");
    Preconditions.checkState(datasetConfig.getReadDefinition() != null, "Unexpected state");
    Preconditions.checkState(datasetConfig.getReadDefinition().getManifestScanStats() != null, "Unexpected state");
    double baseRowCount = datasetConfig.getReadDefinition().getManifestScanStats().getRecordCount();
    double increaseFactor = config.getContext().getOptions().getOption(PlannerSettings.METADATA_REFRESH_INCREASE_FACTOR);

    //Factor by which to overestimate footerRead row count. In practice have seen that footer read is
    //32 times slower than dirList. Kept the factor as 50 for safety now.
    double threadFactor = config.getContext().getOptions().getOption(PlannerSettings.FOOTER_READING_DIRLIST_RATIO);
    double minFilesChanged = config.getContext().getOptions().getOption(PlannerSettings.MIN_FILES_CHANGED_DURING_REFRESH);

    double addedFilesAfterLastRefresh = Math.max(baseRowCount * increaseFactor, minFilesChanged);

    final PlannerSettings plannerSettings = PrelUtil.getPlannerSettings(cluster);
    double sliceTarget = plannerSettings.getSliceTarget();

    switch (type) {
      case "DirList":
        baseRowCount = baseRowCount + addedFilesAfterLastRefresh;
        break;
      case "FooterReadTableFunction":
        //Number of threads should be thread factor times that of dirList
        baseRowCount = 1 * threadFactor * sliceTarget;
        break;
    }

    return Math.max(baseRowCount, 1);
  }

  @Override
  public boolean updateDatasetConfigWithIcebergMetadataIfNecessary() {
    return repairAndSaveDatasetConfigIfNecessary();
  }
}


text:
LogView::LogView(QWidget *parent)
    :QTableView(parent)
{
    connect(&m_autoScroll, &QTimer::timeout, this, &LogView::scrollToSelected);
    m_autoScroll.setSingleShot(true);
}

void LogView::setModel(QAbstractItemModel *newModel)
{
    if (model())
    {
        disconnect(model(), nullptr, this, nullptr);
    }
    QTableView::setModel(newModel);
    if (newModel)
    {
        connect(newModel, &QAbstractItemModel::rowsInserted, this, &LogView::autoScroll);
        connect(newModel, &QAbstractItemModel::rowsRemoved, this, &LogView::autoScroll);
    }
}

AbstractLogModel* LogView::sourceModel() const
{
    auto filter = static_cast<QAbstractProxyModel*>(model());
    return static_cast<AbstractLogModel*>(filter->sourceModel());
}

const LogMessage* LogView::message(int row) const
{
    auto filter = static_cast<QAbstractProxyModel*>(model());
    auto source = static_cast<AbstractLogModel*>(filter->sourceModel());
    return source->message(filter->mapToSource(filter->index(row, 0)).row());
}

void LogView::nextSeverity(LogSeverity type)
{
    auto selection = selectionModel()->currentIndex().row() + 1;
    auto filter = static_cast<QAbstractProxyModel*>(model());
    auto count = filter->rowCount();
    for (int i = 0; i < count; ++i)
    {
        auto msg = message(selection + i);
        if (msg && msg->severity == type)
        {
            selectionModel()->setCurrentIndex(filter->index((selection + i) % count, 0),
                                              QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
            return;
        }
    }
}

void LogView::previousSeverity(LogSeverity type)
{
    auto filter = static_cast<QAbstractProxyModel*>(model());
    auto count = filter->rowCount();
    auto selection = selectionModel()->currentIndex().row() + count;
    for (int i = 0; i < count; ++i)
    {
        auto msg = message((selection + count - 1 - i) % count);
        if (msg && msg->severity == type)
        {
            selectionModel()->setCurrentIndex(filter->index((selection + count - 1 - i) % count, 0),
                                              QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
            return;
        }
    }
}

void LogView::nextError()
{
    nextSeverity(SEVERITY_ERR);
}

void LogView::previousError()
{
    previousSeverity(SEVERITY_ERR);
}

void LogView::nextWarning()
{
    nextSeverity(SEVERITY_WARN);
}

void LogView::previousWarning()
{
    previousSeverity(SEVERITY_WARN);
}

void LogView::nextNotice()
{
    nextSeverity(SEVERITY_NOTICE);
}

void LogView::previousNotice()
{
    previousSeverity(SEVERITY_NOTICE);
}

void LogView::scrollToSelected()
{
    scrollTo(currentIndex());
    m_autoScroll.stop();
}

void LogView::autoScroll(const QModelIndex &, int first, int)
{
    if (currentIndex().row() == model()->rowCount() - 1)
    {
        scrollToBottom();
    }
    else if (first < currentIndex().row())
    {
        if (!m_autoScroll.isActive())
        {
            m_autoScroll.start();
        }
    }
}

void LogView::scrollToBeginning()
{
    selectRow(0);
}

void LogView::scrollToEnd()
{
    selectRow(model()->rowCount() - 1);
}

QString LogView::selectionAsText() const
{
    auto selection = selectionModel()->selectedRows();
    auto source = sourceModel();

    QString text;
    for (int i = 0; i < selection.size(); ++i)
    {
        auto msg = message(selection[i].row());
        if (!msg)
        {
            continue;
        }
        switch (msg->severity)
        {
        case SEVERITY_INFO:
            text += "info";
            break;
        case SEVERITY_NOTICE:
            text += "notice";
            break;
        case SEVERITY_WARN:
            text += "warning";
            break;
        case SEVERITY_ERR:
            text += "error";
            break;
        default:
            break;
        }
        for (int j = 0; j < source->columnCount(); ++j)
        {
            if (isColumnHidden(j))
            {
                continue;
            }
            text += "\t";
            text += model()->data(model()->index(selection[i].row(), j)).toString();
        }
        text += "\n";
    }
    return text;
}

QString LogView::selectionMessagesAsText() const
{
    auto selection = selectionModel()->selectedRows();

    QString text;
    for (int i = 0; i < selection.size(); ++i)
    {
        auto msg = message(selection[i].row());
        if (!msg)
        {
            continue;
        }
        text += model()->data(model()->index(selection[i].row(), LOGFIELD_MESSAGE)).toString();
        text += "\n";
    }
    return text;
}

void LogView::selectNextMatching(QString text)
{
    if (text.isEmpty())
    {
        return;
    }
    auto selection = selectionModel()->currentIndex().row() + 1;
    auto count = model()->rowCount();
    for (int i = 0; i < count; ++i)
    {
        auto msg = message(selection + i);
        if (!msg)
        {
            continue;
        }
        if (msg->message.contains(text, Qt::CaseInsensitive))
        {
            selectionModel()->setCurrentIndex(model()->index((selection + i) % count, 0),
                                              QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
            return;
        }
    }
}

void LogView::selectPreviousMatching(QString text)
{
    if (text.isEmpty())
    {
        return;
    }
    auto count = model()->rowCount();
    auto selection = selectionModel()->currentIndex().row() + count;
    for (int i = 0; i < count; ++i)
    {
        auto msg = message((selection + count - 1 - i) % count);
        if (!msg)
        {
            continue;
        }
        if (msg->message.contains(text, Qt::CaseInsensitive))
        {
            selectionModel()->setCurrentIndex(model()->index((selection + count - 1 - i) % count, 0),
                                              QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
            return;
        }
    }
}


text:
package org.elasticsearch.xpack.sql.expression.function.scalar;

import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry.Entry;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateAddProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DatePartProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTimeProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.DateTruncProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NamedDateTimeProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.NonIsoDateTimeProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.QuarterProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.datetime.TimeProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.geo.GeoProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StDistanceProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.geo.StWkttosqlProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryMathProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.math.BinaryOptionalMathProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.math.MathProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringNumericProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.BinaryStringStringProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.ConcatFunctionProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.InsertFunctionProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.LocateFunctionProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.ReplaceFunctionProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.StringProcessor;
import org.elasticsearch.xpack.sql.expression.function.scalar.string.SubstringFunctionProcessor;
import org.elasticsearch.xpack.sql.expression.gen.processor.BucketExtractorProcessor;
import org.elasticsearch.xpack.sql.expression.gen.processor.ChainingProcessor;
import org.elasticsearch.xpack.sql.expression.gen.processor.ConstantProcessor;
import org.elasticsearch.xpack.sql.expression.gen.processor.HitExtractorProcessor;
import org.elasticsearch.xpack.sql.expression.gen.processor.Processor;
import org.elasticsearch.xpack.sql.expression.predicate.conditional.CaseProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.conditional.ConditionalProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.conditional.NullIfProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.logical.BinaryLogicProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.logical.NotProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.nulls.CheckNullProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.BinaryArithmeticProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.operator.arithmetic.UnaryArithmeticProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.BinaryComparisonProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.operator.comparison.InProcessor;
import org.elasticsearch.xpack.sql.expression.predicate.regex.RegexProcessor;

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

public final class Processors {

    private Processors() {}

    /**
     * All of the named writeables needed to deserialize the instances of
     * {@linkplain Processors}.
     */
    public static List<NamedWriteableRegistry.Entry> getNamedWriteables() {
        List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
        // base
        entries.add(new Entry(Processor.class, ConstantProcessor.NAME, ConstantProcessor::new));
        entries.add(new Entry(Processor.class, HitExtractorProcessor.NAME, HitExtractorProcessor::new));
        entries.add(new Entry(Processor.class, BucketExtractorProcessor.NAME, BucketExtractorProcessor::new));
        entries.add(new Entry(Processor.class, CastProcessor.NAME, CastProcessor::new));
        entries.add(new Entry(Processor.class, ChainingProcessor.NAME, ChainingProcessor::new));

        // logical
        entries.add(new Entry(Processor.class, BinaryLogicProcessor.NAME, BinaryLogicProcessor::new));
        entries.add(new Entry(Processor.class, NotProcessor.NAME, NotProcessor::new));
        // conditionals
        entries.add(new Entry(Processor.class, CaseProcessor.NAME, CaseProcessor::new));
        entries.add(new Entry(Processor.class, CheckNullProcessor.NAME, CheckNullProcessor::new));
        entries.add(new Entry(Processor.class, ConditionalProcessor.NAME, ConditionalProcessor::new));
        entries.add(new Entry(Processor.class, NullIfProcessor.NAME, NullIfProcessor::new));

        // arithmetic
        entries.add(new Entry(Processor.class, BinaryArithmeticProcessor.NAME, BinaryArithmeticProcessor::new));
        entries.add(new Entry(Processor.class, UnaryArithmeticProcessor.NAME, UnaryArithmeticProcessor::new));
        // comparators
        entries.add(new Entry(Processor.class, BinaryComparisonProcessor.NAME, BinaryComparisonProcessor::new));
        entries.add(new Entry(Processor.class, InProcessor.NAME, InProcessor::new));
        // regex
        entries.add(new Entry(Processor.class, RegexProcessor.NAME, RegexProcessor::new));

        // datetime
        entries.add(new Entry(Processor.class, DateTimeProcessor.NAME, DateTimeProcessor::new));
        entries.add(new Entry(Processor.class, TimeProcessor.NAME, TimeProcessor::new));
        entries.add(new Entry(Processor.class, NamedDateTimeProcessor.NAME, NamedDateTimeProcessor::new));
        entries.add(new Entry(Processor.class, NonIsoDateTimeProcessor.NAME, NonIsoDateTimeProcessor::new));
        entries.add(new Entry(Processor.class, QuarterProcessor.NAME, QuarterProcessor::new));
        entries.add(new Entry(Processor.class, DateAddProcessor.NAME, DateAddProcessor::new));
        entries.add(new Entry(Processor.class, DatePartProcessor.NAME, DatePartProcessor::new));
        entries.add(new Entry(Processor.class, DateTruncProcessor.NAME, DateTruncProcessor::new));
        // math
        entries.add(new Entry(Processor.class, BinaryMathProcessor.NAME, BinaryMathProcessor::new));
        entries.add(new Entry(Processor.class, BinaryOptionalMathProcessor.NAME, BinaryOptionalMathProcessor::new));
        entries.add(new Entry(Processor.class, MathProcessor.NAME, MathProcessor::new));
        // string
        entries.add(new Entry(Processor.class, StringProcessor.NAME, StringProcessor::new));
        entries.add(new Entry(Processor.class, BinaryStringNumericProcessor.NAME, BinaryStringNumericProcessor::new));
        entries.add(new Entry(Processor.class, BinaryStringStringProcessor.NAME, BinaryStringStringProcessor::new));
        entries.add(new Entry(Processor.class, ConcatFunctionProcessor.NAME, ConcatFunctionProcessor::new));
        entries.add(new Entry(Processor.class, InsertFunctionProcessor.NAME, InsertFunctionProcessor::new));
        entries.add(new Entry(Processor.class, LocateFunctionProcessor.NAME, LocateFunctionProcessor::new));
        entries.add(new Entry(Processor.class, ReplaceFunctionProcessor.NAME, ReplaceFunctionProcessor::new));
        entries.add(new Entry(Processor.class, SubstringFunctionProcessor.NAME, SubstringFunctionProcessor::new));
        // geo
        entries.add(new Entry(Processor.class, GeoProcessor.NAME, GeoProcessor::new));
        entries.add(new Entry(Processor.class, StWkttosqlProcessor.NAME, StWkttosqlProcessor::new));
        entries.add(new Entry(Processor.class, StDistanceProcessor.NAME, StDistanceProcessor::new));
        return entries;
    }

    public static List<Object> process(List<Processor> processors, Object input) {
        List<Object> values = new ArrayList<>(processors.size());
        for (Processor p : processors) {
            values.add(p.process(input));
        }
        return values;
    }
}


text:
import _         from 'lodash';
import addresser from '../../lib/addresser';
import error     from '../../lib/error';

export default stateConfigs => {
  let {view, stateName, resolveConfigs, detachHidden, testMode} = stateConfigs;
  let uniqueAddress = addresser.uniqueAddress(stateName);

  if(!view) {
    error.throw('root state should have a designated view', 'state setter');
  }

  if(!resolveConfigs) {
    resolveConfigs = {
      duration: 0,
      store: true
    };
  }

  if(_.isUndefined(detachHidden)) {
    detachHidden = false;
  }

  if(!testMode) {
    var instance = new view();
    instance.render();
  }
  let record = {instance};
  let configs = {root: true, uniqueAddress, detachHidden, resolveConfigs, record};

  _.extend(stateConfigs, configs);

  stateConfigs.views = [_.omit(stateConfigs, 'animate')];
};


text:
/**
 * Allocation Scheme controller
 */
moj.Modules.AllocationScheme = {
  // wrapper for the form controls
  el: '#allocation-filters',

  // to cache the el
  $el: null,

  /**
   * Auto called by moj wrapper
   * cache the el
   * bindEvents
   */
  init: function () {
    this.$el = $(this.el)
    this.bindEvents()
  },

  bindEvents: function () {
    /**
     * Publish the sheme change event
     * passng the value
     * Publish data: {object} {scheme: <input value>}
     */
    this.$el.on('change', 'input', function (e) {
      $.publish('/scheme/change/', {
        scheme: $(e.target).val()
      })
    })
  },

  /**
   * Return the value of the selected radio
   */
  selectedValue: function () {
    return $(this.el).find('input:checked').val()
  }
}


text:
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Urho.Urho2D;
using Urho.Gui;
using Urho.Resources;
using Urho.IO;
using Urho.Navigation;
using Urho.Network;

namespace Urho
{
	/// <summary>
	/// Helper base class for user-defined game logic components that hooks up to update events and forwards them to virtual functions similar to ScriptInstance class.
	/// </summary>
	public unsafe partial class LogicComponent : Component
	{
		unsafe partial void OnLogicComponentCreated ();

		[Preserve]
		public LogicComponent (IntPtr handle) : base (handle)
		{
			OnLogicComponentCreated ();
		}

		[Preserve]
		protected LogicComponent (UrhoObjectFlag emptyFlag) : base (emptyFlag)
		{
			OnLogicComponentCreated ();
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern int LogicComponent_GetType (IntPtr handle);

		private StringHash UrhoGetType ()
		{
			Runtime.ValidateRefCounted (this);
			return new StringHash (LogicComponent_GetType (handle));
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr LogicComponent_GetTypeName (IntPtr handle);

		private string GetTypeName ()
		{
			Runtime.ValidateRefCounted (this);
			return Marshal.PtrToStringAnsi (LogicComponent_GetTypeName (handle));
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern int LogicComponent_GetTypeStatic ();

		private static StringHash GetTypeStatic ()
		{
			Runtime.Validate (typeof(LogicComponent));
			return new StringHash (LogicComponent_GetTypeStatic ());
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr LogicComponent_GetTypeNameStatic ();

		private static string GetTypeNameStatic ()
		{
			Runtime.Validate (typeof(LogicComponent));
			return Marshal.PtrToStringAnsi (LogicComponent_GetTypeNameStatic ());
		}

		[Preserve]
		public LogicComponent () : this (Application.CurrentContext)
		{
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern IntPtr LogicComponent_LogicComponent (IntPtr context);

		[Preserve]
		public LogicComponent (Context context) : base (UrhoObjectFlag.Empty)
		{
			Runtime.Validate (typeof(LogicComponent));
			handle = LogicComponent_LogicComponent ((object)context == null ? IntPtr.Zero : context.Handle);
			Runtime.RegisterObject (this);
			OnLogicComponentCreated ();
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_OnSetEnabled (IntPtr handle);

		/// <summary>
		/// Handle enabled/disabled state change. Changes update event subscription.
		/// </summary>
		public override void OnSetEnabled ()
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_OnSetEnabled (handle);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_Start (IntPtr handle);

		/// <summary>
		/// Called when the component is added to a scene node. Other components may not yet exist.
		/// </summary>
		public void Start ()
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_Start (handle);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_DelayedStart (IntPtr handle);

		/// <summary>
		/// Called before the first update. At this point all other components of the node should exist. Will also be called if update events are not wanted; in that case the event is immediately unsubscribed afterward.
		/// </summary>
		public void DelayedStart ()
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_DelayedStart (handle);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_Stop (IntPtr handle);

		/// <summary>
		/// Called when the component is detached from a scene node, usually on destruction. Note that you will no longer have access to the node and scene at that point.
		/// </summary>
		public void Stop ()
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_Stop (handle);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_Update (IntPtr handle, float timeStep);

		/// <summary>
		/// Called on scene update, variable timestep.
		/// </summary>
		public void Update (float timeStep)
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_Update (handle, timeStep);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_PostUpdate (IntPtr handle, float timeStep);

		/// <summary>
		/// Called on scene post-update, variable timestep.
		/// </summary>
		public void PostUpdate (float timeStep)
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_PostUpdate (handle, timeStep);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_FixedUpdate (IntPtr handle, float timeStep);

		/// <summary>
		/// Called on physics update, fixed timestep.
		/// </summary>
		public void FixedUpdate (float timeStep)
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_FixedUpdate (handle, timeStep);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_FixedPostUpdate (IntPtr handle, float timeStep);

		/// <summary>
		/// Called on physics post-update, fixed timestep.
		/// </summary>
		public void FixedPostUpdate (float timeStep)
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_FixedPostUpdate (handle, timeStep);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern void LogicComponent_SetUpdateEventMask (IntPtr handle, byte mask);

		/// <summary>
		/// Set what update events should be subscribed to. Use this for optimization: by default all are in use. Note that this is not an attribute and is not saved or network-serialized, therefore it should always be called eg. in the subclass constructor.
		/// </summary>
		private void SetUpdateEventMask (byte mask)
		{
			Runtime.ValidateRefCounted (this);
			LogicComponent_SetUpdateEventMask (handle, mask);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern byte LogicComponent_GetUpdateEventMask (IntPtr handle);

		/// <summary>
		/// Return what update events are subscribed to.
		/// </summary>
		private byte GetUpdateEventMask ()
		{
			Runtime.ValidateRefCounted (this);
			return LogicComponent_GetUpdateEventMask (handle);
		}

		[DllImport (Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)]
		internal static extern bool LogicComponent_IsDelayedStartCalled (IntPtr handle);

		/// <summary>
		/// Return whether the DelayedStart() function has been called.
		/// </summary>
		private bool IsDelayedStartCalled ()
		{
			Runtime.ValidateRefCounted (this);
			return LogicComponent_IsDelayedStartCalled (handle);
		}

		public override StringHash Type {
			get {
				return UrhoGetType ();
			}
		}

		public override string TypeName {
			get {
				return GetTypeName ();
			}
		}

		[Preserve]
		public new static StringHash TypeStatic {
			get {
				return GetTypeStatic ();
			}
		}

		public new static string TypeNameStatic {
			get {
				return GetTypeNameStatic ();
			}
		}

		/// <summary>
		/// Return what update events are subscribed to.
		/// Or
		/// Set what update events should be subscribed to. Use this for optimization: by default all are in use. Note that this is not an attribute and is not saved or network-serialized, therefore it should always be called eg. in the subclass constructor.
		/// </summary>
		public byte UpdateEventMask {
			get {
				return GetUpdateEventMask ();
			}
			set {
				SetUpdateEventMask (value);
			}
		}

		/// <summary>
		/// Return whether the DelayedStart() function has been called.
		/// </summary>
		public bool DelayedStartCalled {
			get {
				return IsDelayedStartCalled ();
			}
		}
	}
}


text:
package com.licaigc.algorithm.idgen;

/**
 * Created by zhaowencong on 16/3/22.
 */
public class SplitIdGen {

    public long ms;
    public long shardId;
    public long seqId;

    public void splitId(long id){
        this.ms=(long)(id>>23) + IdGenConst.epoch;
        this.shardId = (id >> 12) & IdGenConst.shardMask;
        this.seqId = id & IdGenConst.seqMask;
        System.out.println("ms:" + ms + "-shardId:" + shardId + "-seqId:"+seqId);
    }
}


text:
require('../lib/bigSlide');
$('.menu-link').bigSlide();

$('[data-confirm]').click(function(e) {
    if(!confirm($(this).data('confirm'))) {
        e.preventDefault();
    }
});

var React = require('react');

var Editor = require('../components/editor');
React.render(<Editor /> , document.getElementById('editor-component'));

var VisualizationImporter = require('../components/visualization-importer');

var defaults = window.lightning.editor;
React.render(<VisualizationImporter initialSource={defaults.source} importPreview={"import"} path={defaults.path} url={defaults.url} name={defaults.name} location={defaults.location}  /> , document.getElementById('visualization-importer'));

require('../lib/modal');


text:
package co.cask.cdap.api.plugin;

import co.cask.cdap.api.annotation.Beta;
import co.cask.cdap.api.artifact.ArtifactId;

import java.util.Map;
import java.util.SortedMap;

/**
 * Represents class for selecting plugin.
 */
@Beta
public class PluginSelector {

  /**
   * Selects a plugin. The default implementation returns the last entry in the given map.
   *
   * @param plugins set of available plugins. The {@link ArtifactId} is sorted in ascending order of plugin jar
   *                name followed by plugin version.
   * @return a {@link Map.Entry} for the selected plugin.
   */
  public Map.Entry<ArtifactId, PluginClass> select(SortedMap<ArtifactId, PluginClass> plugins) {
    return plugins.tailMap(plugins.lastKey()).entrySet().iterator().next();
  }
}


text:
/**
 * Created by Srikar on 21-12-2016.
 */
import { Component } from '@angular/core';
import {PostsService} from "../../services/posts.service";

@Component({
  moduleId: module.id,
  selector: 'user',
  templateUrl: 'user.component.html',
  providers: [PostsService]
})

export class UserComponent{
  name: string;
  age: number; //Age is just a number
  email: string;
  address: address;
  hobbies: [];
  showHobbies: boolean;
  postpool: postpool[];

  constructor(private poster: PostsService){
    this.name = 'Sriark Deddy',
    this.age = '23',
    this.email = 'sriark@srisri.com',
    this.address = {
      street: 'Kingsley Road',
      city: 'Dover',
      county: 'Southampton',
    }
    this.hobbies = ['History', 'Music', 'Programming']
    this.showHobbies = false;
    this.poster.getPosts().subscribe(posts => {
      console.log(JSON.stringify(posts));
      this.postpool = posts;
    })
  }
  toggleHobbies(){
    this.showHobbies = !this.showHobbies;
  }

  addHobby(hobby){
    this.hobbies.push(hobby);
    //console.log(hobby);
  }

  delHobby(num){
    this.hobbies.splice(num,1);
  }
}

interface address{
  street: string;
  city: string;
  county: string;
}

interface postpool{
  id: number;
  title: string;
  body: string;
}