text:
"""Basic neural network layers."""

from ..block import Block, HybridBlock
from ..utils import _indent

class Sequential(Block):
    """Stacks `Block`s sequentially.

    Example::

        net = nn.Sequential()
        # use net's name_scope to give child Blocks appropriate names.
        with net.name_scope():
            net.add(nn.Dense(10, activation='relu'))
            net.add(nn.Dense(20))
    """
    def __init__(self, prefix=None, params=None):
        super(Sequential, self).__init__(prefix=prefix, params=params)

    def add(self, block):
        """Adds block on top of the stack."""
        self.register_child(block)

    def forward(self, x):
        for block in self._children:
            x = block(x)
        return x

    def __repr__(self):
        s = '{name}(\n{modstr}\n)'
        modstr = '\n'.join(['  ({key}): {block}'.format(key=key,
                                                        block=_indent(block.__repr__(), 2))
                            for key, block in enumerate(self._children)
                            if isinstance(block, Block)])
        return s.format(name=self.__class__.__name__,
                        modstr=modstr)

    def __getitem__(self, i):
        return self._children[i]

    def __len__(self):
        return len(self._children)

class HybridSequential(HybridBlock):
    """Stacks `HybridBlock`s sequentially.

    Example::

        net = nn.Sequential()
        # use net's name_scope to give child Blocks appropriate names.
        with net.name_scope():
            net.add(nn.Dense(10, activation='relu'))
            net.add(nn.Dense(20))
    """
    def __init__(self, prefix=None, params=None):
        super(HybridSequential, self).__init__(prefix=prefix, params=params)

    def add(self, block):
        """Adds block on top of the stack."""
        self.register_child(block)

    def hybrid_forward(self, F, x):
        for block in self._children:
            x = block(x)
        return x

    def __repr__(self):
        s = '{name}(\n{modstr}\n)'
        modstr = '\n'.join(['  ({key}): {block}'.format(key=key,
                                                        block=_indent(block.__repr__(), 2))
                            for key, block in enumerate(self._children)
                            if isinstance(block, Block)])
        return s.format(name=self.__class__.__name__,
                        modstr=modstr)

    def __getitem__(self, i):
        return self._children[i]

    def __len__(self):
        return len(self._children)

class Dense(HybridBlock):
    """Just your regular densely-connected NN layer.

    `Dense` implements the operation:
    `output = activation(dot(input, weight) + bias)`
    where `activation` is the element-wise activation function
    passed as the `activation` argument, `weight` is a weights matrix
    created by the layer, and `bias` is a bias vector created by the layer
    (only applicable if `use_bias` is `True`).

    Note: the input must be a tensor with rank 2. Use `flatten` to convert it
    to rank 2 manually if necessary.

    Parameters
    ----------
    units : int
        Dimensionality of the output space.
    activation : str
        Activation function to use. See help on `Activation` layer.
        If you don't specify anything, no activation is applied
        (ie. "linear" activation: `a(x) = x`).
    use_bias : bool
        Whether the layer uses a bias vector.
    weight_initializer : str or `Initializer`
        Initializer for the `kernel` weights matrix.
    bias_initializer: str or `Initializer`
        Initializer for the bias vector.
    in_units : int, optional
        Size of the input data. If not specified, initialization will be
        deferred to the first time `forward` is called and `in_units`
        will be inferred from the shape of input data.
    prefix : str or None
        See document of `Block`.
    params : ParameterDict or None
        See document of `Block`.

    Input shape:
        A 2D input with shape `(batch_size, in_units)`.

    Output shape:
        The output would have shape `(batch_size, units)`.
    """
    def __init__(self, units, activation=None, use_bias=True,
                 weight_initializer=None, bias_initializer='zeros',
                 in_units=0, **kwargs):
        super(Dense, self).__init__(**kwargs)
        with self.name_scope():
            self._units = units
            self._in_units = in_units
            self.weight = self.params.get('weight', shape=(units, in_units),
                                          init=weight_initializer,
                                          allow_deferred_init=True)
            if use_bias:
                self.bias = self.params.get('bias', shape=(units,),
                                            init=bias_initializer,
                                            allow_deferred_init=True)
            else:
                self.bias = None
            if activation is not None:
                self.act = Activation(activation, prefix=activation+'_')
            else:
                self.act = None

    def hybrid_forward(self, F, x, weight, bias=None):
        if bias is None:
            act = F.FullyConnected(x, weight, no_bias=True, num_hidden=self._units,
                                   name='fwd')
        else:
            act = F.FullyConnected(x, weight, bias, num_hidden=self._units,
                                   name='fwd')
        if self.act is not None:
            act = self.act(act)
        return act

    def __repr__(self):
        s = '{name}({layout}, {act})'
        return s.format(name=self.__class__.__name__,
                        act=self.act if self.act else 'linear',
                        layout='{0} -> {1}'.format(self._in_units, self._units) if self._in_units
                        else self._units)

class Activation(HybridBlock):
    """Applies an activation function to input.

    Parameters
    ----------
    activation : str
        Name of activation function to use.
        See :func:`~mxnet.ndarray.Activation` for available choices.

    Input shape:
        Arbitrary.

    Output shape:
        Same shape as input.
    """
    def __init__(self, activation, **kwargs):
        self._act_type = activation
        super(Activation, self).__init__(**kwargs)

    def _alias(self):
        return self._act_type

    def hybrid_forward(self, F, x):
        return F.Activation(x, act_type=self._act_type, name='fwd')

    def __repr__(self):
        s = '{name}({_act_type})'
        return s.format(name=self.__class__.__name__,
                        **self.__dict__)

class Dropout(HybridBlock):
    """Applies Dropout to the input.

    Dropout consists in randomly setting a fraction `rate` of input units
    to 0 at each update during training time, which helps prevent overfitting.

    Parameters
    ----------
    rate : float
        Fraction of the input units to drop. Must be a number between 0 and 1.

    Input shape:
        Arbitrary.

    Output shape:
        Same shape as input.

    References
    ----------
        `Dropout: A Simple Way to Prevent Neural Networks from Overfitting
        <http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf>`_
    """
    def __init__(self, rate, **kwargs):
        super(Dropout, self).__init__(**kwargs)
        self._rate = rate

    def hybrid_forward(self, F, x):
        return F.Dropout(x, p=self._rate, name='fwd')

    def __repr__(self):
        s = '{name}(p = {_rate})'
        return s.format(name=self.__class__.__name__,
                        **self.__dict__)

class BatchNorm(HybridBlock):
    """Batch normalization layer (Ioffe and Szegedy, 2014).
    Normalizes the input at each batch, i.e. applies a transformation
    that maintains the mean activation close to 0 and the activation
    standard deviation close to 1.

    Parameters
    ----------
    axis : int, default 1
        The axis that should be normalized. This is typically the channels
        (C) axis. For instance, after a `Conv2D` layer with `layout='NCHW'`,
        set `axis=1` in `BatchNorm`. If `layout='NHWC'`, then set `axis=3`.
    momentum: float, default 0.9
        Momentum for the moving average.
    epsilon: float, default 1e-5
        Small float added to variance to avoid dividing by zero.
    center: bool, default True
        If True, add offset of `beta` to normalized tensor.
        If False, `beta` is ignored.
    scale: bool, default True
        If True, multiply by `gamma`. If False, `gamma` is not used.
        When the next layer is linear (also e.g. `nn.relu`),
        this can be disabled since the scaling
        will be done by the next layer.
    beta_initializer: str or `Initializer`, default 'zeros'
        Initializer for the beta weight.
    gamma_initializer: str or `Initializer`, default 'ones'
        Initializer for the gamma weight.
    moving_mean_initializer: str or `Initializer`, default 'zeros'
        Initializer for the moving mean.
    moving_variance_initializer: str or `Initializer`, default 'ones'
        Initializer for the moving variance.
    in_channels : int, default 0
        Number of channels (feature maps) in input data. If not specified,
        initialization will be deferred to the first time `forward` is called
        and `in_channels` will be inferred from the shape of input data.

    Input shape:
        Arbitrary.

    Output shape:
        Same shape as input.
    """
    def __init__(self, axis=1, momentum=0.9, epsilon=1e-5, center=True, scale=True,
                 beta_initializer='zeros', gamma_initializer='ones',
                 running_mean_initializer='zeros', running_variance_initializer='ones',
                 in_channels=0, **kwargs):
        super(BatchNorm, self).__init__(**kwargs)
        self._kwargs = {'axis': axis, 'eps': epsilon, 'momentum': momentum,
                        'fix_gamma': not scale}
        if in_channels != 0:
            self.in_channels = in_channels

        self.gamma = self.params.get('gamma', grad_req='write' if scale else 'null',
                                     shape=(in_channels,), init=gamma_initializer,
                                     allow_deferred_init=True)
        self.beta = self.params.get('beta', grad_req='write' if center else 'null',
                                    shape=(in_channels,), init=beta_initializer,
                                    allow_deferred_init=True)
        self.running_mean = self.params.get('running_mean', grad_req='null',
                                            shape=(in_channels,),
                                            init=running_mean_initializer,
                                            allow_deferred_init=True)
        self.running_var = self.params.get('running_var', grad_req='null',
                                           shape=(in_channels,),
                                           init=running_variance_initializer,
                                           allow_deferred_init=True)

    def hybrid_forward(self, F, x, gamma, beta, running_mean, running_var):
        return F.BatchNorm(x, gamma, beta, running_mean, running_var,
                           name='fwd', **self._kwargs)

    def __repr__(self):
        s = '{name}({content}'
        if hasattr(self, 'in_channels'):
            s += ', in_channels={0}'.format(self.in_channels)
        s += ')'
        return s.format(name=self.__class__.__name__,
                        content=', '.join(['='.join([k, v.__repr__()])
                                           for k, v in self._kwargs.items()]))

class LeakyReLU(HybridBlock):
    """Leaky version of a Rectified Linear Unit.

    It allows a small gradient when the unit is not active::

        `f(x) = alpha * x for x < 0`,
        `f(x) = x for x >= 0`.

    Parameters
    ----------
    alpha : float
        slope coefficient for the negative half axis. Must be >= 0.

    Input shape:
        Arbitrary.

    Output shape:
        Same shape as input.
    """
    def __init__(self, alpha, **kwargs):
        super(LeakyReLU, self).__init__(**kwargs)
        self._alpha = alpha

    def hybrid_forward(self, F, x):
        return F.LeakyReLU(x, act_type='leaky', slope=self._alpha, name='fwd')

    def __repr__(self):
        s = '{name}({alpha})'
        return s.format(name=self.__class__.__name__,
                        alpha=self._alpha)

class Embedding(HybridBlock):
    """Turns non-negative integers (indexes/tokens) into dense vectors
    of fixed size. eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]

    Parameters
    ----------
    input_dim : int
        Size of the vocabulary, i.e. maximum integer index + 1.
    output_dim : int
        Dimension of the dense embedding.
    dtype : str or np.dtype, default 'float32'
        Data type of output embeddings.
    weight_initializer : Initializer
        Initializer for the `embeddings` matrix.

    Input shape:
        2D tensor with shape: `(N, M)`.

    Output shape:
        3D tensor with shape: `(N, M, output_dim)`.
    """
    def __init__(self, input_dim, output_dim, dtype='float32',
                 weight_initializer=None, **kwargs):
        super(Embedding, self).__init__(**kwargs)
        self._kwargs = {'input_dim': input_dim, 'output_dim': output_dim,
                        'dtype': dtype}
        self.weight = self.params.get('weight', shape=(input_dim, output_dim),
                                      init=weight_initializer,
                                      allow_deferred_init=True)

    def hybrid_forward(self, F, x, weight):
        return F.Embedding(x, weight, name='fwd', **self._kwargs)

    def __repr__(self):
        s = '{block_name}({input_dim} -> {output_dim}, {dtype})'
        return s.format(block_name=self.__class__.__name__,
                        **self._kwargs)

