text:
"""Generate a single discrete time SIR model.
"""
from . import data_model
import numpy as np
from scipy import stats
import xarray as xr

# Generate Betas
# Beta, or the growth rate of the infection, depends on the covariates.
# Here we implement three different functional forms for the dependency.

SPLIT_TIME = 100

def generate_betas_from_single_random_covariate(num_locations):
  """Beta depend on a single covariate that is randomly generated.

  Args:
    num_locations: an int representing the number of locations to simulate

  Returns:
    beta: an xr.DataArray consisting of the growth rate
      for each epidemic
    v: an xr.DataArray consisting of the randomly generated covariate for each
      location
    alpha: an xr.DataArray consisting of the weights for each covariate
  """
  v = xr.DataArray(
      np.random.uniform(0.0, 1.0, (num_locations, 1)),
      dims=['location', 'static_covariate'])
  alpha = xr.DataArray(np.ones(1), dims=['static_covariate'])
  beta = 0.4 * np.exp(alpha @ v)

  return beta, v, alpha

def generate_betas_effect_mod(num_locations):
  """Betas depend on 2 discrete, randomly generated effects.

  Args:
    num_locations: an int representing the number of locations to simulate

  Returns:
    beta: an xr.DataArray consisting of the growth rate
      for each epidemic
    v: an xr.DataArray consisting of the randomly generated covariate for each
      location
    alpha: an xr.DataArray consisting of the weights for each covariate
  """
  v = xr.DataArray(np.random.binomial(1, 0.5, size=(num_locations, 2)),
                   dims={'location': num_locations, 'static_covariate': 2})
  hd = v.values[:, 0]
  ws = v.values[:, 1]
  beta_np = np.exp(np.log(1.5) + np.log(2.0) * (hd == 1) * (ws == 0))
  beta = xr.DataArray(beta_np, dims={'location': num_locations})

  return beta, v, xr.DataArray(np.array([1, 1]), dims={'static_covariate': 2})

def generate_betas_many_cov2(num_locations, num_pred=1, num_not_pred=2):
  """Betas depend on real valued vector of covariates.

  Args:
    num_locations: an int representing the number of locations to simulate.
    num_pred: an int representing the number of covariates that affect beta.
    num_not_pred: an int representing the number of covariates that do not
      affect beta.

  Returns:
    beta: an xr.DataArray consisting of the growth rate
      for each epidemic
    v: an xr.DataArray consisting of the randomly generated covariate for each
      location
    alpha: an xr.DataArray consisting of the weights for each covariate
  """
  # generate random covariates
  # sample from range -1, 1 uniformly
  v = xr.DataArray(np.random.uniform(
      low=-1.0, high=1.0, size=(num_locations, num_pred + num_not_pred)),
                   dims={'location': num_locations,
                         'static_covariate': num_pred+num_not_pred})

  # construct weights for each covariate
  alpha_1 = np.ones(num_pred)
  alpha_0 = np.zeros(num_not_pred)
  alpha = xr.DataArray(np.concatenate((alpha_1, alpha_0), axis=0),
                       dims={'static_covariate': num_pred+num_not_pred})

  # this has a different functional form than we've seen before
  beta_np = 1 + np.exp(np.matmul(alpha.values, v.values.T))
  beta = xr.DataArray(beta_np, dims={'location': num_locations})

  return beta, v, alpha

def gen_dynamic_beta_random_time(num_locations, num_time_steps):
  """Betas change at a random time between 1 and num_time_steps-1.

  Args:
    num_locations: an int representing the number of locations to simulate
    num_time_steps: an int representing the number of time steps to simulate

  Returns:
    beta: an xr.DataArray consisting of the growth rate
      for each epidemic with dimensions (location, time)
    v: an xr.DataArray consisting of the randomly generated covariate for each
      location with dimensions (location, time, 1)
    alpha: an xr.DataArray consisting of the weights for each covariate with
      dimension 1.
  """
  time = np.random.randint(1, num_time_steps-1, num_locations)
  cov = np.zeros((num_locations, num_time_steps, 1))
  for i in range(num_locations):
    cov[i][time[i]:] = 1
  v = xr.DataArray(cov, dims=['location', 'time', 'dynamic_covariate'])
  alpha = np.random.uniform(-1., 0.)*xr.DataArray(np.ones(1), dims=['dynamic_covariate'])
  beta = 0.4 * np.exp(alpha @ v)
  return beta, v, alpha

def gen_social_distancing_weight(num_locations):
  alpha = np.random.uniform(-1., 0., 1)
  return alpha

def new_sir_simulation_model(num_locations, num_time_steps,
                             num_static_covariates, num_dynamic_covariates=0):
  """Return a zero data_model.new_model with extra simulation parameters.

  Args:
    num_locations: int representing the number of locations to model epidemics
      for
    num_time_steps: int representing the maximum number of time steps the
      epidemic can have
    num_static_covariates: int representing the number of static covariates for
      each location
    num_dynamic_covariates: int representing the number of dynamic covariates
      for each location.

  Returns:
    ds: an xr.Dataset representing the new infections and
      covariates for each location and representing the simulation parameters.
      All datavalues are initialized to 0.
  """
  if num_time_steps < SPLIT_TIME:
    raise ValueError('num_time_steps must be at least %d' % (SPLIT_TIME,))
  ds = data_model.new_model(num_locations, num_time_steps,
                            num_static_covariates, num_dynamic_covariates)
  ds['canonical_split_time'] = SPLIT_TIME
  ds['canonical_split_time'].attrs['description'] = (
      'Int representing the canonical time at which to split the data.')

  ds['static_weights'] = data_model.new_dataarray(
      {'static_covariate': num_static_covariates})

  # TODO(edklein) should population_size be a covariate?
  ds['population_size'] = data_model.new_dataarray({'location': num_locations})
  ds['population_size'].attrs[
      'description'] = 'Int representing the population size in each location.'

  ds['fraction_infected'] = data_model.new_dataarray({
      'location': num_locations
  })
  ds['fraction_infected'].attrs['description'] = (
      'Float representing the fraction of the population '
      'infected at the day %d.' % (SPLIT_TIME,))

  ds['start_time'] = data_model.new_dataarray({
      'location': num_locations
  })
  ds['start_time'].attrs['description'] = (
      'Int representing the infection start time at each location')

  ds['recovery_rate'] = data_model.new_dataarray({'location': num_locations})
  ds['recovery_rate'].attrs[
      'description'] = ('Float representing the recovery rate in each location.'
                        ' This is used in the SIR simulation of the epidemic.')

  if num_dynamic_covariates > 0:
    ds['dynamic_weights'] = data_model.new_dataarray(
        {'time': num_time_steps,
         'dynamic_covariate': num_dynamic_covariates})

    ds['growth_rate'] = data_model.new_dataarray({'location': num_locations,
                                                  'time': num_time_steps})
    ds['growth_rate'].attrs[
        'description'] = ('Float representing the growth rate in each location'
                          ' at each point in time.'
                          'This is used in the SIR simulation of the epidemic.')
  else:
    ds['growth_rate'] = data_model.new_dataarray({'location': num_locations})
    ds['growth_rate'].attrs[
        'description'] = ('Float representing the growth rate in each location.'
                          'This is used in the SIR simulation of the epidemic.')

  return ds

def _helper_ground_truth_setup(population_size,
                               num_time_steps):
  """A helper function that sets up time0 of an SIR simulation.

  This helper function calculates the number of susceptible, infected, and
  recovered individuals at the begining of a simulation. It returns these
  values to be used as initial values in _helper_ground_truth_loop.

  Args:
    population_size: a xr.DataArray representing the population size in each
      location
    num_time_steps: an int representing the number of simulation 'days' to run
      at each location.

  Returns:
    new_infections: a DataArray with shape (location, time).
      The infections at time 0 are initialized to 1 in all locations.
    num_susceptible: a DataArray with shape (location,) containing the
      number of susceptible individuals in each location at time 0.
    num_infected: a DataArray with shape (location,) containing the
      number of infected individuals (1) in each location at time 0.
    num_recovered: a DataArray with shape (location,) containing the
      number of recovered individuals in each location at time 0.
  """
  num_locations = population_size.sizes['location']

  num_recovered = data_model.new_dataarray({
      'location': num_locations,
  }).astype(int)

  new_infections = data_model.new_dataarray({
      'location': num_locations,
      'time': num_time_steps
  }).astype(int)
  # at each start time, we have 1 infection
  new_infections[dict(time=0)] = 1
  # setup for t-0
  num_infected = new_infections.sel(time=0).copy()

  num_susceptible = population_size.copy()
  num_susceptible -= num_infected
  return new_infections, num_susceptible, num_infected, num_recovered

def _helper_ground_truth_loop(num_susceptible, num_recovered, num_infected,
                              beta_time_t, gamma, population_size,
                              prob_infection_constant):
  """A helper function to calculate SIR for one time step of an SIR simulation.

  This helper function calculates the number of susceptible, infected, and
  recovered individuals at one time step. It returns these values to be used as
  initial values in the next call.

  Args:
    num_susceptible: a DataArray with shape (location,) containing the
      number of susceptible individuals in each location at time t.
    num_infected: a DataArray with shape (location,) containing the
      number of infected individuals (1) in each location at time t.
    num_recovered: a DataArray with shape (location,) containing the
      number of recovered individuals in each location at time t.
    beta_time_t: a xr.DataArray representing the growth rate of the disease in
      each location at time t.
    gamma: a xr.DataArray representing the recovery rate of the disease in each
      location
    population_size: a xr.DataArray representing the population size in each
      location
    prob_infection_constant: a float representing a constant that we multiply
      the probability of becoming infected by. We noticed that a value of 1. led
      to curves that were short in time and clustered in time. By changing this
      to less than 1., our models fit better.

  Returns:
    num_new_infections: a DataArray with shape (location,) containing the
      number of *new* infections that occured at thime t+1.
    num_susceptible: a DataArray with shape (location,) containing the
      number of susceptible individuals in each location at time t+1.
    num_infected: a DataArray with shape (location,) containing the
      number of infected individuals (1) in each location at time t+1.
    num_recovered: a DataArray with shape (location,) containing the
      number of recovered individuals in each location at time t+1.
  """
  # Calculate the probability that a person becomes infected
  # Python3 doesn't seem to work, so force a float

  frac_pop_infected = num_infected.astype(float) / population_size
  prob_infected = prob_infection_constant * (
      1 - np.exp(-frac_pop_infected * beta_time_t))
  # Make sure prob_infected is between 0 and 1
  prob_infected = prob_infected.where(prob_infected > 0, 0)
  prob_infected = prob_infected.where(prob_infected < 1, 1)

  # Determine the number of new infections
  # By drawing from a binomial distribution
  # Record the number of infections that occured at this time point
  num_new_infections = stats.binom.rvs(
      num_susceptible.astype(int), prob_infected)

  # Calculate the probability that a person recovers
  prob_recover = 1 - np.exp(-gamma)

  # Determine the number of recoveries
  # by drawing from a binomial distribution
  num_new_recoveries = stats.binom.rvs(num_infected, prob_recover)

  num_susceptible -= num_new_infections
  num_recovered += num_new_recoveries
  num_infected += num_new_infections - num_new_recoveries
  return num_new_infections, num_susceptible, num_recovered, num_infected

