text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(updateMask, environment) {
  // [START dataplex_v1_generated_DataplexService_UpdateEnvironment_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. Mask of fields to update.
   */
  // const updateMask = {}
  /**
   *  Required. Update description.
   *  Only fields specified in `update_mask` are updated.
   */
  // const environment = {}
  /**
   *  Optional. Only validate the request, but do not perform mutations.
   *  The default is false.
   */
  // const validateOnly = true

  // Imports the Dataplex library
  const {DataplexServiceClient} = require('@google-cloud/dataplex').v1;

  // Instantiates a client
  const dataplexClient = new DataplexServiceClient();

  async function callUpdateEnvironment() {
    // Construct request
    const request = {
      updateMask,
      environment,
    };

    // Run request
    const [operation] = await dataplexClient.updateEnvironment(request);
    const [response] = await operation.promise();
    console.log(response);
  }

  callUpdateEnvironment();
  // [END dataplex_v1_generated_DataplexService_UpdateEnvironment_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
'use strict';

var d                 = require('d')
  , isObservableValue = require('observable-value/is-observable-value')

  , defineProperties = Object.defineProperties
  , clear, toDOM, toDOMAttr, getValue, setValue, onNextTick;

clear = function () {
	delete this._domInjected;
	delete this.toDOM;
	delete this.toDOMAttr;
	delete this.value;
};
toDOM = function (document) {
	clear.call(this);
	return this.toDOM.apply(this, arguments);
};
toDOMAttr = function (element, name) {
	clear.call(this);
	return this.toDOMAttr.apply(this, arguments);
};
getValue = function () {
	clear.call(this);
	return this.value;
};
setValue = function (nu) {
	clear.call(this);
	this.value = nu;
};

onNextTick = function () {
	if (!this.hasOwnProperty('_domInjected')) return;
	clear.call(this);
	throw new TypeError("Unconsumed observable\n\n" +
		"Possibly result of '_if' (or similar) domjs extension was neither inserted into " +
		"any of the DOM elements nor set as an attribute value.\n\n" +
		"Results for extensions that return observables must be injected directly into elements " +
		"(eventually passthru via 'insert' function). Otherwise they won't be injected automatically " +
		"by the view engine (as it's the case with results of base domjs functions.\n\n" +
		"Value: " + String(this.value) + "\n" +
		"HTML: " + this.toDOM(document).innerHTML);
};

module.exports = function (observable) {
	if (!isObservableValue(observable)) return observable;
	defineProperties(observable, {
		_domInjected: d(false),
		toDOM: d(toDOM),
		toDOMAttr: d(toDOMAttr),
		value: d.gs(getValue, setValue)
	});
	// Naturally we should use `nextTick`, still it appears as "too fast" for Firefox
	// (some DOM rendering is split among event loops)
	setTimeout(onNextTick.bind(observable), 0);
	return observable;
};

redpajama_set_name: RedPajamaGithub


text:
// from https://gist.github.com/Integralist/4966463

/**
 * Shorten a string by a specified number of characters and end the string
 * using either a user specified suffix or a default suffix.
 * Ensures string is not abbreviated prematurely (e.g. half way through a word)
 *
 * Dependencies:
 *     - clean_string
 *     - is_too_short
 *     - crop
 *
 * @param user_str {string} user specified string
 * @param user_max {number} the maximum allowed characters before abbreviating
 * @param user_suffix {string} the characters used to end the string
 * @return {string} the abbreviated string
 */
function abbreviate (user_str, user_max, user_suffix) {
  var suffix = (typeof user_suffix !== 'undefined' ? user_suffix : '...');
  var max = user_max - suffix.length;
  var string = clean_string(user_str); // remove all extraneous white space

  if (shorter_than(string, max)) {
    return string;
  }

  return crop(string, max, suffix);
}

/**
 * Removes any unnecessary spaces from the specified string
 *
 * @param string {string} user specified string
 * @return {string} the string cleared of unnecessary spaces
 */
function clean_string (string) {
  var startend_spaces = /^\s+|\s+$/g;
  var linebreak_spaces = /[\r\n]*\s*[\r\n]+/g;
  var tab_spaces = /[ \t]+/g;

  return string.replace(startend_spaces, '').replace(linebreak_spaces, ' ').replace(tab_spaces, ' ');
}

/**
 * Checks if the string length is less or equal to the maximum allowed
 *
 * @param string {string} user specified string
 * @param max {number} the maximum allowed characters before abbreviating
 * @return {boolean} whether the length of the string exceeds the maximum
 */
function shorter_than (string, max) {
  return string.length <= max;
}

/**
 * Crops the string so its length is under the max allowed, and also
 * adds the specified suffix to the end of the string
 * Ensures string is not abbreviated prematurely (e.g. half way through a word)
 *
 * @param string {string} user specified string
 * @param max {number} the maximum allowed characters before abbreviating
 * @param suffix {string} the characters used to end the string
 * @return {string} the abbreviated string
 */
function crop (string, max, suffix) {
  var abbr = '';
  var counter = 0;
  var len;
  var ending_space = /[ ]$/g;

  string = string.split(' ');
  len = string.length;

  while (counter < len) {
    // individual characters of a string can be accessed via bracket notation
    if ((abbr + string[counter]).length < max) {
      abbr += string[counter] + ' ';
    } else {
      break;
    }

    counter++;
  }

  return abbr.replace(ending_space, '') + suffix;
}

// Example usage:
console.log(abbreviate('this is my very long string that probably should be cropped at some point soon', 11, '!!!'));
console.log(abbreviate('this is my very long string that probably should be cropped at some point soon', 20));


text:
/*
*--------------------------------------------------------------------------------------------
* Title:    Trackball Demo
* Author:    Brian L. Little
* Date:      11/13/2011
* Licensing: See end of program listing
*
* Hardware Requirements: Parallax Trackball (27908)
* Test Board:            Mini Development Board
* Compatible Boards:     Any
*
* Comments:
* This is a simple demo showing how to use Parallax's trackball with PropGCC
* The switch should be set up using any group of 5 ports starting with the basePin
* The wiring is as follows:
*
*    Port         Pin on Switch   Description
*    ----------------------------------------
*                 Pin 1          +5V
*    basePin + 4  Pin 2           Up
*    basePin + 3  Pin 3           Center
*    basePin + 2  Pin 4           Left
*                 Pin 5           Ground
*    basePin + 1  Pin 6           Down
*    basePin + 5  Pin 7           LED
*    basePin      Pin 8          Right
*--------------------------------------------------------------------------------------------
*/
#include "propeller.h"
#include "stdio.h"
#include <cog.h>

const int basePin = 0;            // Base pin for the 6 pin grouping

void main (int argc,  char* argv[])
{
  int mask = 0x0000001f << basePin;    // This masks only the input pins of the grouping through
  int ledMask = 0x00000020 << basePin;  // Masks out the pin with the LED
  int offMask = 0xffffffdf << basePin;  // Mask to turn off LED
  int temp[5];                          // This array holds the value of a certain direction
  int i;                                // Loop counter
  int state = 0;            // Holds the last value from the switch contacts
  int a = 0;                // Holds the computed value from the switch contacts
  int b = 0;                        // Holds the current value from the switch contacts
  int ledDelay = 0;                     // Holds the delay count on how long the LED is on

  DIRA |= ledMask;                      // Set the LED Pin as an output

  printf("\r\n\r\nTrackball Demo\r\n");

  state = INA & mask;            // Read in the inputs and mask it for switch contacts

  for(;;)                // Loop continously
  {
    b = INA & mask;                    // Read in inputs
    a = b ^ state;                      // Xor with last reading to see if there is a change
    waitcnt(CLKFREQ/20000 + CNT);       // 20 mSec delay for debouncing the switch for next reading

    if (ledDelay > 100)                 // Is led on deley greter than 100
    {
      OUTA |= ledMask;                  // Turn on LED
      ledDelay--;                       // Decrease LED delay count
      if (ledDelay < 0)                 // Make sure ledDelay doesn't go below 0
      {
    ledDelay = 0;
      }
    }
    else                                // if led on delay < 101
    {
      OUTA &= offMask;            // Turn off LED
    }
    if (a != 0)                // Reading will be non-zero if there is a change from
                                    // the previous reating
    {
      state = b;                // Set the last reading to be the current value
      a = a >> basePin;                 // Shift current reading so it can be read into an array
      ledDelay = 3500;                  // Set LED delay
      for(i = 0; i < 5; i++)        // Put each switch state into an array value
      {
        temp[i] = a & 0x00000001;       // Mask only one switch in the lsb of the current value
                                        // and put in the array
        a = a >> 1;                     // Shift current value so next switch is in lsb
      }

      if(temp[0] == 1)                  // If temp[0] (Right) is high then display Right
        printf("Right\r\n");

      if(temp[1] == 1)            // If temp[1] (Down) is high then display Down
        printf("Down\r\n");

      if(temp[2] == 1)                  // If temp[2] (Left) is high then display Left
        printf("Left\r\n");

      if(temp[3] == 1)                  // If temp[3] (Center) is high then display Center
        printf("Center\r\n");

      if(temp[4] == 1)                  // If temp[4] (Up) is high then display Up
        printf("Up\r\n");

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

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

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


text:
#pragma once

#include "../Configuration.hpp"

#if ARDUINOJSON_ENABLE_STD_STREAM

#include "../Print.hpp"

#include <ostream>

namespace ArduinoJson {
namespace Internals {

class StreamPrintAdapter : public Print {
 public:
  explicit StreamPrintAdapter(std::ostream& os) : _os(os) {}

  virtual size_t write(uint8_t c) {
    _os << static_cast<char>(c);
    return 1;
  }

 private:
  // cannot be assigned
  StreamPrintAdapter& operator=(const StreamPrintAdapter&);

  std::ostream& _os;
};
}
}

#endif  // ARDUINOJSON_ENABLE_STD_STREAM


text: from . import path, display


text:
"""The differential evolution global optimization algorithm.

Differential evolution (DE) is a population-based global optimization scheme.
It is applicable to problems with a continuous parameter space. Because it
does not require computing gradients, it is also applicable to
non-differentiable functions. For more details see:
https://en.wikipedia.org/wiki/Differential_evolution

DE starts with a population of candidate solutions (represented as vectors).
It generates new trial solutions by a combination of
- "mutation", namely adding the weighted difference between
  two population vectors to a target vector, and
- "crossover", namely mixing the target with the content of a third.

If the trial vector thus constructed yields a lower cost value it
replaces the target vector it was made from. This process is repeated for
each member of the population to complete one generation.

There are a number of different schemes that fall under the DE umbrella.
The established notation for representing these schemes
is as `DE/x/y/z` where `x` specifies how the population member to be mutated is
selected (may be `rand` if it is chosen randomly or `best` if the best
member is chosen), `y` specifies the number of difference vectors used and `z`
denotes the crossover scheme employed. This may be `bin` if binary
recombination is used or `exp` if exponential crossover is used.

The most commonly employed scheme is `DE/rand/1/bin`. This is the one
implemented in this module.
"""

import collections
import numpy as np
import tensorflow.compat.v2 as tf

from tensorflow_probability.python.distributions import categorical
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.util import seed_stream

_DifferentialEvolutionOptimizerResults = collections.namedtuple(
    '_DifferentialEvolutionOptimizerResults', [
        'converged',  # Scalar boolean tensor indicating whether the minimum
                      # was found within tolerance.
        'failed',  # Scalar boolean tensor indicating whether the search failed.
                   # This may happen if the objective values become NaN for
                   # the entire population.
        'position',  # A list of tensors containing the best argument value
                     # found during the search. If the search converged, then
                     # this value is the argmin of the objective function.
        'objective_value',  # A tensor containing the value of the objective
                            # function at the `position`. If the search
                            # converged, then this is the (local) minimum of
                            # the objective function.
        'final_population',  # The final state of the population.
        'final_objective_values',  # The objective function evaluated at the
                                   # final population.
        'initial_population',  # The starting population.
        'initial_objective_values',  # The objective function evaluated at the
                                     # initial population.
        'num_iterations'  # The number of generations the population was
                          # evolved.
    ])

class DifferentialEvolutionOptimizerResults(
    _DifferentialEvolutionOptimizerResults):
  """Results of a differential evolution optimization run.

  The object has the following attributes:
    converged: Scalar boolean `Tensor` indicating whether the minimum was
      found within the specified tolerances.
    failed: Scalar boolean tensor indicating whether the search failed.
      This may happen if the objective values become NaN for the entire
      population.
    position: A `Tensor` containing the best point found during the search.
      If the search converged, then this value is the argmin of the
      objective function within the specified tolerances.
    objective_value: A tensor containing the value of the objective
      function at the `position`. If the search
      converged, then this is the (local) minimum of
      the objective function.
    final_population: The final state of the population.
    final_objective_values: The objective function evaluated at the
      final population.
    initial_population: The starting population.
    initial_objective_values: The objective function evaluated at the
      initial population.
    num_iterations: The number of generations the population was evolved.
  """

# Class to keep track of the loop variables in the minimize method.
_MinimizeLoopVars = collections.namedtuple(
    '_MinimizeLoopVars',
    [
        'converged',
        'failed',
        'num_iterations',
        'population',
        'population_values'
    ])

def one_step(
    objective_function,
    population,
    population_values=None,
    differential_weight=0.5,
    crossover_prob=0.9,
    seed=None,
    name=None):
  """Performs one step of the differential evolution algorithm.

  Args:
    objective_function:  A Python callable that accepts a batch of possible
      solutions and returns the values of the objective function at those
      arguments as a rank 1 real `Tensor`. This specifies the function to be
      minimized. The input to this callable may be either a single `Tensor`
      or a Python `list` of `Tensor`s. The signature must match the format of
      the argument `population`. (i.e., objective_function(*population) must
      return the value of the function to be minimized).
    population:  `Tensor` or Python `list` of `Tensor`s representing the
      current population vectors. Each `Tensor` must be of the same real dtype.
      The first dimension indexes individual population members while the
      rest of the dimensions are consumed by the value function. For example,
      if the population is a single `Tensor` of shape [n, m1, m2], then `n` is
      the population size and the output of `objective_function` applied to the
      population is a `Tensor` of shape [n]. If the population is a python
      list of `Tensor`s then each `Tensor` in the list should have the first
      axis of a common size, say `n` and `objective_function(*population)`
      should return a `Tensor` of shape [n]. The population must have at least
      4 members for the algorithm to work correctly.
    population_values: A `Tensor` of rank 1 and real dtype. The result of
      applying `objective_function` to the `population`. If not supplied it is
      computed using the `objective_function`.
      Default value: None.
    differential_weight: Real scalar `Tensor`. Must be positive and less than
      2.0. The parameter controlling the strength of mutation.
      Default value: 0.5
    crossover_prob: Real scalar `Tensor`. Must be between 0 and 1. The
      probability of recombination per site.
      Default value: 0.9
    seed: `int` or None. The random seed for this `Op`. If `None`, no seed is
      applied.
      Default value: None.
    name: (Optional) Python str. The name prefixed to the ops created by this
      function. If not supplied, the default name 'one_step' is
      used.
      Default value: None

  Returns:
    A sequence containing the following elements (in order):
    next_population: A `Tensor` or Python `list` of `Tensor`s of the same
      structure as the input population. The population at the next generation.
    next_population_values: A `Tensor` of same shape and dtype as input
      `population_values`. The function values for the `next_population`.
  """
  with tf.name_scope(name or 'one_step'):
    population, _ = _ensure_list(population)
    if population_values is None:
      population_values = objective_function(*population)
    population_size = tf.shape(population[0])[0]
    stream = seed_stream.SeedStream(seed, salt='one_step')
    mixing_indices = _get_mixing_indices(population_size, seed=stream())
    # Construct the mutated solution vectors. There is one for each member of
    # the population.
    mutants = _get_mutants(population,
                           population_size,
                           mixing_indices,
                           differential_weight)
    # Perform recombination between the parents and the mutants.
    candidates = _binary_crossover(population,
                                   population_size,
                                   mutants,
                                   crossover_prob,
                                   seed=stream())
    candidate_values = objective_function(*candidates)
    if population_values is None:
      population_values = objective_function(*population)

    population_values = tf.where(
        tf.math.is_nan(population_values),
        dtype_util.as_numpy_dtype(population_values.dtype)(np.inf),
        population_values)

    to_replace = candidate_values < population_values

    def _replace(c_part, p_part):
      to_replace_reshaped = tf.reshape(
          to_replace, shape=ps.concat([
              [population_size],
              ps.ones([ps.size(ps.shape(c_part)[:-1])], dtype=np.int32)
          ], axis=0))
      return tf.where(to_replace_reshaped, c_part, p_part)

    next_population = tf.nest.map_structure(_replace, candidates, population)
    next_values = tf.where(to_replace, candidate_values, population_values)

  return next_population, next_values

def minimize(objective_function,
             initial_population=None,
             initial_position=None,
             population_size=50,
             population_stddev=1.,
             max_iterations=100,
             func_tolerance=0,
             position_tolerance=1e-8,
             differential_weight=0.5,
             crossover_prob=0.9,
             seed=None,
             name=None):
  """Applies the Differential evolution algorithm to minimize a function.

  Differential Evolution is an evolutionary optimization algorithm which works
  on a set of candidate solutions called the population. It iteratively
  improves the population by applying genetic operators of mutation and
  recombination. The objective function `f` supplies the fitness of each
  candidate. A candidate `s_1` is considered better than `s_2` if
  `f(s_1) < f(s_2)`.

  This method allows the user to either specify an initial population or a
  single candidate solution. If a single solution is specified, a population
  of the specified size is initialized by adding independent normal noise
  to the candidate solution.

  The implementation also supports a multi-part specification of the state. For
  example, consider the objective function:

  ```python
  # x is a tensor of shape [n, m] while y is of shape [n].
  def objective(x, y):
    return tf.math.reduce_sum(x ** 2, axis=-1) + y ** 2
  ```
  The state in this case is specified by two input tensors `x` and `y`. To
  apply the algorithm to this objective function, one would need to specify
  either an initial population as a list of two tensors of shapes
  `[population_size, k]` and `[population_size]`. The following code shows the
  complete example:

  ```python
    population_size = 40
    # With an initial population and a multi-part state.
    initial_population = (tf.random.normal([population_size]),
                          tf.random.normal([population_size]))
    def easom_fn(x, y):
      return -(tf.math.cos(x) * tf.math.cos(y) *
               tf.math.exp(-(x-np.pi)**2 - (y-np.pi)**2))

    optim_results = tfp.optimizer.differential_evolution_minimize(
        easom_fn,
        initial_population=initial_population,
        seed=43210)

    print(optim_results.converged)
    print(optim_results.position)  # Should be (close to) [pi, pi].
    print(optim_results.objective_value)    # Should be -1.

    # With a single starting point
    initial_position = (tf.constant(1.0), tf.constant(1.0))

    optim_results = tfp.optimizer.differential_evolution_minimize(
        easom_fn,
        initial_position=initial_position,
        population_size=40,
        population_stddev=2.0,
        seed=43210)
  ```

  Args:
    objective_function: A Python callable that accepts a batch of possible
      solutions and returns the values of the objective function at those
      arguments as a rank 1 real `Tensor`. This specifies the function to be
      minimized. The input to this callable may be either a single `Tensor`
      or a Python `list` of `Tensor`s. The signature must match the format of
      the argument `population`. (i.e. objective_function(*population) must
      return the value of the function to be minimized).
    initial_population: A real `Tensor` or Python list of `Tensor`s.
      If a list, each `Tensor` must be of rank at least 1 and with a common
      first dimension. The first dimension indexes into the candidate solutions
      while the rest of the dimensions (if any) index into an individual
      solution. The size of the population must be at least 4. This is a
      requirement of the DE algorithm.
    initial_position: A real `Tensor` of any shape. The seed solution used
      to initialize the population of solutions. If this parameter is specified
      then `initial_population` must not be specified.
    population_size: A positive scalar int32 `Tensor` greater than 4. The
      size of the population to evolve. This parameter is ignored if
      `initial_population` is specified.
      Default value: 50.
    population_stddev: A positive scalar real `Tensor` of the same dtype
      as `initial_position`. This parameter is ignored if `initial_population`
      is specified. Used to generate the population from the `initial_position`
      by adding random normal noise with zero mean and the specified standard
      deviation.
      Default value: 1.0
    max_iterations: Positive scalar int32 `Tensor`. The maximum number of
      generations to evolve the population for.
      Default value: 100
    func_tolerance: Scalar `Tensor` of the same dtype as the output of the
      `objective_function`. The algorithm stops if the absolute difference
      between the largest and the smallest objective function value in the
      population is below this number.
      Default value: 0
    position_tolerance: Scalar `Tensor` of the same real dtype as
      `initial_position` or `initial_population`. The algorithm terminates if
      the largest absolute difference between the coordinates of the population
      members is below this threshold.
      Default value: 1e-8
    differential_weight: Real scalar `Tensor`. Must be positive and less than
      2.0. The parameter controlling the strength of mutation in the algorithm.
      Default value: 0.5
    crossover_prob: Real scalar `Tensor`. Must be between 0 and 1. The
      probability of recombination per site.
      Default value: 0.9
    seed: `int` or None. The random seed for this `Op`. If `None`, no seed is
      applied.
      Default value: None.
    name: (Optional) Python str. The name prefixed to the ops created by this
      function. If not supplied, the default name
      'differential_evolution_minimize' is used.
      Default value: None

  Returns:
    optimizer_results: An object containing the following attributes:
      converged: Scalar boolean `Tensor` indicating whether the minimum was
        found within the specified tolerances.
      num_objective_evaluations: The total number of objective
        evaluations performed.
      position: A `Tensor` containing the best point found during the search.
        If the search converged, then this value is the argmin of the
        objective function within the specified tolerances.
      objective_value: A `Tensor` containing the value of the objective
        function at the `position`. If the search
        converged, then this is the (local) minimum of
        the objective function.
      final_population: The final state of the population.
      final_objective_values: The objective function evaluated at the
        final population.
      initial_population: The starting population.
      initial_objective_values: The objective function evaluated at the
        initial population.
      num_iterations: The number of iterations of the main algorithm body.

  Raises:
    ValueError: If neither the initial population, nor the initial position
      are specified or if both are specified.
  """

  if initial_population is None and initial_position is None:
    raise ValueError('Either the initial population or the initial position '
                     'must be specified.')
  if initial_population is not None and initial_position is not None:
    raise ValueError('Only one of initial population or initial position '
                     'should be specified')

  with tf.name_scope(name or 'minimize'):
    (
        was_iterable,
        population,
        population_values,
        max_iterations,
        func_tolerance,
        position_tolerance,
        differential_weight,
        crossover_prob
    ) = _get_initial_args(objective_function,
                          initial_population,
                          initial_position,
                          population_size,
                          population_stddev,
                          max_iterations,
                          func_tolerance,
                          position_tolerance,
                          differential_weight,
                          crossover_prob,
                          seed)

    def evolve_body(loop_vars):
      """Performs one step of the evolution."""
      next_population, next_population_values = one_step(
          objective_function,
          loop_vars.population,
          population_values=loop_vars.population_values,
          differential_weight=differential_weight,
          crossover_prob=crossover_prob,
          seed=seed)
      converged = _check_convergence(next_population,
                                     next_population_values,
                                     func_tolerance,
                                     position_tolerance)

      failed = _check_failure(next_population_values)

      return [_MinimizeLoopVars(
          converged=converged,
          failed=failed,
          num_iterations=loop_vars.num_iterations+1,
          population=next_population,
          population_values=next_population_values)]

    def evolve_cond(loop_vars):
      should_stop = (
          loop_vars.failed |
          loop_vars.converged |
          (max_iterations is not None and
           loop_vars.num_iterations >= max_iterations))
      return ~should_stop

    initial_vars = _MinimizeLoopVars(
        converged=tf.convert_to_tensor(False),
        failed=tf.convert_to_tensor(False),
        num_iterations=tf.convert_to_tensor(0),
        population=population,
        population_values=population_values)
    final_state = tf.while_loop(
        cond=evolve_cond, body=evolve_body, loop_vars=(initial_vars,))[0]
    best_position, best_values = _find_best_in_population(
        final_state.population,
        final_state.population_values)
    # Ensure we return a similar structure to what the user supplied.
    final_population = final_state.population
    if not was_iterable:
      final_population = final_population[0]
      best_position = best_position[0]
    return DifferentialEvolutionOptimizerResults(
        converged=final_state.converged,
        failed=final_state.failed,
        position=best_position,
        objective_value=best_values,
        final_population=final_population,
        final_objective_values=final_state.population_values,
        initial_population=population,
        initial_objective_values=population_values,
        num_iterations=final_state.num_iterations)

def _get_initial_args(objective_function,
                      initial_population,
                      initial_position,
                      population_size,
                      population_stddev,
                      max_iterations,
                      func_tolerance,
                      position_tolerance,
                      differential_weight,
                      crossover_prob,
                      seed):
  """Processes initial args."""
  was_iterable = False
  if initial_position is not None:
    initial_position, was_iterable = _ensure_list(initial_position)

  if initial_population is not None:
    initial_population, was_iterable = _ensure_list(initial_population)

  population = _get_starting_population(initial_population,
                                        initial_position,
                                        population_size,
                                        population_stddev,
                                        seed=seed)

  differential_weight = tf.convert_to_tensor(
      differential_weight, dtype=population[0].dtype.base_dtype)

  crossover_prob = tf.convert_to_tensor(crossover_prob)
  population_values = objective_function(*population)
  if max_iterations is not None:
    max_iterations = tf.convert_to_tensor(max_iterations)
  func_tolerance = tf.convert_to_tensor(
      func_tolerance, dtype=population_values.dtype.base_dtype)
  position_tolerance = tf.convert_to_tensor(
      position_tolerance, dtype=population[0].dtype.base_dtype)
  return (was_iterable,
          population,
          population_values,
          max_iterations,
          func_tolerance,
          position_tolerance,
          differential_weight,
          crossover_prob)

def _check_failure(population_values):
  """Checks if all the population values are NaN/infinite."""
  return tf.math.reduce_all(tf.math.is_inf(population_values))

def _find_best_in_population(population, values):
  """Finds the population member with the lowest value."""
  best_value = tf.math.reduce_min(values)
  best_index = tf.where(tf.math.equal(values, best_value))[0, 0]

  return ([population_part[best_index] for population_part in population],
          best_value)

def _check_convergence(population,
                       population_values,
                       func_tolerance,
                       position_tolerance):
  """Checks whether the convergence criteria have been met."""
  # Check func tolerance
  value_range = tf.math.abs(
      tf.math.reduce_max(population_values) -
      tf.math.reduce_min(population_values))
  value_converged = value_range <= func_tolerance
  # Ideally, we would compute the position convergence by computing the
  # pairwise distance between every member of the population and checking if
  # the maximum of those is less than the supplied tolerance. However, this is
  # completely infeasible in terms of performance. We adopt a more conservative
  # approach which checks the distance between the first population member
  # with the rest of the population. If the largest such distance is less than
  # half the supplied tolerance, we stop. The reason why this is sufficient is
  # as follows. For any pair of distinct points (a, b) in the population, we
  # have the relation:  |a - b| <= |x0 - a| + |x0 - b|, where x0 is any
  # other point. In particular, let x0 be the first element of the population
  # and suppose that the largest distance between this point and any other
  # member is epsilon. Then, for any pair of points (a, b),
  # |a - b| <= 2 * epsilon and hence, the maximum distance between any pair of
  # points in the population is bounded above by twice the distance between
  # the first point and other points.
  half_tol = position_tolerance / 2
  def part_converged(part):
    return tf.math.reduce_max(tf.math.abs(part - part[0])) <= half_tol

  x_converged = tf.math.reduce_all(
      [part_converged(part) for part in population])
  return value_converged | x_converged

def _get_starting_population(initial_population,
                             initial_position,
                             population_size,
                             population_stddev,
                             seed):
  """Constructs the initial population.

  If an initial population is not already provided, this function constructs
  a population by adding random normal noise to the initial position.

  Args:
    initial_population: None or a list of `Tensor`s. The initial population.
    initial_position: None or a list of `Tensor`s. The initial position.
      If initial_population is None, this argument must not be None.
    population_size: Scalar integer `Tensor`. The number of members in the
      population. If the initial population is not None, this parameter is
      ignored.
    population_stddev: A positive scalar real `Tensor` of the same dtype
      as `initial_position` or `initial_population` (whichever is not None).
      This parameter is ignored if `initial_population`
      is specified. Used to generate the population from the
      `initial_position` by adding random normal noise with zero mean and
      the specified standard deviation.
    seed: Seed for random number generation.

  Returns:
    A list of `Tensor`s. The initial population.
  """
  if initial_population is not None:
    return [tf.convert_to_tensor(part) for part in initial_population]
  # Constructs the population by adding normal noise to the initial position.
  stream = seed_stream.SeedStream(seed, salt='get_starting_population')
  population = []
  for part in initial_position:
    part = tf.convert_to_tensor(part)
    part_event_shape = tf.shape(part)
    # We only draw population_size-1 random vectors because we want to ensure
    # that the supplied position is part of the population. The first member
    # is set to be the initial_position.
    population_part_shape = tf.concat([[population_size-1],
                                       part_event_shape], axis=0)
    population_part = tf.random.normal(population_part_shape,
                                       stddev=population_stddev,
                                       dtype=part.dtype.base_dtype,
                                       seed=stream())
    population_part += part
    population_part = tf.concat([[part], population_part], axis=0)
    population.append(population_part)
  return population

def _binary_crossover(population,
                      population_size,
                      mutants,
                      crossover_prob,
                      seed):
  """Performs recombination by binary crossover for the current population.

  Let v_i denote the i'th component of the member v and m_i the corresponding
  component of the mutant vector corresponding to v. Then the crossed over
  vector w_i is determined by setting w_i =
  (m_i with probability=crossover_prob else v_i). In addition, DE requires that
  at least one of the components is crossed over (otherwise we end
  up with no change). This is done by choosing on index say k randomly where
  a force crossover is performed (i.e. w_k = m_k). This is the scheme
  implemented in this function.

  Args:
    population: A Python list of `Tensor`s where each `Tensor` in the list
      must be of rank at least 1 and all the elements must have a common
      first dimension. The base population to cross over.
    population_size: A scalar integer `Tensor`. The number of elements in the
      population (i.e. size of the first dimension of any member of
      `population`).
    mutants: A Python list of `Tensor`s with the same structure as `population`.
      The mutated population.
    crossover_prob: A positive real scalar `Tensor` bounded above by 1.0. The
      probability of a crossover being performed for each axis.
    seed: `int` or None. The random seed for this `Op`. If `None`, no seed is
      applied.

  Returns:
    A list of `Tensor`s of the same structure, dtype and shape as `population`.
    The recombined population.
  """
  sizes = [tf.cast(tf.size(x), dtype=tf.float64) for x in population]
  stream = seed_stream.SeedStream(seed, salt='binary_crossover')
  force_crossover_group = categorical.Categorical(sizes).sample(
      [population_size, 1], seed=stream())
  recombinants = []
  for i, population_part in enumerate(population):
    pop_part_flat = tf.reshape(population_part, [population_size, -1])
    mutant_part_flat = tf.reshape(mutants[i], [population_size, -1])
    part_size = tf.size(population_part) // population_size
    force_crossovers = tf.one_hot(
        tf.random.uniform([population_size],
                          minval=0,
                          maxval=part_size,
                          dtype=tf.int32,
                          seed=stream()),
        part_size,
        on_value=True,
        off_value=False,
        dtype=tf.bool)  # Tensor of shape [population_size, size]
    group_mask = tf.math.equal(force_crossover_group, i)
    force_crossovers &= group_mask
    do_binary_crossover = tf.random.uniform(
        [population_size, part_size],
        dtype=crossover_prob.dtype.base_dtype,
        seed=stream()) < crossover_prob
    do_binary_crossover |= force_crossovers
    recombinant_flat = tf.where(
        do_binary_crossover, mutant_part_flat, pop_part_flat)
    recombinant = tf.reshape(recombinant_flat, tf.shape(population_part))
    recombinants.append(recombinant)
  return recombinants

def _get_mutants(population,
                 population_size,
                 mixing_indices,
                 differential_weight):
  """Computes the mutatated vectors for each population member.

  Args:
    population:  Python `list` of `Tensor`s representing the
      current population vectors. Each `Tensor` must be of the same real dtype.
      The first dimension of each `Tensor` indexes individual
      population members. For example, if the population is a list with a
      single `Tensor` of shape [n, m1, m2], then `n` is the population size and
      the shape of an individual solution is [m1, m2].
      If there is more than one element in the population, then each `Tensor`
      in the list should have the first axis of the same size.
    population_size: Scalar integer `Tensor`. The size of the population.
    mixing_indices: `Tensor` of integral dtype and shape [n, 3] where `n` is the
      number of members in the population. Each element of the `Tensor` must be
      a valid index into the first dimension of the population (i.e range
      between `0` and `n-1` inclusive).
    differential_weight: Real scalar `Tensor`. Must be positive and less than
      2.0. The parameter controlling the strength of mutation.

  Returns:
    mutants: `Tensor` or Python `list` of `Tensor`s of the same shape and dtype
      as the input population. The mutated vectors.
  """
  mixing_indices = tf.reshape(mixing_indices, [-1])
  weights = tf.stack([1.0, differential_weight, -differential_weight])
  def _mutant_part(population_part):
    donors = tf.gather(population_part, mixing_indices)
    donors = tf.transpose(
        a=tf.reshape(donors, [population_size, 3, -1]), perm=[0, 2, 1])
    return tf.math.reduce_sum(donors * weights, axis=-1)

  return [_mutant_part(population_part) for population_part in population]

def _get_mixing_indices(size, seed=None, name=None):
  """Generates an array of indices suitable for mutation operation.

  The mutation operation in differential evolution requires that for every
  element of the population, three distinct other elements be chosen to produce
  a trial candidate. This function generates an array of shape [size, 3]
  satisfying the properties that:
    (a). array[i, :] does not contain the index 'i'.
    (b). array[i, :] does not contain any overlapping indices.
    (c). All elements in the array are between 0 and size - 1 inclusive.

  Args:
    size: Scalar integer `Tensor`. The number of samples as well as a the range
      of the indices to sample from.
    seed: `int` or None. The random seed for this `Op`. If `None`, no seed is
      applied.
      Default value: `None`.
    name:  Python `str` name prefixed to Ops created by this function.
      Default value: 'get_mixing_indices'.

  Returns:
    sample: A `Tensor` of shape [size, 3] and same dtype as `size` containing
    samples without replacement between 0 and size - 1 (inclusive) with the
    `i`th row not including the number `i`.
  """
  with tf.name_scope(name or 'get_mixing_indices'):
    size = tf.convert_to_tensor(size)
    dtype = size.dtype
    stream = seed_stream.SeedStream(seed, salt='get_mixing_indices')
    first = tf.random.uniform([size],
                              maxval=size-1,
                              dtype=dtype,
                              seed=stream())
    second = tf.random.uniform([size],
                               maxval=size-2,
                               dtype=dtype,
                               seed=stream())
    third = tf.random.uniform([size],
                              maxval=size-3,
                              dtype=dtype,
                              seed=stream())

    # Shift second if it is on top of or to the right of first
    second = tf.where(first < second, second, second + 1)
    smaller = tf.math.minimum(first, second)
    larger = tf.math.maximum(first, second)
    # Shift the third one so it does not coincide with either the first or the
    # second number. Assuming first < second, shift by 1 if the number is in
    # [first, second) and by 2 if the number is greater than or equal to the
    # second.
    third = tf.where(third < smaller, third, third + 1)
    third = tf.where(third < larger, third, third + 1)
    sample = tf.stack([first, second, third], axis=1)
    to_avoid = tf.expand_dims(tf.range(size), axis=-1)
    sample = tf.where(sample < to_avoid, sample, sample + 1)
    return sample

def _ensure_list(tensor_or_list):
  """Converts the input arg to a list if it is not a list already.

  Args:
    tensor_or_list: A `Tensor` or a Python list of `Tensor`s. The argument to
      convert to a list of `Tensor`s.

  Returns:
    A tuple of two elements. The first is a Python list of `Tensor`s containing
    the original arguments. The second is a boolean indicating whether
    the original argument was a list or tuple already.
  """
  if isinstance(tensor_or_list, (list, tuple)):
    return list(tensor_or_list), True
  return [tensor_or_list], False


text:
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';

import {TooltipDirective} from './tooltip.directive';
import {TooltipContentComponent} from './tooltip.component';
import {TooltipService} from './tooltip.service';

import {InjectionService} from './injection.service';

@NgModule({
	declarations: [TooltipContentComponent, TooltipDirective],
	providers: [InjectionService, TooltipService],
	exports: [TooltipContentComponent, TooltipDirective],
	imports: [CommonModule],
	entryComponents: [TooltipContentComponent]
})
export class CommonTooltipModule {
}


text:
package org.apache.drill.exec.store.hive;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import io.netty.buffer.DrillBuf;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.drill.common.exceptions.DrillRuntimeException;
import org.apache.drill.common.exceptions.ExecutionSetupException;
import org.apache.drill.common.exceptions.UserException;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.common.types.TypeProtos.DataMode;
import org.apache.drill.common.types.TypeProtos.MajorType;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.expr.holders.Decimal18Holder;
import org.apache.drill.exec.expr.holders.Decimal28SparseHolder;
import org.apache.drill.exec.expr.holders.Decimal38SparseHolder;
import org.apache.drill.exec.expr.holders.Decimal9Holder;
import org.apache.drill.exec.planner.logical.DrillScanRel;
import org.apache.drill.exec.planner.physical.PlannerSettings;
import org.apache.drill.exec.server.options.OptionSet;
import org.apache.drill.exec.util.DecimalUtility;
import org.apache.drill.exec.vector.NullableBigIntVector;
import org.apache.drill.exec.vector.NullableBitVector;
import org.apache.drill.exec.vector.NullableDateVector;
import org.apache.drill.exec.vector.NullableDecimal18Vector;
import org.apache.drill.exec.vector.NullableDecimal28SparseVector;
import org.apache.drill.exec.vector.NullableDecimal38SparseVector;
import org.apache.drill.exec.vector.NullableDecimal9Vector;
import org.apache.drill.exec.vector.NullableFloat4Vector;
import org.apache.drill.exec.vector.NullableFloat8Vector;
import org.apache.drill.exec.vector.NullableIntVector;
import org.apache.drill.exec.vector.NullableTimeStampVector;
import org.apache.drill.exec.vector.NullableVarBinaryVector;
import org.apache.drill.exec.vector.NullableVarCharVector;
import org.apache.drill.exec.vector.NullableVarDecimalVector;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.work.ExecErrorConstants;

import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.IOConstants;
import org.apache.hadoop.hive.ql.metadata.HiveStorageHandler;
import org.apache.hadoop.hive.ql.metadata.HiveUtils;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector.Category;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
import org.apache.hadoop.hive.serde2.typeinfo.BaseCharTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.DecimalTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.HiveDecimalUtils;
import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.mapred.InputFormat;
import org.apache.hadoop.mapred.JobConf;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_STORAGE;

public class HiveUtilities {
  private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(HiveUtilities.class);

  /** Partition value is received in string format. Convert it into appropriate object based on the type. */
  public static Object convertPartitionType(TypeInfo typeInfo, String value, final String defaultPartitionValue) {
    if (typeInfo.getCategory() != Category.PRIMITIVE) {
      // In Hive only primitive types are allowed as partition column types.
      throw new DrillRuntimeException("Non-Primitive types are not allowed as partition column type in Hive, " +
          "but received one: " + typeInfo.getCategory());
    }

    if (defaultPartitionValue.equals(value)) {
      return null;
    }

    final PrimitiveCategory pCat = ((PrimitiveTypeInfo) typeInfo).getPrimitiveCategory();

    try {
      switch (pCat) {
        case BINARY:
          return value.getBytes();
        case BOOLEAN:
          return Boolean.parseBoolean(value);
        case DECIMAL: {
          DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) typeInfo;
          return HiveDecimalUtils.enforcePrecisionScale(HiveDecimal.create(value), decimalTypeInfo);
        }
        case DOUBLE:
          return Double.parseDouble(value);
        case FLOAT:
          return Float.parseFloat(value);
        case BYTE:
        case SHORT:
        case INT:
          return Integer.parseInt(value);
        case LONG:
          return Long.parseLong(value);
        case STRING:
        case VARCHAR:
          return value.getBytes();
        case CHAR:
          return value.trim().getBytes();
        case TIMESTAMP:
          return Timestamp.valueOf(value);
        case DATE:
          return Date.valueOf(value);
      }
    } catch(final Exception e) {
      // In Hive, partition values that can't be converted from string are considered to be NULL.
      logger.trace("Failed to interpret '{}' value from partition value string '{}'", pCat, value);
      return null;
    }

    throwUnsupportedHiveDataTypeError(pCat.toString());
    return null;
  }

  public static void populateVector(final ValueVector vector, final DrillBuf managedBuffer, final Object val,
      final int start, final int end) {
    TypeProtos.MinorType type = vector.getField().getType().getMinorType();

    switch(type) {
      case VARBINARY: {
        NullableVarBinaryVector v = (NullableVarBinaryVector) vector;
        byte[] value = (byte[]) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value, 0, value.length);
        }
        break;
      }
      case BIT: {
        NullableBitVector v = (NullableBitVector) vector;
        Boolean value = (Boolean) val;
        for (int i = start; i < end; i++) {
          v.getMutator().set(i, value ? 1 : 0);
        }
        break;
      }
      case FLOAT8: {
        NullableFloat8Vector v = (NullableFloat8Vector) vector;
        double value = (double) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
      case FLOAT4: {
        NullableFloat4Vector v = (NullableFloat4Vector) vector;
        float value = (float) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
      case TINYINT:
      case SMALLINT:
      case INT: {
        NullableIntVector v = (NullableIntVector) vector;
        int value = (int) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
      case BIGINT: {
        NullableBigIntVector v = (NullableBigIntVector) vector;
        long value = (long) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
      case VARCHAR: {
        NullableVarCharVector v = (NullableVarCharVector) vector;
        byte[] value = (byte[]) val;
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value, 0, value.length);
        }
        break;
      }
      case TIMESTAMP: {
        NullableTimeStampVector v = (NullableTimeStampVector) vector;
        DateTime ts = new DateTime(((Timestamp) val).getTime()).withZoneRetainFields(DateTimeZone.UTC);
        long value = ts.getMillis();
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
      case DATE: {
        NullableDateVector v = (NullableDateVector) vector;
        DateTime date = new DateTime(((Date)val).getTime()).withZoneRetainFields(DateTimeZone.UTC);
        long value = date.getMillis();
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }

      case DECIMAL9: {
        final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
        final NullableDecimal9Vector v = ((NullableDecimal9Vector) vector);
        final Decimal9Holder holder = new Decimal9Holder();
        holder.scale = v.getField().getScale();
        holder.precision = v.getField().getPrecision();
        holder.value = DecimalUtility.getDecimal9FromBigDecimal(value, holder.scale);
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, holder);
        }
        break;
      }

      case DECIMAL18: {
        final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
        final NullableDecimal18Vector v = ((NullableDecimal18Vector) vector);
        final Decimal18Holder holder = new Decimal18Holder();
        holder.scale = v.getField().getScale();
        holder.precision = v.getField().getPrecision();
        holder.value = DecimalUtility.getDecimal18FromBigDecimal(value, holder.scale);
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, holder);
        }
        break;
      }

      case DECIMAL28SPARSE: {
      final int needSpace = Decimal28SparseHolder.nDecimalDigits * DecimalUtility.INTEGER_SIZE;
        Preconditions.checkArgument(managedBuffer.capacity() > needSpace,
            String.format("Not sufficient space in given managed buffer. Need %d bytes, buffer has %d bytes",
                needSpace, managedBuffer.capacity()));

        final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
        final NullableDecimal28SparseVector v = ((NullableDecimal28SparseVector) vector);
        final Decimal28SparseHolder holder = new Decimal28SparseHolder();
        holder.scale = v.getField().getScale();
        holder.precision = v.getField().getPrecision();
        holder.buffer = managedBuffer;
        holder.start = 0;
        DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale,
            Decimal28SparseHolder.nDecimalDigits);
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, holder);
        }
        break;
      }

      case DECIMAL38SPARSE: {
      final int needSpace = Decimal38SparseHolder.nDecimalDigits * DecimalUtility.INTEGER_SIZE;
        Preconditions.checkArgument(managedBuffer.capacity() > needSpace,
            String.format("Not sufficient space in given managed buffer. Need %d bytes, buffer has %d bytes",
                needSpace, managedBuffer.capacity()));
        final BigDecimal value = ((HiveDecimal)val).bigDecimalValue();
        final NullableDecimal38SparseVector v = ((NullableDecimal38SparseVector) vector);
        final Decimal38SparseHolder holder = new Decimal38SparseHolder();
        holder.scale = v.getField().getScale();
        holder.precision = v.getField().getPrecision();
        holder.buffer = managedBuffer;
        holder.start = 0;
        DecimalUtility.getSparseFromBigDecimal(value, holder.buffer, 0, holder.scale,
            Decimal38SparseHolder.nDecimalDigits);
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, holder);
        }
        break;
      }
      case VARDECIMAL: {
        final BigDecimal value = ((HiveDecimal) val).bigDecimalValue()
            .setScale(vector.getField().getScale(), RoundingMode.HALF_UP);
        final NullableVarDecimalVector v = ((NullableVarDecimalVector) vector);
        for (int i = start; i < end; i++) {
          v.getMutator().setSafe(i, value);
        }
        break;
      }
    }
  }

  public static MajorType getMajorTypeFromHiveTypeInfo(final TypeInfo typeInfo, final OptionSet options) {
    switch (typeInfo.getCategory()) {
      case PRIMITIVE: {
        PrimitiveTypeInfo primitiveTypeInfo = (PrimitiveTypeInfo) typeInfo;
        MinorType minorType = HiveUtilities.getMinorTypeFromHivePrimitiveTypeInfo(primitiveTypeInfo, options);
        MajorType.Builder typeBuilder = MajorType.newBuilder().setMinorType(minorType)
            .setMode(DataMode.OPTIONAL); // Hive columns (both regular and partition) could have null values

        switch (primitiveTypeInfo.getPrimitiveCategory()) {
          case CHAR:
          case VARCHAR:
            BaseCharTypeInfo baseCharTypeInfo = (BaseCharTypeInfo) primitiveTypeInfo;
            typeBuilder.setPrecision(baseCharTypeInfo.getLength());
            break;
          case DECIMAL:
            DecimalTypeInfo decimalTypeInfo = (DecimalTypeInfo) primitiveTypeInfo;
            typeBuilder.setPrecision(decimalTypeInfo.getPrecision()).setScale(decimalTypeInfo.getScale());
            break;
          default:
            // do nothing, other primitive categories do not have precision or scale
        }

        return typeBuilder.build();
      }

      case LIST:
      case MAP:
      case STRUCT:
      case UNION:
      default:
        throwUnsupportedHiveDataTypeError(typeInfo.getCategory().toString());
    }

    return null;
  }

  public static TypeProtos.MinorType getMinorTypeFromHivePrimitiveTypeInfo(PrimitiveTypeInfo primitiveTypeInfo,
                                                                           OptionSet options) {
    switch(primitiveTypeInfo.getPrimitiveCategory()) {
      case BINARY:
        return TypeProtos.MinorType.VARBINARY;
      case BOOLEAN:
        return TypeProtos.MinorType.BIT;
      case DECIMAL: {

        if (!options.getOption(PlannerSettings.ENABLE_DECIMAL_DATA_TYPE_KEY).bool_val) {
          throw UserException.unsupportedError()
              .message(ExecErrorConstants.DECIMAL_DISABLE_ERR_MSG)
              .build(logger);
        }
        return MinorType.VARDECIMAL;
      }
      case DOUBLE:
        return TypeProtos.MinorType.FLOAT8;
      case FLOAT:
        return TypeProtos.MinorType.FLOAT4;
      // TODO (DRILL-2470)
      // Byte and short (tinyint and smallint in SQL types) are currently read as integers
      // as these smaller integer types are not fully supported in Drill today.
      case SHORT:
      case BYTE:
      case INT:
        return TypeProtos.MinorType.INT;
      case LONG:
        return TypeProtos.MinorType.BIGINT;
      case STRING:
      case VARCHAR:
      case CHAR:
        return TypeProtos.MinorType.VARCHAR;
      case TIMESTAMP:
        return TypeProtos.MinorType.TIMESTAMP;
      case DATE:
        return TypeProtos.MinorType.DATE;
    }
    throwUnsupportedHiveDataTypeError(primitiveTypeInfo.getPrimitiveCategory().toString());
    return null;
  }

  /**
   * Utility method which gets table or partition {@link InputFormat} class. First it
   * tries to get the class name from given StorageDescriptor object. If it doesn't contain it tries to get it from
   * StorageHandler class set in table properties. If not found throws an exception.
   * @param job {@link JobConf} instance needed incase the table is StorageHandler based table.
   * @param sd {@link StorageDescriptor} instance of currently reading partition or table (for non-partitioned tables).
   * @param table Table object
   * @throws Exception
   */
  public static Class<? extends InputFormat<?, ?>> getInputFormatClass(final JobConf job, final StorageDescriptor sd,
      final Table table) throws Exception {
    final String inputFormatName = sd.getInputFormat();
    if (Strings.isNullOrEmpty(inputFormatName)) {
      final String storageHandlerClass = table.getParameters().get(META_TABLE_STORAGE);
      if (Strings.isNullOrEmpty(storageHandlerClass)) {
        throw new ExecutionSetupException("Unable to get Hive table InputFormat class. There is neither " +
            "InputFormat class explicitly specified nor StorageHandler class");
      }
      final HiveStorageHandler storageHandler = HiveUtils.getStorageHandler(job, storageHandlerClass);
      TableDesc tableDesc = new TableDesc();
      tableDesc.setProperties(MetaStoreUtils.getTableMetadata(table));
      storageHandler.configureInputJobProperties(tableDesc, table.getParameters());
      return (Class<? extends InputFormat<?, ?>>) storageHandler.getInputFormatClass();
    } else {
      return (Class<? extends InputFormat<?, ?>>) Class.forName(inputFormatName) ;
    }
  }

  /**
   * Utility method which adds give configs to {@link JobConf} object.
   *
   * @param job {@link JobConf} instance.
   * @param properties New config properties
   */
  public static void addConfToJob(final JobConf job, final Properties properties) {
    for (Object obj : properties.keySet()) {
      job.set((String) obj, (String) properties.get(obj));
    }
  }

  /**
   * Wrapper around {@link MetaStoreUtils#getPartitionMetadata(Partition, Table)} which also adds parameters from table
   * to properties returned by {@link MetaStoreUtils#getPartitionMetadata(Partition, Table)}.
   *
   * @param partition the source of partition level parameters
   * @param table     the source of table level parameters
   * @return properties
   */
  public static Properties getPartitionMetadata(final HivePartition partition, final HiveTableWithColumnCache table) {
    final Properties properties;
    restoreColumns(table, partition);
    properties = MetaStoreUtils.getPartitionMetadata(partition, table);

    // SerDe expects properties from Table, but above call doesn't add Table properties.
    // Include Table properties in final list in order to not to break SerDes that depend on
    // Table properties. For example AvroSerDe gets the schema from properties (passed as second argument)
    for (Map.Entry<String, String> entry : table.getParameters().entrySet()) {
      if (entry.getKey() != null && entry.getKey() != null) {
        properties.put(entry.getKey(), entry.getValue());
      }
    }

    return properties;
  }

  /**
   * Sets columns from table cache to table and partition.
   *
   * @param partition partition which will set column list
   * @param table     the source of column lists cache
   */
  public static void restoreColumns(HiveTableWithColumnCache table, HivePartition partition) {
    // exactly the same column lists for partitions or table
    // stored only one time to reduce physical plan serialization
    if (partition != null && partition.getSd().getCols() == null) {
      partition.getSd().setCols(table.getColumnListsCache().getColumns(partition.getColumnListIndex()));
    }
    if (table.getSd().getCols() == null) {
      table.getSd().setCols(table.getColumnListsCache().getColumns(0));
    }
  }

  /**
   * Wrapper around {@link MetaStoreUtils#getSchema(StorageDescriptor, StorageDescriptor, Map, String, String, List)}
   * which also sets columns from table cache to table and returns properties returned by
   * {@link MetaStoreUtils#getSchema(StorageDescriptor, StorageDescriptor, Map, String, String, List)}.
   */
  public static Properties getTableMetadata(HiveTableWithColumnCache table) {
    restoreColumns(table, null);
    return MetaStoreUtils.getSchema(table.getSd(), table.getSd(), table.getParameters(),
      table.getDbName(), table.getTableName(), table.getPartitionKeys());
  }

  public static void throwUnsupportedHiveDataTypeError(String unsupportedType) {
    StringBuilder errMsg = new StringBuilder();
    errMsg.append(String.format("Unsupported Hive data type %s. ", unsupportedType));
    errMsg.append(System.getProperty("line.separator"));
    errMsg.append("Following Hive data types are supported in Drill for querying: ");
    errMsg.append(
        "BOOLEAN, TINYINT, SMALLINT, INT, BIGINT, FLOAT, DOUBLE, DATE, TIMESTAMP, BINARY, DECIMAL, STRING, VARCHAR and CHAR");

    throw UserException.unsupportedError()
        .message(errMsg.toString())
        .build(logger);
  }

  /**
   * Returns property value. If property is absent, return given default value.
   * If property value is non-numeric will fail.
   *
   * @param tableProperties table properties
   * @param propertyName property name
   * @param defaultValue default value used in case if property is absent
   * @return property value
   * @throws NumberFormatException if property value is not numeric
   */
  public static int retrieveIntProperty(Properties tableProperties, String propertyName, int defaultValue) {
    Object propertyObject = tableProperties.get(propertyName);
    if (propertyObject == null) {
      return defaultValue;
    }

    try {
      return Integer.valueOf(propertyObject.toString());
    } catch (NumberFormatException e) {
      throw new NumberFormatException(String.format("Hive table property %s value '%s' is non-numeric",
          propertyName, propertyObject.toString()));
    }
  }

  /**
   * Checks if given table has header or footer.
   * If at least one of them has value more then zero, method will return true.
   *
   * @param table table with column cache instance
   * @return true if table contains header or footer, false otherwise
   */
  public static boolean hasHeaderOrFooter(HiveTableWithColumnCache table) {
    Properties tableProperties = getTableMetadata(table);
    int skipHeader = retrieveIntProperty(tableProperties, serdeConstants.HEADER_COUNT, -1);
    int skipFooter = retrieveIntProperty(tableProperties, serdeConstants.FOOTER_COUNT, -1);
    return skipHeader > 0 || skipFooter > 0;
  }

  /**
   * This method checks whether the table is transactional and set necessary properties in {@link JobConf}.<br>
   * If schema evolution properties aren't set in job conf for the input format, method sets the column names
   * and types from table/partition properties or storage descriptor.
   *
   * @param job the job to update
   * @param sd storage descriptor
   */
  public static void verifyAndAddTransactionalProperties(JobConf job, StorageDescriptor sd) {

    if (AcidUtils.isTablePropertyTransactional(job)) {
      AcidUtils.setTransactionalTableScan(job, true);

      // No work is needed, if schema evolution is used
      if (Utilities.isSchemaEvolutionEnabled(job, true) && job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS) != null &&
          job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES) != null) {
        return;
      }

      String colNames;
      String colTypes;

      // Try to get get column names and types from table or partition properties. If they are absent there, get columns
      // data from storage descriptor of the table
      colNames = job.get(serdeConstants.LIST_COLUMNS);
      colTypes = job.get(serdeConstants.LIST_COLUMN_TYPES);

      if (colNames == null || colTypes == null) {
        colNames = sd.getCols().stream()
            .map(FieldSchema::getName)
            .collect(Collectors.joining(","));
        colTypes = sd.getCols().stream()
            .map(FieldSchema::getType)
            .collect(Collectors.joining(","));
      }

      job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS, colNames);
      job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, colTypes);
    }
  }

  /**
   * Rule is matched when all of the following match:
   * <ul>
   * <li>GroupScan in given DrillScalRel is an {@link HiveScan}</li>
   * <li> {@link HiveScan} is not already rewritten using Drill's native readers</li>
   * <li> InputFormat in table metadata and all partitions metadata contains the same value {@param tableInputFormatClass}</li>
   * <li> No error occurred while checking for the above conditions. An error is logged as warning.</li>
   *</ul>
   * @param call rule call
   * @return True if the rule can be applied. False otherwise
   */
  public static boolean nativeReadersRuleMatches(RelOptRuleCall call, Class tableInputFormatClass) {
    final DrillScanRel scanRel = call.rel(0);

    if (!(scanRel.getGroupScan() instanceof HiveScan) || ((HiveScan) scanRel.getGroupScan()).isNativeReader()) {
      return false;
    }

    final HiveScan hiveScan = (HiveScan) scanRel.getGroupScan();
    final HiveConf hiveConf = hiveScan.getHiveConf();
    final HiveTableWithColumnCache hiveTable = hiveScan.getHiveReadEntry().getTable();

    if (HiveUtilities.containsUnsupportedDataTypes(hiveTable)) {
      return false;
    }

    final Class<? extends InputFormat<?, ?>> tableInputFormat = getInputFormatFromSD(
        HiveUtilities.getTableMetadata(hiveTable), hiveScan.getHiveReadEntry(), hiveTable.getSd(), hiveConf);
    if (tableInputFormat == null || !tableInputFormat.equals(tableInputFormatClass)) {
      return false;
    }

    final List<HiveTableWrapper.HivePartitionWrapper> partitions = hiveScan.getHiveReadEntry().getHivePartitionWrappers();
    if (partitions == null) {
      return true;
    }

    final List<FieldSchema> tableSchema = hiveTable.getSd().getCols();
    // Make sure all partitions have the same input format as the table input format
    for (HiveTableWrapper.HivePartitionWrapper partition : partitions) {
      final StorageDescriptor partitionSD = partition.getPartition().getSd();
      Class<? extends InputFormat<?, ?>> inputFormat = getInputFormatFromSD(HiveUtilities.getPartitionMetadata(
          partition.getPartition(), hiveTable), hiveScan.getHiveReadEntry(), partitionSD, hiveConf);
      if (inputFormat == null || !inputFormat.equals(tableInputFormat)) {
        return false;
      }

      // Make sure the schema of the table and schema of the partition matches. If not return false. Schema changes
      // between table and partition can happen when table schema is altered using ALTER statements after some
      // partitions are already created. Currently native reader conversion doesn't handle schema changes between
      // partition and table. Hive has extensive list of convert methods to convert from one type to rest of the
      // possible types. Drill doesn't have the similar set of methods yet.
      if (!partitionSD.getCols().equals(tableSchema)) {
        logger.debug("Partitions schema is different from table schema. Currently native reader conversion can't " +
            "handle schema difference between partitions and table");
        return false;
      }
    }

    return true;
  }

  /**
   * Get the input format from given {@link StorageDescriptor}
   *
   * @param properties table properties
   * @param hiveReadEntry hive read entry
   * @param sd storage descriptor
   * @return {@link InputFormat} class or null if a failure has occurred. Failure is logged as warning.
   */
  private static Class<? extends InputFormat<?, ?>> getInputFormatFromSD(final Properties properties,
                                                                  final HiveReadEntry hiveReadEntry, final StorageDescriptor sd, final HiveConf hiveConf) {
    final Table hiveTable = hiveReadEntry.getTable();
    try {
      final String inputFormatName = sd.getInputFormat();
      if (!Strings.isNullOrEmpty(inputFormatName)) {
        return (Class<? extends InputFormat<?, ?>>) Class.forName(inputFormatName);
      }

      final JobConf job = new JobConf(hiveConf);
      HiveUtilities.addConfToJob(job, properties);
      return HiveUtilities.getInputFormatClass(job, sd, hiveTable);
    } catch (final Exception e) {
      logger.warn("Failed to get InputFormat class from Hive table '{}.{}'. StorageDescriptor [{}]",
          hiveTable.getDbName(), hiveTable.getTableName(), sd.toString(), e);
      return null;
    }
  }

  /**
   * This method allows to check whether the Hive Table contains
   * <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Types#LanguageManualTypes-ComplexTypes">
   * Hive Complex Types</a><p>
   * TODO: Need to implement it, DRILL-3290. Appropriate (new or existed) Drill types should be selected.
   *
   * @param hiveTable Thrift table from Hive Metastore
   * @return true if table contains unsupported data types, false otherwise
   */
  public static boolean containsUnsupportedDataTypes(final Table hiveTable) {
    for (FieldSchema hiveField : hiveTable.getSd().getCols()) {
      final Category category = TypeInfoUtils.getTypeInfoFromTypeString(hiveField.getType()).getCategory();
      if (category == Category.MAP ||
          category == Category.STRUCT ||
          category == Category.UNION ||
          category == Category.LIST) {
        logger.debug("Hive table contains unsupported data type: {}", category);
        return true;
      }
    }
    return false;
  }
}