class Flatten(HybridBlock):
    """Flattens the input to two dimensional.

    Input shape:
        Arbitrary shape `(N, a, b, c, ...)`

    Output shape:
        2D tensor with shape: `(N, a*b*c...)`
    """
    def __init__(self, **kwargs):
        super(Flatten, self).__init__(**kwargs)

    def hybrid_forward(self, F, x):
        return x.reshape((0, -1))

    def __repr__(self):
        return self.__class__.__name__


text:
#import "NSObject.h"

@interface MRUtilities : NSObject
{
}

+ (long long)operatingSystemMajorVersion;
+ (long long)operatingSystemMinorVersion;
+ (long long)operationQueueConcurrentOperationCount;
+ (id)executeScript:(id)arg1 withHeader:(id)arg2 andAttributes:(id)arg3;
+ (struct CGColorSpace *)newColorSpaceForDevice;
+ (double)transformTime:(double)arg1 forAnimationPath:(id)arg2 inPlug:(id)arg3;
+ (struct CGPoint)valueForPointAnimationPath:(id)arg1 inPlug:(id)arg2 atTime:(double)arg3 defaultsTo:(struct CGPoint)arg4 previousKeyPoint:(struct CGPoint *)arg5 nextKeyPoint:(struct CGPoint *)arg6;
+ (float)valueForScalarAnimationPath:(id)arg1 inPlug:(id)arg2 atTime:(double)arg3 defaultsTo:(float)arg4 previousKeyValue:(float *)arg5 nextKeyValue:(float *)arg6;
+ (void)initialize;

@end

redpajama_set_name: RedPajamaGithub


text:
#include <errno.h>
#include <unistd.h>

#include "native_client/src/untrusted/nacl/nacl_irt.h"

int getdents(int desc, struct dirent *buf, size_t count) {
  size_t nread;
  int error = __libnacl_irt_fdio.getdents(desc, buf, count, &nread);
  if (error) {
    errno = error;
    return -1;
  }
  return nread;
}


text:
<?php

namespace Ahe\gsbBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * VisiteurRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class VisiteurRepository extends EntityRepository
{
    public function findByLoginAndMdp($login, $mdp) {
        $queryBuilder = $this->createQueryBuilder('unVisiteur') ;
        $queryBuilder-> where('unVisiteur.login = :login')
                        ->setParameter('login', $login)
                     ->andWhere ('unVisiteur.mdp = :mdp')
                        ->setParameter('mdp',$mdp) ;
        $result = $queryBuilder->getQuery()->getOneOrNullResult() ;

        return $result ;
    }
}


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

namespace ResotelApp.Models
{
    ///  Option's discount : can theoretically be valid for a given period of time.
    public class Discount : IValidable, IDataErrorInfo
    {
        private Dictionary<string, Func<string>> _propertiesValidations;

        public int Id { get; set; }
        [Required]
        public double ReduceByPercent { get; set; }
        public DateRange Validity { get; set; }

        string IDataErrorInfo.Error
        {
            get
            {
                string error = null;
                StringBuilder stringBuilder = new StringBuilder();

                foreach (KeyValuePair<string, Func<string>> propValidationFnKvp in _propertiesValidations)
                {
                    string propError = propValidationFnKvp.Value();
                    if (propError != null)
                    {
                        stringBuilder.Append(propError + ";");
                    }
                }

                if (stringBuilder.Length > 0)
                {
                    error = stringBuilder.ToString();
                }
                return error;
            }
        }

        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                string error = null;
                if(_propertiesValidations.ContainsKey(columnName))
                {
                    error = _propertiesValidations[columnName]();
                }
                return error;
            }
        }

        public Discount()
        {
            _propertiesValidations = new Dictionary<string, Func<string>> {
                { nameof(ReduceByPercent), _validateReduceByPercent },
                { nameof(Validity), _validateValidity }
            };
        }

        private string _validateReduceByPercent()
        {
            string error = null;
            if(ReduceByPercent < 0)
            {
                error = string.Format("La promotion {0} est invalide car le pourcentage de réduction doit être positif ou null.", Id);
            }
            return error;
        }

        private string _validateValidity()
        {
            string error = null;
            string validityError = Validity == null ? null : ((IDataErrorInfo)Validity).Error;
            if (validityError != null)
            {
                error = string.Format("La validité de la promotion {0} est invalide car {1}", Id, validityError);
            }
            return error;
        }

        /// Validates a discount
        /// <returns>true if the discount is valid, false otherwise</returns>
        /// <remarks>This method must be called before saving or showing an instance</remarks>
        public bool Validate()
        {
            bool reduceByPercentValidates = _validateReduceByPercent() == null;

            bool validityValidates = _validateValidity() == null;

            return reduceByPercentValidates && validityValidates;
        }
    }
}


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using System.Reflection;
using SF.Sys.Linq;
using SF.Sys.Reflection;

namespace SF.Sys.Linq.Expressions
{
	public static class ExpressionExtension
	{
		public static Expression Create(this Type type, params Expression[] args)
		{
			return Create(type, (IEnumerable<Expression>)args);
		}
		public static Expression Create(this Type type, IEnumerable<Expression> args)
		{
			return Expression.New(
				type.GetConstructor((from a in args select a.Type).ToArray()),
				args
				);
		}
		public static Expression ThrowException(this Expression expr)
		{
			return Expression.Throw(expr);
		}
		public static Expression Block(params Expression[] es)
		{
			return Expression.Block(es);
		}
		public static Expression Block(IEnumerable<Expression> es)
		{
			return Expression.Block(es);
		}
		public static Expression Assign(this Expression left, Expression right)
		{
			return Expression.Assign(left, right);
		}
		public static Expression AssignValue<T>(this Expression left, T right)
		{
			return Expression.Assign(left, Expression.Constant(right));
		}
		public static Expression WithNullDefault(this Expression expr,Func<Expression,Expression> Mapper=null, Expression defaultValue=null)
		{
			if (expr.Type.IsValue())
				return expr;

			if (expr.NodeType == ExpressionType.Parameter)
			{
				var result = Mapper == null ? expr : Mapper(expr);
				if (defaultValue != null && defaultValue.Type != result.Type)
					throw new InvalidOperationException($"空值默认值类型{defaultValue.Type}和表达式类型{result.Type}不同");
				return
					Expression.Condition(
						expr.Equal(Expression.Constant(null, expr.Type)),
						defaultValue ?? Expression.Constant(null, result.Type),
						result
						);
			}
			else
			{
				var v = Expression.Variable(expr.Type);
				var result = Mapper == null ? v : Mapper(v);
				if (defaultValue != null && defaultValue.Type != result.Type)
					throw new InvalidOperationException($"空值默认值类型{defaultValue.Type}和表达式类型{result.Type}不同");
				return Expression.Block(
					new[] { v },
					v.Assign(expr),
					Expression.Condition(
						v.Equal(Expression.Constant(null, expr.Type)),
						defaultValue ?? Expression.Constant(null, result.Type),
						result
						)
					);
			}
		}
		public static Expression CallMethod(this Expression obj, MethodInfo method, params Expression[] args)
		{
			return Expression.Call(
				obj,
				method,
				args
				);
		}
		public static Expression CallMethod(this Expression obj, string name, params Expression[] args)
		{
			return CallMethod(obj, obj.Type.FindMethod(name, BindingFlags.Public | BindingFlags.Instance), args);
		}
		public static Expression CallMethod(this Expression obj, string name, IEnumerable<Expression> args)
		{
			return CallMethod(obj, obj.Type.FindMethod(name, BindingFlags.Public | BindingFlags.Instance), args.ToArray());
		}
		public static MethodInfo FindMethod(this Type type, string name, BindingFlags flags)
		{
			var m = type.GetMethod(name, flags);
			if (m != null)
				return m;
			foreach (var t in type.GetInterfaces())
			{
				m = t.FindMethod(name, flags);
				if (m != null)
					return m;
			}
			return null;

			//type.method(name, BindingFlags.NonPublic | BindingFlags.Instance) ??
			//type.method(name, BindingFlags.NonPublic | BindingFlags.Static);
		}
		public static MethodInfo Method(this Type type, string name, System.Reflection.BindingFlags flags)
		{
			return type.GetMethod(name, flags);
		}
		public static MethodInfo Method(this Type type, string name, params Type[] types)
		{
			name += "<" + new string(',', types.Length - 1) + ">";
			var m =
				type.GetMethod(name, BindingFlags.Public | BindingFlags.Instance) ??
				type.GetMethod(name, BindingFlags.Public | BindingFlags.Static);

			//type.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance) ??
			//type.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static);
			if (m == null)
				return null;
			return m.MakeGenericMethod(types);
		}
		public static MemberInfo Member(this Type type, string name)
		{
			return
				type.Property(name, BindingFlags.Public | BindingFlags.Instance) ??
				type.Property(name, BindingFlags.Public | BindingFlags.Static) ??
				type.Field(name, BindingFlags.Public | BindingFlags.Instance) ??
				type.Field(name, BindingFlags.Public | BindingFlags.Static);
			/*type.prop(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.SetProperty) ??
			type.prop(name, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.SetProperty) ??
			type.field(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.SetField) ??
			type.field(name, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField | BindingFlags.SetField);
			 */
		}
		public static MemberInfo Property(this Type type, string name, BindingFlags flags)
		{
			return type.GetProperties(flags).FirstOrDefault(p => p.Name == name);
		}
		public static MemberInfo Field(this Type type, string name, BindingFlags flags)
		{
			return type.GetField(name, flags);
		}

		public static Expression Loop(Expression body, LabelTarget break_target = null, LabelTarget continue_target = null)
		{
			return Expression.Loop(body, break_target, continue_target);
		}
		public static Expression Then(this Expression expr, params Expression[] true_expr)
		{
			return true_expr.Length == 1 ?
				Expression.IfThen(expr, true_expr[0]) :
				Expression.IfThen(expr, Block(true_expr));
		}
		public static Expression Then(this Expression expr, IEnumerable<Expression> true_expr)
		{
			return Then(expr, true_expr.ToArray());
		}
		public static Expression Then(this Expression expr, Expression true_expr, Expression false_expr)
		{
			return Expression.IfThenElse(expr, true_expr, false_expr);
		}
		public static Expression ForCondition(this Expression expr, Expression true_expr, Expression false_expr)
		{
			return Expression.Condition(expr, true_expr, false_expr);
		}
		public static Expression ThenLoop(this Expression cond, params Expression[] body)
		{
			var bl = Expression.Label();
			var b = body.Length == 1 ? body[0] : Block(body);
			return Loop(cond.Then(b, Expression.Break(bl)), bl);
		}