def generate_ground_truth(population_size,
                          beta,
                          gamma,
                          num_time_steps,
                          prob_infection_constant=0.2):
  """A function that generates infections over time using a discrete SIR model.

  We assume that the epidemic starts with a single case at time 0.
  We then simulate the number of infected individuals as a function of time,
  until the number of infected individuals is 0.
  This is the epidemic curve. Returns the epidemic curves as a function of time.

  Args:
    population_size: a xr.DataArray representing the population size in each
      location
    beta: a xr.DataArray representing the growth rate of the disease in each
      location
    gamma: a xr.DataArray representing the recovery rate of the disease in each
      location
    num_time_steps: an int representing the number of simulation 'days' to run
      at each location.
    prob_infection_constant: a float representing a constant that we multiply
      the probability of becoming infected by. We noticed that a value of 1. led
      to curves that were short in time and clustered in time. By changing this
      to less than 1., our models fit better.

  Returns:
    new_infections: a xr.DataArray representing the new_infections at each
      (location, time).
  """

  new_infections, num_susceptible, num_infected, num_recovered = _helper_ground_truth_setup(
      population_size, num_time_steps)

  if 'time' not in beta.dims:
    beta = beta.expand_dims({'time': new_infections.sizes['time']})

  for t in new_infections.time[1:]:
    beta_time_t = beta[dict(time=t)]
    num_new_infections, num_susceptible, num_recovered, num_infected = _helper_ground_truth_loop(
        num_susceptible, num_recovered, num_infected, beta_time_t, gamma,
        population_size, prob_infection_constant)
    new_infections[dict(time=t)] = num_new_infections

  return new_infections

def generate_social_distancing_ground_truth(population_size,
                                            beta,
                                            gamma,
                                            num_time_steps,
                                            social_distancing_threshold,
                                            gen_social_distancing_weight_fn,
                                            prob_infection_constant=0.2
                                            ):
  """Generate infections over time using SIR with a variable growth rate.

  We assume that the epidemic starts with a single case at time 0.
  We then simulate the number of infected individuals as a function of time.
  When the number of infected individuals reaches num_infected_threshold,
  we decrease the growth rate by an amount determined by social_distance_fn.
  We continue simulating the number of infected individuals until we reach
  num_time_steps. This is the epidemic curve. Returns the epidemic curves as a
  function of time.

  Args:
    population_size: a xr.DataArray representing the population size in each
      location
    beta: a xr.DataArray representing the static growth rate of the disease in
      each location
    gamma: a xr.DataArray representing the recovery rate of the disease in each
      location
    num_time_steps: an int representing the number of simulation 'days' to run
      at each location.
    social_distancing_threshold: an array of ints of shape (num_locations)
      indicating the number of infections at each location when we change the
      growth rate.
    gen_social_distancing_weight_fn: A (partial) function that generates the
      weights of the social distancing covariate. Function is called with the
      argument num_locations.
    prob_infection_constant: a float representing a constant that we multiply
      the probability of becoming infected by. We noticed that a value of 1. led
      to curves that were short in time and clustered in time. By changing this
      to less than 1., our models fit better.

  Returns:
    beta_td: a xr.DataArray representing the time-dependent growth rate at each
      (location, time).
    dynamic_covariate: a xr.DataArray representing the time-dependent covariate
      at each (location, time). Currently fixed to be one covariate with
      a value of either 0 or 1.
    dynamic_weights: a xr.DataArray representing the weight of dynamic_covariate
      currently a 1d array with dimension ['dynamic_covariate'].
    new_infections: a xr.DataArray representing the new_infections at each
      (location, time).
  """

  new_infections, num_susceptible, num_infected, num_recovered = _helper_ground_truth_setup(
      population_size, num_time_steps)
  num_locations = population_size.sizes['location']

  # need to compute the change in growth rate at a given
  # infection load. This will be represented by a time-dependent covariate
  # that will be 0 or 1 in all locations. (It's possible we'll
  # want to allow the value of it to change eventually.) The weight will be
  # constant in time, although we might store it as time-dependent for
  # consistency/scalability
  dynamic_alpha = gen_social_distancing_weight_fn(num_locations)
  dynamic_weights = xr.DataArray(dynamic_alpha, dims=['dynamic_covariate'])

  beta_td = beta.copy()

  if 'time' not in beta_td.dims:
    beta_td = beta_td.expand_dims({'time': new_infections.sizes['time']}).copy()

  dynamic_covariate = xr.zeros_like(new_infections)
  dynamic_covariate = dynamic_covariate.expand_dims({'dynamic_covariate':1}).copy()

  # No locations start off above their threshold
  # at t=0
  infection_threshold = xr.zeros_like(beta).expand_dims({'dynamic_covariate':1})

  for t in new_infections.time[1:]:
    # Update growth rate if needed
    dynamic_covariate[dict(time=t)] = infection_threshold.astype(int)
    beta_td[dict(time=t)] = beta + (dynamic_weights @ infection_threshold.astype(int))

    beta_time_t = beta_td[dict(time=t)]
    num_new_infections, num_susceptible, num_recovered, num_infected = _helper_ground_truth_loop(
        num_susceptible, num_recovered, num_infected, beta_time_t, gamma,
        population_size, prob_infection_constant)
    new_infections[dict(time=t)] = num_new_infections

    # Check if we need to update growth rate
    total_infected = population_size - num_susceptible
    infection_threshold = (total_infected > social_distancing_threshold).T.expand_dims({'dynamic_covariate':1})

  return beta_td, dynamic_covariate, dynamic_weights, new_infections

def _helper_setup_sir_sim(gen_constant_beta_fn,
                          num_locations,
                          num_time_steps=500,
                          constant_gamma=0.33,
                          population_size=10000,
                          gen_dynamic_beta_fn=None):
  """Helper function to set up and store a bunch of variables in a xr.DataSet.

  Returns a xr.Dataset containing the growth rate, covariates, weights,
  population size, and recovery rate.

  Args:
    gen_constant_beta_fn: a partial function to generate the constant beta
      values for each epidemic when passed num_locations.
    num_locations: an int representing the number of locations to run
    num_time_steps: an int representing the number of simulation 'days'
      (default 500)
    constant_gamma: a float representing the constant recovery rate (default
      0.33)
    population_size: a xr.DataArray representing the population size in each
      location. If none, defaults to 10000 in each location.
    gen_dynamic_beta_fn: A function to generate the dynamic beta
      values for each epidemic when passed num_locations and num_time_steps.
      None if the betas are all static.

  Returns:
    trajectories: a xr.Dataset containing the growth rate, covariates, weights,
      population size, and recovery rate.
  """
  # generate growth rate for all locations
  beta, v, alpha = gen_constant_beta_fn(num_locations)

  if type(population_size) is int:
    population_size = xr.DataArray(population_size * np.ones(num_locations), dims=['location'])

  static_covariates = xr.concat((v, population_size), 'static_covariate')
  num_static_covariates = static_covariates.sizes['static_covariate']

  # give population_size a weight of 0
  static_weights = xr.concat((alpha, xr.DataArray(np.array([0]), dims=['static_covariate'])), 'static_covariate')

  if gen_dynamic_beta_fn:
    beta_td, v_td, alpha_td = gen_dynamic_beta_fn(num_locations, num_time_steps)
    num_dynamic_covariates = (v_td.dynamic_covariate)
    beta = beta_td + beta.expand_dims({'time': num_time_steps})

  else:
    num_dynamic_covariates=0

  trajectories = new_sir_simulation_model(num_locations,
                                          num_time_steps, num_static_covariates,
                                          num_dynamic_covariates)

  trajectories['growth_rate'] = beta
  trajectories['static_covariates'] = static_covariates
  trajectories['static_weights'] = static_weights

  if gen_dynamic_beta_fn:
    trajectories['dynamic_weights'] = alpha_td
    trajectories['dynamic_covariates'] = v_td

  trajectories['population_size'] = population_size
  trajectories['recovery_rate'].data = constant_gamma * np.ones(num_locations)

  return trajectories

def generate_simulations(gen_constant_beta_fn,
                         num_locations,
                         num_time_steps=500,
                         constant_gamma=0.33,
                         population_size=10000,
                         gen_dynamic_beta_fn=None,
                         fraction_infected_limits=(.05, 1.),
                         prob_infection_constant=0.2):
  """Generate many SIR curves.

  Generate infection curves for num_locations. The locations may have different
  covariates, and thus different trajectories.

  Args:
    gen_constant_beta_fn: a partial function to generate the constant beta
      values for each epidemic when passed num_locations.
    num_locations: an int representing the number of locations to run
    num_time_steps: an int representing the number of simulation 'days'
      (default 500)
    constant_gamma: a float representing the constant recovery rate (default
      0.33)
    population_size: a xr.DataArray representing the population size in each
      location. If none, defaults to 10000 in each location.
    gen_dynamic_beta_fn: A function to generate the dynamic beta
      values for each epidemic when passed num_locations and num_time_steps.
      None if the betas are all static.
    fraction_infected_limits: A pair of floats in [0, 1] representing the limits
      on the fraction of the population that will be infected at SPLIT_TIME.
    prob_infection_constant: a float representing a constant that we multiply
      the probability of becoming infected by. We noticed that a value of 1. led
      to curves that were short in time and clustered in time. By changing this
      to less than 1., our models fit better.

  Returns:
    trajectories: a xr.Dataset of the simulated infections over time
  """
  trajectories = _helper_setup_sir_sim(gen_constant_beta_fn,
                                       num_locations,
                                       num_time_steps,
                                       constant_gamma,
                                       population_size,
                                       gen_dynamic_beta_fn)

  # Initially, all trajectories start at time 0.
  # The actual start_time will be updated to be consistent with
  # fraction_infected being infected at SPLIT_TIME.
  trajectories['new_infections'] = generate_ground_truth(
      trajectories.population_size, trajectories.growth_rate,
      trajectories.recovery_rate,
      trajectories.sizes['time'], prob_infection_constant)

  return data_model.shift_timeseries(trajectories, fraction_infected_limits, SPLIT_TIME)