text:
import React, { Component, PropTypes } from 'react';
import Styles from './styles.scss';
import BreakPoints from './breakpoints';
import cx from 'classnames';

/**
 * @param {int} currentWidth
 * @param {object} breakPoints
 *
 * @returns {string} breakPoint name
 */
function getCurrentBreakpoint(currentWidth, breakPoints) {
    const breakPoint = Object.keys(breakPoints).find((bp) => {
        let current = bp;

        if (typeof bp === 'object') {
            current = bp.name;
        }

        return currentWidth >= breakPoints[current].min && currentWidth <= breakPoints[current].max;
    });

    return breakPoint;
}

export default class PixelPerfect extends Component {
    static propTypes = {
        component: PropTypes.string.isRequired,
        children: PropTypes.object,
        opacity: PropTypes.number,
        breakPoints: PropTypes.object,
        templates: PropTypes.array,
        state: PropTypes.string
    };

    static defaultProps = {
        opacity: 80,
        breakPoints: BreakPoints,
        templates: [
            BreakPoints.phonePortrait.name,
            BreakPoints.phoneLandscape.name,
            BreakPoints.tabletPortrait.name,
            BreakPoints.tabletLandscape.name
        ],
        state: 'Default'
    };

    componentDidMount = () => {
        this.setState({
            width: global.window.innerWidth,
            currentBreakpoint: getCurrentBreakpoint(global.window.innerWidth, this.props.breakPoints),
            opacity: this.props.opacity,
            state: {
                isMenuVisible: false,
                current: this.props.state
            }
        });

        global.window.onresize = this.onResize;
    };