		public static Expression To(this Expression v, Type type)
		{
			return Expression.Convert(v, type);
		}
		public static Expression To<T>(this Expression v)
		{
			return v.To(typeof(T));
		}
		public static Expression UseEnumerator<T>(this Expression e, Func<Expression, Expression> body)
		{
			return e.To<IEnumerable<T>>().CallMethod("GetEnumerator").Use(body);
		}
		public static Type MakeGenericType(this Type type, IEnumerable<Type> types)
		{
			return type.MakeGenericType(types.ToArray());
		}
		public static Type MakeGenericType<T>(this Type type)
		{
			return type.MakeGenericType(typeof(T));
		}
		public static Type MakeGenericType<T1, T2>(this Type type)
		{
			return type.MakeGenericType(typeof(T1), typeof(T2));
		}
		public static Type MakeGenericType<T1, T2, T3>(this Type type)
		{
			return type.MakeGenericType(typeof(T1), typeof(T2), typeof(T3));
		}
		public static Type MakeGenericType<T1, T2, T3, T4>(this Type type)
		{
			return type.MakeGenericType(typeof(T1), typeof(T2), typeof(T3), typeof(T4));
		}
		public static Expression UseEnumerator(this Expression e, Type type, Func<Expression, Expression> body)
		{
			return e.To(typeof(IEnumerable<>).MakeGenericType(type)).CallMethod("GetEnumerator").Use(body);
		}
		public static Expression Iterator(this Expression e, Type type, Func<Expression, Expression> body)
		{
			if (e.Type != typeof(IEnumerator<>).MakeGenericType(type))
				throw new ArgumentException();
			var v = type.AsVariable();
			return e.CallMethod("MoveNext").ThenLoop(
				Expression.Block(
					new ParameterExpression[] { (ParameterExpression)v },
					v.Assign(e.GetMember("Current")),
					body(v)
				));
		}
		public static Expression Iterator(this Expression e, ParameterExpression arg, Func<Expression, Expression> body)
		{
			if (e.Type != typeof(IEnumerator<>).MakeGenericType(arg.Type))
				throw new ArgumentException();
			return e.CallMethod("MoveNext").ThenLoop(
				Expression.Block(
					arg.Assign(e.GetMember("Current")),
					body(arg)
				));
		}
		public static Expression Iterator<T>(this Expression e, Func<Expression, Expression> body)
		{
			return Iterator(e, typeof(T), body);
		}
		public static Expression ForEach<T>(this Expression e, Func<Expression, Expression> body)
		{
			return e.UseEnumerator<T>(ie => ie.Iterator<T>(body));
		}
		public static Expression ForEach(this Expression e, Type type, Func<Expression, Expression> body)
		{
			return e.UseEnumerator(type, ie => ie.Iterator(type, body));
		}
		public static Expression ForEach(this Expression e, ParameterExpression arg, Func<Expression, Expression> body)
		{
			return e.UseEnumerator(arg.Type, ie => ie.Iterator(arg, body));
		}
		public static Expression Use(this Expression e, Func<Expression, Expression> body)
		{
			var v = e.Type.AsVariable();
			return Expression.Block(
				new ParameterExpression[] { (ParameterExpression)v },
				new Expression[]{
					v.Assign(e),
					Expression.TryFinally(
						body(v),
						v.To<IDisposable>().CallMethod("Dispose")
						)
					}
				);
		}
		public static Expression While(this Expression body, Expression cond)
		{
			var bl = Expression.Label();
			return Loop(
				Block(
					body,
					Not(cond).Then(Expression.Break(bl))
				),
				bl);
		}
		public static Expression Call(this MethodInfo method, params Expression[] args)
		{
			return Expression.Call(
				null,
				method,
				args
				);
		}
		public static Expression Call(this Expression instance, MethodInfo method, params Expression[] args)
		{
			return Expression.Call(
				instance,
				method,
				args
				);
		}
		public static Expression AsParameter(this Type type, string name)
		{
			return Expression.Parameter(type, name);
		}

		public static Expression AsVariable(this Type type, string name = null)
		{
			return Expression.Variable(type, name);
		}
		public static Expression AsVariable<T>(string name = null)
		{
			return AsVariable(typeof(T), name);
		}

		public static Expression Add(this Expression left, Expression right)
		{
			return Expression.Add(left, right);
		}
		public static Expression Subtract(this Expression left, Expression right)
		{
			return Expression.Subtract(left, right);
		}
		public static Expression Multiply(this Expression left, Expression right)
		{
			return Expression.Multiply(left, right);
		}
		public static Expression Divide(this Expression left, Expression right)
		{
			return Expression.Divide(left, right);
		}
		public static Expression Modulo(this Expression left, Expression right)
		{
			return Expression.Modulo(left, right);
		}
		public static Expression GetMember(this Expression left, MemberInfo member)
		{
			return Expression.MakeMemberAccess(left, member);
		}
		public static Expression GetMember(this Expression left, string member)
		{
			return left.GetMember(
				left.Type.Property(member, BindingFlags.Public | BindingFlags.Instance) ??
				left.Type.Field(member, BindingFlags.Public | BindingFlags.Instance)
				);
		}
		public static Expression SetProperty(this Expression left,PropertyInfo prop,Expression value)
		{
			return Expression.Call(
				left,
				prop.GetSetMethod(),
				value
				);
		}
		public static Expression Get(this MemberInfo member)
		{
			return Expression.MakeMemberAccess(null, member);
		}
		public static Expression LessThan(this Expression left, Expression right)
		{
			return Expression.LessThan(left, right);
		}
		public static Expression LessThanOrEqual(this Expression left, Expression right)
		{
			return Expression.LessThanOrEqual(left, right);
		}
		public static Expression GreaterThan(this Expression left, Expression right)
		{
			return Expression.GreaterThan(left, right);
		}
		public static Expression GreaterThanOrEqual(this Expression left, Expression right)
		{
			return Expression.GreaterThanOrEqual(left, right);
		}
		public static Expression Equal(this Expression left, Expression right)
		{
			return Expression.Equal(left, right);
		}
		public static Expression NotEqual(this Expression left, Expression right)
		{
			return Expression.NotEqual(left, right);
		}
		public static Expression Not(this Expression left)
		{
			return Expression.Not(left);
		}
		public static T Compile<T>(this Expression e, params Expression[] args)
		{
			return Expression.Lambda<T>(e, from a in args select (ParameterExpression)a).Compile();
		}
		public static Delegate Compile(this Expression e, params Expression[] args)
		{
			return Expression.Lambda(e, from a in args select (ParameterExpression)a).Compile();
		}
		public static Delegate Compile(this Expression e, Type DelegateType,params Expression[] args)
		{
			return Expression.Lambda(DelegateType, e, from a in args select (ParameterExpression)a).Compile();
		}
		public static Expression<T> Lambda<T>(this Expression e, params Expression[] args)
		{
			return Expression.Lambda<T>(e, from a in args select (ParameterExpression)a);
		}
		public static Expression Lambda(this Expression e, params Expression[] args)
		{
			return Expression.Lambda(e, from a in args select (ParameterExpression)a);
		}
		public static IEnumerable<Expression> SelfAndChildren(this Expression e)
		{
			yield return e;
			switch (e.NodeType)
			{
				case ExpressionType.Lambda:
					{
						var mi = (LambdaExpression)e;

						foreach (var c in mi.Parameters)
							yield return c;

						foreach (var c in mi.Body.SelfAndChildren())
							yield return c;

						break;
					}
				case ExpressionType.MemberInit:
					{
						var mi = (MemberInitExpression)e;

						foreach (var c in mi.NewExpression.SelfAndChildren())
							yield return c;

						foreach (var b in mi.Bindings)
						{
							switch (b.BindingType)
							{
								case MemberBindingType.Assignment:
									{
										var oe = ((MemberAssignment)b).Expression;
										foreach (var c in oe.SelfAndChildren())
											yield return c;
									}
									break;
								case MemberBindingType.ListBinding:
								case MemberBindingType.MemberBinding:
								default:
									throw new NotSupportedException();
							}
						}
						break;
					}
				case ExpressionType.New:
					{
						var ne = (NewExpression)e;
						foreach (var arg in ne.Arguments)
							foreach (var c in arg.SelfAndChildren())
								yield return c;
						break;
					}
				case ExpressionType.NewArrayInit:
					{
						var nae = (NewArrayExpression)e;
						foreach (var arg in nae.Expressions)
							foreach (var c in arg.SelfAndChildren())
								yield return c;
						break;
					}
				case ExpressionType.MemberAccess:
					{
						var ma = (MemberExpression)e;
						foreach (var c in ma.Expression.SelfAndChildren())
							yield return c;
						break;
					}
				case ExpressionType.Call:
					{
						var ce = (MethodCallExpression)e;
						if (ce.Object != null)
							foreach (var c in ce.Object.SelfAndChildren())
								yield return c;
						foreach (var arg in ce.Arguments)
							foreach (var c in arg.SelfAndChildren())
								yield return c;
						break;
					}
				default:
					var be = e as BinaryExpression;
					if (be != null)
					{
						foreach (var c in be.Left.SelfAndChildren())
							yield return c;

						foreach (var c in be.Right.SelfAndChildren())
							yield return c;

					}
					var ue = e as UnaryExpression;
					if (ue != null)
					{
						foreach (var c in ue.Operand.SelfAndChildren())
							yield return c;
					}
					throw new NotSupportedException();
			}
		}

		public static void CollectArguments(this Expression exp, ICollection<ParameterExpression> list)
		{
			Visit(exp, (e, l, i, enter) =>
			{
				if (!enter)
					return true;
				if (e.NodeType != ExpressionType.Parameter)
					return true;
				var pe = (ParameterExpression)e;
				var v = list.FirstOrDefault((ex) => ex.Name == pe.Name);
				if (v == null)
				{
					list.Add(pe);
					return true;
				}
				if (v != pe)
					throw new ArgumentException();
				return true;

			});
		}

		public static bool Visit(this Expression exp, Func<Expression, int, int, bool, bool> visitor)
		{
			return Visit(exp, 0, 0, visitor);
		}

