text:
import requests
import hmac
import hashlib
import time
import base64
import urllib

from decimal import Decimal

ORDER_OPEN = 'open'
ORDER_CLOSED = 'closed'

class KrakenException(Exception):
    def __init__(self, error):
        self.errors = error

    def __str__(self):
        return "\n".join(self.errors)

class KrakenOrder(object):
    """ Kraken order.
    """
    def __init__(self, otype, oid):
        self.otype = otype
        self.oid = oid

class KrakenPlugin(object):
    """ Kraken.com plugin

    Note: At Kraken we actually trade in XBT/EUR, but we need to re-calculate
    prices to USD so they are comparable to what other plugins work with.

    API documentation:
        https://www.kraken.com/help/api

    :param key: API key
    :param secret: API secret
    :param eurusd_rate: current EUR/USD exchange rate
    """
    def __init__(self, key, secret, eurusd_rate):
        self.name = 'kraken.com [EUR]'

        self._url = 'https://api.kraken.com'
        self._version = '0'
        self._key = key
        self._secret = secret
        self._eurusd_rate = eurusd_rate

        self.refresh_account_info()

    def refresh_account_info(self):
        path_balance = 'private/Balance'
        self._account_info = self._http_post(path_balance)

        path_trade_volume = 'private/TradeVolume'
        self._trade_volume = self._http_post(path_trade_volume,
                { 'pair': 'XXBTZEUR' })

    def refresh_order_book(self):
        path = 'public/Depth'
        result = self._http_get(path, {
                'pair': 'XXBTZEUR',
                'count': 1,
            })
        self._order_book = result['XXBTZEUR']

    def refresh_orders(self):
        """ Refresh my orders.
        """
        path_open = 'private/OpenOrders'
        result = self._http_post(path_open)
        self._open_orders = result['open']

        path_closed = 'private/ClosedOrders'
        result = self._http_post(path_closed)
        self._closed_orders = result['closed']

    def create_bid_order(self, volume, price):
        """ Create a BID ("I want to buy") order.

        :param volume: Volume in XBT
        :param price: Price in USD
        :return: Order ID
        """
        path = 'private/AddOrder'
        price_eur = price / self._eurusd_rate
        data = {
                'pair': 'XXBTZEUR',
                'type': 'buy',
                'ordertype': 'limit',
                'price': price_eur,
                'volume': "{0:.8f}".format(volume),
            }
        response = self._http_post(path, data)
        order = KrakenOrder(otype='bid', oid=response['txid'][0])
        return order

    def create_ask_order(self, volume, price):
        """ Create an ASK ("I want to sell") order.

        :param volume: Volume in XBT
        :param price: Price in USD
        :return: Order ID
        """
        path = 'private/AddOrder'
        price_eur = price / self._eurusd_rate
        data = {
                'pair': 'XXBTZEUR',
                'type': 'sell',
                'ordertype': 'limit',
                'price': price_eur,
                'volume': "{0:.8f}".format(volume),
            }
        response = self._http_post(path, data)
        order = KrakenOrder(otype='ask', oid=response['txid'][0])
        return order

    def get_order_status(self, order):
        """ Get order status. Possible values: 'open', 'closed'. Raise exception
        if the order was not found.
        """
        # Refresh orders
        self.refresh_orders()

        # Check open orders
        for oid in self._open_orders.keys():
            if oid == order.oid:
                status = self._open_orders[oid]['status']
                if status in ('open', 'pending'):
                    return ORDER_OPEN
                elif status == 'cancelled':
                    raise BitstampException('Order was cancelled')
                elif status == 'expired':
                    raise BitstampException('Order expired')
                else:
                    raise BitstampException('Unexpected order status: {0}'.format(status))

        # Check closed orders
        for oid in self._closed_orders.keys():
            if oid == order.oid:
                status = self._closed_orders[oid]['status']
                if status == 'closed':
                    return ORDER_CLOSED
                else:
                    raise BitstampException('Unexpected order status: {0}'.format(status))

        # If the order is not open nor closed it does not exist - we raise an
        # exception
        raise BitstampException('Order not found')

    def cancel_order(self, order):
        """ Cancel open order.
        """
        path = 'private/CancelOrder'
        data = {
                'txid': order.oid,
            }
        self._http_post(path, data)

    @property
    def trade_fee(self):
        return Decimal(self._trade_volume['fees']['XXBTZEUR']['fee'])

    @property
    def open_orders(self):
        return self._open_orders

    @property
    def balance_xbt(self):
        if self._account_info.has_key('XXBT'):
            return Decimal(self._account_info['XXBT'])
        else:
            return Decimal('0.0')

    @property
    def balance_usd(self):
        if self._account_info.has_key('ZEUR'):
            balance_eur = Decimal(self._account_info['ZEUR'])
            return balance_eur * self._eurusd_rate
        else:
            return Decimal('0.0')

    @property
    def avail_xbt(self):
        return self.balance_xbt

    @property
    def avail_usd(self):
        return self.balance_usd

    @property
    def highest_bid(self):
        """ Return the highest bid from the order book.
        """
        (price_eur, volume, _) = self._order_book['bids'][0]
        price_usd = Decimal(price_eur) * self._eurusd_rate
        return {
                'price': Decimal(price_usd),
                'volume': Decimal(volume),
            }

    @property
    def lowest_ask(self):
        """ Return the lowest ask from the order book.
        """
        (price_eur, volume, _) = self._order_book['asks'][0]
        price_usd = Decimal(price_eur) * self._eurusd_rate
        return {
                'price': Decimal(price_usd),
                'volume': Decimal(volume),
            }

    def _sign(self, path, nonce, data):
        """ Create a signature for private requests.
        """
        url = '/{0}/{1}'.format(self._version, path)
        urlencoded_data = urllib.urlencode(data)
        msg = url + hashlib.sha256(str(nonce) + urlencoded_data).digest()
        signature = hmac.new(base64.b64decode(self._secret), msg,
                hashlib.sha512)
        return base64.b64encode(signature.digest())

    def _http_get(self, path, params=None):
        url = '{0}/{1}/{2}'.format(self._url, self._version, path)
        response = requests.get(url, params=params)
        result = response.json()
        if response.status_code != 200 or result['error']:
            raise KrakenException(result['error'])
        return response.json()['result']

    def _http_post(self, path, data={}):
        url = '{0}/{1}/{2}'.format(self._url, self._version, path)

        nonce = int(time.time() * 1e3)
        payload = dict(data)
        payload['nonce'] = nonce

        headers = {
                'API-Key': self._key,
                'API-Sign': self._sign(path, nonce, payload),
            }

        response = requests.post(url, data=payload, headers=headers)
        result = response.json()
        if response.status_code != 200 or result['error']:
            raise KrakenException(result['error'])
        return result['result']


text:
var assumeRole = require('../lib/assume-role');
var assert = require('assert');

function createValidRequest() {
    return {
        account: 'test',
        name: 'test'
    };
}

describe('assumeRole', function() {

    beforeEach(function() {
        request = createValidRequest();
    });

    describe('validation', function() {

        it('should require name', function(cb) {

            delete request.name;

            assert.throws(
                () => {
                    assumeRole(request);
                    cb();
                },
                /name/
            );
            cb();
        });

        it('should require account', function(cb) {

            delete request.account;

            assert.throws(
                () => {
                    assumeRole(request);
                    cb();
                },
                /account/
            );
            cb();
        });

    });

});

redpajama_set_name: RedPajamaGithub


text:
import * as Sentry from "@sentry/browser";
import environment from '@/environment';

Sentry.init({
  dsn: environment.sentryDsn,
  release: environment.release,
  ignoreErrors: [
    'Network Error',
    'Non-Error promise rejection captured',
    'Request failed with status code 422',
    'Request aborted',
    'Request failed with status code 401',
    'Request failed with status code 404',
    'Request failed with status code 522',
    'Request failed with status code 500',
    'Request failed with status code 520',
    'Request failed with status code 503',
    'Request failed with status code 502',
    'timeout of 0ms exceeded',
    'null is not an object (evaluating \'ReaderArticleFinderJS.adoptableArticle().outerHTML\')',
    'Improper range'
  ],
  tracesSampleRate: 0.0,
});


text:
package jp.co.acroquest.endosnipe.javelin.converter;

public class TestConverterForClass_01 extends AbstractConverter
{
    @Override
    public void convertImpl()
    {
        System.out.println(getClass().getName() + " applied to " + getClassName() + ".");
    }