    constructor() {
        super();
        this.state = {
            currentBreakpoint: '',
            state: {},
            width: null,
            opacity: null,
            visible: true
        };
    }

    /**
     * Change opacity
     *
     * @param event
     */
    onOpacityClick = (event) => {
        let opacity;
        if (event.target.dataset.opacity === 'up') {
            opacity = this.state.opacity + 20;
            if (opacity > 100) {
                opacity = 100;
            }
        } else if (event.target.dataset.opacity === 'down') {
            opacity = this.state.opacity - 20;
            if (opacity < 0) {
                opacity = 0;
            }
        }

        this.setState({
            opacity,
            visible: opacity > 0
        });
    };

    onHideClick = () => {
        this.setState({
            visible: !this.state.visible
        });
    };

    toggleStateMenu = (event) => {
        if (event.target.tagName === 'LI') {
            return;
        }

        this.setState({
            state: {
                ...this.state.state,
                isMenuVisible: !this.state.state.isMenuVisible
            }
        });
    };

    changeState = (event) => {
        this.setState({
            state: {
                isMenuVisible: false,
                current: event.target.dataset.state
            }
        });
    };

    /**
     * Resize window
     */
    onResize = () => {
        const width = global.window.innerWidth;

        this.setState({
            width,
            currentBreakpoint: getCurrentBreakpoint(width, this.props.breakPoints)
        });
    };