		static bool Visit(Expression exp, int level, int index, Func<Expression, int, int, bool, bool> visitor)
		{
			if (!visitor(exp, level, index, true))
				return false;
			switch (exp.NodeType)
			{
				case ExpressionType.Parameter:
				case ExpressionType.Constant:
					break;
				case ExpressionType.MemberAccess:
					{
						var me = (MemberExpression)exp;
						if (me.Expression != null && !Visit(me.Expression, level + 1, 0, visitor))
							return false;
						break;
					}
				case ExpressionType.MemberInit:
					{
						var mi = (MemberInitExpression)exp;
						Visit(mi.NewExpression, level + 1, 0, visitor);
						var idx = 1;
						foreach (var b in mi.Bindings)
						{
							switch (b.BindingType)
							{
								case MemberBindingType.Assignment:
									Visit(((MemberAssignment)b).Expression, level + 1, idx++, visitor);
									break;
								default:
									throw new NotSupportedException();
							}
						}
						break;
					}
				case ExpressionType.New:
					{
						var ne = (NewExpression)exp;
						var idx = 0;
						var nl = level + 1;
						foreach (var a in ne.Arguments)
							if (!Visit(a, nl, idx++, visitor))
								return false;
						break;
					}
				case ExpressionType.NewArrayInit:
					{
						var ne = (NewArrayExpression)exp;
						var idx = 0;
						var nl = level + 1;
						foreach (var a in ne.Expressions)
							if (!Visit(a, nl, idx++, visitor))
								return false;
						break;
					}
				case ExpressionType.Call:
					{
						var me = (MethodCallExpression)exp;
						var idx = 0;
						var nl = level + 1;
						if (me.Object != null && !Visit(me.Object, nl, idx++, visitor))
							return false;
						foreach (var a in me.Arguments)
							if (!Visit(a, nl, idx++, visitor))
								return false;
						break;
					}
				default:
					var be = exp as BinaryExpression;
					if (be != null)
					{
						if (!Visit(be.Left, level + 1, 0, visitor))
							return false;
						if (!Visit(be.Right, level + 1, 1, visitor))
							return false;
						break;
					}
					var ue = exp as UnaryExpression;
					if (ue != null)
					{
						if (!Visit(ue.Operand, level + 1, 0, visitor))
							return false;
						break;
					}
					throw new NotSupportedException();
			}
			return visitor(exp, level, index, false);
		}
		public static MemberBinding Replace(this MemberBinding b, Func<Expression, Expression> Mapper)
		{
			switch (b.BindingType)
			{
				case MemberBindingType.Assignment:
					{
						var oe = ((MemberAssignment)b).Expression;
						var ne = oe.Replace(Mapper);
						if (oe == ne) return b;
						return Expression.Bind(b.Member, ne);
					}
				case MemberBindingType.ListBinding:
				case MemberBindingType.MemberBinding:
				default:
					throw new NotSupportedException();
			}
		}
		public static Expression Replace(this Expression expr, Func<Expression, Expression> Mapper)
		{
			var e = Mapper(expr);
			if (e == null || e!=expr)
				return e;

			switch (e.NodeType)
			{
				case ExpressionType.Lambda:
					{
						var mi = (LambdaExpression)e;
						var newBody = (NewExpression)Replace(mi.Body, Mapper);
						var newArgs = mi.Parameters.Select(Mapper).Cast<ParameterExpression>().ToArray();
						if (newBody == mi.Body && newArgs.AllEquals(mi.Parameters))
							return e;

						return Expression.Lambda(newBody, newArgs);
					}
				case ExpressionType.MemberInit:
					{
						var mi = (MemberInitExpression)e;
						var newExpr = (NewExpression)Replace(mi.NewExpression, Mapper);
						var binds = mi.Bindings.Select(ie => Replace(ie, Mapper)).ToArray();
						if (newExpr == mi.NewExpression && binds.AllEquals(mi.Bindings))
							return e;
						return Expression.MemberInit(newExpr, binds);
					}
				case ExpressionType.New:
					{
						var ne = (NewExpression)e;
						var args = ne.Arguments.Select(a => a.Replace(Mapper)).ToArray();
						if (args.AllEquals(ne.Arguments))
							return e;
						return Create(ne.Type, args);
					}
				case ExpressionType.NewArrayInit:
					{
						var nae = (NewArrayExpression)e;
						var args = nae.Expressions.Select(a => a.Replace(Mapper)).ToArray();
						if (args.AllEquals(nae.Expressions))
							return e;
						return Expression.NewArrayInit(
							nae.Type.GetElementType(),
							args
							);
					}
				case ExpressionType.MemberAccess:
					{
						var ma = (MemberExpression)e;
						var ne = ma.Expression.Replace(Mapper);
						if (ne == ma.Expression)
							return e;
						return Expression.MakeMemberAccess(ne, ma.Member);
					}
				case ExpressionType.Constant:
					{
						return e;
					}
				case ExpressionType.Call:
					{
						var c = (MethodCallExpression)e;
						var nobj = c.Object == null ? null : c.Object.Replace(Mapper);
						var nargs = c.Arguments.Select(a => a.Replace(Mapper)).ToArray();
						if (nobj == c.Object && nargs.AllEquals(c.Arguments))
							return e;
						return Expression.Call(
							nobj,
							c.Method,
							nargs
							);
					}
				default:

					var be = e as BinaryExpression;
					if (be != null)
					{
						var nl = be.Left.Replace(Mapper);
						var nr = be.Right.Replace(Mapper);
						if (nl == be.Left && nr == be.Right)
							return e;
						return Expression.MakeBinary(
							e.NodeType,
							nl,
							nr,
							be.IsLifted,
							be.Method,
							be.Conversion
							);
					}
					var ue = e as UnaryExpression;
					if (ue != null)
					{
						var nue = ue.Operand.Replace(Mapper);
						if (nue == ue.Operand)
							return e;
						return Expression.MakeUnary(
							e.NodeType,
							nue,
							ue.Type,
							ue.Method
							);
					}
					if (e is ParameterExpression)
						return e;

					throw new NotSupportedException();
			}
		}

		public static Expression Replace(this Expression expr, Dictionary<Expression, Expression> args)
		{
			return expr.Replace(e =>
			{
				if (args.TryGetValue(e, out var ne))
					return ne;
				return e;
			});
		}

		public static MemberBinding Replace(this MemberBinding expr, Dictionary<Expression, Expression> args)
		{
			return expr.Replace(e =>
			{
				if (args.TryGetValue(e, out var ne))
					return ne;
				return e;
			});
		}
		public static Expression ReplaceAndValidateReference(
			this Expression expr,
			Dictionary<Expression, Expression> args
			)
		{
			return expr.Replace(e =>
			{
				if (args.TryGetValue(e, out var ne))
					return ne;
				var r = e as ConstantExpression;
				if (r != null)
				{
					var type = r.Type;
					if (type.HasElementType)
						type = type.GetElementType();
					if (type.IsGenericType)
					{
						var gt = type.GetGenericTypeDefinition();
						if (gt == typeof(IEnumerable<>) || gt == typeof(Dictionary<,>) || gt == typeof(List<>))
							type = gt.GetGenericArguments().Last();
					}
					if (!type.IsConstType())
						throw new NotSupportedException($"表达式不支持类型为{r.Type}的引用:{r.Value}");
				}
				return e;
			});
		}

	}
}


text:
import datetime
from In.core.object_meta import ObjectMeta

class OAuthLoginMeta(ObjectMeta):

	__class_type_base_name__ = 'OAuthLoginBase'
	__class_type_name__ = 'OAuthLogin'

class OAuthLoginBase(Object, metaclass = OAuthLoginMeta):
	'''Base class of all IN OAuthLoginBase.

	'''
	__allowed_children__ = None
	__default_child__ = None

@IN.register('OAuthLogin', type = 'OAuthLogin')
class OAuthLogin(OAuthLoginBase):
	'''Base class of all IN OAuthLoginBase.

	'''

class OAuthLoginManager:
	''''''

	def add_connection_if_not_exists(self, nabar_id, oauth_nabar_id, provider):

		# add new oauth connection if not exists

		try:

			db = IN.db
			cursor = db.execute('''select o.id
				FROM account.oauth_connection o
				where
				o.nabar_id = %(nabar_id)s AND
				o.oauth_nabar_id = %(oauth_nabar_id)s AND
				o.provider = %(provider)s
				''', {
				'nabar_id' : nabar_id,
				'oauth_nabar_id' : oauth_nabar_id,
				'provider' : provider,
			})

			if cursor.rowcount == 0:
				db.insert({
					'table' : 'account.oauth_connection',
					'columns' : ['nabar_id', 'oauth_nabar_id', 'provider'],
					'values' : [
						[nabar_id, oauth_nabar_id, provider]
					]
				}).execute()

				db.connection.commit()

		except Exception as e:
			IN.logger.debug()
			db.connection.rollback()

	def add_email_if_not_exists(self, nabar_id, email):

		try:

			db = IN.db

			# add new email if not exists

			cursor = db.execute('''select l.nabar_id
				FROM account.login l
				JOIN account.nabar a ON l.nabar_id = a.id
				where a.status = 1  AND
				l.type = %(type)s and l.status = 1 AND
				l.value = %(email)s
				LIMIT 1''', {
				'type' : 'email',
				'email' : email,
			})

			if cursor.rowcount == 0:

				login_id = In.nabar.NabarLogin({
					'id' : None,				# new login
					'nabar_id' : nabar_id,
					'value' : email,
					'type' : 'email',
					'created' : datetime.datetime.now(),
					'status' : IN.nabar.NABAR_STATUS_ACTIVE, # active
				}).insert()

				db.connection.commit()

		except Exception as e:
			IN.logger.debug()
			db.connection.rollback()

	def register_nabar(self, name, email, gender = 1):

		if type(gender) is str:
			gender = gender.lower()
			try:
				gender = {'female' : 0,  'male' : 1, 'shemale' : 2}[gender] # throw error
			except Exception as e1:
				gender = 1 # default

		nabar_id = In.nabar.Nabar({
			'id' : None,		# new nabar
			'name' : name,		# display name
			'gender' : gender,
			'created' : datetime.datetime.now(),
			'status' : IN.nabar.NABAR_STATUS_ACTIVE, 		# disabled by default
			'roles' : [IN.nabar.confirmed_role_id],
			'data' : {
				'primary_email' : email
			},
		}).insert(False)

		if not nabar_id:
			return

		nabar = IN.entitier.load_single('Nabar', nabar_id)

		# update the nabar_id and nabar cache
		nabar.nabar_id = nabar_id
		nabar.save()

		return nabar_id

@IN.hook
def In_app_init(app):
	# set the messenger

	IN.oauth_login = OAuthLoginManager()


text:
#if !defined(CETTY_CRAFT_BUILDER_CRAFTRPCCLIENTBUILDER_H)
#define CETTY_CRAFT_BUILDER_CRAFTRPCCLIENTBUILDER_H

#include <cetty/protobuf/service/builder/ProtobufClientBuilder.h>

namespace cetty {
namespace craft {
namespace builder {

using namespace cetty::channel;
using namespace cetty::protobuf::service::builder;

class CraftClientBuilder : private boost::noncopyable {
public:
    CraftClientBuilder();
    CraftClientBuilder(int threadCnt);
    CraftClientBuilder(const EventLoopPtr& eventLoop);
    CraftClientBuilder(const EventLoopPoolPtr& eventLoopPool);

    void setServiceInitializer(const Channel::PipelineInitializer& initializer) {
        builder_.setServiceInitializer(initializer);
    }

    void addConnection(const std::string& host, int port, int limit = 1) {
        builder_.addConnection(host, port, limit);
    }

    ChannelPtr build() {
        return builder_.build();
    }

private:
    ProtobufClientBuilder builder_;
};

}
}
}

#endif //#if !defined(CETTY_CRAFT_BUILDER_CRAFTRPCCLIENTBUILDER_H)

// Local Variables:
// mode: c++
// End:


text:
package org.hippoecm.repository.quartz;

import java.text.ParseException;
import java.util.Collection;
import java.util.Date;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;

import org.apache.commons.lang.StringUtils;
import org.hippoecm.repository.util.JcrUtils;
import org.onehippo.repository.scheduling.RepositoryJobCronTrigger;
import org.onehippo.repository.scheduling.RepositoryJobInfo;
import org.onehippo.repository.scheduling.RepositoryJobSimpleTrigger;
import org.onehippo.repository.scheduling.RepositoryJobTrigger;
import org.onehippo.repository.scheduling.RepositoryScheduler;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.impl.triggers.SimpleTriggerImpl;