def generate_social_distancing_simulations(gen_constant_beta_fn,
                                           gen_social_distancing_weight_fn,
                                           num_locations,
                                           num_time_steps=500,
                                           constant_gamma=0.33,
                                           population_size=10000,
                                           social_distancing_threshold=10000/4,
                                           fraction_infected_limits=(.05, 1.),
                                           prob_infection_constant=0.2,
                                           shift_timeseries=True):
  """Generate many SIR curves with social distancing.

  Generate many SIR curves with social distancing implemented when the number of
  cumulative infections reaches fraction_infected_limits. The locations may have
  different covariates, and thus different trajectories.

  Args:
    gen_constant_beta_fn: a partial function to generate the constant beta
      values for each epidemic when passed num_locations.
    gen_social_distancing_weight_fn: A (partial) function that generates the
      weights of the social distancing covariate. Function is called with the
      argument num_locations.
    num_locations: an int representing the number of locations to run
    num_time_steps: an int representing the number of simulation 'days'
      (default 500)
    constant_gamma: a float representing the constant recovery rate (default
      0.33)
    population_size: a xr.DataArray representing the population size in each
      location. If none, defaults to 10000 in each location.
    social_distancing_threshold: a DataArray representing the number of
      infected individuals in each location when we implement social distancing.
    fraction_infected_limits: A pair of floats in [0, 1] representing the limits
      on the fraction of the population that will be infected at SPLIT_TIME.
    prob_infection_constant: a float representing a constant that we multiply
      the probability of becoming infected by. We noticed that a value of 1. led
      to curves that were short in time and clustered in time. By changing this
      to less than 1., our models fit better.
    shift_timeseries: A bool indicating whether we should shift the trajectories
      based on fraction_infected_limits. If False, all trajectories will start
      with 1 infection at time t=0.

  Returns:
    trajectories: a xr.Dataset of the simulated infections over time
  """
  # generate growth rate for all locations
  trajectories = _helper_setup_sir_sim(gen_constant_beta_fn,
                                       num_locations,
                                       num_time_steps,
                                       constant_gamma,
                                       population_size,
                                       gen_dynamic_beta_fn=None)

  beta, dynamic_covariates, dynamic_weights, new_infections = generate_social_distancing_ground_truth(
      trajectories.population_size, trajectories.growth_rate,
      trajectories.recovery_rate,
      trajectories.sizes['time'], social_distancing_threshold,
      gen_social_distancing_weight_fn, prob_infection_constant)

  trajectories['growth_rate'] = beta
  trajectories['dynamic_covariates'] = dynamic_covariates
  trajectories['dynamic_weights'] = dynamic_weights
  trajectories['new_infections'] = new_infections

  if not shift_timeseries:
    return trajectories
  else:
    return data_model.shift_timeseries(trajectories, fraction_infected_limits,
                                       SPLIT_TIME)


text:
package org.gluu.model.attribute;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.gluu.model.GluuStatus;
import org.gluu.model.user.UserRole;
import org.gluu.persist.annotation.AttributeName;
import org.gluu.persist.annotation.DataEntry;
import org.gluu.persist.annotation.JsonObject;
import org.gluu.persist.annotation.ObjectClass;
import org.gluu.persist.model.base.Entry;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Arrays;

/**
 * Attribute Metadata
 *
 * @author Yuriy Movchan
 * @author Javier Rojas Blum
 * @version February 9, 2015
 */