    render() {
        const { templates, component, breakPoints } = this.props;
        const { width, currentBreakpoint, state, visible } = this.state;
        const currentOpacity = this.state.opacity;
        const hideClasses = cx({
            [Styles.hide]: true,
            [Styles.disabled]: currentOpacity === 0
        });

        const StateClasses = cx({
            [Styles.states]: true,
            [Styles.disabled]: !state.isMenuVisible
        });

        const result = templates.find((current) => {
            return typeof current === 'object' && current.name === currentBreakpoint;
        });

        const statesList = result ? result.states.map((current) => {
            return (

{ current }

            );
        }) : null;

        const image = templates.filter((breakPoint) => {
            const bp = typeof breakPoint === 'object' ? breakPoint.name : breakPoint;

            return bp === this.state.currentBreakpoint
                && breakPoints[bp]
                && global.window.innerWidth === breakPoints[bp].template
                && visible;
        }).map((breakPoint) => {
            let filename = breakPoint;

            if (typeof breakPoint === 'object') {
                filename = breakPoint.name;

                if (state.current !== 'Default') {
                    filename += `__${state.current}`;
                }
            }
            const src = `/PixelPerfect/${component.replace('.', '//')}/${filename}.jpg`;

            return (

            );
        });

        return (

Component:

{ component }

State:

{ state.current }

                                    { statesList }

Breakpoint:

{ currentBreakpoint }

Width:

{ `${width}px` }

Opacity:

                                    -

{ currentOpacity }

                                    +

                                    { visible ? 'Hide' : 'Show' }

                        { image }

                    { this.props.children }

        );
    }
}