import static org.hippoecm.repository.quartz.HippoSchedJcrConstants.HIPPOSCHED_ATTRIBUTE_NAMES;
import static org.hippoecm.repository.quartz.HippoSchedJcrConstants.HIPPOSCHED_ATTRIBUTE_VALUES;
import static org.hippoecm.repository.quartz.HippoSchedJcrConstants.HIPPOSCHED_JOBGROUP;
import static org.hippoecm.repository.quartz.HippoSchedJcrConstants.HIPPOSCHED_REPOSITORY_JOB;
import static org.hippoecm.repository.quartz.HippoSchedJcrConstants.HIPPOSCHED_REPOSITORY_JOB_CLASS;

/**
 * RepositoryScheduler service implementation.
 */
public class RepositorySchedulerImpl implements RepositoryScheduler {

    private final Session session;
    private final JCRScheduler scheduler;

    RepositorySchedulerImpl(Session session, JCRScheduler scheduler) {
        this.session = session;
        this.scheduler = scheduler;
    }

    @Override
    public void scheduleJob(final RepositoryJobInfo jobInfo, final RepositoryJobTrigger trigger) throws RepositoryException {
        synchronized (session) {
            try {
                scheduler.scheduleJob(createQuartzJobDetail(jobInfo), createQuartzTrigger(trigger));
            } catch (SchedulerException e) {
                throw new RepositoryException(e);
            }
        }
    }

    @Override
    public void deleteJob(final String jobName, final String groupName) throws RepositoryException {
        synchronized (session) {
            final Node jobNode = getJobNode(jobName, groupName);
            if (jobNode != null) {
                jobNode.remove();
                session.save();
            }
        }
    }

    @Override
    public void deleteJob(final String jobIdentifier) throws RepositoryException {
        synchronized (session) {
            final Node jobNode = session.getNodeByIdentifier(jobIdentifier);
            if (jobNode != null) {
                jobNode.remove();
                session.save();
            }
        }
    }

    @Override
    public boolean checkExists(final String jobName, final String groupName) throws RepositoryException {
        return getJobNode(jobName, groupName) != null;
    }

    @Override
    public void executeJob(final String jobName, String groupName) throws RepositoryException {
        final Node jobNode = getJobNode(jobName, groupName);
        if (jobNode == null) {
            throw new RepositoryException("No such job: " + getGroupName(groupName) + "/" + jobName);
        }
        executeJob(jobNode.getIdentifier());
    }

    @Override
    public void executeJob(final String jobIdentifier) throws RepositoryException {
        try {
            final RepositoryJobDetail jobDetail = (RepositoryJobDetail) scheduler.getJobDetail(new JobKey(jobIdentifier));
            final Job job = jobDetail.getJobClass().newInstance();
            job.execute(new JobExecutionContextImpl(scheduler, jobDetail));
        } catch (SchedulerException | InstantiationException | IllegalAccessException e) {
            throw new RepositoryException(e);
        }
    }

    private Trigger createQuartzTrigger(final RepositoryJobTrigger trigger) throws RepositoryException {
        if (trigger instanceof RepositoryJobCronTrigger) {
            final String cronExpression = ((RepositoryJobCronTrigger) trigger).getCronExpression();
            try {
                return new CronTriggerImpl(trigger.getName(), null, cronExpression);
            } catch (ParseException e) {
                throw new RepositoryException(e);
            }
        }
        if (trigger instanceof RepositoryJobSimpleTrigger) {
            final Date startTime = ((RepositoryJobSimpleTrigger) trigger).getStartTime();
            final int repeatCount = ((RepositoryJobSimpleTrigger) trigger).getRepeatCount();
            final long repeatInterval = ((RepositoryJobSimpleTrigger) trigger).getRepeatInterval();
            if (repeatCount != 0) {
                return new SimpleTriggerImpl(trigger.getName(), startTime, null, repeatCount, repeatInterval);
            } else {
                return new SimpleTriggerImpl(trigger.getName(), startTime);
            }
        }
        throw new RepositoryException("Unknown trigger type " + trigger.getClass().getName());
    }

    private JobDetail createQuartzJobDetail(final RepositoryJobInfo jobInfo) throws RepositoryException {
        Node jobNode = jobInfo.createNode(session);
        if (jobNode == null) {
            jobNode = newJobNode(jobInfo);
        }
        jobNode.setProperty(HIPPOSCHED_REPOSITORY_JOB_CLASS, jobInfo.getJobClass().getName());
        jobNode.setProperty(HIPPOSCHED_ATTRIBUTE_NAMES, attributeNames(jobInfo));
        jobNode.setProperty(HIPPOSCHED_ATTRIBUTE_VALUES, attributeValues(jobInfo));

        return new RepositoryJobDetail(jobNode, jobInfo);
    }

    private Node newJobNode(final RepositoryJobInfo info) throws RepositoryException {
        final String name = info.getName();
        final String group = info.getGroup();
        final Node moduleConfig = session.getNode(SchedulerModule.getModuleConfigPath());
        final Node jobGroup;
        if (moduleConfig.hasNode(group)) {
            jobGroup = moduleConfig.getNode(group);
        } else {
            jobGroup = moduleConfig.addNode(group, HIPPOSCHED_JOBGROUP);
        }
        if (jobGroup.hasNode(name)) {
            throw new RepositoryException("A job with name '" + name + "' already exists in job group '" + group + "'");
        }
        return jobGroup.addNode(name, HIPPOSCHED_REPOSITORY_JOB);
    }

    private Node getJobNode(final String jobName, final String groupName) throws RepositoryException {
        synchronized (session) {
            final Node moduleConfig = session.getNode(SchedulerModule.getModuleConfigPath());
            final Node groupNode = JcrUtils.getNodeIfExists(moduleConfig, getGroupName(groupName));
            if (groupNode != null) {
                return JcrUtils.getNodeIfExists(groupNode, jobName);
            }
        }
        return null;
    }

    private String getGroupName(final String groupName) {
        return StringUtils.isEmpty(groupName) ? "default" : groupName;
    }

    private String[] attributeNames(final RepositoryJobInfo info) {
        final Collection<String> attributeNames = info.getAttributeNames();
        return attributeNames.toArray(new String[attributeNames.size()]);
    }