@DataEntry(sortBy = "displayName")
@ObjectClass(value = "Attribute")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Attribute extends Entry implements Serializable {

    private static final long serialVersionUID = 4817004894646725606L;

    @AttributeName(ignoreDuringUpdate = true)
    private String inum;

    @AttributeName(name = "oxAttributeType")
    private String type;

    @AttributeName
    private String lifetime;

    @AttributeName(name = "oxSourceAttribute")
    private String sourceAttribute;

    @AttributeName
    private String salt;

    @AttributeName(name = "oxNameIdType")
    private String nameIdType;

    @NotNull
    @Pattern(regexp = "^[a-zA-Z0-9]+$", message = "Name should contain alphabetical and numeric characters only")
    @Size(min = 1, max = 30, message = "Length of the Name should be between 1 and 30")
    @AttributeName(name = "gluuAttributeName")
    private String name;

    @NotNull
    @Size(min = 0, max = 60, message = "Length of the Display Name should not exceed 60")
    @AttributeName
    private String displayName;

    @NotNull
    @Size(min = 0, max = 4000, message = "Length of the Description should not exceed 4000")
    @AttributeName
    private String description;

    @AttributeName(name = "gluuAttributeOrigin")
    private String origin;

    @NotNull
    @AttributeName(name = "gluuAttributeType")
    private AttributeDataType dataType;

    @NotNull
    @AttributeName(name = "gluuAttributeEditType")
    private UserRole[] editType;

    @NotNull
    @AttributeName(name = "gluuAttributeViewType")
    private UserRole[] viewType;

    @AttributeName(name = "gluuAttributeUsageType")
    private AttributeUsageType[] usageType;

    @AttributeName(name = "oxAuthClaimName")
    private String oxAuthClaimName;

    @AttributeName(name = "seeAlso")
    private String seeAlso;

    @AttributeName(name = "gluuStatus")
    private GluuStatus status;

    @AttributeName(name = "gluuSAML1URI")
    private String saml1Uri;

    @AttributeName(name = "gluuSAML2URI")
    private String saml2Uri;

    @AttributeName(ignoreDuringUpdate = true)
    private String urn;

    @AttributeName(name = "oxSCIMCustomAttribute")
    private Boolean oxSCIMCustomAttribute;

    @AttributeName(name = "oxMultivaluedAttribute")
    private Boolean multiValuedAttribute;

    @JsonObject
    @AttributeName(name = "oxValidation")
    private AttributeValidation attributeValidation;

    @AttributeName(name = "gluuTooltip")
    private String gluuTooltip;

    public String getInum() {
        return inum;
    }

    public void setInum(String inum) {
        this.inum = inum;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getLifetime() {
        return lifetime;
    }

    public void setLifetime(String lifetime) {
        this.lifetime = lifetime;
    }

    public String getSourceAttribute() {
        return sourceAttribute;
    }

    public void setSourceAttribute(String sourceAttribute) {
        this.sourceAttribute = sourceAttribute;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getNameIdType() {
        return nameIdType;
    }

    public void setNameIdType(String nameIdType) {
        this.nameIdType = nameIdType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getOrigin() {
        return origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }

    public AttributeDataType getDataType() {
        return dataType;
    }

    public void setDataType(AttributeDataType dataType) {
        this.dataType = dataType;
    }

    public UserRole[] getEditType() {
        return editType;
    }

    public void setEditType(UserRole[] editType) {
        this.editType = editType;
    }

    public UserRole[] getViewType() {
        return viewType;
    }

    public void setViewType(UserRole[] viewType) {
        this.viewType = viewType;
    }

    public AttributeUsageType[] getUsageType() {
        return usageType;
    }

    public void setUsageType(AttributeUsageType[] usageType) {
        this.usageType = usageType;
    }

    public String getOxAuthClaimName() {
        return oxAuthClaimName;
    }

    public void setOxAuthClaimName(String oxAuthClaimName) {
        this.oxAuthClaimName = oxAuthClaimName;
    }

    public String getSeeAlso() {
        return seeAlso;
    }

    public void setSeeAlso(String seeAlso) {
        this.seeAlso = seeAlso;
    }

    public GluuStatus getStatus() {
        return status;
    }

    public void setStatus(GluuStatus status) {
        this.status = status;
    }

    public String getSaml1Uri() {
        return saml1Uri;
    }

    public void setSaml1Uri(String saml1Uri) {
        this.saml1Uri = saml1Uri;
    }

    public String getSaml2Uri() {
        return saml2Uri;
    }

    public void setSaml2Uri(String saml2Uri) {
        this.saml2Uri = saml2Uri;
    }

    public String getUrn() {
        return urn;
    }

    public void setUrn(String urn) {
        this.urn = urn;
    }

    public Boolean getOxSCIMCustomAttribute() {
        return oxSCIMCustomAttribute;
    }

    public void setOxSCIMCustomAttribute(Boolean oxSCIMCustomAttribute) {
        this.oxSCIMCustomAttribute = oxSCIMCustomAttribute;
    }

    public Boolean getMultiValuedAttribute() {
        return multiValuedAttribute;
    }

    public void setMultiValuedAttribute(Boolean multivaluedAttribute) {
        this.multiValuedAttribute = multivaluedAttribute;
    }

    public String getGluuTooltip() {
        return gluuTooltip;
    }

    public void setGluuTooltip(String gluuTooltip) {
        this.gluuTooltip = gluuTooltip;
    }

    public AttributeValidation getAttributeValidation() {
        return attributeValidation;
    }

    public void setAttributeValidation(AttributeValidation attributeValidation) {
        this.attributeValidation = attributeValidation;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((dataType == null) ? 0 : dataType.hashCode());
        result = prime * result + ((description == null) ? 0 : description.hashCode());
        result = prime * result + ((displayName == null) ? 0 : displayName.hashCode());
        result = prime * result + Arrays.hashCode(editType);
        result = prime * result + ((gluuTooltip == null) ? 0 : gluuTooltip.hashCode());
        result = prime * result + ((inum == null) ? 0 : inum.hashCode());
        result = prime * result + ((lifetime == null) ? 0 : lifetime.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((nameIdType == null) ? 0 : nameIdType.hashCode());
        result = prime * result + ((origin == null) ? 0 : origin.hashCode());
        result = prime * result + ((oxAuthClaimName == null) ? 0 : oxAuthClaimName.hashCode());
        result = prime * result + ((multiValuedAttribute == null) ? 0 : multiValuedAttribute.hashCode());
        result = prime * result + ((oxSCIMCustomAttribute == null) ? 0 : oxSCIMCustomAttribute.hashCode());
        result = prime * result + ((salt == null) ? 0 : salt.hashCode());
        result = prime * result + ((saml1Uri == null) ? 0 : saml1Uri.hashCode());
        result = prime * result + ((saml2Uri == null) ? 0 : saml2Uri.hashCode());
        result = prime * result + ((seeAlso == null) ? 0 : seeAlso.hashCode());
        result = prime * result + ((sourceAttribute == null) ? 0 : sourceAttribute.hashCode());
        result = prime * result + ((status == null) ? 0 : status.hashCode());
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        result = prime * result + ((urn == null) ? 0 : urn.hashCode());
        result = prime * result + Arrays.hashCode(usageType);
        result = prime * result + Arrays.hashCode(viewType);
        return result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
//// [thing.d.ts]
declare namespace Foo {
    export interface Bar {}
    export function f(): Bar;
}
export = Foo;
//// [index.ts]
import { f } from "./thing";
export const thing = f();

//// [index.js]
"use strict";
exports.__esModule = true;
var thing_1 = require("./thing");
exports.thing = thing_1.f();

//// [index.d.ts]
export declare const thing: import("./thing").Bar;


text:
<?php
/**
 * This is the base class for the Request and Response objects and contains
 * those methods and properties which are common to both.
 *
 * @author Thomas Wilson <thomas@thomaspwilson.com>
 * @since 0.1.0
 */
abstract class Http_Message {
    protected $body;
    protected $headers = array();
    protected $httpVersion = '1.1';

    /**
     * Retrieves the body of the message as a string.
     * @return string
     */
    public function getBody() {
        return $this->body;
    }
    /**
     * Sets the content of the body of the request to the given value. Note that
     * stream-based containers and wrappers are processed immediately in order
     * to provide faster and multiple read capability.
     * @param mixed $body The body of the message
     */
    public function setBody($body) {
        if(is_resource($body)) {
            $this->body = stream_get_contents($body);
        }

        else if(is_string($body)) {
            $this->body = $body;
        }
    }
    /**
     * Basically just an alias for setHeader
     * @param string $name
     * @param string $value
     */
    public function addHeader($name, $value) {
        $this->setHeader($name, $value);
    }
    /**
     * Retrieves the array of message headers.
     * @return array
     */
    public function getHeaders() {
        return $this->headers;
    }
    /**
     * Retrieves the value of the HTTP header with the given name.
     *
     * Header naming is case-insensitive.
     * @param string $name The name of the header
     * @return string|null
     */
    public function getHeader($name) {
        $name = strtolower($name);
        foreach($this->headers as $k => $v) {
            if(strtolower($k) === $name) {
                return $v;
            }
        }
        return null;
    }
    /**
     * Sets the message headers to the given array of headers, discarding the
     * old headers.
     * @param array $headers The list of new headers
     */
    public function setHeaders(array $headers) {
        $this->headers = $headers;
    }
    /**
     * Appends the given array of headers to the existing list of headers, only
     * overwriting those that already exist.
     *
     * @param array $headers The headers to append
     */
    public function addHeaders(array $headers) {
        $this->headers = array_merge($this->headers, $headers);
    }
    /**
     * Sets the given header to the given value. Overwrites an existing header
     * of the same name.
     * @param string $name
     * @param string $value
     */
    public function setHeader($name, $value) {
        $this->removeHeader($name);
        $this->headers[$name] = $value;
    }
    /**
     * Removes the header indicated by the given name. The name must be treated
     * as case-insensitive.
     * @param string $name The name of the header
     * @return boolean True on success, false otherwise
     */
    public function removeHeader($name) {
        foreach($this->headers as $k => $v) {
            if(strtolower($k) === strtolower($name)) {
                unset($this->headers[$k]);
                return true;
            }
        }
        return false;
    }
    /**
     * Sets the HTTP version used to pass the message.
     * @param string $version Either 1.0 or 1.1
     */
    public function setHttpVersion($version) {
        if($version !== '1.0' && $version !== '1.1') {
            throw new InvalidArgumentException('Invalid HTTP Version: '.$version);
        }
        $this->httpVersion = $version;
    }
    /**
     * Returns the HTTP version used to pass the message.
     * @return string
     */
    public function getHttpVersion() {
        return $this->httpVersion;
    }
}


text:
class Widget
{
protected:
    class WidgetIterator
    {
    private:
        Widget const* mThis;
        int32_t mLevel;
    public:
        WidgetIterator( Widget const* This = NULL ): mThis( This ), mLevel( 0 ) {}
        Widget const& operator*()
        {
            return *mThis;
        }
        Widget const* operator->()
        {
            return mThis;
        }
        bool operator==( WidgetIterator const& Other )const
        {
            return mThis == Other.mThis;
        }
        bool operator!=( WidgetIterator const& Other )const
        {
            return !operator==( Other );
        }
        WidgetIterator& operator++();
    };
    friend class WidgetIterator;
public:
    struct Prop
    {
        union
        {
            double ToDouble;
            int32_t ToInt;
            const char* ToStr;
        } Value;
        enum Type_t
        {
            T_Null,
            T_Double,
            T_Int,
            T_Str,
        };
        explicit Prop( Widget* owner );
        Prop( Prop const& Other );
        operator std::string()const;
        operator int32_t()const;
        operator double()const;
        Prop& operator=( std::string const& Str );
        Prop& operator=( char const* Buf );
        Prop& operator=( int32_t I );
        Prop& operator=( double D );
        Type_t GetType()const
        {
            return Type;
        }
        bool IsResolvable() const;
        bool IsModelValue() const; // starts with %
        bool IsModelIndex() const; // starts with #
        bool IsAutoId() const; // starts with %%
        bool IsVectorModelValue() const; // starts with %, contains #
        ~Prop();
        ModelValue const& ResolveModel() const;
        Widget* GetOwner() const;
    private:
        Type_t Type;
        Widget* mOwner;
        void Init( std::string const& Str );
        void Cleanup();
        int32_t ResolveIndex() const;
    };
    enum PropertyType
    {
        PT_Visible,
        PT_Highlight,
        PT_Enabled,
        PT_Text,
        PT_FontSize,
        PT_Color,
        PT_HighlightColor,
        PT_Progress,
        PT_MaxProgress,
        PT_ActorVisual, // name of the actor visual
        PT_Animation,   // name of the animation of the actor visual, defaults to body_idle
        PT_State,       // current state of the animation, defaults to 0
        PT_Index,
        PT_Columns,
        PT_Rows,
        PT_Source,
        PT_StartId,
        PT_StartIdBase,
        PT_StartIdStep,
        PT_SubtreeHidden,
    };
    typedef WidgetIterator const_iterator;  // rename to hierarchy iterator?
    const_iterator begin()const;
    const_iterator end()const;
    Widget( int32_t Id );
    virtual ~Widget();
    void AddChild( Widget* Child );
    virtual bool AreDimensionsSet()const;
    virtual glm::vec4 const& GetDimensions()const;
    void SetRelativeDimensions( glm::vec4 const& Dim );
    Widget* GetHit( const glm::vec2& Pos );
    Widget* GetNext()const; // vagy child_iterator?
    Prop const& operator()( PropertyType Property )const;
    Prop& operator()( PropertyType Property );
    int32_t GetId()const;
    virtual void Init( Json::Value& Descriptor );
    virtual bool Trigger()
    {
        return false;
    }
    virtual void OnMouseEnter() {}
    virtual void OnMouseLeave() {}
    Widget const* Parent() const;
protected:
    virtual void UpdateDimensions();
    virtual void UpdateSelfDimensions();
    virtual void UpdateChildrenDimensions();
    bool IsInside( const glm::vec2& Pos )const;
    void ParseIntProp( PropertyType Pt, Json::Value& Val, int32_t Default );
    void ParseDoubleProp( PropertyType Pt, Json::Value& Val, double Default );
    void ParseStrProp( PropertyType Pt, Json::Value& Val, std::string const& Default );
    static void ParseIntProp( Prop& Pt, Json::Value& Val, int32_t Default );
    static void ParseDoubleProp( Prop& Pt, Json::Value& Val, double Default );
    static void ParseStrProp( Prop& Pt, Json::Value& Val, std::string const& Default );
    static int32_t ParseColor( Json::Value& Color, int32_t Default );
    int32_t mZOrder;
    Widget* mParent;
    Widget* mNext;
    Widget* mPrev;
    Widget* mFirstChild;
    Widget* mLastChild;
    glm::vec4 mRelativeDimensions;
    glm::vec4 mDimensions;
    int32_t mTypeId;
    bool mDimSet;
    struct PropertyRepo_t : public Repository<Prop>
    {
        Widget* const mOwner;
        Prop mDefaultProperty;
        PropertyRepo_t( Widget* owner );
        Prop& Mutable( PropertyType Property );
    };
    PropertyRepo_t mProperties;
};

#endif//INCLUDED_UI_WIDGET_H


text:
disable r

# To see the key combo you want to use just do:
# cat > /dev/null
# And press it

bindkey "^K"      kill-whole-line                      # ctrl-k
bindkey "^R"      history-incremental-search-backward  # ctrl-r
bindkey "^A"      beginning-of-line                    # ctrl-a
bindkey "^E"      end-of-line                          # ctrl-e

# bindkey "[B"      history-search-forward               # down arrow
# bindkey "[A"      history-search-backward              # up arrow
# History search with up and down arrow keys

if [[ -n "${key[Up]}"   ]]
then
  bindkey  "${key[Up]}" history-beginning-search-backward
else
  bindkey "^[[A" history-beginning-search-backward
fi

if [[ -n "${key[Down]}" ]]
then
  bindkey  "${key[Down]}" history-beginning-search-forward
else
  bindkey "^[[B" history-beginning-search-forward
fi

bindkey "^D"      delete-char                          # ctrl-d
bindkey "^F"      forward-char                         # ctrl-f
bindkey "^B"      backward-char                        # ctrl-b

bindkey -e   # Default to standard emacs bindings, regardless of editor string


text:
<?php

namespace WindowsAzure\MediaServices\Models;

/**
 * Represents EncodingType type enum used in media services.
 *
 * @category  Microsoft
 *
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 *
 * @version   Release: 0.4.3_2016-05
 *
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class EncodingType
{
    /**
     * None
     *
     * @var string
     */
    const None = "None";

    /**
     * Standard
     *
     * @var string
     */
    const Standard = "Standard";
}


text:
import { isArray, noop } from '@qgrid/core';
import { IQueryBuilderSchema, QueryBuilderService } from '../query-builder.service';
import { typeMapping } from './operator';
import { suggestFactory, suggestsFactory } from './suggest.service';
import { Validator } from './validator';

export const getValue = (line, id, props) => {
  const group = line.get(id);
  if (group) {
    if (group.expressions.length === 1) {
      const expr = group.expressions[0];
      const prop = props.filter(p => Object.prototype.hasOwnProperty.call(expr, p))[0];
      if (prop) {
        const value = expr[prop];
        if (isArray(value) && value.length) {
          return value[0];
        }

        return value;
      }
    }
  }

  return null;
};

export class WhereSchema {
  constructor(private service: QueryBuilderService) {
  }

  factory(): IQueryBuilderSchema {
    const service = this.service;
    const suggest = suggestFactory(service, '#field');
    const suggests = suggestsFactory(service, '#field');
    const validator = new Validator(service);

    return this.service.build()
      .node('#logical', function (logical) {
        logical
          .attr('serialize', {
            '#logical-op': ['value'],
          })
          .attr('class', {
            'qb-logical': true,
            'qb-and': function (node) {
              const op = node.line.get('#logical-op');
              return op.expressions[0].value === 'AND';
            },
            'qb-or': function (node) {
              const op = node.line.get('#logical-op');
              return op.expressions[0].value === 'OR';
            },
          })
          .select('#logical-op', {
            classes: ['qb-operation'],
            options: ['AND', 'OR'],
            value: 'AND',
          })
          .node('#condition', function (condition) {
            condition
              .attr('serialize', {
                '#field': ['value'],
                '#operator': ['value'],
                '#value': ['value'],
                '#from': ['value'],
                '#to': ['value'],
                '#in-operand': ['values'],
              })
              .select('#field', {
                classes: ['qb-field'],
                options: service.columns().map(c => c.key),
                value: service.columns().length ? service.columns()[0].key : '',
                getLabel: function (node, line, key) {
                  const column = service.columns().filter(c => c.key === key)[0];
                  return (column && column.title) || null;
                },
                getType: function (node, line, key) {
                  const column = service.columns().filter(c => c.key === key)[0];
                  return (column && column.type) || null;
                },
                change: function (node, line) {
                  const field = this.value;
                  const type = this.getType(field);
                  const ops = typeMapping[type] || [];
                  const op = line.get('#operator').expressions[0];

                  if (ops.indexOf(op.value) < 0) {
                    op.value = ops.length ? ops[0] : null;
                    op.change();
                  } else {
                    const operand = line.get('#operand').expressions[0];
                    if (operand.validate) {
                      const result = operand.validate();
                      if (result.length) {
                        operand.value = null;
                      }
                    } else {
                      operand.value = null;
                    }
                  }
                },
              })
              .select('#operator', {
                classes: ['qb-operator'],
                getOptions: function (node, line) {
                  const field = line.get('#field').expressions[0];
                  const name = field.value;
                  const type = field.getType(name);

                  return type ? typeMapping[type] : [];
                },
                value: 'EQUALS',
                change: function (node, line) {
                  switch (this.value.toLowerCase()) {
                    case 'equals':
                    case 'not equals':
                    case 'greater than':
                    case 'less than':
                    case 'greater or eq. to':
                    case 'less or eq. to':
                    case 'like':
                    case 'not like':
                    case 'starts with':
                    case 'ends with':
                      line.put('#operand', node, function (schema) {
                        schema.input('#value', {
                          classes: {
                            'qb-operand': true,
                            'qb-has-value': function () {
                              return !!this.value;
                            },
                            'qb-invalid': function (n) {
                              return !this.isValid(n);
                            },
                          },
                          value: getValue(line, '#operand', ['value', 'values']),
                          validate: function () {
                            const field = line.get('#field').expressions[0].value;
                            return validator.for(field)(this.value);
                          },
                          placeholderText: 'Select value',
                          suggest: suggest,
                          options: null,
                          refresh: function (n, l) {
                            this.options = this.suggest(n, l);
                          },
                        });
                      });
                      break;
                    case 'between':
                      line.put('#operand', node, function (operand) {
                        operand
                          .input('#from', {
                            classes: {
                              'qb-operand': true,
                              'qb-has-value': function () {
                                return !!this.value;
                              },
                              'qb-invalid': function (n) {
                                return !this.isValid(n);
                              },
                            },
                            validate: function () {
                              const field = line.get('#field').expressions[0].value;
                              return validator.for(field)(this.value);
                            },
                            options: suggest,
                            value: null,
                            placeholderText: 'Select value',
                          })
                          .label('#and', {
                            classes: ['qb-operand', 'qb-operand-and-label'],
                            text: 'AND',
                          })
                          .input('#to', {
                            classes: {
                              'qb-operand': true,
                              'qb-has-value': function () {
                                return !!this.value;
                              },
                              'qb-invalid': function (n) {
                                return !this.isValid(n);
                              },
                            },
                            value: null,
                            validate: function () {
                              const field = line.get('#field').expressions[0].value;
                              return validator.for(field)(this.value);
                            },
                            placeholderText: 'Select value',
                            suggest: suggest,
                            options: null,
                            refresh: function (n, l) {
                              this.options = this.suggest(n, l);
                            },
                          });
                      });
                      break;
                    case 'in':
                      line.put('#operand', node, function (schema) {
                        schema
                          .label('#in-open', {
                            text: '(',
                          })
                          .multiselect('#in-operand', {
                            classes: {
                              'qb-operand': true,
                              'qb-has-value': function () {
                                return !!this.values.length;
                              },
                              'qb-invalid': function (n) {
                                return !this.isValid(n);
                              },
                            },
                            validate: function () {
                              const field = line.get('#field').expressions[0].value;
                              return validator.for(field)(this.values);
                            },
                            values: [],
                            options: suggests,
                            placeholderText: 'Select value',
                            add: function (n, l, v) {
                              if (v && this.values.indexOf(v) < 0) {
                                this.values.push(v);
                              }
                            },
                          })
                          .label('#in-close', {
                            text: ')',
                          });
                      });
                      break;
                    case 'is empty':
                    case 'is not empty':
                      line.put('#operand', node, noop);
                      break;
                  }
                },
              })
              .group('#operand', function (schema) {
                schema.autocomplete('#value', {
                  classes: {
                    'qb-operand': true,
                    'qb-has-value': function () {
                      return !!this.value;
                    },
                    'qb-invalid': function (node) {
                      return !this.isValid(node);
                    },
                  },
                  value: null,
                  validate: function (node, line) {
                    const field = line.get('#field').expressions[0].value;
                    return validator.for(field)(this.value);
                  },
                  placeholderText: 'Select value',
                  suggest: suggest,
                  options: null,
                  refresh: function (node, line) {
                    this.options = this.suggest(node, line);
                  },
                });
              });
          });
      });
  }
}


text:
package com.yogee.zhebuy.interfaces.common;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yogee.zhebuy.common.config.Global;
import com.yogee.zhebuy.common.persistence.annotation.ApiVersion;
import com.yogee.zhebuy.common.utils.Hashids;
import com.yogee.zhebuy.common.utils.StringUtils;
import com.yogee.zhebuy.interfaces.util.HttpResultUtil;
import com.yogee.zhebuy.interfaces.util.HttpServletRequestUtils;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyBusiness;
import com.yogee.zhebuy.modules.ebuy.entity.EbuyProCategory;
import com.yogee.zhebuy.modules.ebuy.service.EbuyBusinessService;
import com.yogee.zhebuy.modules.ebuy.service.EbuyProCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("${apiPath}/{version}")
public class CategoryInterface {
    private static final Logger logger = LoggerFactory.getLogger(CategoryInterface.class);
    //用于对id进行加密
    private Hashids hashids = new Hashids(Global.getConfig("web.hashids.salt"));
    @Autowired
    private EbuyProCategoryService ebuyProCategoryService;
    @Autowired
    private EbuyBusinessService ebuyBusinessService;

    /**
     * 获取分类
     * @param request
     * @return
     */
    @ApiVersion(1)
    @RequestMapping(value = "getCategory", method = RequestMethod.POST)
    @ResponseBody
    public String newUserRegistration(HttpServletRequest request) {
        logger.info("app getCategory---------- Start--------");

        Map jsonData = HttpServletRequestUtils.readJsonData(request);
        int totalInt = 0;
        int countInt = 10;
        String total = (String) jsonData.get("total");
        if (StringUtils.isNotEmpty(total)) {
            totalInt = Integer.parseInt(total);
        }

        String count = (String) jsonData.get("count");
        if (StringUtils.isNotEmpty(count)) {
            countInt = Integer.parseInt(count);
        }
        String type = (String) jsonData.get("type");
        if (StringUtils.isEmpty(type)) {
            logger.error("请填写请求类型!");
            return HttpResultUtil.errorJson("请填写请求类型!");
        }
        String businessId = (String) jsonData.get("businessId");
        if (StringUtils.isNotEmpty(businessId)) {
            businessId = hashids.decode(businessId)[0] + "";
        }
        Map dataMap = Maps.newHashMap();
        List topList = Lists.newArrayList();
        String cityId="";
        if(StringUtils.isNotEmpty(businessId)){
            //businessId不为空
            EbuyBusiness ebuyBusiness =  ebuyBusinessService.get(businessId);//根据商家获一级分类
            //服务商和供应商供应类型父级Id
            if(ebuyBusiness.getType().equals("1") || ebuyBusiness.getType().equals("0")){
                if(StringUtils.isNotEmpty(ebuyBusiness.getCategoryPids())){
                    String[] stringArray = ebuyBusiness.getCategoryPids().split(",");
                    List<EbuyProCategory> cateTop = ebuyProCategoryService.findTopCateList(stringArray);//获取一级
                    for (EbuyProCategory cateTops : cateTop){
                        List<EbuyProCategory> cateSecond = ebuyProCategoryService.findSecondByTopId(Integer.parseInt(cateTops.getId()));
                        Map mapTop = Maps.newHashMap();
                        mapTop.put("topCateId",cateTops.getId());
                        mapTop.put("topImg", Global.getDomain() + cateTops.getImg());
                        mapTop.put("topCateName",cateTops.getName());
                        List secondList = Lists.newArrayList();
                        //只请求一级分类
                        if (type.equals("1")){
                            for (EbuyProCategory cateSeconds : cateSecond){
                                Map mapSecond = Maps.newHashMap();
                                mapSecond.put("secondCateId",cateSeconds.getId());
                                mapSecond.put("secondCateName",cateSeconds.getName());
                                secondList.add(mapSecond);
                            }
                        }
                        mapTop.put("secondCate",secondList);
                        topList.add(mapTop);
                    }
                    dataMap.put("topCate",topList);
                }else{
                    dataMap.put("topCate",topList);
                    return HttpResultUtil.successJson(dataMap);
                }
            }else{
                EbuyBusiness ebuyBusinessBean =  ebuyBusinessService.get(businessId);//根据商家获一级分类
                cityId = ebuyBusinessBean.getCityId();
                List<EbuyProCategory> cateTop = ebuyProCategoryService.findTopCateListNo(cityId);//获取一级
                for (EbuyProCategory cateTops : cateTop){
                    List<EbuyProCategory> cateSecond = ebuyProCategoryService.findSecondByTopId(Integer.parseInt(cateTops.getId()));
                    Map mapTop = Maps.newHashMap();
                    mapTop.put("topCateId",cateTops.getId());
                    mapTop.put("topImg", Global.getDomain() + cateTops.getImg());
                    mapTop.put("topCateName",cateTops.getName());
                    List secondList = Lists.newArrayList();
                    //只请求一级分类
                    if (type.equals("1")){
                        for (EbuyProCategory cateSeconds : cateSecond){
                            Map mapSecond = Maps.newHashMap();
                            mapSecond.put("secondCateId",cateSeconds.getId());
                            mapSecond.put("secondCateName",cateSeconds.getName());
                            secondList.add(mapSecond);
                        }
                    }
                    mapTop.put("secondCate",secondList);
                    topList.add(mapTop);
                }
                dataMap.put("topCate",topList);
            }
        }else{
        //businessId为空
            List<EbuyProCategory> cateTop = ebuyProCategoryService.findTopCateListNo(cityId);//获取一级
            for (EbuyProCategory cateTops : cateTop){
                List<EbuyProCategory> cateSecond = ebuyProCategoryService.findSecondByTopId(Integer.parseInt(cateTops.getId()));
                Map mapTop = Maps.newHashMap();
                mapTop.put("topCateId",cateTops.getId());
                mapTop.put("topImg", Global.getDomain() + cateTops.getImg());
                mapTop.put("topCateName",cateTops.getName());
                List secondList = Lists.newArrayList();
                //只请求一级分类
                if (type.equals("1")){
                    for (EbuyProCategory cateSeconds : cateSecond){
                        Map mapSecond = Maps.newHashMap();
                        mapSecond.put("secondCateId",cateSeconds.getId());
                        mapSecond.put("secondCateName",cateSeconds.getName());
                        secondList.add(mapSecond);
                    }
                }
                mapTop.put("secondCate",secondList);
                topList.add(mapTop);
            }
            dataMap.put("topCate",topList);
            }

        return HttpResultUtil.successJson(dataMap);
    }

}


text:
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements. See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to you under the Apache License, Version
    2.0 (the "License"); you may not use this file except in compliance
    with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0 Unless required by
    applicable law or agreed to in writing, software distributed under
    the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
    OR CONDITIONS OF ANY KIND, either express or implied. See the
    License for the specific language governing permissions and
    limitations under the License.
  -->
<results>
  <status>OK</status>
  <url>http://url.language.com</url>
  <language>en</language>
  <iso-639-3>ISO_639_3_CODE</iso-639-3>
  <ethnologue>http://www.ethnologue.com/show_country_bibl.asp?name=GB</ethnologue>
  <native-speakers>321321</native-speakers>
  <wikipedia>http://en.wikipedia.org/wiki/English_language</wikipedia>
</results>


text:
/**
 * Dashboard data stores
 */

var dispatcher = require('rlux').Dispatcher;
var Map = require('immutable').Map;
var constants = require('../constants');
var eventEmitter = new(require('events').EventEmitter)();
var eventName = 'dashboardDataStore_changed';

var dashboardDataStore = {};

var data = Map({});

dashboardDataStore.get = function(source) {
  if (data.has(source))
    return data.get(source).data;
  return undefined;
};

dashboardDataStore.getStatus = function(source) {
  if (data.has(source))
    return data.get(source).status;
  return constants.stores.statuses.loading;
};

dashboardDataStore.subscribe = function(listener) {
  eventEmitter.addListener(eventName, listener);
};

dashboardDataStore.unsubscribe = function(listener) {
  eventEmitter.removeListener(eventName, listener);
};

dashboardDataStore.dispatchIndex = dispatcher.register(function(payload) {
  var action = payload.action;

  switch (action.type) {
    case constants.actions.dataLoaded:
      setData(action.source, action.data);
      eventEmitter.emit(eventName);
      break;
    case constants.actions.dataLoadingFailed:
      setDataFailedStatus(action.source);
      eventEmitter.emit(eventName);
      break;
  }
});

/**
 * Adds or updates data in data store
 */
function setData(source, newData) {
  var d;
  if (data.has(source)) {
    d = data.get(source);
  } else {
    d = {};
  }
  d.data = newData.results;
  d.status = constants.stores.statuses.ready;
  data = data.set(source, d);
}

/**
 * Sets data in failed status in data store
 */
function setDataFailedStatus(source) {
  var d;
  if (data.has(source)) {
    d = data.get(source);
  } else {
    d = {};
  }
  d.data = null;
  d.status = constants.stores.statuses.failed;
  data = data.set(source, d);
}

module.exports = dashboardDataStore;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.cognizant</groupId>
    <artifactId>cognizant-intelligent-test-scripter</artifactId>
    <version>1.4</version>
    <packaging>pom</packaging>
    <modules>
        <module>QcConnection</module>
        <module>StoryWriter</module>
        <module>GridNode</module>
        <module>ExtensionConnect</module>
        <module>Datalib</module>
        <module>TestData - Csv</module>
        <module>Engine</module>
        <module>IDE</module>
        <module>Dist</module>
    </modules>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <com4j.version>20110320</com4j.version>

        <selenium.version>3.141.59</selenium.version>
        <sikuli.version>1.1.0</sikuli.version>
        <galen.version>2.4.4</galen.version>
        <javaclient.version>7.0.0</javaclient.version>
        <ngwebdriver.version>1.0</ngwebdriver.version>
        <ashot.version>1.5.2</ashot.version>
        <commons-cli.version>1.3.1</commons-cli.version>
        <javamail.version>1.4.7</javamail.version>
        <json-simple.version>1.1.1</json-simple.version>
        <jcsv.version>1.4.0</jcsv.version>

        <jackson.version>2.8.8</jackson.version>
        <commonscsv.version>1.4</commonscsv.version>
        <annon.detect>3.0.5</annon.detect>
        <jetty.version>9.4.5.v20170502</jetty.version>

        <geherkin.version>5.0.0</geherkin.version>
        <autocomplete.version>2.6.1</autocomplete.version>
        <apache.poi.version>4.0.1</apache.poi.version>

        <setupDir>../Dist/release</setupDir>
        <resourceDir>../Resources</resourceDir>

        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>

    </properties>
    <name>Cognizant Intelligent Test Scripter</name>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <filesets>
                        <fileset>
                            <directory>Dist</directory>
                            <includes>
                                <include>release/**/*</include>
                                <include>release</include>
                            </includes>
                            <followSymlinks>false</followSymlinks>
                        </fileset>
                    </filesets>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
using System.Collections.Generic;
using System.Text;

namespace Moonlit.Net.Web
{
    public interface IWebMessageFormatter
    {
        string CreatePostData(IEnumerable<WebParameter> parameters);
        T Deserialize<T>(byte[] bytes, Encoding encoding);
    }
}


text:
package main

import (
    "os"
    "io/ioutil"
    "image"
    "image/png"
    "math"
    "bytes"
    "fmt"
    "encoding/hex"
)

func main() {
    // Check command line arguments
    if len(os.Args) != 3 {
        fmt.Println("Usage: js2png <js_file> <png_file>")
        os.Exit(1)
    }

    var src_filename = os.Args[1]
    var dst_filename = os.Args[2]

    // Read source file
    src, err := ioutil.ReadFile(src_filename)
    if err != nil { panic(err) }

    // Create data buffer
    var buffer = new(bytes.Buffer)

    // Write payload size
    var payload_sz = len(src)

    buffer.WriteByte(0)
    buffer.WriteByte(uint8(payload_sz >> 56 & 0xff))
    buffer.WriteByte(uint8(payload_sz >> 48 & 0xff))
    buffer.WriteByte(255)
    buffer.WriteByte(uint8(payload_sz >> 40 & 0xff))
    buffer.WriteByte(uint8(payload_sz >> 32 & 0xff))
    buffer.WriteByte(uint8(payload_sz >> 24 & 0xff))
    buffer.WriteByte(255)
    buffer.WriteByte(uint8(payload_sz >> 16 & 0xff))
    buffer.WriteByte(uint8(payload_sz >> 8 & 0xff))
    buffer.WriteByte(uint8(payload_sz & 0xff))
    buffer.WriteByte(255)

    // Write payload into buffer as RGBA pixels
    var data_sz = int(math.Ceil(float64(payload_sz) / 3))

    for i := 0; i < data_sz; i++ {
        p := i * 3

        _, err := buffer.Write(src[p:p + 3])
        if err!= nil { panic(err) }

        buffer.WriteByte(255)
    }

    // Create bitmap to fit the payload
    var bitmap_sz = int(buffer.Len() / 4)
    w := int(math.Ceil(math.Sqrt(float64(bitmap_sz))))
    h := int(math.Ceil(float64(bitmap_sz) / float64(w)))

    rect := image.Rect(0, 0, w, h)
    img := image.NewNRGBA(rect)
    img.Pix = make([]uint8, w * h * 4)

    // Copy payload into bitmap
    copy(img.Pix, buffer.Bytes())

    // Log
    fmt.Printf("Source:\n%s\n", hex.Dump(src))
    fmt.Printf("Buffer:\n%s\n", hex.Dump(buffer.Bytes()))
    fmt.Printf("Image:\n%s\n", hex.Dump(img.Pix))

    // Write bitmap to PNG file
    dst, err := os.Create(dst_filename)
    if err != nil { panic(err) }
    defer dst.Close()

    png.Encode(dst, img)
}


text:
<?php

namespace Fuel\Session;

use Fuel\Foundation\Applidation;

/**
 * Session manager class
 */
class Manager
{
	/**
	 * @var Driver
	 */
	protected $driver;

	/**
	 * @var array
	 */
	protected $config;

	/**
	 * @var Applidation
	 */
	protected $app;

	/**
	 * @var DataContainer
	 */
	protected $data;

	/**
	 * @var FlashContainer
	 */
	protected $flash;

	/**
	 * @var mixed
	 */
	protected $rotationInterval;

	/**
	 * @var integer
	 */
	protected $rotationTimer;

	/**
	 * @param Driver           $driver
	 * @param array            $config
	 * @param Application|null $app
	 */
	public function __construct(Driver $driver, array $config = [], Application $app = null)
	{
		// store the driver and config
		$this->driver = $driver;
		$this->config = $config;
		$this->app = $app;

		// create the containers
		$this->reset();

		// tell the driver who manages the session, and what the containers are
		$this->driver->setInstances($this, $this->data, $this->flash);

		// set the session rotation interval and the default rotation timer
		if ( ! isset($config['rotation_time']))
		{
			$this->rotationInterval = 300;
		}
		elseif ( ! is_numeric($config['rotation_time']) or $config['rotation_time'] <= 0 or $config['rotation_time'] === false)
		{
			$this->rotationInterval = false;
		}
		else
		{
			$this->rotationInterval = (int) $config['rotation_time'];
			$this->rotationTimer = time() + $this->rotationInterval;
		}

		// any namespace defined?
		if (isset($config['namespace']))
		{
			if ($config['namespace'] === true)
			{
				$config['namespace'] = $app ? $app->getName() : false;
			}
			$this->setNamespace($config['namespace']);
		}

		// any flash namespace defined?
		if (isset($config['flash_namespace']))
		{
			$this->setFlashNamespace($config['flash_namespace']);
		}

		// flash auto expiration defined?
		if (isset($config['flash_auto_expire']) and $config['flash_auto_expire'] == false)
		{
			// by default, expire flash when getting the flash variable
			$this->flash->setExpiryOnGet();
		}
		else
		{
			// by default, expire flash on the next session load
			$this->flash->setExpiryOnRequest();
		}
	}

	/**
	 * Magic method, captures calls to the containers and the driver
	 *
	 * @param string $method
	 * @param array  $arguments
	 *
	 * @return mixed
	 *
	 * @since 2.0
	 */
	public function __call($method , Array $arguments)
	{
		// is this a flash method?
		if (substr($method, -5) == 'Flash')
		{
			$method = substr($method, 0, strlen($method)-5);

			if (is_callable(array($this->flash, $method)))
			{
				return call_user_func_array(array($this->flash, $method), $arguments);
			}
		}

		// data method?
		elseif (is_callable(array($this->data, $method)))
		{
			return call_user_func_array(array($this->data, $method), $arguments);
		}

		// driver method?
		elseif (substr($method, 0, 3) == 'get' and is_callable(array($this->driver, $method)))
		{
			return call_user_func_array(array($this->driver, $method), $arguments);
		}

		throw new \BadMethodCallException('Method Session::'.$method.'() does not exists');
	}

	/**
	 * Creates a new session
	 *
     * @return boolean
	 */
	public function create()
	{
		// reset the data containers
		$this->reset();

		// and create a new session
		return $this->driver->create();
	}

	/**
	 * Starts a session
	 *
	 * @return boolean
	 */
	public function start()
	{
		return $this->driver->start();
	}

	/**
	 * Reads the session data into the session store
	 *
	 * @return boolean
	 */
	public function read()
	{
		return $this->driver->read();
	}

	/**
	 * Writes the container data to the session store
	 *
	 * @return boolean
	 */
	public function write()
	{
		// do we need to rotate?
		if ($this->rotationInterval and $this->rotationTimer < time())
		{
			$this->rotate();
		}

		return $this->driver->write();
	}

	/**
	 * Stops a session
	 *
	 * @return boolean
	 */
	public function stop()
	{
		// do we need to rotate?
		if ($this->rotationInterval and $this->rotationTimer < time())
		{
			$this->rotate();
		}

		// stop the current session
		return $this->driver->stop();
	}

	/**
	 * Rotates the session id, and reset the rotation timer if needed
	 */
	public function rotate()
	{
		// update the session id rotation timer
		if ($this->rotationInterval)
		{
			$this->rotationTimer = time() + $this->rotationInterval;
		}

		// regenerate the session id
		$this->driver->regenerate($this);
	}

	/**
	 * Destroys the current session
	 */
	public function destroy()
	{
		$this->reset();

		return $this->driver->destroy($this);
	}

	/**
	 * Returns the current rotation interval timer
	 *
	 * @return integer
	 */
	public function getRotationTimer()
	{
		return $this->rotationTimer;
	}

	/**
	 * Sets the rotation interval timer
	 *
	 * @param integer $time
	 */
	public function setRotationTimer($time)
	{
		$this->rotationTimer = $time;
	}

	/**
	 * Returns the current session namespace
	 *
	 * @return string
	 */
	public function getNamespace()
	{
		return $this->config['namespace'];
	}

	/**
	 * Sets the session namespace
	 *
	 * @param string $name
	 */
	public function setNamespace($name)
	{
		$this->config['namespace'] = is_bool($name) ? $name : (string) $name;

		if ($this->config['namespace'] === true)
		{
			$this->config['namespace'] = $this->app ? $app->getName() : false;
		}

		$this->data->setNamespace($this->config['namespace']);
	}

	/**
	 * Returns the current session flash namespace
	 *
	 * @return string
	 */
	public function getFlashNamespace()
	{
		return $this->config['flash_namespace'];
	}

	/**
	 * Sets the session flash namespace
	 *
	 * @param string $name
	 */
	public function setFlashNamespace($name)
	{
		$this->config['flash_namespace'] = (string) $name;

		$this->flash->setNamespace($this->config['flash_namespace']);
	}

	/**
	 * Resets the data and flash data containers
	 */
	protected function reset()
	{
		// create the data container
		$this->data = new DataContainer();

		// create the flash container
		$this->flash = new FlashContainer();

		// initialise the flash expiry store
		$this->flash->set(FlashContainer::EXPIRE_DATA_KEY, array());

	}
}


text:
void simulate_radiances(int n, // Size of temperature array
			// Input variables:
			double surface_temperature,
			const double* temperature,
			// Output variables:
			double radiance[2],
			// Output Jacobians:
			double dradiance_dsurface_temperature[2],
			double* dradiance_dtemperature);


text:
require_relative '../swagger/operation'
require_relative '../swagger/tag'

module Swaggard
  module Parsers
    class Controllers

      def run(yard_objects, routes)
        tag = nil
        operations = []
        alias_names = []

        yard_objects.each do |yard_object|
          if yard_object.type == :class
            tag = Swagger::Tag.new(yard_object)
          elsif tag && yard_object.type == :method

            alias_name = Struct.new(:original, :alias)
            yard_object.tags.each do |_tag|
              alias_names << alias_name.new(createOriginalPath(yard_object, tag), _tag.text) if _tag.tag_name == 'name'
            end

            operation = Swagger::Operation.new(yard_object, tag, routes)
            operations << operation if operation.valid?
          end
        end

        return unless operations.any?

        return tag, operations, alias_names
      end

      private

      def createOriginalPath(yard_object, tag)
        "#{tag.controller_class.to_s}.#{yard_object.name}_body"
      end

    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SerializationsTest</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.service

Class SerializationsTest

java.lang.Object

org.apache.cassandra.AbstractSerializationsTester

org.apache.cassandra.service.SerializationsTest

public class SerializationsTest
extends AbstractSerializationsTester

Field Summary

Fields inherited from class org.apache.cassandra.AbstractSerializationsTester

CUR_VER, EXECUTE_WRITES, VERSION_MAP

Constructor Summary

Constructors

Constructor and Description

SerializationsTest()

Method Summary

Methods

Modifier and Type
Method and Description

void
testSyncCompleteRead()

void
testSyncRequestRead()

void
testValidationCompleteRead()

void
testValidationRequestRead()

Methods inherited from class org.apache.cassandra.AbstractSerializationsTester

getInput, getOutput, getVersion, testSerializedSize

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SerializationsTest

public SerializationsTest()

Method Detail

testValidationRequestRead

public void testValidationRequestRead()
                               throws java.io.IOException

Throws:

java.io.IOException

testValidationCompleteRead

public void testValidationCompleteRead()
                                throws java.io.IOException

Throws:

java.io.IOException

testSyncRequestRead

public void testSyncRequestRead()
                         throws java.io.IOException

Throws:

java.io.IOException

testSyncCompleteRead

public void testSyncCompleteRead()
                          throws java.io.IOException

Throws:

java.io.IOException

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
"""
============
Load Dataset
============

Conventionally, the h5py package is used to create, read, write, and modify h5 files.

Pycroscopy uses h5py to read hdf5 files and the ioHDF5 subpackage (a light wrapper around h5py) within pycroscopy
to create / write back to the file. Please see the example on writing hdf5 files for more information on creating and
writing to h5 files using pycroscopy.

In the event that modification / addition of data to the existing file is of interest,
it is recommended that the file be opened using ioHDF5. The same h5py handles can be obtained easily from ioHDF5.
Note that ioHDF5 always reads the files in the 'r+' mode that allows modification of the file.

In this example, we will be loading the Raw_Data dataset from the hdf5 file.

"""

# Code source: pycroscopy
# Liscense: MIT

from __future__ import division, print_function, absolute_import, unicode_literals
import h5py
try:
    # This package is not part of anaconda and may need to be installed.
    import wget
except ImportError:
    import pip
    pip.main(['install', 'wget'])
    import wget

from os import remove
import pycroscopy as px

# Downloading the file from the pycroscopy Github project
url = 'https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/data/BELine_0004.h5'
h5_path = 'temp.h5'
_ = wget.download(url, h5_path)

# h5_path = px.io_utils.uiGetFile(caption='Select .h5 file', filter='HDF5 file (*.h5)')

# Read the file using using h5py:
h5_file1 = h5py.File(h5_path, 'r')

# Look at the contents of the file:
px.hdf_utils.print_tree(h5_file1)

# Access the "Raw_Data" dataset from its absolute path
h5_raw1 = h5_file1['Measurement_000/Channel_000/Raw_Data']
print('h5_raw1: ', h5_raw1)

# We can get to the same dataset through relative paths:

# Access the Measurement_000 group first
h5_meas_grp = h5_file1['Measurement_000']
print('h5_meas_grp:', h5_meas_grp)

# Now we can access the "Channel_000" group via the h5_meas_grp object
h5_chan_grp = h5_meas_grp['Channel_000']

# And finally, the same raw dataset can be accessed as:
h5_raw1_alias_1 = h5_chan_grp['Raw_Data']
print('h5_raw1_alias_1:', h5_raw1_alias_1)

# Another way to get this dataset is via functions written in pycroscopy:
h5_dsets = px.hdf_utils.getDataSet(h5_file1, 'Raw_Data')
print('h5_dsets:', h5_dsets)

# In this case, there is only a single Raw_Data, so we an access it simply as:
h5_raw1_alias_2 = h5_dsets[0]
print('h5_raw1_alias_2:', h5_raw1_alias_2)

# Let's just check to see if these are indeed aliases of the same dataset:
print('All aliases of the same dataset?', h5_raw1 == h5_raw1_alias_1 and h5_raw1 == h5_raw1_alias_2)

# Let's close this file
h5_file1.close()

# Load the dataset with pycroscopy
hdf = px.ioHDF5(h5_path)

# Getting the same h5py handle to the file:
h5_file2 = hdf.file

h5_raw2 = h5_file2['Measurement_000/Channel_000/Raw_Data']
print('h5_raw2:', h5_raw2)

h5_file2.close()

# Delete the temporarily downloaded h5 file:
remove(h5_path)


text:
package piperouter

import (
    . "github.com/levythu/gurgling"
)

type PipeRouter struct {
    Router
}

func pipeToUrl(req Request, res Response) {

}

func APipeRouter() Router {
    var trouter=ARouter().Use(pipeToUrl)
    return PipeRouter{
        Router: trouter,
    }
}


text:
Connection::Connection(string host, int port, string channel)
{
    this->host = host;
    this->port = port;
    this->channel = channel;
}

// Destruktor
Connection::~Connection()
{
}

void Connection::Connect() {
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("Failed to create socket...");
        Disconnect();
        return;
    }
    hostent *hp = gethostbyname(host.c_str());
    if (!hp)
    {
        perror("Failed to get hostname...");
        Disconnect();
        return;
    }

    sockaddr_in sin;
    memset((char*)&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    memcpy((char*)&sin.sin_addr, hp->h_addr, hp->h_length);
    sin.sin_port = htons(port);
    memset(&(sin.sin_zero), 0, 8*sizeof(char));

    if (connect(sock, (sockaddr*) &sin, sizeof(sin)) == -1)
    {
        perror("Failed to connect socket...");
        Disconnect();
        return;
    }
}
void Connection::Disconnect()
{
    close(sock);
}
void Connection::Send(string msg) {
    send(sock, msg.c_str(), msg.length(), 0);
}
bool Connection::Receive(string &buf) {
    char buffer[BUFFER_SIZE+1] = {0};
    if (recv(sock, buffer, BUFFER_SIZE*sizeof(char), 0) < 0) {
        perror("Failed to receive message...");
        return false;
    }
    buf = ParseIrc(string(buffer));
    return true;
}
void Connection::Identify(string name, string pw, string channel)
{
    Send("NICK " + name + "\r\n");
    Send("USER " + name + " 0 0  :" + name + "\r\n");
    Send("PRIVMSG NickServ IDENTIFY " + pw + "\r\n");
    SetChannel(channel);
    Send("PRIVMSG #" + channel + " :Hallo!\r\n");
}
void Connection::PingPong(string buffer)
{
    size_t pos = buffer.find("PING");
    if (pos != string::npos) {
        string pong("PONG" + buffer.substr(pos + 4)+"\r\n");
        cout << pong << endl;
        Send(pong);
    }
}
string Connection::ParseIrc(string buffer) {
    if (buffer.find("\r\n") == buffer.length()-2)
        buffer.erase(buffer.length()-2);
    return buffer;
}
void Connection::SetChannel(string channel)
{
    Send("JOIN #" + channel + "\r\n");
    this->channel = channel;
}
string Connection::GetChannel()
{
    return channel;
}


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

namespace WebAddressbookTests
{
    [Table("group_list")]
    public class GroupData : IEquatable<GroupData>, IComparable<GroupData>
    {
        public GroupData()
        { }

        public GroupData(string name)
        {
            Name = name;
        }

        public bool Equals(GroupData other)
        {
            if (Object.ReferenceEquals(other, null))
            {
                return false;
            }
            if (Object.ReferenceEquals(this, other))
            {
                return true;
            }
            return Name == other.Name;
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }

        public override string ToString()
        {
            return "name= " + Name
                + "\r\nheader= " + Header
                + "\r\nfooter= " + Footer;
        }

        public int CompareTo(GroupData other)
        {
            if (Object.ReferenceEquals(other, null))
            {
                return 1;
            }
            return Name.CompareTo(other.Name);
        }

        [Column("group_id", IsPrimaryKey = true, IsIdentity = true)]
        public string Id { get; set; }

        [Column("group_name")]
        public string Name { get; set; }

        [Column("group_header")]
        public string Header { get; set; }

        [Column("group_footer")]
        public string Footer { get; set; }

        [Column("deprecated")]
        public string Deprecated { get; set; }

        public static List<GroupData> GetAll()
        {
            using (AddressBookDb db = new AddressBookDb())
            {
                return (from g in db.Groups.Where(x => x.Deprecated == "0000-00-00 00:00:00") select g).ToList();
            }
        }

        public List<ContactData> GetContacts()
        {
            using (AddressBookDb db = new AddressBookDb())
            {
                return (from c in db.Contacts.Where(x => x.Deprecated == "0000-00-00 00:00:00")
                        from gcr in db.GCR.Where(rel => rel.GroupId == Id && rel.ContactId == c.Id)
                        select c).Distinct().ToList();
            }
        }
    }
}


text:
/* global require, describe, it */
'use strict';

// MODULES //

var chai = require( 'chai' ),
	table = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'datasets-us-states-names-capitals', function tests() {

	it( 'should export an object', function test() {
		expect( table ).to.be.an( 'object' );
		assert.strictEqual( Object.keys( table ).length, 50 );
	});

	it( 'should map state names to capitals', function test() {
		assert.strictEqual( table[ 'Missouri' ], 'Jefferson City' );
		assert.strictEqual( table[ 'New Jersey' ], 'Trenton' );
		assert.strictEqual( table[ 'California' ], 'Sacramento' );
	});

});


text:
"""
Parsers
"""
from rest_framework import parsers
from rest_framework.exceptions import ParseError

from . import utils, renderers, exceptions

class JSONParser(parsers.JSONParser):
    """
    A JSON API client will send a payload that looks like this:

        {
            "data": {
                "type": "identities",
                "id": 1,
                "attributes": {
                    "first_name": "John",
                    "last_name": "Coltrane"
                }
            }
        }

    We extract the attributes so that DRF serializers can work as normal.
    """
    media_type = 'application/vnd.api+json'
    renderer_class = renderers.JSONRenderer

    @staticmethod
    def parse_attributes(data):
        return utils.format_keys(data.get('attributes'), 'underscore') if data.get('attributes') else dict()

    @staticmethod
    def parse_relationships(data):
        relationships = (utils.format_keys(data.get('relationships'), 'underscore')
                         if data.get('relationships') else dict())

        # Parse the relationships
        parsed_relationships = dict()
        for field_name, field_data in relationships.items():
            field_data = field_data.get('data')
            if isinstance(field_data, dict) or field_data is None:
                parsed_relationships[field_name] = field_data
            elif isinstance(field_data, list):
                parsed_relationships[field_name] = list(relation for relation in field_data)
        return parsed_relationships

    def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as JSON and returns the resulting data
        """
        result = super(JSONParser, self).parse(stream, media_type=media_type, parser_context=parser_context)
        data = result.get('data')

        if data:
            from rest_framework_json_api.views import RelationshipView
            if isinstance(parser_context['view'], RelationshipView):
                # We skip parsing the object as JSONAPI Resource Identifier Object and not a regular Resource Object
                if isinstance(data, list):
                    for resource_identifier_object in data:
                        if not (resource_identifier_object.get('id') and resource_identifier_object.get('type')):
                            raise ParseError(
                                'Received data contains one or more malformed JSONAPI Resource Identifier Object(s)'
                            )
                elif not (data.get('id') and data.get('type')):
                    raise ParseError('Received data is not a valid JSONAPI Resource Identifier Object')

                return data

            request = parser_context.get('request')

            # Check for inconsistencies
            resource_name = utils.get_resource_name(parser_context)
            if data.get('type') != resource_name and request.method in ('PUT', 'POST', 'PATCH'):
                raise exceptions.Conflict(
                    "The resource object's type ({data_type}) is not the type "
                    "that constitute the collection represented by the endpoint ({resource_type}).".format(
                        data_type=data.get('type'),
                        resource_type=resource_name
                    )
                )
            if not data.get('id') and request.method in ('PATCH', 'PUT'):
                raise ParseError("The resource identifier object must contain an 'id' member")

            # Construct the return data
            parsed_data = {'id': data.get('id')}
            parsed_data.update(self.parse_attributes(data))
            parsed_data.update(self.parse_relationships(data))
            return parsed_data

        else:
            raise ParseError('Received document does not contain primary data')


text:
package org.opencb.hpg.bigdata.core.io;

import htsjdk.variant.variantcontext.VariantContext;
import org.opencb.biodata.models.variant.avro.VariantAvro;
import org.opencb.biodata.tools.variant.converters.avro.VariantContextToVariantConverter;
import org.opencb.commons.run.ParallelTaskRunner;
import org.opencb.hpg.bigdata.core.avro.VariantAvroAnnotator;
import org.opencb.hpg.bigdata.core.io.avro.AvroEncoder;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.function.Predicate;

/**
 * Created by jtarraga on 04/10/17.
 */
public class ConvertEncodeTask implements ParallelTaskRunner.Task<VariantContext, ByteBuffer> {
    private ConvertTask convertTask;
    protected AvroEncoder<VariantAvro> encoder;

    public ConvertEncodeTask(VariantContextToVariantConverter converter, List<List<Predicate<VariantAvro>>> filters,
                             VariantAvroAnnotator annotator) {
        convertTask = new ConvertTask(converter, filters, annotator);
        this.encoder = new AvroEncoder<>(VariantAvro.getClassSchema());
    }

    @Override
    public List<ByteBuffer> apply(List<VariantContext> variantContexts) throws RuntimeException {
        List<VariantAvro> variantAvros = convertTask.apply(variantContexts);

        // Encode
        encoder = new AvroEncoder<>(VariantAvro.getClassSchema());
        List<ByteBuffer> encoded;
        try {
            encoded = encoder.encode(variantAvros);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return encoded;
    }
}