text:
<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'bio' => $faker->text($maxNbChars = 200),
        'email' => $faker->email,
        'phone' => $faker->phoneNumber,
        'avatar' => $faker->imageUrl($width = 960, $height = 960, 'people'),
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
        'created_at' => $faker->dateTimeBetween($startDate = '-10 days', $endDate = '-6 days'),
        'updated_at' => $faker->dateTimeBetween($startDate = '-6 days', $endDate = '-4 days'),
    ];
});

$factory->define(App\Idea::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'description' => $faker->text($maxNbChars = 400),
        'photo' => $faker->imageUrl($width = 1200, $height = 400),
        'created_at' => $faker->dateTimeBetween($startDate = '-4 days', $endDate = '-2 days'),
        'updated_at' => $faker->dateTimeBetween($startDate = '-2 days', $endDate = 'now'),
    ];
});


text:
from ..data import BoletoData, custom_property

class BoletoCaixa(BoletoData):
    '''
        Gera Dados necessários para criação de boleto para o banco Caixa
        Economica Federal

    '''

    agencia_cedente = custom_property('agencia_cedente', 4)
    conta_cedente = custom_property('conta_cedente', 6)
    # nosso_numero = custom_property('nosso_numero', 10)

    def __init__(self):
        super(BoletoCaixa, self).__init__()
        self.codigo_banco = "104"
        self.local_pagamento = u"Preferencialmente nas Casas Lotéricas e Agências da Caixa"
        self.logo_image = "logo_bancocaixa.jpg"

    @property
    def dv_nosso_numero(self):
        resto2 = self.modulo11(self.nosso_numero.split('-')[0], 9, 1)
        digito = 11 - resto2
        if digito in [10, 11]:
            return 0
        return digito

    @property
    def campo_livre(self):
        content = "%10s%4s%11s" % (self.nosso_numero,
                                   self.agencia_cedente,
                                   self.conta_cedente.split('-')[0])
        return content

    def format_nosso_numero(self):
        return "{}-{}".format(self.nosso_numero, str(self.dv_nosso_numero))