    private String[] attributeValues(final RepositoryJobInfo info) {
        final Collection<String> attributeNames = info.getAttributeNames();
        final String[] attributeValues = new String[attributeNames.size()];
        int i = 0;
        for (String attributeName : attributeNames) {
            attributeValues[i] = info.getAttribute(attributeName);
            i++;
        }
        return attributeValues;
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/AbituHub.iml" filepath="$PROJECT_DIR$/.idea/modules/AbituHub.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/app/app.iml" filepath="$PROJECT_DIR$/.idea/modules/app/app.iml" />
    </modules>
  </component>
</project>


text:
[Morse](https://github.com/morse-simulator/morse) robotic simulator in a docker container

1st release - testing runtime case studies..

to use it in your [docker](http://docker.com) setup:

    docker pull giodegas/morse
    docker run -it giodegas/morse morse --noaudio check

you should get this output log:

    * Checking up your environment...
    * Running on Linux. Alright.
    * Found MORSE libraries in '/usr/local/lib/python3.4/site-packages/morse/blender'. Alright.
    * Trying to figure out a prefix from the script location...
    * Default scene found. The prefix seems ok. Using it.
    * Setting $MORSE_ROOT environment variable to default prefix [/usr/local/]
    * Checking version of /opt/blender/blender-2.73-linux-glibc211-x86_64/blender... Found v.2.73.0
    * Blender found from $MORSE_BLENDER. Using it (Blender v.2.73.0)
    * Checking version of Python within Blender /opt/blender/blender-2.73-linux-glibc211-x86_64/blender... Found v.3.4.2
    * Blender emitted errors during launch:
    AL lib: (EE) ALCplaybackOSS_open: Could not open /dev/dsp: No such file or directory
    * Blender and Morse are using Python 3.4.2. Alright.
    * Your environment is correctly setup to run MORSE.

then you can interact with morse:

    $ docker start <container>
    $ docker exec -it <container> /bin/bash
    # morse --noaudio create <your_scene>
    # morse --noaudio run <your_scene> -noaudio

if you have problem running under X, debug trying to make x11-apps to launch

    $ docker start <container>
    $ docker exec -it <container> /bin/bash
    # xeyes &

or use [subuser](https://github.com/subuser-security/subuser).

## Fastmode graphics

As described in the [morse installation documentation](http://www.openrobots.org/morse/doc/1.2/user/installation.html), using the

    fastmode=True

in your scene contructors, morse will render you scene in wireframe mode, but some camera sensors will not be available.


text:
from bokeh.charts import Scatter, output_file, show
from bokeh.sampledata.autompg import autompg as df

tooltips=[
    ('Cylinders', '@cyl'),
    ('Displacement', '@displ'),
    ('Weight', '@weight'),
    ('Acceleration', '@accel')
]

p = Scatter(df, x='mpg', y='hp', title="HP vs MPG",
            xlabel="Miles Per Gallon", ylabel="Horsepower",
            tooltips=tooltips)

output_file("scatter.html")

show(p)


text:
.. _building-c-or-cython-extensions:

======================
C or Cython Extensions
======================

.. warning::

   This page has not been fully adapted from astropy

Scikit-beam supports using C extensions for wrapping C libraries and Cython for
speeding up computationally-intensive calculations. Both Cython and C extension
building can be customized using the ``get_extensions`` function of the
``setup_package.py`` file. If defined, this function must return a list of
:class:`distutils.core.Extension` objects. The creation process is left to the
subpackage designer, and can be customized however is relevant for the
extensions in the subpackage.

While C extensions must always be defined through the ``get_extensions``
mechanism, Cython files (ending in ``.pyx``) are automatically located and
loaded in separate extensions if they are not in ``get_extensions``. For
Cython extensions located in this way, headers for numpy C functions are
included in the build, but no other external headers are included. ``.pyx``
files present in the extensions returned by ``get_extensions`` are not
included in the list of extensions automatically generated extensions. Note
that this allows disabling a Cython file by providing an extension that
includes the Cython file, but giving it the special ``name`` 'cython_skip'. Any
extension with this package name will not be built by ``setup.py``.

.. note::

    If an :class:`~distutils.core.Extension` object is provided for Cython
    source files using the ``get_extensions`` mechanism, it is very
    important that the ``.pyx`` files be given as the ``source``, rather than the
    ``.c`` files generated by Cython.

Installing C header files
-------------------------

If your C extension needs to be linked from other third-party C code,
you probably want to install its header files along side the Python module.

    1) Create an ``include`` directory inside of your package for
       all of the header files.

    2) Use the ``get_package_data`` hook in ``setup_package.py`` to
       install those header files.  For example, the ``scikit-beam.wcs``
       package has this::

           def get_package_data():
               return {'scikit-beam.wcs': ['include/*.h']}

Preventing importing at build time
----------------------------------

In rare cases, some packages may need to be imported at build time.
Unfortunately, anything that requires a C or Cython extension will fail to
import until the build phase has completed. In this cases, the
``_ASTROPY_SETUP_`` variable can be used to determine if the package is being
imported as part of the build and choose to not import problematic modules.
``_ASTROPY_SETUP_`` is inserted into the builtins, and is `True` when inside
of scikit-beam's ``setup.py`` script, and `False` otherwise.

For example, suppose there is a subpackage ``foo`` that needs to
import a module called ``version.py`` at build time in order to set
some version information, and also has a C extension, ``process``,
that will not be available in the source tree.  In this case,
``scikit-beam/foo/__init__.py`` would probably want to check the value of
``_ASTROPY_SETUP_`` before importing the C extension::

    try:
        from . import process
    except ImportError:
        if not _ASTROPY_SETUP_:
            raise

    from . import version


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

namespace AjaxControlToolkit {

    public class MultipartFormDataParser {
        const string EOF = "\r\n";

        public static FileHeaderInfo ParseHeaderInfo(byte[] bytes, Encoding encoding) {
            var data = Parse(bytes, encoding);
            FileHeaderInfo result = null;
            foreach(var s in data.Boundaries) {
                if(s.Contains("Content-Disposition")) {
                    var nameMatch = new Regex(@"(?<=name\=\"")(.*?)(?=\"")").Match(s);
                    var fileNameMatch = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")").Match(s);

                    if(nameMatch.Success && fileNameMatch.Success && nameMatch.Value == "act-file-data") {
                        // Look for Content-Type
                        var re = new Regex(@"(?<=Content\-Type:)(.*?)(?=" + EOF + EOF + ")");
                        var contentTypeMatch = re.Match(data.Source);

                        if(!contentTypeMatch.Success)
                            return null;

                        // Find start index position of file contents. That should be 2 lines after Content Type.
                        var startIndexOld = contentTypeMatch.Index + contentTypeMatch.Length + (EOF + EOF).Length;
                        var startIndex = GetContentTypeIndex(bytes, encoding, contentTypeMatch.Value) + contentTypeMatch.Length + (EOF + EOF).Length;

                        result = new FileHeaderInfo {
                            StartIndex = startIndex,
                            BoundaryDelimiterLength = (EOF + data.Delimiter + EOF + EOF).Length,
                            //endIndex - startIndex,
                            FileName = fileNameMatch.Value.Trim(),
                            ContentType = contentTypeMatch.Value.Trim()
                        };
                    }
                }
            }

            return result;
        }

        static int GetContentTypeIndex(byte[] bytes,  Encoding encoding, string contentTypeString) {
            var contentTypeBytes = encoding.GetBytes(contentTypeString);
            return bytes.StartingIndex(contentTypeBytes).First();
        }

        static MultipartFormData Parse(byte[] bytes, Encoding encoding) {
            var source = encoding.GetString(bytes);
            var firstEofIndex = source.IndexOf(EOF);
            if(firstEofIndex < 0)
                return null;

            var boundaryDelimiter = source.Substring(0, firstEofIndex);
            var boundaries = source.Split(new[] { boundaryDelimiter }, StringSplitOptions.RemoveEmptyEntries);
            return new MultipartFormData {
                Boundaries = boundaries,
                Delimiter = boundaryDelimiter,
                Source = source
            };
        }

        class MultipartFormData {
            internal string[] Boundaries { get; set; }
            internal string Source { get; set; }
            internal string Delimiter { get; set; }
        }
    }

}


text:
<?xml version="1.0"?>
<doc>
<assembly>
<name>
Jeopardyized!
</name>
</assembly>
<members>
<member name="P:Jeopardized_.My.Resources.Resources.ResourceManager">
	<summary>
  Returns the cached ResourceManager instance used by this class.
</summary>
</member><member name="P:Jeopardized_.My.Resources.Resources.Culture">
	<summary>
  Overrides the current thread's CurrentUICulture property for all
  resource lookups using this strongly typed resource class.
</summary>
</member><member name="T:Jeopardized_.My.Resources.Resources">
	<summary>
  A strongly-typed resource class, for looking up localized strings, etc.
</summary>
</member>
</members>
</doc>


text:
package com.microsoft.azure.management.digitaltwins.v2020_03_01_preview.implementation;

import com.microsoft.azure.AzureClient;
import com.microsoft.azure.AzureServiceClient;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import com.microsoft.rest.RestClient;

/**
 * Initializes a new instance of the AzureDigitalTwinsManagementClientImpl class.
 */
public class AzureDigitalTwinsManagementClientImpl extends AzureServiceClient {
    /** the {@link AzureClient} used for long running operations. */
    private AzureClient azureClient;

    /**
     * Gets the {@link AzureClient} used for long running operations.
     * @return the azure client;
     */
    public AzureClient getAzureClient() {
        return this.azureClient;
    }

    /** The subscription identifier. */
    private String subscriptionId;

    /**
     * Gets The subscription identifier.
     *
     * @return the subscriptionId value.
     */
    public String subscriptionId() {
        return this.subscriptionId;
    }

    /**
     * Sets The subscription identifier.
     *
     * @param subscriptionId the subscriptionId value.
     * @return the service client itself
     */
    public AzureDigitalTwinsManagementClientImpl withSubscriptionId(String subscriptionId) {
        this.subscriptionId = subscriptionId;
        return this;
    }

    /** Version of the DigitalTwinsInstance Management API. */
    private String apiVersion;

    /**
     * Gets Version of the DigitalTwinsInstance Management API.
     *
     * @return the apiVersion value.
     */
    public String apiVersion() {
        return this.apiVersion;
    }

    /** The preferred language for the response. */
    private String acceptLanguage;

    /**
     * Gets The preferred language for the response.
     *
     * @return the acceptLanguage value.
     */
    public String acceptLanguage() {
        return this.acceptLanguage;
    }

    /**
     * Sets The preferred language for the response.
     *
     * @param acceptLanguage the acceptLanguage value.
     * @return the service client itself
     */
    public AzureDigitalTwinsManagementClientImpl withAcceptLanguage(String acceptLanguage) {
        this.acceptLanguage = acceptLanguage;
        return this;
    }

    /** The retry timeout in seconds for Long Running Operations. Default value is 30. */
    private int longRunningOperationRetryTimeout;

    /**
     * Gets The retry timeout in seconds for Long Running Operations. Default value is 30.
     *
     * @return the longRunningOperationRetryTimeout value.
     */
    public int longRunningOperationRetryTimeout() {
        return this.longRunningOperationRetryTimeout;
    }

    /**
     * Sets The retry timeout in seconds for Long Running Operations. Default value is 30.
     *
     * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value.
     * @return the service client itself
     */
    public AzureDigitalTwinsManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) {
        this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout;
        return this;
    }

    /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */
    private boolean generateClientRequestId;

    /**
     * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
     *
     * @return the generateClientRequestId value.
     */
    public boolean generateClientRequestId() {
        return this.generateClientRequestId;
    }

    /**
     * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true.
     *
     * @param generateClientRequestId the generateClientRequestId value.
     * @return the service client itself
     */
    public AzureDigitalTwinsManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) {
        this.generateClientRequestId = generateClientRequestId;
        return this;
    }

    /**
     * The DigitalTwinsInner object to access its operations.
     */
    private DigitalTwinsInner digitalTwins;

    /**
     * Gets the DigitalTwinsInner object to access its operations.
     * @return the DigitalTwinsInner object.
     */
    public DigitalTwinsInner digitalTwins() {
        return this.digitalTwins;
    }

    /**
     * The DigitalTwinsEndpointsInner object to access its operations.
     */
    private DigitalTwinsEndpointsInner digitalTwinsEndpoints;

    /**
     * Gets the DigitalTwinsEndpointsInner object to access its operations.
     * @return the DigitalTwinsEndpointsInner object.
     */
    public DigitalTwinsEndpointsInner digitalTwinsEndpoints() {
        return this.digitalTwinsEndpoints;
    }

    /**
     * The OperationsInner object to access its operations.
     */
    private OperationsInner operations;

    /**
     * Gets the OperationsInner object to access its operations.
     * @return the OperationsInner object.
     */
    public OperationsInner operations() {
        return this.operations;
    }

    /**
     * Initializes an instance of AzureDigitalTwinsManagementClient client.
     *
     * @param credentials the management credentials for Azure
     */
    public AzureDigitalTwinsManagementClientImpl(ServiceClientCredentials credentials) {
        this("https://management.azure.com", credentials);
    }

    /**
     * Initializes an instance of AzureDigitalTwinsManagementClient client.
     *
     * @param baseUrl the base URL of the host
     * @param credentials the management credentials for Azure
     */
    public AzureDigitalTwinsManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) {
        super(baseUrl, credentials);
        initialize();
    }

    /**
     * Initializes an instance of AzureDigitalTwinsManagementClient client.
     *
     * @param restClient the REST client to connect to Azure.
     */
    public AzureDigitalTwinsManagementClientImpl(RestClient restClient) {
        super(restClient);
        initialize();
    }

    protected void initialize() {
        this.apiVersion = "2020-03-01-preview";
        this.acceptLanguage = "en-US";
        this.longRunningOperationRetryTimeout = 30;
        this.generateClientRequestId = true;
        this.digitalTwins = new DigitalTwinsInner(restClient().retrofit(), this);
        this.digitalTwinsEndpoints = new DigitalTwinsEndpointsInner(restClient().retrofit(), this);
        this.operations = new OperationsInner(restClient().retrofit(), this);
        this.azureClient = new AzureClient(this);
    }

    /**
     * Gets the User-Agent header for the client.
     *
     * @return the user agent string.
     */
    @Override
    public String userAgent() {
        return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "AzureDigitalTwinsManagementClient", "2020-03-01-preview");
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.wpi.first.wpilibj.autonomous;

import edu.wpi.first.wpilibj.Loader_3;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 * @author johnw_000
 */
public class DropLoaderArm extends Command{
	private final Loader_3 load;
	private double loadTime;
	private double startTime;
	private boolean isDown;
	public DropLoaderArm(Loader_3 load){
		this.load = (Loader_3) load;
	}
	protected void initialize() {
		this.setInterruptible(false);
		startTime = 0;
		loadTime = .5;
		isDown = false;
	}

	protected void execute() {

		startTime = Timer.getFPGATimestamp();
		if(Timer.getFPGATimestamp() <=  startTime + loadTime){
			load.runLoader(-.3);
			isDown = true;
		}
	}

	protected boolean isFinished() {
		return isDown;

	}

	protected void end() {

	}

	protected void interrupted() {

	}

}


text:
{% extends "base.html" %}
{% block title %}{{ _('File not found.')}}{% endblock %}
{% block content %}
<h1>{{ _('File not found.')}}</h1>
{% endblock %}


text:
#ifndef OSMIUM_OSM_DIFF_OBJECT_HPP
#define OSMIUM_OSM_DIFF_OBJECT_HPP

#include <osmium/osm/item_type.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>

namespace osmium {

    class Node;
    class Way;
    class Relation;

    class DiffObject {

    protected:

        osmium::OSMObject* m_prev;
        osmium::OSMObject* m_curr;
        osmium::OSMObject* m_next;

    public:

        DiffObject() noexcept :
            m_prev(nullptr),
            m_curr(nullptr),
            m_next(nullptr) {
        }

        explicit DiffObject(osmium::OSMObject& prev, osmium::OSMObject& curr, osmium::OSMObject& next) noexcept :
            m_prev(&prev),
            m_curr(&curr),
            m_next(&next) {
        }

        DiffObject(const DiffObject&) = default;
        DiffObject& operator=(const DiffObject&) = default;

        DiffObject(DiffObject&&) = default;
        DiffObject& operator=(DiffObject&&) = default;

        const osmium::OSMObject& prev() const noexcept {
            return *m_prev;
        }