    public void init()
    {
    }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace SimplyFast.IoC
{
    [SuppressMessage("ReSharper", "UnusedMember.Global")]
    [AttributeUsage(AttributeTargets.Method)]
    [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
    public class InjectAttribute : Attribute
    {
    }
}


text:
/**
 * 使用access-token-mongo组件和wechat-enterprise-api生成wxapi组件,用于调用微信API
 * Created by 文琪 on 2015/4/22.
 */

var API = require('wechat-enterprise-api');

/*
options参数
    - db 必须。mongoDB数据库连接字符串
    - access_token_col access-token-mongo组件使用的集合的名称,默认为access_tokens
    - corpId 必须。微信企业号的ID
    - secret 必须。微信企业号管理组的secret
    - agentId 必须。调用api的应用的Id
    - expire token的过期时间,默认为7000(毫秒)
*/
module.exports = function (options) {
    var AccessToken = require('access-token-mongo')(options.db, options.access_token_col);

    var wxapi = new API(options.corpId, options.secret, options.agentId,
        function(callback){
            AccessToken.getToken({
                appId: options.corpId,
                appSecret: options.secret
            }, function(err, token){
                callback(null, token);
            })
        },
        function(token, callback){
            AccessToken.saveToken({
                appId: options.corpId,
                appSecret: options.secret,
                expire: options.expire || 7000
            }, token, function(){
                callback(null, token);
            });
        }
    );

    return wxapi;
};


text:
//
//  OCSDefinition.h
//  Reliant
//
//  Created by Michael Seghers on 6/05/12.
//  Copyright (c) 2012 AppFoundry. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
Describes an object configuration in the application context.
*/
@interface OCSDefinition : NSObject

/**
The key for the definition. This key will also be the key for looking up the object.
*/
@property (nonatomic, strong) NSString *key;

/**
The aliases for the definition. These aliases also identify this definition.
 */
@property (nonatomic, readonly) NSArray *aliases;

/**
The class of the object that this definition represents.
 */
@property (weak, nonatomic) Class implementingClass;

/**
Flag to indicate when the object should be loaded in the application context. Lazy means only when first requested, eager means directly at startup. This only makes sence for singleton objects. Prototypes are always lazily loaded.
 */
@property (nonatomic, assign) BOOL lazy;

/**
Flag to indicate if the object is a singleton or a prototype. Singletons, as the words says, will only be initialized once in a context. Prototypes will be created each time they are requested.
*/
@property (nonatomic, assign) BOOL singleton;

/**
The scope name for this definition. The name should be mapped to a scope instance, using an OCSScopeFactory implementation.

@see OCSScope
@see OCSScopeFactory
*/
@property(nonatomic, strong) NSString *scope;

/**
Adds an alias for the object. An object can be retrieved through one of these aliases.

@param alias the alias
 */
- (void) addAlias:(NSString *) alias;

/**
Returns YES if the definition holds the given alias. NO otherwise.

@param alias the alias to look for
*/
- (BOOL) isAlsoKnownWithAlias:(NSString *) alias;

@end


text:
"""Package contenant le paramètre 'dupliquer' de la commande 'rapport'."""

from primaires.interpreteur.masque.parametre import Parametre

class PrmDupliquer(Parametre):

    """Commande 'rapport dupliquer'"""

    def __init__(self):
        """Constructeur du paramètre."""
        Parametre.__init__(self, "dupliquer", "duplicate")
        self.nom_groupe = "administrateur"
        self.schema = "<nombre> <depuis:nombre>"
        self.aide_courte = "marque un rapport comme dupliqué"
        self.aide_longue = \
            "Cette commande est un raccourci pour indiquer qu'un rapport " \
            "est une duplication d'un autre rapport. Il attend deux " \
            "numéros de rapport : le premier est le rapport dupliqué (à " \
            "fermer), le second est le rapport depuis lequel il est " \
            "dupliqué. Si on veut noter par exemple que le rapport " \
            "|ent|100|ff| est une copie du rapport |ent|56|ff|, on entre " \
            "%rapport% %rapport:dupliquer%|cmd| 100 56|ff|. Il est plus " \
            "courant de laisser les rapports anciens ouverts et de " \
            "dupliquer les nouveaux, ce qui fait que le premier nombre " \
            "est souvent plus élevé que le second, pour mémoire."

    def interpreter(self, personnage, dic_masques):
        """Méthode d'interprétation de commande"""
        id = dic_masques["nombre"].nombre
        depuis = dic_masques["depuis"].nombre
        try:
            rapport = importeur.rapport.rapports[id]
        except KeyError:
            personnage << "|err|Le rapport {} n'existe pas.|ff|".format(id)
            return

        try:
            depuis = importeur.rapport.rapports[depuis]
        except KeyError:
            personnage << "|err|Le rapport {} n'existe pas.|ff|".format(depuis)
            return

        if not rapport.ouvert:
            personnage << "|err|Le rapport {} est déjà fermé.|ff|".format(id)
            return

        rapport.description.ajouter_paragraphe(
                "|att|Ce rapport est une duplication du rapport " \
                "{}.|ff|".format(depuis.id))
        rapport.statut = "dupliqué"
        personnage << "Le rapport #{} est noté comme dupliqué de #{}.".format(
                rapport.id, depuis.id)


text:
{% extends 'base.html' %}

{% load bootstrap3 %}

{% block content %}

Enter New Password

	{% if validlink %}

			Please enter your new password twice so we can verify you typed it in correctly.

		<form action='' method='post'>
			{% csrf_token %}
			{% bootstrap_form form %}
			<button type='submit' class='btn btn-primary'>Change my password</button>
		</form>
	{% else %}

			The password reset link was invalid, possibly because it has already been used.
			Please request a new password reset.

	{% endif %}
{% endblock %}


text:
namespace Auth0.ManagementApi.Clients
{
  using System.Threading;
  using System.Threading.Tasks;
  using Models.AttackProtection;

  public interface IAttackProtectionClient
  {
    /// <summary>
    /// Get the suspicious IP throttling configuration.
    /// </summary>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>A <see cref="SuspiciousIpThrottling"/> containing the configuration.</returns>
    Task<SuspiciousIpThrottling> GetSuspiciousIpThrottlingAsync(
      CancellationToken cancellationToken = default);

    /// <summary>
    /// Update the suspicious IP throttling configuration.
    /// </summary>
    /// <param name="request">Specifies criteria to use when updating the configuration.</param>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>The <see cref="SuspiciousIpThrottling"/> that was updated.</returns>
    Task<SuspiciousIpThrottling> UpdateSuspiciousIpThrottlingAsync(SuspiciousIpThrottling request,
      CancellationToken cancellationToken = default);

    /// <summary>
    /// Get breached password detection settings.
    /// </summary>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>A <see cref="BreachedPasswordDetection"/> containing the configuration.</returns>
    Task<BreachedPasswordDetection> GetBreachedPasswordDetectionAsync(
      CancellationToken cancellationToken = default);

    /// <summary>
    /// Update breached password detection settings.
    /// </summary>
    /// <param name="request">Specifies criteria to use when updating the configuration.</param>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>The <see cref="BreachedPasswordDetection"/> that was updated.</returns>
    Task<BreachedPasswordDetection> UpdateBreachedPasswordDetectionAsync(BreachedPasswordDetection request,
      CancellationToken cancellationToken = default);

    /// <summary>
    /// Get the brute force configuration.
    /// </summary>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>A <see cref="BruteForceProtection"/> containing the configuration.</returns>
    Task<BruteForceProtection> GetBruteForceProtectionAsync(CancellationToken cancellationToken = default);

    /// <summary>
    /// Update the brute force configuration.
    /// </summary>
    /// <param name="request">Specifies criteria to use when updating the configuration.</param>
    /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
    /// <returns>The <see cref="BruteForceProtection"/> that was updated.</returns>
    Task<BruteForceProtection> UpdateBruteForceProtectionAsync(BruteForceProtection request,
      CancellationToken cancellationToken = default);
  }
}


text:
#pragma once
#include <aws/elasticloadbalancingv2/ElasticLoadBalancingv2_EXPORTS.h>
#include <aws/elasticloadbalancingv2/ElasticLoadBalancingv2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/elasticloadbalancingv2/model/TargetDescription.h>

namespace Aws
{
namespace ElasticLoadBalancingv2
{
namespace Model
{

  /**
   *
Contains the parameters for DeregisterTargets.

   */
  class AWS_ELASTICLOADBALANCINGV2_API DeregisterTargetsRequest : public ElasticLoadBalancingv2Request
  {
  public:
    DeregisterTargetsRequest();
    Aws::String SerializePayload() const override;

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline const Aws::String& GetTargetGroupArn() const{ return m_targetGroupArn; }

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline void SetTargetGroupArn(const Aws::String& value) { m_targetGroupArnHasBeenSet = true; m_targetGroupArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline void SetTargetGroupArn(Aws::String&& value) { m_targetGroupArnHasBeenSet = true; m_targetGroupArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline void SetTargetGroupArn(const char* value) { m_targetGroupArnHasBeenSet = true; m_targetGroupArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline DeregisterTargetsRequest& WithTargetGroupArn(const Aws::String& value) { SetTargetGroupArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline DeregisterTargetsRequest& WithTargetGroupArn(Aws::String&& value) { SetTargetGroupArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of the target group.

     */
    inline DeregisterTargetsRequest& WithTargetGroupArn(const char* value) { SetTargetGroupArn(value); return *this;}

    /**
     *
The targets.

     */
    inline const Aws::Vector<TargetDescription>& GetTargets() const{ return m_targets; }

    /**
     *
The targets.

     */
    inline void SetTargets(const Aws::Vector<TargetDescription>& value) { m_targetsHasBeenSet = true; m_targets = value; }

    /**
     *
The targets.

     */
    inline void SetTargets(Aws::Vector<TargetDescription>&& value) { m_targetsHasBeenSet = true; m_targets = value; }

    /**
     *
The targets.

     */
    inline DeregisterTargetsRequest& WithTargets(const Aws::Vector<TargetDescription>& value) { SetTargets(value); return *this;}

    /**
     *
The targets.

     */
    inline DeregisterTargetsRequest& WithTargets(Aws::Vector<TargetDescription>&& value) { SetTargets(value); return *this;}

    /**
     *
The targets.

     */
    inline DeregisterTargetsRequest& AddTargets(const TargetDescription& value) { m_targetsHasBeenSet = true; m_targets.push_back(value); return *this; }

    /**
     *
The targets.

     */
    inline DeregisterTargetsRequest& AddTargets(TargetDescription&& value) { m_targetsHasBeenSet = true; m_targets.push_back(value); return *this; }

  private:
    Aws::String m_targetGroupArn;
    bool m_targetGroupArnHasBeenSet;
    Aws::Vector<TargetDescription> m_targets;
    bool m_targetsHasBeenSet;
  };

} // namespace Model
} // namespace ElasticLoadBalancingv2
} // namespace Aws


text:
"""GTFlow Estimator definition."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.boosted_trees.estimator_batch import model
from tensorflow.contrib.boosted_trees.python.utils import losses
from tensorflow.contrib.learn.python.learn.estimators import estimator
from tensorflow.contrib.learn.python.learn.estimators import head as head_lib
from tensorflow.python.ops import math_ops

class GradientBoostedDecisionTreeClassifier(estimator.Estimator):
  """An estimator using gradient boosted decision trees."""

  def __init__(self,
               learner_config,
               examples_per_layer,
               n_classes=2,
               num_trees=None,
               feature_columns=None,
               weight_column_name=None,
               model_dir=None,
               config=None,
               label_keys=None,
               feature_engineering_fn=None,
               logits_modifier_function=None,
               center_bias=True,
               use_core_libs=False,
               output_leaf_index=False):
    """Initializes a GradientBoostedDecisionTreeClassifier estimator instance.

    Args:
      learner_config: A config for the learner.
      examples_per_layer: Number of examples to accumulate before growing a
        layer. It can also be a function that computes the number of examples
        based on the depth of the layer that's being built.
      n_classes: Number of classes in the classification.
      num_trees: An int, number of trees to build.
      feature_columns: A list of feature columns.
      weight_column_name: Name of the column for weights, or None if not
        weighted.
      model_dir: Directory for model exports, etc.
      config: `RunConfig` object to configure the runtime settings.
      label_keys: Optional list of strings with size `[n_classes]` defining the
        label vocabulary. Only supported for `n_classes` > 2.
      feature_engineering_fn: Feature engineering function. Takes features and
        labels which are the output of `input_fn` and returns features and
        labels which will be fed into the model.
      logits_modifier_function: A modifier function for the logits.
      center_bias: Whether a separate tree should be created for first fitting
        the bias.
      use_core_libs: Whether feature columns and loss are from the core (as
        opposed to contrib) version of tensorflow.
      output_leaf_index: whether to output leaf indices along with predictions
        during inference. The leaf node indexes are available in predictions
        dict by the key 'leaf_index'. It is a Tensor of rank 2 and its shape is
        [batch_size, num_trees].
        For example,
        result_iter = classifier.predict(...)
        for result_dict in result_iter:
          # access leaf index list by result_dict["leaf_index"]
          # which contains one leaf index per tree

    Raises:
      ValueError: If learner_config is not valid.
    """
    if n_classes > 2:
      # For multi-class classification, use our loss implementation that
      # supports second order derivative.
      def loss_fn(labels, logits, weights=None):
        result = losses.per_example_maxent_loss(
            labels=labels,
            logits=logits,
            weights=weights,
            num_classes=n_classes)
        return math_ops.reduce_mean(result[0])
    else:
      loss_fn = None
    head = head_lib.multi_class_head(
        n_classes=n_classes,
        weight_column_name=weight_column_name,
        enable_centered_bias=False,
        loss_fn=loss_fn,
        label_keys=label_keys)
    if learner_config.num_classes == 0:
      learner_config.num_classes = n_classes
    elif learner_config.num_classes != n_classes:
      raise ValueError("n_classes (%d) doesn't match learner_config (%d)." %
                       (learner_config.num_classes, n_classes))
    super(GradientBoostedDecisionTreeClassifier, self).__init__(
        model_fn=model.model_builder,
        params={
            'head': head,
            'feature_columns': feature_columns,
            'learner_config': learner_config,
            'num_trees': num_trees,
            'weight_column_name': weight_column_name,
            'examples_per_layer': examples_per_layer,
            'center_bias': center_bias,
            'logits_modifier_function': logits_modifier_function,
            'use_core_libs': use_core_libs,
            'output_leaf_index': output_leaf_index,
        },
        model_dir=model_dir,
        config=config,
        feature_engineering_fn=feature_engineering_fn)

class GradientBoostedDecisionTreeRegressor(estimator.Estimator):
  """An estimator using gradient boosted decision trees."""

  def __init__(self,
               learner_config,
               examples_per_layer,
               label_dimension=1,
               num_trees=None,
               feature_columns=None,
               label_name=None,
               weight_column_name=None,
               model_dir=None,
               config=None,
               feature_engineering_fn=None,
               logits_modifier_function=None,
               center_bias=True,
               use_core_libs=False,
               output_leaf_index=False):
    """Initializes a GradientBoostedDecisionTreeRegressor estimator instance.

    Args:
      learner_config: A config for the learner.
      examples_per_layer: Number of examples to accumulate before growing a
        layer. It can also be a function that computes the number of examples
        based on the depth of the layer that's being built.
      label_dimension: Number of regression labels per example. This is the size
        of the last dimension of the labels `Tensor` (typically, this has shape
        `[batch_size, label_dimension]`).
      num_trees: An int, number of trees to build.
      feature_columns: A list of feature columns.
      label_name: String, name of the key in label dict. Can be null if label
          is a tensor (single headed models).
      weight_column_name: Name of the column for weights, or None if not
        weighted.
      model_dir: Directory for model exports, etc.
      config: `RunConfig` object to configure the runtime settings.
      feature_engineering_fn: Feature engineering function. Takes features and
        labels which are the output of `input_fn` and returns features and
        labels which will be fed into the model.
      logits_modifier_function: A modifier function for the logits.
      center_bias: Whether a separate tree should be created for first fitting
        the bias.
      use_core_libs: Whether feature columns and loss are from the core (as
        opposed to contrib) version of tensorflow.
      output_leaf_index: whether to output leaf indices along with predictions
        during inference. The leaf node indexes are available in predictions
        dict by the key 'leaf_index'. For example,
        result_dict = classifier.predict(...)
        for example_prediction_result in result_dict:
          # access leaf index list by example_prediction_result["leaf_index"]
          # which contains one leaf index per tree
    """
    head = head_lib.regression_head(
        label_name=label_name,
        label_dimension=label_dimension,
        weight_column_name=weight_column_name,
        enable_centered_bias=False)
    if label_dimension == 1:
      learner_config.num_classes = 2
    else:
      learner_config.num_classes = label_dimension
    super(GradientBoostedDecisionTreeRegressor, self).__init__(
        model_fn=model.model_builder,
        params={
            'head': head,
            'feature_columns': feature_columns,
            'learner_config': learner_config,
            'num_trees': num_trees,
            'weight_column_name': weight_column_name,
            'examples_per_layer': examples_per_layer,
            'logits_modifier_function': logits_modifier_function,
            'center_bias': center_bias,
            'use_core_libs': use_core_libs,
            'output_leaf_index': False,
        },
        model_dir=model_dir,
        config=config,
        feature_engineering_fn=feature_engineering_fn)

class GradientBoostedDecisionTreeEstimator(estimator.Estimator):
  """An estimator using gradient boosted decision trees.

  Useful for training with user specified `Head`.
  """

  def __init__(self,
               learner_config,
               examples_per_layer,
               head,
               num_trees=None,
               feature_columns=None,
               weight_column_name=None,
               model_dir=None,
               config=None,
               feature_engineering_fn=None,
               logits_modifier_function=None,
               center_bias=True,
               use_core_libs=False,
               output_leaf_index=False):
    """Initializes a GradientBoostedDecisionTreeEstimator estimator instance.

    Args:
      learner_config: A config for the learner.
      examples_per_layer: Number of examples to accumulate before growing a
        layer. It can also be a function that computes the number of examples
        based on the depth of the layer that's being built.
      head: `Head` instance.
      num_trees: An int, number of trees to build.
      feature_columns: A list of feature columns.
      weight_column_name: Name of the column for weights, or None if not
        weighted.
      model_dir: Directory for model exports, etc.
      config: `RunConfig` object to configure the runtime settings.
      feature_engineering_fn: Feature engineering function. Takes features and
        labels which are the output of `input_fn` and returns features and
        labels which will be fed into the model.
      logits_modifier_function: A modifier function for the logits.
      center_bias: Whether a separate tree should be created for first fitting
        the bias.
      use_core_libs: Whether feature columns and loss are from the core (as
        opposed to contrib) version of tensorflow.
      output_leaf_index: whether to output leaf indices along with predictions
        during inference. The leaf node indexes are available in predictions
        dict by the key 'leaf_index'. For example,
        result_dict = classifier.predict(...)
        for example_prediction_result in result_dict:
          # access leaf index list by example_prediction_result["leaf_index"]
          # which contains one leaf index per tree
    """
    super(GradientBoostedDecisionTreeEstimator, self).__init__(
        model_fn=model.model_builder,
        params={
            'head': head,
            'feature_columns': feature_columns,
            'learner_config': learner_config,
            'num_trees': num_trees,
            'weight_column_name': weight_column_name,
            'examples_per_layer': examples_per_layer,
            'logits_modifier_function': logits_modifier_function,
            'center_bias': center_bias,
            'use_core_libs': use_core_libs,
            'output_leaf_index': False,
        },
        model_dir=model_dir,
        config=config,
        feature_engineering_fn=feature_engineering_fn)

class GradientBoostedDecisionTreeRanker(estimator.Estimator):
  """A ranking estimator using gradient boosted decision trees."""

  def __init__(
      self,
      learner_config,
      examples_per_layer,
      head,
      ranking_model_pair_keys,
      num_trees=None,
      feature_columns=None,
      weight_column_name=None,
      model_dir=None,
      config=None,
      label_keys=None,
      feature_engineering_fn=None,
      logits_modifier_function=None,
      center_bias=False,
      use_core_libs=False,
      output_leaf_index=False,
  ):
    """Initializes a GradientBoostedDecisionTreeRanker instance.

    This is an estimator that can be trained off the pairwise data and can be
    used for inference on non-paired data. This is essentially LambdaMart.
    Args:
      learner_config: A config for the learner.
      examples_per_layer: Number of examples to accumulate before growing a
        layer. It can also be a function that computes the number of examples
        based on the depth of the layer that's being built.
      head: `Head` instance.
      ranking_model_pair_keys: Keys to distinguish between features
        for left and right part of the training pairs for ranking. For example,
        for an Example with features "a.f1" and "b.f1", the keys would be
        ("a", "b").
      num_trees: An int, number of trees to build.
      feature_columns: A list of feature columns.
      weight_column_name: Name of the column for weights, or None if not
        weighted.
      model_dir: Directory for model exports, etc.
      config: `RunConfig` object to configure the runtime settings.
      label_keys: Optional list of strings with size `[n_classes]` defining the
        label vocabulary. Only supported for `n_classes` > 2.
      feature_engineering_fn: Feature engineering function. Takes features and
        labels which are the output of `input_fn` and returns features and
        labels which will be fed into the model.
      logits_modifier_function: A modifier function for the logits.
      center_bias: Whether a separate tree should be created for first fitting
        the bias.
      use_core_libs: Whether feature columns and loss are from the core (as
        opposed to contrib) version of tensorflow.
      output_leaf_index: whether to output leaf indices along with predictions
        during inference. The leaf node indexes are available in predictions
        dict by the key 'leaf_index'. It is a Tensor of rank 2 and its shape is
        [batch_size, num_trees].
        For example,
        result_iter = classifier.predict(...)
        for result_dict in result_iter:
          # access leaf index list by result_dict["leaf_index"]
          # which contains one leaf index per tree

    Raises:
      ValueError: If learner_config is not valid.
    """
    super(GradientBoostedDecisionTreeRanker, self).__init__(
        model_fn=model.ranking_model_builder,
        params={
            'head': head,
            'n_classes': 2,
            'feature_columns': feature_columns,
            'learner_config': learner_config,
            'num_trees': num_trees,
            'weight_column_name': weight_column_name,
            'examples_per_layer': examples_per_layer,
            'center_bias': center_bias,
            'logits_modifier_function': logits_modifier_function,
            'use_core_libs': use_core_libs,
            'output_leaf_index': output_leaf_index,
            'ranking_model_pair_keys': ranking_model_pair_keys,
        },
        model_dir=model_dir,
        config=config,
        feature_engineering_fn=feature_engineering_fn)


text:
import React from 'react';
import Component from '../../Component';
import Tab from './Tab';
import childrenOf from '../../prop-types/childrenOf';
import CONTEXT_TYPES from './contextTypes';
import MODULE from './module';

export default class Nav extends Component {
  static module = MODULE;

  static contextTypes = CONTEXT_TYPES;

  static propTypes = {
    children: childrenOf(Tab),
  };

  render() {
    return (
      <nav
        id={this.formatID('tabs-nav')}
        className={this.formatChildClass('nav')}
      >
        <ol>
          {this.props.children}
        </ol>
      </nav>
    );
  }
}


text:
<?php

namespace Phlexible\Component\AccessControl\Domain;

use Phlexible\Component\AccessControl\Model\EntryInterface;

/**
 * Access control entry
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class Entry implements EntryInterface
{
    /**
     * @var int
     */
    private $id;

    private $objectIdentityId;

    /**
     * @var AccessControlList
     */
    private $acl;

    /**
     * @var string
     */
    private $objectType;

    /**
     * @var string
     */
    private $objectIdentifier;

    /**
     * @var string
     */
    private $securityType;

    /**
     * @var string
     */
    private $securityIdentifier;

    /**
     * @var int
     */
    private $mask;

    /**
     * @var int
     */
    private $stopMask;

    /**
     * @var int
     */
    private $noInheritMask;

    /**
     * @param AccessControlList $acl
     * @param string            $objectType
     * @param string            $objectIdentifier
     * @param string            $securityType
     * @param string            $securityIdentifier
     * @param int               $mask
     * @param int               $stopMask
     * @param int               $noInheritMask
     */
    public function __construct(AccessControlList $acl, $objectType, $objectIdentifier, $securityType, $securityIdentifier, $mask, $stopMask, $noInheritMask)
    {
        $this->acl = $acl;
        $this->objectType = $objectType;
        $this->objectIdentifier = $objectIdentifier;
        $this->securityType = $securityType;
        $this->securityIdentifier = $securityIdentifier;
        $this->mask = $mask;
        $this->stopMask = $stopMask;
        $this->noInheritMask = $noInheritMask;
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * {@inheritdoc}
     */
    public function getAcl()
    {
        return $this->acl;
    }

    /**
     * {@inheritdoc}
     */
    public function getObjectType()
    {
        return $this->objectType;
    }

    /**
     * {@inheritdoc}
     */
    public function getObjectIdentifier()
    {
        return $this->objectIdentifier;
    }

    /**
     * {@inheritdoc}
     */
    public function getSecurityType()
    {
        return $this->securityType;
    }

    /**
     * {@inheritdoc}
     */
    public function getSecurityIdentifier()
    {
        return $this->securityIdentifier;
    }

    /**
     * {@inheritdoc}
     */
    public function getMask()
    {
        return $this->mask;
    }

    /**
     * {@inheritdoc}
     */
    public function setMask($mask)
    {
        $this->mask = $mask;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getStopMask()
    {
        return $this->stopMask;
    }

    /**
     * {@inheritdoc}
     */
    public function setStopMask($stopMask)
    {
        $this->stopMask = $stopMask;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getNoInheritMask()
    {
        return $this->noInheritMask;
    }

    /**
     * {@inheritdoc}
     */
    public function setNoInheritMask($inheritMask)
    {
        $this->noInheritMask = $inheritMask;

        return $this;
    }
}


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr-osx64-bld/build/content/xslt/public/nsIXSLTProcessorPrivate.idl
 */

#ifndef __gen_nsIXSLTProcessorPrivate_h__
#define __gen_nsIXSLTProcessorPrivate_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIXSLTProcessorPrivate */
#define NS_IXSLTPROCESSORPRIVATE_IID_STR "b8d727f7-67f4-4dc1-a318-ec0c87280816"

#define NS_IXSLTPROCESSORPRIVATE_IID \
  {0xb8d727f7, 0x67f4, 0x4dc1, \
    { 0xa3, 0x18, 0xec, 0x0c, 0x87, 0x28, 0x08, 0x16 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIXSLTProcessorPrivate : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXSLTPROCESSORPRIVATE_IID)

  enum { DISABLE_ALL_LOADS = 1U };

  /* attribute unsigned long flags; */
  NS_SCRIPTABLE NS_IMETHOD GetFlags(PRUint32 *aFlags) = 0;
  NS_SCRIPTABLE NS_IMETHOD SetFlags(PRUint32 aFlags) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIXSLTProcessorPrivate, NS_IXSLTPROCESSORPRIVATE_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIXSLTPROCESSORPRIVATE \
  NS_SCRIPTABLE NS_IMETHOD GetFlags(PRUint32 *aFlags); \
  NS_SCRIPTABLE NS_IMETHOD SetFlags(PRUint32 aFlags);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIXSLTPROCESSORPRIVATE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetFlags(PRUint32 *aFlags) { return _to GetFlags(aFlags); } \
  NS_SCRIPTABLE NS_IMETHOD SetFlags(PRUint32 aFlags) { return _to SetFlags(aFlags); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIXSLTPROCESSORPRIVATE(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetFlags(PRUint32 *aFlags) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetFlags(aFlags); } \
  NS_SCRIPTABLE NS_IMETHOD SetFlags(PRUint32 aFlags) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetFlags(aFlags); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsXSLTProcessorPrivate : public nsIXSLTProcessorPrivate
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIXSLTPROCESSORPRIVATE

  nsXSLTProcessorPrivate();

private:
  ~nsXSLTProcessorPrivate();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsXSLTProcessorPrivate, nsIXSLTProcessorPrivate)

nsXSLTProcessorPrivate::nsXSLTProcessorPrivate()
{
  /* member initializers and constructor code */
}

nsXSLTProcessorPrivate::~nsXSLTProcessorPrivate()
{
  /* destructor code */
}

/* attribute unsigned long flags; */
NS_IMETHODIMP nsXSLTProcessorPrivate::GetFlags(PRUint32 *aFlags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsXSLTProcessorPrivate::SetFlags(PRUint32 aFlags)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIXSLTProcessorPrivate_h__ */


text:
[![Build Status](https://travis-ci.org/joaovicente/Tracy.svg)](https://travis-ci.org/joaovicente/Tracy)
[![Coverage Status](https://coveralls.io/repos/joaovicente/Tracy/badge.svg?branch=develop)](https://coveralls.io/github/joaovicente/Tracy)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.apm4all.tracy/Tracy/badge.svg?style=flat)](http://mvnrepository.com/artifact/com.apm4all.tracy/Tracy)

# What is Tracy  ?
Tracy is an instrumentation library designed to capture Java code execution paths by capturing discrete transaction processing, telemetry events containing timing, call-flow-ancestry and host identification, along with any other context a developer would like to capture.

# Why does Tracy exist?
* I want to understand the performance characteristics of web applications at each tier/service through analysis of discrete transaction telemetry events.
* I want be able to record transaction metadata at any tier so I can then do ad-hoc analysis to better understand the effect user actions have on the system.
* I believe an Open Source APM core framework can provide standardized building blocks enabling an engineering team to gain insight into the dynamics of their system.
* I believe that with a standardized Open Source APM core, engineering teams can more easily build their own tools for increased application insight and analytics.

## Architecture
The Tracy library is part of a suite of components which make the Tracy framework. The Tracy framework objective is to capture telemetry in a manner such that it can be used to measure and analyze transactions passing through a system.

### Sample system

Consider a system made up of:
* Gateway
* Service 1
* Service 2

The diagram below depicts a Task (distinct user interaction with the system) being executed in the system.
A Task is defined by a discrete user interaction with the system with the intent to produce a result. In a HTTP context, it starts with a user Request and ends with a Response, including all of its inter-system interactions executed in the context of the request.

To understand the telemetry event model of Tracy it is important to understand the following concepts:
* `TracyFrame:` Telemetry (JSON) event containing identification of the Task, Component, Operation (e.g. class method name), Host and method before/after timing information.
```javascript
  {
    "taskId":"T-1234",
    "label":"gwServerMethod",
    "optId":"AAAA",
    "parentOptId":"0000",
    "msecBefore":1427817826500,
    "msecAfter" :1427817826620,
    "msecElapsed":120
  }
```
* `taskId:` Correlation identifier of a TracyTask (spanning multiple hosts/JVMs). taskId MUST be unique (i.e. must not be re-used for more than one Task)
* `label:` Identifier which will be used to identify the Operation (e.g. Java method)
* `optId:` Operation identifier, which identifies segment of code execution. optId is automatically generated by the Tracy library (MUST be unique within a taskId)
* `parentOptId:` The optId of the ancestor (calling method optId if in the same JVM, otherwise RPC originating method on the client JVM). parentOptId is the key to organize TracyFrames into a Graph.

These concepts become clearer when we look at a TracyTask as a graph for the sample system described above

The following code snippets illustrate how to inline instrument to produce the TracyFrames for the _Gateway_ component shown above.

_Context initialisation code:_
```java
public void servletInitialisationMethod() {
    Tracy.setContext("T-1234", "0000", "Gateway");
}
```

_Method instrumentation code:_
```java
public void gwServerMethod() {
  Tracy.before("gwServerMethod");
  // Do work
  gwClientMethod();
  Tracy.after("gwServerMethod");
}

public void gwClientMethod() {
  Tracy.before("gwClientMethod");
  // Calling Service1 here
  Tracy.after("gwClientMethod");
}
```

_Context termination code:_
```java
public void servletFinalizationMethod() {
    for (String event : Tracy.getEventsAsJson())  {
      System.out.println(event);
    }
    Tracy.clearContext();
}
```

If you want something a little more hands-on have a look at the Tracy simulator code in [hello-tracy project](https://github.com/joaovicente/hello-tracy/blob/master/src/main/java/com/apm4all/tracy/HelloTracy.java) or [TracyTest.java](https://github.com/joaovicente/Tracy/blob/develop/src/test/java/com/apm4all/tracy/TracyTest.java)

Another visualization which is particularly useful for performance analysis is the timeline

## Going further with Tracy
Peer Open Source projects
 [tracy-web-services](https://github.com/joaovicente/tracy-web-services) and [tracy-ui](https://github.com/joaovicente/tracy-ui) (screenshot below) then provide backend and visualization from Tracy events, including application performance statistics and drill-downs.

For more information on how it all comes together in your development environment using Docker see https://github.com/joaovicente/tracy-demo
## Version history ##

### 4.0.0 ###
* Introduced `Tracy.annotateRoot()` to allow annotations straight throught to the  root Tracy frame
* Introduced `@Profiled` and `@RequestProfiling` interfaces kindly donated by [Jakub Staš](https://github.com/JakubStas)

### 3.5.3 ###
* Fixed [Issue #7](https://github.com/joaovicente/Tracy/issues/7) `Tracy.setContext() ` with null parenOptId
* Extended test coverage for Tracy.frameError... methods when different errors are raised at 2 frame depth levels

### 3.5.2 ###
* Extending [Issue #3](https://github.com/joaovicente/Tracy/issues/3) to handle backslash

### 3.5.1 ###
* Handling annotation values containing double quotes as per [Issue #3](https://github.com/joaovicente/Tracy/issues/3)

### 3.5.0 ###
* Implemented `Tracy.frameErrorWithoutPopping(String error) `

### 3.4.0 ###
* Implemented `Tracy.annotate(String name, float value) ` and `Tracy.annotate(String name, double value) `

### 3.3.1 ###
* Improved hostname resolution robustess

### 3.3.0 ###
* `getHttpResponseBufferAnnotations() ` now returning annotations in CSV format
* Implemented `Tracy.annotate(String name, boolean value) `

### 3.2.2 ###
* Making Tracy.HTTP_HEADER_X_TRACY_ANNOTATIONS public

### 3.2.1 ###
* getHttpResponseBufferAnnotations() now returns an empty string instead of null if no there are no annotations to retrieve

### 3.2.0 ###
* Added `annotateOnHttpResponseBuffer(String key)` and `getHttpResponseBufferAnnotations()` implementation allowing to send annotations to Client via `X-Tracy-Annotations ` HTTP header
* Added `annotateFromHttpRequestAnnotations()` to facilitate annotating annotations received from the Client in the `X-Tracy-Annotations` HTTP header (currently only supporting string annotations in CSV format e.g. `key1,val1,key2,val2`)

### 3.1.0 ###
* Tracy.getEventsAsJsonTracySegment() introduced to support tracy-publisher `{"tracySegment":[{"taskId":"TID-ab1234-x"`...

### 3.0.0 ###
* Tracy to respect annotation type in JSON Tracy representation `{"taskId":"ABCDE","label":"myCall","optId":"BED1","msecBefore":1427817826607,"msecAfter":1427817826608,"msecElapsed":1, "myAge":43...}` instead of `{"taskId":"ABCDE","label":"myCall","optId":"BED1","msecBefore":"1427817826607","msecAfter":"1427817826608","msecElapsed":"1", "myAge":"43"...}`

### 2.5.0 ###
* Tracy.annotate("anyKey", null) to create a {"anyKey": "null"} annotation
* Tracy.setTaskId(String myFinalTaskId)
* Tracy.getEventsAsJsonArray()

### 2.4.1 ###
* Added TracyEvent.getAnnotation(key)

### 2.4.0 ###
* Removed legacy TracyFuture implementation and tests (new implementation illustrated in TracyConcurrentTest)
* To remove ambiguity, now only supporting one Tracy.context() with three string parameters: TaskId (null generates a random one), parentOptId, componentName

### 2.3.0 ###
* Implemented Tracy.annotate(String longName, long longValue)
* In case where an exception is thown `Tracy.frameError(String errorString)` can be used to close Tracy stack frame with a `errorString` error.
* In case where an exception is thown `Tracy.outerError(String errorString)` can be used to close all Tracy frames with a a generic error and the outer frame with `errorString`.
* Fixed issue where when annotate was called before first Tracy.before() an java.util.EmptyStackException. Tracy now silently ignores the annotation() call

### 2.2.0 ###
* Improved multi-threading support for `java.util.concurrent` using TracyCallable (composite extension of `java.util.concurrent.Callable`) and TracyFutureTask as an extension of `java.util.concurrent.FutureTask`. See `TracyConcurrentTest.java` for usage

### 2.1.0 ###
* Produce `"error"="Unknown"` when Tracy event is not-aftered
* Support for `component` label

### 2.0.2 ###
* Implemented Tracy.annotate(String intName, int intValue) for user convenience
* Allow for user defined optIds - Tracy.setOptId("U001")
* Add safety upon exception thrown unit test
* Improved Tracy API protection against NullPointerException when context is not initialised

### 2.0.1 ###
* Upgrading to junit version 4.11

### 2.0.0 ###
* Improved Futures API by introducing TracyableFutureRequest and TracyableFutureResponse

### 1.2.0 ###
* Added Tracy event output as JSON using Tracy.getEventsAsJson()

### 1.1.0 ###
* Disable tracing if Tracy.setContext() is not called

### 1.0.0 ###
* Initial release - Performance tested. 99th percentile latency below 1ms for 9 event Tracy


text:
package com.consol.citrus.zookeeper.client;

/**
 * @author Martin Maher
 * @since 2.5
 */
public class ZooClientConfig {

    private String id;
    private String url;
    private int timeout;

    public ZooClientConfig() {
    }

    public ZooClientConfig(String id, String url, int timeout) {
        this.id = id;
        this.url = url;
        this.timeout = timeout;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public static ZooKeeperClientConfigBuilder createDefaultConfigBuilder() {
        return new ZooKeeperClientConfigBuilder();
    }

    public static class ZooKeeperClientConfigBuilder {
        public static final String DEFAULT_URL = "localhost:2181";
        public static final int DEFAULT_TIMEOUT = 2000;

        private String id;
        private String url = DEFAULT_URL;
        private int timeout = DEFAULT_TIMEOUT;

        public ZooKeeperClientConfigBuilder withId(String id) {
            this.id = id;
            return this;
        }

        public ZooKeeperClientConfigBuilder withUrl(String url) {
            this.url = url;
            return this;
        }

        public ZooKeeperClientConfigBuilder withTimeout(int timeout) {
            this.timeout = timeout;
            return this;
        }

        public ZooClientConfig build() {
            return new ZooClientConfig(id, url, timeout);
        }

    }
}


text:
 yammer group last meesage id

**Namespace:** [OfficeDevPnP.Core.Entities](OfficeDevPnP.Core.Entities.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public Nullable<Int32> last_message_id { get; set; }
```

### Property Value
Type: System.Nullable<System.Int32>

## See also
- [YammerGroupStats](OfficeDevPnP.Core.Entities.YammerGroupStats.md)
- [OfficeDevPnP.Core.Entities](OfficeDevPnP.Core.Entities.md)


text:
package net.xpece.material.navigationdrawer.descriptors;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.annotation.AttrRes;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import net.xpece.material.navigationdrawer.R;
import net.xpece.material.navigationdrawer.internal.Utils;
import net.xpece.material.navigationdrawer.internal.ViewHolder;

/**
 * Created by Eugen on 10. 1. 2015.
 */
public class BaseNavigationItemDescriptor extends AbsNavigationItemDescriptor
    implements GraphicNavigationItemDescriptor {
    /** Whether item stays active after selecting. */
    protected boolean sticky = false;

    /** Icon resource ID. Gets colored appropriately. */
    @DrawableRes
    protected int iconId = 0;

    /** Item label. */
    protected String text = null;
    @StringRes
    protected int textId = 0;

    /** Color of item icon and text when selected. */
    protected int activeColor = 0xff000000;
    @ColorRes
    protected int activeColorId = R.color.mnd_text_primary_light;
    @AttrRes
    int activeColorAttr = android.R.attr.textColorPrimary;

    /** Color of item icon when not selected. Should be 54% black or 100% white. */
    protected int passiveColor = 0;
    @ColorRes
    protected int passiveColorId = 0;
    @AttrRes
    int passiveColorAttr = 0;
    /**
     * Whether the passive colors have been modified.
     * If not use primary text color for icon in case of dark theme.
     */
    private boolean customPassiveColor = false;

    private Drawable icon = null;
    /** Whether the icon should be tinted. */
    private boolean tintIcon = true;

    private boolean enabled = true;

    public BaseNavigationItemDescriptor(int id) {super(id);}

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    public BaseNavigationItemDescriptor enable() {
        this.enabled = true;
        return this;
    }

    public BaseNavigationItemDescriptor disable() {
        this.enabled = false;
        return this;
    }

    public BaseNavigationItemDescriptor iconResource(@DrawableRes int icon) {
        this.iconId = icon;
        this.icon = null;
        return this;
    }

    @Override
    public Drawable getIcon(Context context) {
        if (iconId != 0) {
            Drawable d = ContextCompat.getDrawable(context, iconId);
            if (d != null) {
                d.mutate();
            }
            return d;
        } else {
            return icon;
        }
    }

    public BaseNavigationItemDescriptor iconColorAlwaysPassiveOff() {
        this.tintIcon = true;
        return this;
    }

    public BaseNavigationItemDescriptor iconColorAlwaysPassiveOn() {
        this.tintIcon = false;
        return this;
    }

    @Override
    public boolean isIconColorAlwaysPassiveOff() {
        return this.tintIcon;
    }

    public BaseNavigationItemDescriptor text(String text) {
        this.text = text;
        this.textId = 0;
        return this;
    }

    public BaseNavigationItemDescriptor text(@StringRes int text) {
        this.textId = text;
        this.text = null;
        return this;
    }

    @Override
    public String getText(Context context) {
        if (textId != 0) {
            return context.getString(textId);
        } else {
            return text;
        }
    }

    public BaseNavigationItemDescriptor activeColor(int color) {
        this.activeColor = color;
        this.activeColorId = 0;
        this.activeColorAttr = 0;
        return this;
    }

    public BaseNavigationItemDescriptor activeColorResource(@ColorRes int color) {
        this.activeColorId = color;
        this.activeColor = 0;
        this.activeColorAttr = 0;
        return this;
    }

    public BaseNavigationItemDescriptor activeColorAttribute(@AttrRes int color) {
        this.activeColorAttr = color;
        this.activeColorId = 0;
        this.activeColor = 0;
        return this;
    }

    @Override
    public int getActiveColor(Context context) {
        if (activeColorAttr != 0) {
            return Utils.getColor(context, activeColorAttr, 0xff000000);
        } else if (activeColorId != 0) {
            return context.getResources().getColor(activeColorId);
        } else {
            return activeColor;
        }
    }

    public BaseNavigationItemDescriptor passiveColor(int color) {
        this.customPassiveColor = true;
        this.passiveColor = color;
        this.passiveColorId = 0;
        this.passiveColorAttr = 0;
        return this;
    }

    public BaseNavigationItemDescriptor passiveColorResource(@ColorRes int color) {
        this.customPassiveColor = true;
        this.passiveColorId = color;
        this.passiveColorAttr = 0;
        this.passiveColor = 0;
        return this;
    }

    public BaseNavigationItemDescriptor passiveColorAttribute(@AttrRes int color) {
        this.customPassiveColor = true;
        this.passiveColorAttr = color;
        this.passiveColorId = 0;
        this.passiveColor = 0;
        return this;
    }

    @Override
    public int getPassiveColor(Context context) {
        if (!customPassiveColor) {
            // icons in dark themes should be 100% white
            final int secondary = Utils.getColor(context, android.R.attr.textColorSecondary, 0xde000000);
            if ((secondary & 0xffffff) == 0xffffff) {
                return Utils.getColor(context, android.R.attr.textColorPrimary, 0xffffffff);
            } else {
                return secondary;
            }
        } else if (passiveColorAttr != 0) {
            return Utils.getColor(context, passiveColorAttr, 0xde000000);
        } else if (passiveColorId != 0) {
            return context.getResources().getColor(passiveColorId);
        } else {
            return passiveColor;
        }
    }

    public BaseNavigationItemDescriptor sticky() {
        sticky = true;
        return this;
    }

    public BaseNavigationItemDescriptor notSticky() {
        sticky = false;
        return this;
    }

    @Override
    public boolean isSticky() {
        return sticky;
    }

    @Override
    public int getLayoutId() {
        return R.layout.mnd_item_base;
    }

    @Override
    public void bindView(View view, boolean selected) {
        super.bindView(view, selected);

        Context context = view.getContext();

        ImageView icon = ViewHolder.get(view, R.id.icon);
        TextView text = ViewHolder.get(view, R.id.text);

        Drawable iconDrawable = getIcon(context);
        boolean tintIcon = isIconColorAlwaysPassiveOff();
        int passiveColor = getPassiveColor(context);
        int activeColor = getActiveColor(context);
        String textString = getText(context);
        int textColor = Utils.getColor(context, android.R.attr.textColorPrimary, 0xde000000);

        text.setText(textString);
        if (selected) {
            text.setTextAppearance(context, R.style.TextAppearance_MaterialNavigationDrawer_Item_Selected);
            text.setTextColor(activeColor);
        } else {
            text.setTextAppearance(context, R.style.TextAppearance_MaterialNavigationDrawer_Item);
            text.setTextColor(textColor);
        }
//    text.setTextColor(Utils.createActivatedColor(textColor, activeColor));

        if (iconDrawable != null) {
            if (tintIcon && selected) {
                icon.setImageDrawable(Utils.tintDrawable(iconDrawable, activeColor));
            } else {
                icon.setImageDrawable(Utils.tintDrawable(iconDrawable, passiveColor));
            }
            icon.setVisibility(View.VISIBLE);
        } else {
            icon.setVisibility(View.GONE);
            icon.setImageDrawable(null);
        }
    }

    @Override
    public String toString() {
        return "BaseNavigationItemDescriptor{" +
            "id=" + id +
            "sticky=" + sticky +
            '}';
    }

    @Override
    public BaseNavigationItemDescriptor activatedBackground(Drawable drawable) {
        return (BaseNavigationItemDescriptor) super.activatedBackground(drawable);
    }

    @Override
    public BaseNavigationItemDescriptor activatedBackgroundResource(@ColorRes int drawable) {
        return (BaseNavigationItemDescriptor) super.activatedBackgroundResource(drawable);
    }

    @Override
    public BaseNavigationItemDescriptor activatedBackgroundAttribute(@AttrRes int drawable) {
        return (BaseNavigationItemDescriptor) super.activatedBackgroundAttribute(drawable);
    }

    @Override
    public BaseNavigationItemDescriptor clearActivatedBackground() {
        return (BaseNavigationItemDescriptor) super.clearActivatedBackground();
    }

    @Override
    public boolean isRecyclable() {
        return true;
    }
}


text:
Deployed in OpenShift using this cartridge:
https://cartreflect-claytondev.rhcloud.com/reflect?github=jcsantosbr/clojure-cartridge

Result in:
http://frodo2-jcsantosbr.rhcloud.com/


text:
package com.p1.mobile.p1android.ui.adapters;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.p1.mobile.p1android.R;
import com.p1.mobile.p1android.io.model.SoftwareLicense;

public class AboutAdapter extends BaseAdapter {

	public AboutAdapter(Activity activity, List<SoftwareLicense> licenses){
		this.activity = activity;
		//this.softwares = softwares;
		this.licenses = licenses;
	}

	static class ViewHolder {
		private TextView name;
		private TextView license;
	}

	private Activity activity;
	private List<SoftwareLicense> licenses = new LinkedList<SoftwareLicense>();

	@Override
	public int getCount() {
		return licenses.size();
	}

	@Override
    public Object getItem(int position) {
    	return position;
    }

    @Override
    public long getItemId(int position) {
    	return position;
    }

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder;
		LayoutInflater inflator = activity.getLayoutInflater();
		final SoftwareLicense license = licenses.get(position);

        if (convertView == null) {
        	holder = new ViewHolder();

        	convertView = inflator.inflate(R.layout.about_item, null);

        	holder.name = (TextView) convertView.findViewById(R.id.software_name);
        	holder.license = (TextView) convertView.findViewById(R.id.license_name);

        	convertView.setTag(holder);
        }
        else {
        	holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(license.getSoftwareName());
        holder.license.setText(license.getLicenseName());

        return convertView;
	}

}


text:
#ifndef __CERBERUS_SUBSCRIPTION_HPP__
#define __CERBERUS_SUBSCRIPTION_HPP__

#include "proxy.hpp"

namespace cerb {

    class Server;

    class LongConnection
        : public ProxyConnection
    {
    protected:
        util::sref<Server> const _attached_server;
    public:
        LongConnection(int clientfd, Server* svr);
        ~LongConnection();

        void on_events(int events);
    };

    class Subscription
        : public LongConnection
    {
        class ServerConn
            : public ProxyConnection
        {
            Subscription* const _peer;
        public:
            ServerConn(util::Address const& addr, Buffer subs_cmd,
                       Subscription* peer);

            void on_events(int events);
            void after_events(std::set<Connection*>& active_conns);
            std::string str() const;
        };

        ServerConn _server;
    public:
        Subscription(Proxy* proxy, int clientfd, Server* peer, Buffer subs_cmd);

        void after_events(std::set<Connection*>& active_conns);
        std::string str() const;
    };

    class BlockedListPop
        : public LongConnection
    {
        class ServerConn
            : public ProxyConnection
        {
            BlockedListPop* const _peer;
            Buffer _buffer;
        public:
            ServerConn(util::Address const& addr, Buffer cmd, BlockedListPop* peer);

            void on_events(int events);
            void on_error();
            void after_events(std::set<Connection*>& active_conns);
            std::string str() const;
        };

        ServerConn _server;
        Proxy* const _proxy;
    public:
        BlockedListPop(Proxy* proxy, int clientfd, Server* peer, Buffer cmd);

        void after_events(std::set<Connection*>& active_conns);
        std::string str() const;
        void restore_client(Buffer const& rsp, bool update_slot_map);
    };

}

#endif /* __CERBERUS_SUBSCRIPTION_HPP__ */


text:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

namespace System;

/// <summary>
/// Helpful logging-related extension methods on <see cref="IServiceProvider"/>.
/// </summary>
internal static class LoggingServiceProviderExtensions
{
    /// <summary>
    /// Retrieves an instance of <see cref="ILogger"/> given the type name <typeparamref name="T"/>.
    /// This is equivalent to <see cref="LoggerFactoryExtensions.CreateLogger{T}(ILoggerFactory)"/>.
    /// </summary>
    /// <returns>
    /// An <see cref="ILogger"/> instance, or null if <paramref name="services"/> is null or the
    /// <see cref="IServiceProvider"/> cannot produce an <see cref="ILoggerFactory"/>.
    /// </returns>
    public static ILogger GetLogger<T>(this IServiceProvider? services)
    {
        return GetLogger(services, typeof(T));
    }

    /// <summary>
    /// Retrieves an instance of <see cref="ILogger"/> given the type name <paramref name="type"/>.
    /// This is equivalent to <see cref="LoggerFactoryExtensions.CreateLogger{T}(ILoggerFactory)"/>.
    /// </summary>
    /// <returns>
    /// An <see cref="ILogger"/> instance, or null if <paramref name="services"/> is null or the
    /// <see cref="IServiceProvider"/> cannot produce an <see cref="ILoggerFactory"/>.
    /// </returns>
    public static ILogger GetLogger(this IServiceProvider? services, Type type)
    {
        // Compiler won't allow us to use static types as the type parameter
        // for the call to CreateLogger<T>, so we'll duplicate its logic here.
        return services?.GetService<ILoggerFactory>()?.CreateLogger(type.FullName!) ?? NullLogger.Instance;
    }
}


text:
package com.b2international.snowowl.core.api.preferences.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.annotation.Nullable;

import org.osgi.service.prefs.Preferences;

import com.google.common.io.Closeables;

public class ConfigurationEntrySerializer<T> {

	private final Preferences preferences;
	private final String key;
	private final File defaultsFile;

	public ConfigurationEntrySerializer(final Preferences preferences, final String key) {
		this(preferences, key, null);
	}

	public ConfigurationEntrySerializer(final Preferences preferences, final String key, final File defaultsFile) {
		this.preferences = preferences;
		this.key = key;
		this.defaultsFile = defaultsFile;
	}

	public String getKey() {
		return key;
	}

	public final T getDefault() {
		final T defaultFromFile = getDefaultFromFile();
		return (null != defaultFromFile) ? defaultFromFile : computeDefault();
	}

	private final T getDefaultFromFile() {

		if (null == defaultsFile || !defaultsFile.canRead()) {
			return null;
		}

		return new XStreamWrapper(this).fromXML(defaultsFile);
	}

	/**
	 * Computes a default value in case a default file is not available.
	 *
	 * @return the computed default value; {@code null} by default, subclasses should override
	 */
	protected T computeDefault() {
		return null;
	}

	public void serialize(final T entry) {
		preferences.put(key, toXml(entry));
	}

	public String toXml(@Nullable final T entry) {
		return null == entry ? "" : new XStreamWrapper(this).toXML(entry);
	}

	public T deserialize() {

		final String xml = preferences.get(key, null);

		if (xml == null) {
			return getDefault();
		} else {
			return new XStreamWrapper(this).fromXML(xml);
		}
	}

	/**
	 * For internal use only; serializes current contents into the defaults file.
	 */
	public void serializeDefaults() throws IOException {

		FileOutputStream stream = null;

		try {
			stream = new FileOutputStream(defaultsFile);
			new XStreamWrapper(this).toXML(computeDefault(), stream);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			Closeables.close(stream, true);
		}
	}
}


text:
<!doctype html>

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">

The Stigma of Sigma Algebras

$M(X)$ –
countably additive measures
on the
$\sigma$-algebra
generated by the
open sets
of the
topology
on the set $X$.

Topology – a study of the word “near”.

A topology on a set is a collection of open subsets closed under finite
intersection and arbitrary union.

A definition of “near” only a mathematician could love.

Algebra (of sets) – a study of the words “not” and “or”

An algebra is a collection of subsets (including the empty set) closed under complement and union.

Algebras are closed under intersection (“and”) by De Morgans's laws.

Measure – a study of the word “count”.

A measure satisfies $\mu(A\cup B) = \mu(A) + \mu(B) - \mu(A\cap B)$ and $\mu(\emptyset) = 0$.

Measures don't double count. Note $\mu(A\cup B) = \mu(A) + \mu(B)$ if $A$ and $B$ are disjoint
($A\cap B = \emptyset$).

A countably additive measure satisfies
$\mu(\bigcup\{A_i\mid i\in\mathbb{N}\}) = \sum\{\mu(A_i)\mid i\in\mathbb{N}\}$
if $\{A_i\}$ are pairwise disjoint.

Riesz Representation Theorem: If $X$ is a compact Hausdorff space then $M(X) \cong C(X)^*$.

$C(X)^*$ – continuous linear functionals on $C(X)$.

Compact – the next best thing to being finite.

A set is compact if every open covering contains a finite subcovering.

A definition only a mathematician could love.

A topology is Hausdorff if for every point and every open set not
containing the point there exists an open set containing the point that
does not intersect the open set.

Sigma-algebras are great for proofs involving
$\lim\limits_{n\to\infty}\int f_n\,d\mu = \int\lim\limits_{n\to\infty} f_n\,d\mu$.

But they drag in a lot of machinery if you don't need to do that.

The proof is highly technical – 6 pages in Rudin's Real and Complex Analysis.

If $X$ is any set then $B(X)^* \cong ba(X)$.

$B(X)$ – bounded functions on $X$.

$ba(X)$ – finitely additive measures on $X$.

Note $\{\displaystyle\sum_i a_i 1_{A_i}\mid a_i\in\mathbb{R}, A_i\subseteq X\}$ is norm dense in $B(X)$.

If $\lambda\in ba(X)$ define $L(\sum_i a_i 1_{A_i}) = \sum_i a_i \lambda(A_i)$.

Well-defined since $\sum_i a_i 1_{A_i} = \sum_j b_j 1_{B_j}$ where $\{B_j\}$ are pairwise disjoint.

If $L\in B(X)^*$ define $\lambda(A) = L(1_A)$.

Norm preserving since ...

Same proof for $B(X,\mathcal{A})^* \cong ba(X,\mathcal{A})$ for any algebra $\mathcal{A}$.

Let $P\in ba(\Omega)$ be positive with $P(\Omega) = 1$.
The conditional expectation of $X$ given an algebra $\mathcal{A}$ is $Y = E[X|\mathcal{A}]$
where $Y$ is $\mathcal{A}$ measurable and $\int_A X\,dP = \int_A Y\,dP$ for all $A\in\mathcal{A}$.

This is equivalent to $(XP)|_\mathcal{A} = Y(P|_\mathcal{A})$ where
$ZP$ is the measure $(ZP)(A) = \int_A Z\,dP$ for $Z\in B(\Omega)$.

        <button id='upArrow' type='button' onclick='upArrow()'></button>

        <button id='toggleInterval' type='button' onclick='toggleInterval()'>0</button>

        <button id='downArrow' type='button' onclick='downArrow()'></button>


text:
.om-buttonbar {height: 26px;border: 1px solid #99A8BC;background: url("images/buttonbar/buttonbar-bg.png");}
.om-buttonbar-null {float: left;width: 20px;height: 26px;}
.om-buttonbar .om-btn {float: left;height: 26px;}
.om-buttonbar .om-btn .om-btn-txt{line-height: 27px\9;}
.om-buttonbar .om-state-default .om-btn-bg {background: none;}
.om-buttonbar .om-state-hover{background: url("images/buttonbar/button-hover-bg.png") !important;}
.om-buttonbar-sep {background: url("images/buttonbar/separtor-bg.png");background-repeat: no-repeat;height: 24px;width: 2px;display: block;margin-left:2px;margin-right:2px;margin-top : 2px;float: left;overflow: hidden;}


text:
/******************************************************************************\
  Timer support
\******************************************************************************/

local timerid = 0

local function Execute(self, name)
	self.data.timer.runner = name

	self.data['timer'].timers[name] = nil

	if(self.entity and self.entity.Execute) then
		self.entity:Execute()
	end

	if !self.data['timer'].timers[name] then
		timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
	end

	self.data.timer.runner = nil
end

local function AddTimer(self, name, delay)
	if delay < 10 then delay = 10 end

	local timerName = "e2_" .. self.data.timer.timerid .. "_" .. name

	if self.data.timer.runner == name and timer.Exists(timerName) then
		timer.Adjust(timerName, delay / 1000, 2, function()
			Execute(self, name)
		end)
		timer.Start(timerName)
	elseif !self.data['timer'].timers[name] then
		timer.Create(timerName, delay / 1000, 2, function()
			Execute(self, name)
		end)
	end

	self.data['timer'].timers[name] = true
end

local function RemoveTimer(self, name)
	if self.data['timer'].timers[name] then
		timer.Remove("e2_" .. self.data['timer'].timerid .. "_" .. name)
		self.data['timer'].timers[name] = nil
	end
end

/******************************************************************************/

registerCallback("construct", function(self)
	self.data['timer'] = {}
	self.data['timer'].timerid = timerid
	self.data['timer'].timers = {}

	timerid = timerid + 1
end)

registerCallback("destruct", function(self)
	for name,_ in pairs(self.data['timer'].timers) do
		RemoveTimer(self, name)
	end
end)

/******************************************************************************/

__e2setcost(20)

e2function void interval(rv1)
	AddTimer(self, "interval", rv1)
end

e2function void timer(string rv1, rv2)
	AddTimer(self, rv1, rv2)
end

__e2setcost(5)

e2function void stoptimer(string rv1)
	RemoveTimer(self, rv1)
end

__e2setcost(1)
e2function number clk()
	return self.data.timer.runner == "interval" and 1 or 0
end

e2function number clk(string rv1)
	return self.data.timer.runner == rv1 and 1 or 0
end

e2function string clkName()
	return self.data.timer.runner or ""
end

e2function array getTimers()
	local ret = {}
	local i = 0
	for name in pairs( self.data.timer.timers ) do
		i = i + 1
		ret[i] = name
	end
	self.prf = self.prf + i * 5
	return ret
end

e2function void stopAllTimers()
	for name in pairs(self.data.timer.timers) do
		self.prf = self.prf + 5
		RemoveTimer(self,name)
	end
end

/******************************************************************************/

e2function number curtime()
	return CurTime()
end

e2function number realtime()
	return RealTime()
end

e2function number systime()
	return SysTime()
end

-----------------------------------------------------------------------------------

local function luaDateToE2Table( time, utc )
	local ret = E2Lib.newE2Table()
	local time = os.date((utc and "!" or "") .. "*t",time)

	if not time then return ret end -- this happens if you give it a negative time

	for k,v in pairs( time ) do
		if k == "isdst" then
			ret.s.isdst = (v and 1 or 0)
			ret.stypes.isdst = "n"
		else
			ret.s[k] = v
			ret.stypes[k] = "n"
		end

		ret.size = ret.size + 1
	end

	return ret
end
__e2setcost(10)
-- Returns the server's current time formatted neatly in a table
e2function table date()
	return luaDateToE2Table()
end

-- Returns the specified time formatted neatly in a table
e2function table date( time )
	return luaDateToE2Table(time)
end

-- Returns the server's current time formatted neatly in a table using UTC
e2function table dateUTC()
	return luaDateToE2Table(nil,true)
end

-- Returns the specified time formatted neatly in a table using UTC
e2function table dateUTC( time )
	return luaDateToE2Table(time,true)
end

-- This function has a strange and slightly misleading name, but changing it might break older E2s, so I'm leaving it
-- It's essentially the same as the date function above
e2function number time(string component)
	local ostime = os.date("!*t")
	local ret = ostime[component]

	return tonumber(ret) or ret and 1 or 0 -- the later parts account for invalid components and isdst
end

-----------------------------------------------------------------------------------

__e2setcost(2)
-- Returns the time in seconds
e2function number time()
	return os.time()
end

-- Attempts to construct the time from the data in the given table (same as lua's os.time)
-- The table structure must be the same as in the above date functions
-- If any values are missing or of the wrong type, that value is ignored (it will be nil)
local validkeys = {hour = true, min = true, day = true, sec = true, yday = true, wday = true, month = true, year = true, isdst = true}
e2function number time(table data)
	local args = {}

	for k,v in pairs( data.s ) do
		if data.stypes[k] ~= "n" or not validkeys[k] then continue end

		if k == "isdst" then
			args.isdst = (v == 1)
		else
			args[k] = v
		end
	end

	return os.time( args )
end


text:
package edu.uci.python.runtime.iterator;

import edu.uci.python.runtime.exception.*;
import edu.uci.python.runtime.sequence.*;

/**
 * @author Gulfem
 */

public class PEnumerateIterator implements PIterator {

    private int index;
    private final PIterator iterator;

    public PEnumerateIterator(PIterator iterator) {
        this.iterator = iterator;
    }

    @Override
    public Object __next__() throws StopIterationException {
        /**
         * StopIterationException is not explicitly thrown, but it can be implicitly thrown and
         * stops the iteration when the __next__() method is called on the iterated object.
         */
        return new PTuple((new Object[]{index++, iterator.__next__()}));
    }

}


text:
"""Mutation that renames a model.

Version Added:
    2.2
"""

from __future__ import unicode_literals

from django_evolution.mock_models import MockModel
from django_evolution.mutations.base import BaseModelMutation

class RenameModel(BaseModelMutation):
    """A mutation that renames a model.

    Version Changed:
        2.2:
        Moved into the :py:mod:`django_evolution.mutations.rename_model`
        module.
    """

    simulation_failure_error = \
        'Cannot rename the model "%(app_label)s.%(model_name)s".'

    def __init__(self, old_model_name, new_model_name, db_table):
        """Initialize the mutation.

        Args:
            old_model_name (unicode):
                The old (existing) name of the model to rename.

            new_model_name (unicode):
                The new name for the model.

            db_table (unicode):
                The table name in the database for this model.
        """
        super(RenameModel, self).__init__(old_model_name)

        self.old_model_name = old_model_name
        self.new_model_name = new_model_name
        self.db_table = db_table

    def get_hint_params(self):
        """Return parameters for the mutation's hinted evolution.

        Returns:
            list of unicode:
            A list of parameter strings to pass to the mutation's constructor
            in a hinted evolution.
        """
        params = [
            self.serialize_value(self.old_model_name),
            self.serialize_value(self.new_model_name),
        ]

        if self.db_table:
            params.append(self.serialize_attr('db_table', self.db_table)),

        return params

    def simulate(self, simulation):
        """Simulate the mutation.

        This will alter the database schema to rename the specified model.

        Args:
            simulation (Simulation):
                The state for the simulation.

        Raises:
            django_evolution.errors.SimulationFailure:
                The simulation failed. The reason is in the exception's
                message.
        """
        app_sig = simulation.get_app_sig()

        model_sig = simulation.get_model_sig(self.old_model_name).clone()
        model_sig.model_name = self.new_model_name
        model_sig.table_name = self.db_table

        app_sig.remove_model_sig(self.old_model_name)
        app_sig.add_model_sig(model_sig)

        old_related_model = '%s.%s' % (simulation.app_label,
                                       self.old_model_name)
        new_related_model = '%s.%s' % (simulation.app_label,
                                       self.new_model_name)

        for cur_app_sig in simulation.project_sig.app_sigs:
            for cur_model_sig in cur_app_sig.model_sigs:
                for cur_field_sig in cur_model_sig.field_sigs:
                    if cur_field_sig.related_model == old_related_model:
                        cur_field_sig.related_model = new_related_model

    def mutate(self, mutator, model):
        """Schedule a model rename on the mutator.

        This will instruct the mutator to rename a model. It will be scheduled
        and later executed on the database, if not optimized out.

        Args:
            mutator (django_evolution.mutators.ModelMutator):
                The mutator to perform an operation on.

            model (MockModel):
                The model being mutated.
        """
        old_model_sig = mutator.model_sig

        new_model_sig = old_model_sig.clone()
        new_model_sig.model_name = self.new_model_name
        new_model_sig.table_name = self.db_table

        new_model = MockModel(project_sig=mutator.project_sig,
                              app_name=mutator.app_label,
                              model_name=self.new_model_name,
                              model_sig=new_model_sig,
                              db_name=mutator.database)

        mutator.add_sql(
            self,
            mutator.evolver.rename_table(new_model,
                                         old_model_sig.table_name,
                                         new_model_sig.table_name))


text:
class RemoveUserNameIndex < ActiveRecord::Migration
  def change
    remove_index(:users, column: :name)
  end
end


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.common.errors.InvalidTopicException;
import org.apache.kafka.common.utils.Utils;
import org.junit.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class InternalTopicConfigTest {

    @Test
    public void shouldHaveCompactionPropSetIfSupplied() {
        final Properties properties = new InternalTopicConfig("name",
                                                              Collections.singleton(InternalTopicConfig.CleanupPolicy.compact),
                                                              Collections.<String, String>emptyMap()).toProperties(0);
        assertEquals("compact", properties.getProperty(InternalTopicManager.CLEANUP_POLICY_PROP));
    }

    @Test(expected = NullPointerException.class)
    public void shouldThrowIfNameIsNull() {
        new InternalTopicConfig(null, Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), Collections.<String, String>emptyMap());
    }

    @Test(expected = InvalidTopicException.class)
    public void shouldThrowIfNameIsInvalid() {
        new InternalTopicConfig("foo bar baz", Collections.singleton(InternalTopicConfig.CleanupPolicy.compact), Collections.<String, String>emptyMap());
    }

    @Test
    public void shouldConfigureRetentionMsWithAdditionalRetentionWhenCompactAndDelete() {
        final InternalTopicConfig topicConfig = new InternalTopicConfig("name",
                                                                        Utils.mkSet(InternalTopicConfig.CleanupPolicy.compact, InternalTopicConfig.CleanupPolicy.delete),
                                                                        Collections.<String, String>emptyMap());
        final int additionalRetentionMs = 20;
        topicConfig.setRetentionMs(10);
        final Properties properties = topicConfig.toProperties(additionalRetentionMs);
        assertEquals("30", properties.getProperty(InternalTopicManager.RETENTION_MS));
    }

    @Test
    public void shouldNotConfigureRetentionMsWhenCompact() {
        final InternalTopicConfig topicConfig = new InternalTopicConfig("name",
                                                                        Collections.singleton(InternalTopicConfig.CleanupPolicy.compact),
                                                                        Collections.<String, String>emptyMap());
        topicConfig.setRetentionMs(10);
        final Properties properties = topicConfig.toProperties(0);
        assertNull(null, properties.getProperty(InternalTopicManager.RETENTION_MS));
    }

    @Test
    public void shouldNotConfigureRetentionMsWhenDelete() {
        final InternalTopicConfig topicConfig = new InternalTopicConfig("name",
                                                                        Collections.singleton(InternalTopicConfig.CleanupPolicy.delete),
                                                                        Collections.<String, String>emptyMap());
        topicConfig.setRetentionMs(10);
        final Properties properties = topicConfig.toProperties(0);
        assertNull(null, properties.getProperty(InternalTopicManager.RETENTION_MS));
    }

    @Test
    public void shouldBeCompactedIfCleanupPolicyCompactOrCompactAndDelete() {
        assertTrue(new InternalTopicConfig("name",
                                           Collections.singleton(InternalTopicConfig.CleanupPolicy.compact),
                                           Collections.<String, String>emptyMap()).isCompacted());
        assertTrue(new InternalTopicConfig("name", Utils.mkSet(InternalTopicConfig.CleanupPolicy.compact,
                                                               InternalTopicConfig.CleanupPolicy.delete),
                                           Collections.<String, String>emptyMap()).isCompacted());
    }

    @Test
    public void shouldNotBeCompactedWhenCleanupPolicyIsDelete() {
        assertFalse(new InternalTopicConfig("name",
                                            Collections.singleton(InternalTopicConfig.CleanupPolicy.delete),
                                            Collections.<String, String>emptyMap()).isCompacted());
    }

    @Test
    public void shouldUseCleanupPolicyFromConfigIfSupplied() {
        final InternalTopicConfig config = new InternalTopicConfig("name",
                                                                   Collections.singleton(InternalTopicConfig.CleanupPolicy.delete),
                                                                   Collections.singletonMap("cleanup.policy", "compact"));

        final Properties properties = config.toProperties(0);
        assertEquals("compact", properties.getProperty("cleanup.policy"));
    }

    @Test
    public void shouldHavePropertiesSuppliedByUser() {
        final Map<String, String> configs = new HashMap<>();
        configs.put("retention.ms", "1000");
        configs.put("retention.bytes", "10000");

        final InternalTopicConfig topicConfig = new InternalTopicConfig("name",
                                                                 Collections.singleton(InternalTopicConfig.CleanupPolicy.delete),
                                                                 configs);

        final Properties properties = topicConfig.toProperties(0);
        assertEquals("1000", properties.getProperty("retention.ms"));
        assertEquals("10000", properties.getProperty("retention.bytes"));
    }
}


text:
//------------------------------------------------------------------------------------------------
// File:  guipictureelement.h
//
// Desc:
//
// Copyright (c) 2007-2008 Unseen Studios.   All rights reserved.
//------------------------------------------------------------------------------------------------
#ifndef __GUIPICTUREELEMENT_H__
#define __GUIPICTUREELEMENT_H__

#include "guielement.h"
typedef unsigned long D3DCOLOR;
struct GUIRect;

/**
 * Puts a picture on the screen without distorting it
 */
class GUIPictureElement : public GUIElement
{
  public:

    /**
     * Initializes the class
     */
    GUIPictureElement();

    /**
     * Stores the texture for this element
     */
    void setTexture(int texture);

    /**
     * Calculates the texture coordinates for the the source area for this element using
     * the dimensions of the current texture.  This method will not function unless
     * the internal texture is currently valid.
     */
    void setSourceRegion(const GUIRect* sourceArea, GUILayer* layer);

    /**
     * Calculates the texture coordinates for the the source area for this element
     */
    void setSourceRegion(const GUIRect* sourceArea, GUISize textureDimensions);

  public:

    /**
     * Renders this text list into the given layer.
     */
    bool render(GUILayer* layer);

    /**
     * Gets the texture used by this fill element
     */
    int getTexture();

    /**
     * Gets the width of the picture this element represents
     */
    float getPictureWidth() const;

    /**
     * Gets the height of the picture this element represents
     */
    float getPictureHeight() const;

  protected:

    /**
     * Draws this picture at the provided coordinates
     */
    bool render(GUILayer* layer, float x, float y, float depth);

    /**
     * Draws this picture centered around the given coordinates
     */
    bool renderCentered(GUILayer* layer, float centerX, float centerY, float depth);

  protected:

    /// The texture used by this element to render
    int myTexture;

    /// The diffuse color for this element
    D3DCOLOR myDiffuseColor;

  private:

    /// The size of this picture
    float myPictureWidth, myPictureHeight;

    /// The element's texture coordinates
    ///  indexed by:  vertex row, vertex column, u/v
    float myTexcoords[2][2][2];
};

#endif


text:
<?xml version="1.0"?>
<document>
  <properties>
    <title>Commonclipse eclipse plug-in</title>
    <author email="fgiust(at)sourceforge.net">Fabrizio Giustina</author>
  </properties>

 Commonclipse is an eclipse plugin for jakarta commons-lang users. It features automatic generation of the
        following methods using commons-lang builders:

toString()

hashcode()

equals(Object)

compareTo(Object)

 Commonclipse supports customization of generated methods (custom ToStringStyle, use of appendSuper(),
        excluded fields) through user defined properties. Commonclipse actions are available both in java editor views
        and in package explorer. See screenshots.

 Built methods use jakarta commons-lang 2.0 builders. Commonclipse will not check for the presence of
        commons-lang in your project classpath, you will need to get a copy from jakarta and to set up java build path appropriately.

 April, 16 2005:  new version 1.3.0 for Eclipse 3.1M6 released. See the change log for details and new features.

        Commonclipse is free for both commercial and non commercial use. If you like this plugin you can
          support its development with a small donation.

Click here to donate to Commonclipse

</document>


text:
package org.apache.camel.spring.processor;

import org.apache.camel.CamelContext;
import org.apache.camel.processor.intercept.InterceptFromUriSimpleLogTest;

import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext;

public class SpringInterceptFromUriSimpleLogTest extends InterceptFromUriSimpleLogTest {

    @Override
    public boolean isUseRouteBuilder() {
        return false;
    }

    @Override
    protected CamelContext createCamelContext() throws Exception {
        return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringInterceptFromUriSimpleLogTest.xml");
    }

}


text:
package storage

import (
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/pkg/errors"

	"github.com/hatena/polymerase/pkg/polypb"
	"github.com/hatena/polymerase/pkg/utils"
)

const (
	metaFileName = "META"
)

type PhysicalStorage interface {
	Type() polypb.StorageType
	Create(key polypb.Key, name string) (io.WriteCloser, error)
	Delete(prefixOrKey polypb.Key) error
	BackupStream(key polypb.Key, backupType polypb.BackupType) (io.Reader, error)
	Walk(f func(path string, info os.FileInfo, err error) error) error
	LoadMeta(key polypb.Key) (*polypb.BackupMeta, error)
	StoreMeta(key polypb.Key, meta *polypb.BackupMeta) error
}

type DiskStorage struct {
	backupsDir string
}

func (s *DiskStorage) Type() polypb.StorageType {
	return polypb.StorageType_LOCAL_DISK
}

func (s *DiskStorage) Create(key polypb.Key, name string) (io.WriteCloser, error) {
	dir := filepath.Join(s.backupsDir, string(key))
	if err := os.MkdirAll(dir, 0755); err != nil {
		return nil, err
	}
	f, err := os.Create(filepath.Join(dir, name))
	if err != nil {
		return nil, err
	}
	return f, nil
}

func (s *DiskStorage) Delete(prefixOrKey polypb.Key) error {
	return os.RemoveAll(filepath.Join(s.backupsDir, string(prefixOrKey)))
}

func (s *DiskStorage) BackupStream(key polypb.Key, backupType polypb.BackupType) (io.Reader, error) {
	switch backupType {
	case polypb.BackupType_XTRABACKUP_FULL:
		return os.Open(filepath.Join(s.backupsDir, string(key), utils.XtrabackupFullArtifact))
	case polypb.BackupType_XTRABACKUP_INC:
		return os.Open(filepath.Join(s.backupsDir, string(key), utils.XtrabackupIncArtifact))
	case polypb.BackupType_MYSQLDUMP:
		return os.Open(filepath.Join(s.backupsDir, string(key), utils.MysqldumpArtifact))
	}
	return nil, errors.Errorf("unknown type %s", backupType)
}

func (s *DiskStorage) Walk(f func(path string, info os.FileInfo, err error) error) error {
	return filepath.Walk(s.backupsDir, f)
}

func (s *DiskStorage) LoadMeta(key polypb.Key) (*polypb.BackupMeta, error) {
	var meta polypb.BackupMeta
	r, err := os.Open(filepath.Join(s.backupsDir, string(key), metaFileName))
	if err != nil {
		return nil, err
	}
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	if meta.Unmarshal(data); err != nil {
		return nil, err
	}
	return &meta, nil
}

func (s *DiskStorage) StoreMeta(key polypb.Key, meta *polypb.BackupMeta) error {
	w, err := s.Create(key, metaFileName)
	if err != nil {
		return errors.Errorf("Storing metadata is failed: %s", err)
	}
	defer w.Close()
	data, err := meta.Marshal()
	if err != nil {
		return err
	}
	_, err = w.Write(data)
	return err
}

type fakePhysicalStorage struct {
	PhysicalStorage
	FakeBackupStream func(key polypb.Key, backupType polypb.BackupType) (io.Reader, error)
	FakeCreate       func(key polypb.Key, name string) (io.WriteCloser, error)
}

func (s *fakePhysicalStorage) Type() polypb.StorageType {
	return polypb.StorageType_LOCAL_MEM
}

func (s *fakePhysicalStorage) BackupStream(key polypb.Key, backupType polypb.BackupType) (io.Reader, error) {
	return s.FakeBackupStream(key, backupType)
}

func (s *fakePhysicalStorage) Create(key polypb.Key, name string) (io.WriteCloser, error) {
	return s.FakeCreate(key, name)
}