class BoletoCaixaV2(BoletoCaixa):
    """
        Gera Dados necessários para criação de boleto para o banco Caixa
        Economica Federal ( Nosso número maior que 10 dígitos )
    """
    nosso_numero = custom_property('nosso_numero', 16)
    agencia_cedente = custom_property('agencia_cedente', 4)
    conta_cedente = custom_property('conta_cedente', 6)

    def __init__(self, inicio_nosso_numero):
        super(BoletoCaixaV2, self).__init__()
        self.inicio_nosso_numero = inicio_nosso_numero

    @property
    def dv_nosso_numero(self):
        resto2 = self.modulo11('{}{}'.format(self.inicio_nosso_numero, self.nosso_numero.split('-')[0]), 9, 1)
        digito = 11 - resto2
        if digito in [10, 11]:
            return 0
        return digito

    @property
    def campo_livre(self):
        content = str("%1s%6s%2s%16s" % (self.inicio_nosso_numero[1],
                                         self.conta_cedente.split('-')[0],
                                         self.inicio_nosso_numero,
                                         self.nosso_numero))
        return content

    def format_nosso_numero(self):
        return '{}{}-{}'.format(self.inicio_nosso_numero, self.nosso_numero, str(self.dv_nosso_numero))

class BoletoCaixaSIGCB(BoletoCaixa):
    """
        Gera Dados necessários para criação de boleto para o banco Caixa
        Economica Federal - SIGCB
    """

    nosso_numero = custom_property('nosso_numero', 15)
    agencia_cedente = custom_property('agencia_cedente', 4)
    conta_cedente = custom_property('conta_cedente', 6)

    def __init__(self, inicio_nosso_numero='24'):
        super(BoletoCaixaSIGCB, self).__init__()
        self.inicio_nosso_numero = inicio_nosso_numero

    @property
    def dv_conta_cedente(self):
        resto2 = self.modulo11(self.conta_cedente.split('-')[0], 9, 1)
        digito = 11 - resto2
        if digito in [10, 11]:
            return 0
        return digito

    @property
    def agencia_conta_cedente(self):
        return "{} / {}-{}".format(
            self.agencia_cedente,
            self.conta_cedente.split('-')[0],
            self.dv_conta_cedente)

    @property
    def campo_livre(self):
        content = "{}{}{}{}{}{}{}".format(
            self.conta_cedente.split('-')[0],
            self.dv_conta_cedente,
            self.nosso_numero[:3],
            self.inicio_nosso_numero[0:1],
            self.nosso_numero[3:6],
            self.inicio_nosso_numero[1:2],
            self.nosso_numero[6:15]
        )
        return str("{}{}".format(content, self._dv_num(content)))

    def _dv_num(self, num):
        resto2 = self.modulo11(num.split('-')[0], 9, 1)
        digito = 11 - resto2
        if digito in [10, 11]:
            return 0
        return digito

    def format_nosso_numero(self):
        nnum = "{}{}{}{}".format(
            self.inicio_nosso_numero[0:2],
            self.nosso_numero[:3],
            self.nosso_numero[3:6],
            self.nosso_numero[6:15]
        )
        nossonumero = '{}{}'.format(nnum, self._dv_num(nnum))
        return nossonumero