        const osmium::OSMObject& curr() const noexcept {
            return *m_curr;
        }

        const osmium::OSMObject& next() const noexcept {
            return *m_next;
        }

        bool first() const noexcept {
            return m_prev == m_curr;
        }

        bool last() const noexcept {
            return m_curr == m_next;
        }

        osmium::item_type type() const noexcept {
            return m_curr->type();
        }

        osmium::object_id_type id() const noexcept {
            return m_curr->id();
        }

        osmium::object_version_type version() const noexcept {
            return m_curr->version();
        }

        osmium::changeset_id_type changeset() const noexcept {
            return m_curr->changeset();
        }

        const osmium::Timestamp start_time() const noexcept {
            return m_curr->timestamp();
        }

        /**
         * Return the timestamp when the current version of the object is
         * not valid any more, ie the time when the next version of the object
         * is valid. If this is the last version of the object, this will
         * return a special "end of time" timestamp that is guaranteed to
         * be larger than any normal timestamp.
         */
        const osmium::Timestamp end_time() const noexcept {
            return last() ? osmium::end_of_time() : m_next->timestamp();
        }

        /**
         * Current object version is valid between time "from" (inclusive) and
         * time "to" (not inclusive).
         *
         * This is a bit more complex than you'd think, because we have to
         * handle the case properly where the start_time() == end_time().
         */
        bool is_between(const osmium::Timestamp& from, const osmium::Timestamp& to) const noexcept {
            return start_time() < to &&
                   ((start_time() != end_time() && end_time() >  from) ||
                    (start_time() == end_time() && end_time() >= from));
        }

        /**
         * Current object version is visible at the given timestamp.
         */
        bool is_visible_at(const osmium::Timestamp& timestamp) const noexcept {
            return start_time() <= timestamp && end_time() > timestamp && m_curr->visible();
        }

    }; // class DiffObject

    template <class T>
    class DiffObjectDerived : public DiffObject {

    public:

        DiffObjectDerived(T& prev, T& curr, T& next) noexcept :
            DiffObject(prev, curr, next) {
        }

        DiffObjectDerived(const DiffObjectDerived&) = default;
        DiffObjectDerived& operator=(const DiffObjectDerived&) = default;

        DiffObjectDerived(DiffObjectDerived&&) = default;
        DiffObjectDerived& operator=(DiffObjectDerived&&) = default;

        const T& prev() const noexcept {
            return *static_cast<const T*>(m_prev);
        }

        const T& curr() const noexcept {
            return *static_cast<const T*>(m_curr);
        }

        const T& next() const noexcept {
            return *static_cast<const T*>(m_next);
        }

    }; // class DiffObjectDerived

    typedef DiffObjectDerived<osmium::Node>     DiffNode;
    typedef DiffObjectDerived<osmium::Way>      DiffWay;
    typedef DiffObjectDerived<osmium::Relation> DiffRelation;

} // namespace osmium

#endif // OSMIUM_OSM_DIFF_OBJECT_HPP


text:
package org.randoomz.zdsmessenger.auth.queries;

import android.content.Context;

import org.randoomz.zdsmessenger.auth.Token;
import org.randoomz.zdsmessenger.auth.database.TokenDao;
import org.randoomz.zdsmessenger.auth.actions.RefreshTokenAction;
import org.randoomz.zdsmessenger.auth.actions.RefreshTokenParameter;
import org.randoomz.zdsmessenger.internal.Callback;
import org.randoomz.zdsmessenger.internal.ZdSInitializer;
import org.randoomz.zdsmessenger.internal.exceptions.ZdSException;
import org.randoomz.zdsmessenger.internal.query.Query;
import org.randoomz.zdsmessenger.internal.utils.NetworkConnectivity;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 * Created by Gerard on 15/03/15.
 */
@Singleton
public final class RefreshTokenQuery implements Query<Token> {
  private final Context context;
  private final TokenDao tokenDao;
  private final RefreshTokenAction refreshTokenAction;
  private final NetworkConnectivity networkConnectivity;

  @Inject public RefreshTokenQuery(Context context, TokenDao tokenDao, RefreshTokenAction refreshTokenAction, NetworkConnectivity networkConnectivity) {
    this.context = context;
    this.tokenDao = tokenDao;
    this.refreshTokenAction = refreshTokenAction;
    this.networkConnectivity = networkConnectivity;
  }

  @Override public void execute(Callback<Token> callback) {
    final Token token = tokenDao.get(0);
    if (token == null) {
      callback.failure(new ZdSException("You must have token saved in system to refresh it."));
    } else if (token.hasTokens() && token.isValid()) {
      callback.success(token);
    } else if (token.hasTokens() && !token.isValid() && networkConnectivity.isConnected(context)) {
      final RefreshTokenParameter param = new RefreshTokenParameter(
          ZdSInitializer.get().getClientId(), ZdSInitializer.get().getClientSecret(),
          token.refreshToken());
      refreshTokenAction.request(param, new SaveTokenCallback(tokenDao, callback));
    } else {
      callback.failure(new ZdSException("You must be connected to log in."));
    }
  }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Adelaide Bot. Gard. 6:75. 1982

#### Original name
Casuarina drummondiana Miq.

### Remarks
null


text:
require('es6-shim');
var gulp = require('gulp');
var concat = require('gulp-concat');
var sass = require('gulp-sass');
//var gutil = require('gulp-util');
//var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
//var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var reactify = require('reactify');
var browserify = require('browserify');
var transform = require('vinyl-transform');

function swallowError (error) {
    console.log(error.toString());
    this.emit('end');
}

function scripts(input, output, watch) {
    var bundler,
        options = { debug: true };

    if (watch) {
        bundler = watchify(browserify(input, Object.assign({}, watchify.args, options)));
        bundler.on('update', rebundle);
    } else {
        bundler = browserify(input, options);
    }

    bundler.transform(reactify, { debug: true, harmony: true });

    function rebundle() {
        console.log("building '" + input + "' -> '" + output + "'");
        return bundler.bundle()
            .on('error', swallowError)
            .pipe(source(output))
            .pipe(gulp.dest('dist/js'));
    }

    return rebundle();
}

gulp.task('js-build', function() {
    scripts('./src/client/js/lib.js','lib.js', false);
    scripts('./src/client/js/main.js','main.js', false);
});

gulp.task('js-watch', function() {
    scripts('./src/client/js/lib.js','lib.js', true);
    scripts('./src/client/js/main.js','main.js', true);
});

gulp.task('sass', function () {
    gulp.src([

        // reset
        'src/client/sass/reset.scss',

        // framework
        'src/client/sass/base.scss',
        'src/client/sass/button.scss',
        'src/client/sass/form.scss',
        'src/client/sass/typography.scss',
        'src/client/sass/utility.scss',

        // widgets
        'src/client/sass/*.scss'
    ])
        .pipe(sass({ style: 'compressed' }).on('error', swallowError))
        .pipe(concat('core.css'))
        .pipe(gulp.dest('dist/css'));

    gulp.src(['node_modules/react-select/dist/default.css'])
        .pipe(concat('lib.css'))
        .pipe(gulp.dest('dist/css'));
});

var FILES_TO_COPY = [
    'src/client/**/*.html',
    'src/client/**/*.jpg',
    'src/client/**/*.png'
];

gulp.task('copy', function() {
    gulp.src(FILES_TO_COPY)
      .pipe(gulp.dest('dist'));
});

gulp.task('default', ['js-build', 'copy', 'sass']);

gulp.task('watch', function() {
    scripts('./src/client/js/lib.js','lib.js', true);
    scripts('./src/client/js/main.js','main.js', true);
    gulp.watch('src/**/*.scss', ['sass']);
    gulp.watch(FILES_TO_COPY, ['copy']);
});


text:
package ru.shestakov.start;

public class StartUI {

    public static void main(String[] args) {

        Trade trade = new Trade();

        new StartUI().init(trade);

    }

    public void init(Trade trade) {

    }

}


text:
package org.spongycastle.jce.provider.test;

import java.security.AlgorithmParameters;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.spongycastle.crypto.Digest;
import org.spongycastle.crypto.PBEParametersGenerator;
import org.spongycastle.crypto.digests.SHA1Digest;
import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.generators.OpenSSLPBEParametersGenerator;
import org.spongycastle.crypto.generators.PKCS12ParametersGenerator;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.crypto.params.ParametersWithIV;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import org.spongycastle.util.encoders.Hex;
import org.spongycastle.util.test.SimpleTestResult;
import org.spongycastle.util.test.Test;
import org.spongycastle.util.test.TestResult;

/**
 * test out the various PBE modes, making sure the JCE implementations
 * are compatible woth the light weight ones.
 */
public class PBETest implements Test
{
    private class OpenSSLTest
        implements Test
    {
        char[]    password;
        String    baseAlgorithm;
        String    algorithm;
        int       keySize;
        int       ivSize;

        OpenSSLTest(
            String    baseAlgorithm,
            String    algorithm,
            int       keySize,
            int       ivSize)
        {
            this.password = algorithm.toCharArray();
            this.baseAlgorithm = baseAlgorithm;
            this.algorithm = algorithm;
            this.keySize = keySize;
            this.ivSize = ivSize;
        }

        public String getName()
        {
            return "OpenSSLPBE";
        }

        public TestResult perform()
        {
            byte[] salt = new byte[16];
            int    iCount = 100;

            for (int i = 0; i != salt.length; i++)
            {
                salt[i] = (byte)i;
            }

            try
            {
                OpenSSLPBEParametersGenerator   pGen = new OpenSSLPBEParametersGenerator();

                pGen.init(
                        PBEParametersGenerator.PKCS5PasswordToBytes(password),
                        salt);

                ParametersWithIV params = (ParametersWithIV)pGen.generateDerivedParameters(keySize, ivSize);
                SecretKeySpec    encKey = new SecretKeySpec(((KeyParameter)params.getParameters()).getKey(), baseAlgorithm);

                Cipher          c;

                if (baseAlgorithm.equals("RC4"))
                {
                    c = Cipher.getInstance(baseAlgorithm, "SC");

                    c.init(Cipher.ENCRYPT_MODE, encKey);
                }
                else
                {
                    c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "SC");

                    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));
                }

                byte[]              enc = c.doFinal(salt);

                c = Cipher.getInstance(algorithm, "SC");

                PBEKeySpec          keySpec = new PBEKeySpec(password);
                SecretKeyFactory    fact = SecretKeyFactory.getInstance(algorithm, "SC");

                c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), new PBEParameterSpec(salt, iCount));

                byte[]          dec = c.doFinal(enc);

                if (!arrayEquals(salt, dec))
                {
                    return new SimpleTestResult(false, getName() + ": " + algorithm + "failed encryption/decryption test");
                }