text:
heamy.estimator module
======================================

.. automodule:: heamy.estimator

Regressor
--------------

.. autoclass:: Regressor
    :members:
    :show-inheritance:
    :inherited-members:

Classifier
--------------

.. autoclass:: Classifier
    :members:
    :show-inheritance:
    :inherited-members:


text:
enum dmo_type {
    DMO_CLIENT_SERVER,
    DMO_SERVER,
    DMO_CLIENT
};

enum dmo_sys_type : u32 {
    DMO_NET,
    DMO_SIM,
    DMO_NUM_SYS,
};

struct dmo_systems {
    struct dmo_net *net;
    struct dmo_sim *sim;
};

struct dmo {
    enum dmo_type type;
    u8 running;
    struct dmo_msg *msg;
    struct dmo_systems systems;
};

struct dmo_buffer {
    size_t capacity;
    u8 *data;
    u64 rindex;
    u64 windex;
};

struct dmo * dmo_create(enum dmo_type type);

void dmo_destroy(struct dmo *dmo);

void dmo_start(struct dmo *dmo);

void dmo_stop(struct dmo *dmo);

void dmo_log(i32 level, char const * format, ...);

f64 dmo_time();

struct dmo_buffer * dmo_buffer_create(size_t size);

bool dmo_buffer_can_read(struct dmo_buffer *buffer, size_t size);

bool dmo_buffer_can_write(struct dmo_buffer *buffer, size_t size);

void dmo_buffer_reset(struct dmo_buffer *buffer);


text:
from fabric.api import run,put,cd,parallel,roles,serial,local,runs_once
from env_setup import *

@roles('master')
def simulator():
    global conf
    with cd(env.conf['HADOOPBIN']):
        cmd = './hadoop jar $JAR perf.benchmark.RunSimulator' + \
            ' --conf $CONF' + \
            ' --tableName $TABLENAME' + \
            ' --mode 0' + \
            ' --simName sim' + \
            ' --queriesFile /Users/anil/Dev/repos/mdindex/scripts/queries.log' + \
            ' > ~/logs/sim.log'
        cmd = fill_cmd(cmd)
        run(cmd)

@roles('master')
def simulator_multipred():
    global conf
    with cd(env.conf['HADOOPBIN']):
        cmd = './hadoop jar $JAR perf.benchmark.RunSimulator' + \
            ' --conf $CONF' + \
            ' --tableName $TABLENAME' + \
            ' --mode 1' + \
            ' --simName sim' + \
            ' --queriesFile ~/queries.log' + \
            ' > ~/logs/sim_multipred.log'
        cmd = fill_cmd(cmd)
        run(cmd)


text:
package org.opentripplanner.standalone;

/**
 * PreBoard edges connect a TransitStop to its agency_stop_depart vertices; PreAlight edges connect
 * an agency_stop_arrive vertex to its TransitStop. Applies the local stop rules (see
 * TransitStop.java and LocalStopFinder.java) as well as transfer limits, timed and preferred
 * transfer rules, transfer penalties, and boarding costs. This avoids applying these costs/rules
 * repeatedly in (Pattern)Board edges. These are single station or station-to-station specific
 * costs, rather than trip-pattern specific costs.
 */
public class PreBoardEdge extends FreeEdge implements StationEdge {

    private static final long serialVersionUID = -8046937388471651897L;

    public PreBoardEdge(TransitStop from, TransitStopDepart to) {
        super(from, to);
        if (!(from instanceof TransitStop)) { throw new IllegalStateException("Preboard edges must lead out of a transit stop."); }
    }

    @Override
    public State traverse(State s0) {
        RoutingRequest options = s0.getOptions();

        // Ignore this edge if its stop is banned
        if (!options.bannedStops.isEmpty()) {
            if (options.bannedStops.matches(((TransitStop) this.fromv).getStop())) { return null; }
        }
        if (!options.bannedStopsHard.isEmpty()) {
            if (options.bannedStopsHard.matches(((TransitStop) this.fromv).getStop())) { return null; }
        }

        if (options.arriveBy) {
            /* Traverse backward: not much to do */
            StateEditor s1 = s0.edit(this);
            TransitStop fromVertex = (TransitStop) getFromVertex();

            // apply board slack
            s1.incrementTimeInSeconds(options.boardSlack);
            s1.alightTransit();
            s1.setBackMode(getMode());
            return s1.makeState();
        } else {
            /* Traverse forward: apply stop(pair)-specific costs */

            // Do not pre-board if transit modes are not selected.
            // Return null here rather than in StreetTransitLink so that walk-only
            // options can be used to find transit stops without boarding vehicles.
            if (!options.modes.isTransit()) { return null; }

            // If we've hit our transfer limit, don't go any further
            if (s0.getNumBoardings() > options.maxTransfers) { return null; }

            /* apply transfer rules */
            /*
             * look in the global transfer table for the rules from the previous stop to this stop.
             */
            long t0 = s0.getTimeSeconds();

            long slack;
            if (s0.isEverBoarded()) {
                slack = options.transferSlack - options.alightSlack;
            } else {
                slack = options.boardSlack;
            }
            long board_after = t0 + slack;
            long transfer_penalty = 0;

            // penalize transfers more heavily if requested by the user
            if (s0.isEverBoarded()) {
                // this is not the first boarding, therefore we must have "transferred" -- whether
                // via a formal transfer or by walking.
                transfer_penalty += options.transferPenalty;
            }

            StateEditor s1 = s0.edit(this);
            s1.setTimeSeconds(board_after);
            long wait_cost = board_after - t0;
            s1.incrementWeight(wait_cost + transfer_penalty);
            s1.setBackMode(getMode());
            return s1.makeState();
        }
    }

    public TraverseMode getMode() {
        return TraverseMode.LEG_SWITCH;
    }

    @Override
    public State optimisticTraverse(State s0) {
        // do not include minimum transfer time in heuristic weight
        // (it is path-dependent)
        StateEditor s1 = s0.edit(this);
        s1.setBackMode(getMode());
        return s1.makeState();
    }

    @Override
    public String toString() {
        return "preboard edge at stop " + this.fromv;
    }

}


text:
import { animate, state, style, transition, trigger } from '@angular/animations';
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  Output,
  ViewEncapsulation,
} from '@angular/core';
import { isAndroid } from 'ngx-weui/core';
import { Observable, Observer, Subscription } from 'rxjs';
import { ActionSheetConfig } from './actionsheet.config';
import { ActionSheetMenuItem } from './actionsheet.types';

@Component({
  selector: 'weui-actionsheet',
  exportAs: 'weuiActionsheet',
  templateUrl: './actionsheet.component.html',
  animations: [
    trigger('visibility', [
      state('show', style({ opacity: 1 })),
      state('hide', style({ opacity: 0 })),
      transition('hide <=> show', [animate(200)]),
    ]),
  ],
  host: {
    '[hidden]': '!_shown',
    '[class.weui-skin_android]': 'config.skin === "android"',
  },
  preserveWhitespaces: false,
  changeDetection: ChangeDetectionStrategy.OnPush,
  encapsulation: ViewEncapsulation.None,
})
export class ActionSheetComponent implements OnDestroy {
  private observer: Observer<ActionSheetMenuItem>;
  private destroied = false;
  _shown = false;
  /**
   * 动画状态码
   */
  _shownAnt = false;
  /**
   * 配置项
   */
  @Input() config: ActionSheetConfig;

  /**
   * 菜单内容
   */
  @Input() menus: ActionSheetMenuItem[] = [];

  /**
   * 关闭回调
   */
  @Output() readonly close = new EventEmitter();

  get _visibility(): string {
    return this._shownAnt ? 'show' : 'hide';
  }

  constructor(private DEF: ActionSheetConfig, private cdr: ChangeDetectorRef) {}

  private detectChanges(): void {
    if (this.destroied) {
      return;
    }
    this.cdr.detectChanges();
  }

  /**
   * 显示,组件载入页面后并不会显示,显示调用 `show()` 并订阅结果。
   */
  show(): Observable<ActionSheetMenuItem> {
    this.config = {
      backdrop: true,
      skin: 'auto',
      ...this.DEF,
      ...this.config,
    };
    if (this.config.skin === 'auto') {
      this.config.skin = isAndroid() ? 'android' : 'ios';
    }
    this._shown = true;
    setTimeout(() => {
      this._shownAnt = true;
      this.detectChanges();
    }, 10);
    return new Observable((observer: Observer<ActionSheetMenuItem>) => {
      this.observer = observer;
    });
  }

  /**
   * 隐藏
   *
   * @param is_backdrop 是否从背景上点击
   */
  hide(is_backdrop?: boolean): void {
    if (is_backdrop === true && this.config.backdrop === false) {
      return;
    }

    this._shownAnt = false;
    this.detectChanges();
    setTimeout(
      () => {
        this._shown = false;
        this.close.emit();
      },
      this.config.skin === 'android' ? 200 : 300,
    );
  }

  /**
   * 选择动作
   */
  _onSelect(menu: ActionSheetMenuItem): void {
    this.observer.next(menu);
    this.observer.complete();
    this.hide();
  }

  ngOnDestroy(): void {
    this.destroied = true;
    if (this.observer && this.observer instanceof Subscription) {
      (this.observer as Subscription).unsubscribe();
    }
  }
}