                return new SimpleTestResult(true, getName() + ": Okay");
            }
            catch (Exception e)
            {
                return new SimpleTestResult(false, getName() + ": " + algorithm + " failed - exception " + e, e);
            }
        }
    }

    private class PKCS12Test
        implements Test
    {
        char[]    password;
        String    baseAlgorithm;
        String    algorithm;
        Digest    digest;
        int       keySize;
        int       ivSize;

        PKCS12Test(
            String    baseAlgorithm,
            String    algorithm,
            Digest    digest,
            int       keySize,
            int       ivSize)
        {
            this.password = algorithm.toCharArray();
            this.baseAlgorithm = baseAlgorithm;
            this.algorithm = algorithm;
            this.digest = digest;
            this.keySize = keySize;
            this.ivSize = ivSize;
        }

        public String getName()
        {
            return "PKCS12PBE";
        }

        public TestResult perform()
        {
            byte[] salt = new byte[digest.getDigestSize()];
            int    iCount = 100;

            digest.doFinal(salt, 0);

            try
            {
                PKCS12ParametersGenerator   pGen = new PKCS12ParametersGenerator(digest);

                pGen.init(
                        PBEParametersGenerator.PKCS12PasswordToBytes(password),
                        salt,
                        iCount);

                ParametersWithIV params = (ParametersWithIV)pGen.generateDerivedParameters(keySize, ivSize);

                SecretKeySpec   encKey = new SecretKeySpec(((KeyParameter)params.getParameters()).getKey(), baseAlgorithm);

                Cipher          c;

                if (baseAlgorithm.equals("RC4"))
                {
                    c = Cipher.getInstance(baseAlgorithm, "SC");

                    c.init(Cipher.ENCRYPT_MODE, encKey);
                }
                else
                {
                    c = Cipher.getInstance(baseAlgorithm + "/CBC/PKCS7Padding", "SC");

                    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));
                }

                byte[]          enc = c.doFinal(salt);

                c = Cipher.getInstance(algorithm, "SC");

                PBEKeySpec          keySpec = new PBEKeySpec(password);
                SecretKeyFactory    fact = SecretKeyFactory.getInstance(algorithm, "SC");

                c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), new PBEParameterSpec(salt, iCount));

                byte[]          dec = c.doFinal(enc);

                if (!arrayEquals(salt, dec))
                {
                    return new SimpleTestResult(false, getName() + ": " + algorithm + "failed encryption/decryption test");
                }

                //
                // get the parameters
                //
                AlgorithmParameters param = c.getParameters();
                PBEParameterSpec    spec = (PBEParameterSpec)param.getParameterSpec(PBEParameterSpec.class);

                if (!arrayEquals(salt, spec.getSalt()))
                {
                    return new SimpleTestResult(false, getName() + ": " + algorithm + "failed salt test");
                }

                if (iCount != spec.getIterationCount())
                {
                    return new SimpleTestResult(false, getName() + ": " + algorithm + "failed count test");
                }

                //
                // try using parameters
                //
                keySpec = new PBEKeySpec(password);

                c.init(Cipher.DECRYPT_MODE, fact.generateSecret(keySpec), param);

                dec = c.doFinal(enc);

                if (!arrayEquals(salt, dec))
                {
                    return new SimpleTestResult(false, getName() + ": " + algorithm + "failed encryption/decryption test");
                }

                return new SimpleTestResult(true, getName() + ": Okay");
            }
            catch (Exception e)
            {
                return new SimpleTestResult(false, getName() + ": " + algorithm + " failed - exception " + e, e);
            }
        }
    }

    private PKCS12Test[] pkcs12Tests = {
        new PKCS12Test("DESede", "PBEWITHSHAAND3-KEYTRIPLEDES-CBC",  new SHA1Digest(),   192,  64),
        new PKCS12Test("DESede", "PBEWITHSHAAND2-KEYTRIPLEDES-CBC",  new SHA1Digest(),   128,  64),
        new PKCS12Test("RC4",    "PBEWITHSHAAND128BITRC4",           new SHA1Digest(),   128,   0),
        new PKCS12Test("RC4",    "PBEWITHSHAAND40BITRC4",            new SHA1Digest(),    40,   0),
        new PKCS12Test("RC2",    "PBEWITHSHAAND128BITRC2-CBC",       new SHA1Digest(),   128,  64),
        new PKCS12Test("RC2",    "PBEWITHSHAAND40BITRC2-CBC",        new SHA1Digest(),    40,  64),
        new PKCS12Test("AES",    "PBEWithSHA1And128BitAES-CBC-BC",   new SHA1Digest(),   128, 128),
        new PKCS12Test("AES",    "PBEWithSHA1And192BitAES-CBC-BC",   new SHA1Digest(),   192, 128),
        new PKCS12Test("AES",    "PBEWithSHA1And256BitAES-CBC-BC",   new SHA1Digest(),   256, 128),
        new PKCS12Test("AES",    "PBEWithSHA256And128BitAES-CBC-BC", new SHA256Digest(), 128, 128),
        new PKCS12Test("AES",    "PBEWithSHA256And192BitAES-CBC-BC", new SHA256Digest(), 192, 128),
        new PKCS12Test("AES",    "PBEWithSHA256And256BitAES-CBC-BC", new SHA256Digest(), 256, 128)
    };

    private OpenSSLTest openSSLTests[] = {
        new OpenSSLTest("AES", "PBEWITHMD5AND128BITAES-CBC-OPENSSL", 128, 128),
        new OpenSSLTest("AES", "PBEWITHMD5AND192BITAES-CBC-OPENSSL", 192, 128),
        new OpenSSLTest("AES", "PBEWITHMD5AND256BITAES-CBC-OPENSSL", 256, 128)
    };

    static byte[]   message = Hex.decode("4869205468657265");

    private byte[] hMac1 = Hex.decode("bcc42174ccb04f425d9a5c8c4a95d6fd7c372911");
    private byte[] hMac2 = Hex.decode("cb1d8bdb6aca9e3fa8980d6eb41ab28a7eb2cfd6");

    private Cipher makePBECipher(
        String  algorithm,
        int     mode,
        char[]  password,
        byte[]  salt,
        int     iterationCount)
        throws Exception
    {
        PBEKeySpec          pbeSpec = new PBEKeySpec(password);
        SecretKeyFactory    keyFact = SecretKeyFactory.getInstance(algorithm, "SC");
        PBEParameterSpec    defParams = new PBEParameterSpec(salt, iterationCount);

        Cipher cipher = Cipher.getInstance(algorithm, "SC");

        cipher.init(mode, keyFact.generateSecret(pbeSpec), defParams);

        return cipher;
    }

    private boolean arrayEquals(
        byte[]  a,
        byte[]  b)
    {
        if (a.length != b.length)
        {
            return false;
        }

        for (int i = 0; i != a.length; i++)
        {
            if (a[i] != b[i])
            {
                return false;
            }
        }

        return true;
    }

    public TestResult testPBEHMac(
        String  hmacName,
        byte[]  output)
    {
        SecretKey           key;
        byte[]              out;
        Mac                 mac;

        try
        {
            SecretKeyFactory    fact = SecretKeyFactory.getInstance(hmacName, "SC");

            key = fact.generateSecret(new PBEKeySpec("hello".toCharArray()));

            mac = Mac.getInstance(hmacName, "SC");
        }
        catch (Exception e)
        {
            return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e);
        }

        try
        {
            mac.init(key, new PBEParameterSpec(new byte[20], 100));
        }
        catch (Exception e)
        {
            return new SimpleTestResult(false, getName() + ": Failed - exception " + e.toString(), e);
        }

        mac.reset();

        mac.update(message, 0, message.length);

        out = mac.doFinal();

        if (!arrayEquals(out, output))
        {
            return new SimpleTestResult(false, getName() + ": Failed - expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out)));
        }

        return new SimpleTestResult(true, getName() + ": Okay");
    }

    public TestResult perform()
    {
        byte[] input = Hex.decode("1234567890abcdefabcdef1234567890fedbca098765");

        try
        {
            //
            // DES
            //
            Cipher  cEnc = Cipher.getInstance("DES/CBC/PKCS7Padding", "SC");

            cEnc.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(Hex.decode("30e69252758e5346"), "DES"),
                new IvParameterSpec(Hex.decode("7c1c1ab9c454a688")));

            byte[]  out = cEnc.doFinal(input);

            char[]  password = { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' };

            Cipher  cDec = makePBECipher(
                                "PBEWithSHA1AndDES",
                                Cipher.DECRYPT_MODE,
                                password,
                                Hex.decode("7d60435f02e9e0ae"),
                                2048);

            byte[]  in = cDec.doFinal(out);

            if (!arrayEquals(input, in))
            {
                return new SimpleTestResult(false, getName() + ": DES failed");
            }

            //
            // DESede
            //
            cEnc = Cipher.getInstance("DESede/CBC/PKCS7Padding", "SC");

            cEnc.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1c103ddd97c7cbe8e"), "DES"),
                new IvParameterSpec(Hex.decode("b07bf522c8d608b8")));

            out = cEnc.doFinal(input);

            cDec = makePBECipher(
                                "PBEWithSHAAnd3-KeyTripleDES-CBC",
                                Cipher.DECRYPT_MODE,
                                password,
                                Hex.decode("7d60435f02e9e0ae"),
                                2048);

            in = cDec.doFinal(out);

            if (!arrayEquals(input, in))
            {
                return new SimpleTestResult(false, getName() + ": DESede failed");
            }

            //
            // 40Bit RC2
            //
            cEnc = Cipher.getInstance("RC2/CBC/PKCS7Padding", "SC");

            cEnc.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(Hex.decode("732f2d33c8"), "RC2"),
                new IvParameterSpec(Hex.decode("b07bf522c8d608b8")));

            out = cEnc.doFinal(input);

            cDec = makePBECipher(
                                "PBEWithSHAAnd40BitRC2-CBC",
                                Cipher.DECRYPT_MODE,
                                password,
                                Hex.decode("7d60435f02e9e0ae"),
                                2048);

            in = cDec.doFinal(out);

            if (!arrayEquals(input, in))
            {
                return new SimpleTestResult(false, getName() + ": RC2 failed");
            }

            //
            // 128bit RC4
            //
            cEnc = Cipher.getInstance("RC4", "SC");

            cEnc.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(Hex.decode("732f2d33c801732b7206756cbd44f9c1"), "RC4"));

            out = cEnc.doFinal(input);

            cDec = makePBECipher(
                                "PBEWithSHAAnd128BitRC4",
                                Cipher.DECRYPT_MODE,
                                password,
                                Hex.decode("7d60435f02e9e0ae"),
                                2048);

            in = cDec.doFinal(out);

            if (!arrayEquals(input, in))
            {
                return new SimpleTestResult(false, getName() + ": RC4 failed");
            }

            for (int i = 0; i != pkcs12Tests.length; i++)
            {
                TestResult  res = pkcs12Tests[i].perform();
                if (!res.isSuccessful())
                {
                    return res;
                }
            }

            for (int i = 0; i != openSSLTests.length; i++)
            {
                TestResult  res = openSSLTests[i].perform();
                if (!res.isSuccessful())
                {
                    return res;
                }
            }

            TestResult res = testPBEHMac("PBEWithHMacSHA1", hMac1);

            if (!res.isSuccessful())
            {
                return res;
            }

            res = testPBEHMac("PBEWithHMacRIPEMD160", hMac2);

            if (!res.isSuccessful())
            {
                return res;
            }

            return new SimpleTestResult(true, getName() + ": Okay");
        }
        catch (Exception e)
        {
            return new SimpleTestResult(false, getName() + ": exception - " + e.toString(), e);
        }
    }

    public String getName()
    {
        return "PBETest";
    }

    public static void main(
        String[]    args)
    {
        Security.addProvider(new BouncyCastleProvider());

        Test            test = new PBETest();
        TestResult      result = test.perform();

        System.out.println(result.toString());
    }
}