text:
'use strict';

var request = require('request');
var Opening_hours = require('opening_hours');
var moment = require('moment');
var momentTZ = require('moment-timezone');

function makeSearchString(obj){

    if(obj === undefined) return '';

       // http://stackoverflow.com/a/3608791
    return '?' + Object.keys(obj).map(function(k){
        if(typeof obj[k] === 'object') return encodeURI(k) + '=' + encodeURI(obj[k].toISOString().replace('T',' ').replace('Z','0'));
        else return encodeURI(k) + '=' + encodeURI(obj[k]);
    })
    .join('&');
}

function sendRequest(url, place, attribute){

    return new Promise(

        function(resolve){

            //console.log(url);
            request({
                method: 'GET',
                url: url,
                headers: {'Content-Type': 'application/json;charset=UTF-8'}
            }, function(error, response, body){

                if (!error) {

                    if(response !== undefined && response.statusCode < 400){
                        try {
                            var clone = place.measures ?    Object.assign({}, place) :
                                                            Object.assign({'measures': []}, place);
                            clone.measures[attribute] = JSON.parse(body);
                            resolve(clone);
                        } catch(e) {
                            console.log('Cannot parse body in request ', e);
                            resolve(place);
                        }
                    }
                    else
                    {
                        console.log(Object.assign(
                            new Error('HTTP error because of bad status code ' + body),
                            {
                                HTTPstatus: typeof response === 'undefined'?'':response.statusCode,
                                text: body,
                                error: error
                            }
                        ));
                        resolve(place);
                    }
                }
                else
                {
                    console.log(Object.assign(

                        new Error('HTTP error'),
                        {
                            HTTPstatus: typeof response === 'undefined'?'':response.statusCode,
                            text: body,
                            error: error
                        }
                    ));
                    resolve(place);
                }
            });
        }
    );
}

function processMeasures(place, start, end, mode){

    var oh = place.opening_hours === null ? undefined :
            new Opening_hours(place.opening_hours);

    var results = {'Affluence' : []};
    //console.log('+++', place.name, place.pheromon_id);
    //console.log(start, '->', end);

    // Transform signal strength
    var measures = [];
    //console.log(place.measures);
    if( place.measures !== undefined &&
        place.measures.today !== undefined){

        measures = place.measures.today.map(function(measure){
            var date = momentTZ.tz(measure.date, 'Europe/Paris').toDate();
            //console.log('-', date, measure.value.length);
            return { date: date, signals: measure.value.length };
        });
    }

    var max = ( place.measures !== undefined &&
                place.measures.latest !== undefined) ?
                place.measures.latest.max: 0;
    var nbTicksX = (20-8)*4; // every 15 minutes from 8am to 8pm
    var now = momentTZ().tz('Europe/Paris').toDate();

    // For each tick of 15 minutes
    for (var i = 0; i<nbTicksX; ++i) {

        var beginTick   = moment(start).add(15*i,'minutes').toDate();
        var endTick     = moment(start).add(15*(i+1),'minutes').toDate();

        var date = new Date(now);
        date.setHours(8+Math.floor(i/4),i*15%60, 0);

        var isOpen = oh ? oh.getState(beginTick) : true;
        if(!isOpen){
            results.Affluence.push(-2);//closed
        }
        else if(beginTick > now || measures.length === 0){
            results.Affluence.push(-1);//unknown
        }
        else{
            // Filter values
            var values = measures
            .filter(function(measure){
                return beginTick <= measure.date
                    && measure.date < endTick;
            })
            .map(function(measure){
                return measure.signals;
            });

            // Compute an average
            var avg = (values.reduce(function(sum, a) {
                return sum + a;
            }, 0) / (values.length || 1)) * 100 / max;

            // Fill series
            results.Affluence.push(Math.floor(avg));
        }
    }

    if(mode === 'citizen') return results;

    // List of bins that changed
    measures = [];
    if( place.measures !== undefined &&
        place.measures.bins !== undefined){

        measures = place.measures.bins;
    }

    var ticksY = [];
    measures.forEach(function(measureBin){
        if(ticksY.indexOf(measureBin.value.id) === -1){
            ticksY.push(measureBin.value.id);
        }
    });

    ticksY.forEach(function(binName){

        results[binName] = [];
        for (i = 0; i<=nbTicksX; ++i) results[binName].push(0);

        //console.log('>', binName);
        var iTickXStart = 0;
        var lastAvailabity = true;

        measures
        .filter(function(measure){
            return measure.value.id === binName;
        })
        .map(function(measure){
            date = new Date(measure.date); // UTC -> Local
            return { date: date, bin: measure.value };
        })
        .sort(function(m1, m2){
            return m1.date - m2.date;
        })
        .forEach(function(measure){

            // 1) we go Backward:
            // for each tick unfilled before a measure
            // we fill with the inverse of status
            // if bin is unvailable at 12am, it was "available" before 12am

            // For each tick of 15 minutes included
            var iTickXEnd = iTickXStart;
            for (i = 0; i<nbTicksX; ++i) {

                beginTick   = moment(start).add(15*i,'minutes').toDate();
                endTick     = moment(start).add(15*(i+1),'minutes').toDate();

                if(measure.date < endTick) break;
                if(endTick > now ) break;

                iTickXEnd = i;

                // Color
                // We invert values:
                // if bin is unvailable at 12am, it was "available" before 12am -> Green
                lastAvailabity = measure.bin.a;
                if(lastAvailabity === false){
                    results[binName][i] = 0;// available => green
                }
                else {
                    results[binName][i] = 100;// unavailable => red
                }
            }
            iTickXStart = iTickXEnd;
        });

        // 2) For the rest of the day, we expand the last status of avilability
        for (i = iTickXStart; i<=nbTicksX; ++i) {

            beginTick   = moment(start).add(15*i,'minutes').toDate();
            endTick     = moment(start).add(15*(i+1),'minutes').toDate();

            // This time, we go forward so do not invert values:
            if(beginTick > now ){
                results[binName][i] = -1;//unknown
            }
            else if(lastAvailabity === true){
                results[binName][i] = 0;
            }
            else {
                results[binName][i] = 100;
            }
        }
    });

    return results;
}

module.exports = function(origin, selection){

    return Promise.all(

        selection.places.map(function(place){

            return new Promise(function(resolve){

                var start   = momentTZ.tz(selection.date, 'Europe/Paris').add(8,'hours').toDate();
                var end     = momentTZ.tz(selection.date, 'Europe/Paris').add(20,'hours').toDate();

                var parameters = {
                    id: place.pheromon_id,
                    type: undefined,
                    start: start,
                    end: end
                };

                if( place.pheromon_id === null ||
                    place.pheromon_id === undefined){

                    place['results'] = processMeasures(place, parameters.start, parameters.end);
                    return resolve(place);
                }

                // 1. Latest
                sendRequest(origin + '/placeLatestMeasurement/' + place.pheromon_id + '/wifi', place, 'latest')
                .then(function(placeWithLatest){

                    // 2. wifi
                    parameters.type = 'wifi';

                    sendRequest(origin + '/measurements/place/raw' + makeSearchString(parameters), placeWithLatest, 'today')
                    .then(function(placeWithToday){

                        if(selection.mode === 'citizen'){
                             // Process measures
                            placeWithToday['results'] = processMeasures(placeWithToday, parameters.start, parameters.end, selection.mode);
                            return resolve(placeWithToday);
                        }
                        else {

                            // 3. bins
                            parameters.type = 'bin';

                            sendRequest(origin + '/measurements/place/raw' + makeSearchString(parameters), placeWithToday, 'bins')
                            .then(function(placeWithBins){

                                placeWithBins['results'] = processMeasures(placeWithBins, parameters.start, parameters.end, selection.mode);
                                return resolve(placeWithBins);
                            })
                            .catch(function(error){
                                console.log(error);
                            });
                        }
                    })
                    .catch(function(error){
                        console.log(error);
                    });
                })
                .catch(function(error){
                    console.log(error);
                });
            });
        })
    );
};


text:
package cn.edu.zjnu.acm.judge.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.time.Instant;
import java.util.List;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 *
 * @author zhanhb
 */
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@Builder(builderClassName = "Builder", toBuilder = true)
@Data
@NoArgsConstructor
@SuppressWarnings({"ReturnOfCollectionOrArrayField", "AssignmentToCollectionOrArrayFieldFromParameter"})
public class Problem implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;
    private String title;
    private String description;
    private String input;
    private String output;
    private String sampleInput;
    private String sampleOutput;
    private String hint;
    private String source;
    private Long timeLimit;
    private Long memoryLimit;

    private List<TestData> testData;
    private List<Image> images;

    private Long accepted;
    private Long submit;
    private Long submitUser;
    private Long solved;
    private Instant inDate;
    private Boolean disabled;
    private Instant createdTime;
    private Instant modifiedTime;

    private Long origin;
    private long[] contests;

    // 0 not submitted, 1 accepted, 2 wrong answer
    private Integer status;

    @JsonIgnore
    public int getRatio() {
        Long s = submit, a = accepted;
        return s == null || a == null || s == 0 ? 0 : (int) Math.round(a * 100.0 / s);
    }

    @JsonIgnore
    public int getDifficulty() {
        Long s = submit, a = accepted;
        return s == null || a == null || s == 0 ? 0 : (int) Math.round((s - a) * 100.0 / s);
    }

}

redpajama_set_name: RedPajamaGithub


text:
using NUnit.Framework;
using osu.Game.Rulesets.Osu.Mods;

namespace osu.Game.Rulesets.Osu.Tests.Mods
{
    public class TestSceneOsuModFlashlight : OsuModTestScene
    {
        [TestCase(600)]
        [TestCase(120)]
        [TestCase(1200)]
        public void TestFollowDelay(double followDelay) => CreateModTest(new ModTestData { Mod = new OsuModFlashlight { FollowDelay = { Value = followDelay } }, PassCondition = () => true });

        [TestCase(1f)]
        [TestCase(0.5f)]
        [TestCase(1.5f)]
        [TestCase(2f)]
        public void TestSizeMultiplier(float sizeMultiplier) => CreateModTest(new ModTestData { Mod = new OsuModFlashlight { SizeMultiplier = { Value = sizeMultiplier } }, PassCondition = () => true });

        [Test]
        public void TestComboBasedSize([Values] bool comboBasedSize) => CreateModTest(new ModTestData { Mod = new OsuModFlashlight { ComboBasedSize = { Value = comboBasedSize } }, PassCondition = () => true });
    }
}


text:
{% extends "layouts/base.html" %}
{% load widget_tweaks %}
{% load staticfiles %}

{% block title %}Company Profile{% endblock %}

{% block head %}
{{ form.media }}
{% endblock %}

{% block header %}{% include 'header.html' %}{% endblock %}
{% block sidebar %}{% include 'sidebar.html' %}{% endblock %}

{% block content %}

        Company Profile
        Edit

		<form role="form" action="" method="POST">

Details

								{{ form.name.label }}
								{{ form.name|add_class:"form-control" }}
								{{ form.name.errors }}

								{{ form.description.label }}
								{{ form.description|add_class:"form-control" }}
								{{ form.description.errors }}

								API {{ form.endpoint.label }}
								{{ form.endpoint|add_class:"form-control" }}
								{{ form.endpoint.errors }}

Integration

								{{ form.apple_url.label }}
								{{ form.apple_url|add_class:"form-control" }}
								{{ form.apple_url.errors }}

Actions

							{% csrf_token %}
  							<button class="btn btn-primary" type="submit">Save</button>

		</form>

{% endblock %}

{% block script %}

{% endblock %}


text:
import Component from '@glimmer/component';
import { inject as service } from '@ember/service';
import { action } from '@ember/object';
import { truncateVerifiId } from 'dummy/utils/truncate-verifi-id';
import { titleize } from 'dummy/utils/titleize';
import { formatId } from 'dummy/utils/format-id';
import MusicalWorkSvg from 'dummy/images/media-registry/musical-work.svg';

export default class MusicalWorkEmbedded extends Component {
  @service router;

  get musicalWorkEmbedded() {
    let card = this.args.model;
    if (!card) {
      return 'N/A';
    }

    return {
      id: card?.iswc,
      type: 'musical-work',
      imgURL: MusicalWorkSvg,
      title: titleize(card?.title),
      description: card.composer
        ? `by ${card?.artist}, ${card?.composer}`
        : `by ${card?.description}`,
      fields: [
        {
          title: 'iswc',
          value: card?.iswc,
        },
        {
          title: 'verifi id',
          value: truncateVerifiId(card?.verifi_id),
        },
      ],
    };
  }

  @action
  transitionToMusicalWork() {
    if (this.args.model.id === 'the-sun-comes-out') {
      if (this.args.model.version) {
        return this.router.transitionTo(
          'media-registry.musical-works.work-version',
          'the-sun-comes-out',
          this.args.model.version
        );
      }
      this.router.transitionTo(
        'media-registry.musical-works.work',
        'the-sun-comes-out'
      );
    } else {
      this.router.transitionTo(
        'media-registry.item.musical-work',
        formatId(this.args.model.title)
      );
    }
  }
}


text:
""" Hyperparameter optimization of DNN model
Uses hyperopt module to search for optimal DNN hyper parameters.

Note: 'output_size' can't be changed during hyperparameter search as data preprocessing depends on this parameter.
      If you need to search over this parameter, make sure to re-execute 'feature_engineering.load_data' in '_objective' function (can be expensive).

.. See https://github.com/PaulEmmanuelSotir/NYC_TaxiTripDuration
"""
from sklearn.utils import resample
import tensorflow as tf
import hyperopt as ho
import pandas as pd
import numpy as np
import time
import math
import os

import utils
import nyc_dnn

# Full example of hyperparameter search space:
# HP_SPACE = {'epochs': 200,
#            'early_stopping': 20,
#            'lr': ho.hp.loguniform('lr', math.log(2e-5), math.log(2e-3)),
#            'momentum': ho.hp.uniform('momentum', 0.8, 0.95),
#            'depth': ho.hp.choice('depth', [4, 5, 6, 7, 8, 9]),
#            'hidden_size': ho.hp.choice('hidden_size', [256, 512, 1024]),
#            'batch_size': ho.hp.choice('batch_size', [256, 512, 1024, 2048]),
#            'dropout_keep_prob': ho.hp.uniform('dropout_keep_prob', 0.75, 0.9),
#            'l2_regularization': ho.hp.loguniform('l2_regularization', math.log(1e-6), math.log(1e-3)),
#            'output_size': ho.hp.choice('output_size', [1, 128, 256, 512])}

# Hyperparameter optimization space and algorithm
MAX_EVALS = 100
SUB_TRAINSET_SIZE = 1.
ALLOW_GPU_MEM_GROWTH = True
OPT_ALGO = ho.tpe.suggest
HP_SPACE = {'epochs': 50,
            'early_stopping': 10,
            'lr': ho.hp.loguniform('lr', math.log(2e-5), math.log(2e-3)),  # TODO: add tf.train.exponential_decay
            'momentum': ho.hp.uniform('momentum', 0.8, 0.95),
            'depth': 6,
            'embedding_dim': 8,
            'max_embedding_values': 64,
            'hidden_size': 512,
            'batch_size': 1024,
            'dropout_keep_prob': ho.hp.uniform('dropout_keep_prob', 0.7, 1.0),
            'l2_regularization': ho.hp.loguniform('l2_regularization', math.log(1e-7), math.log(1e-3)),
            'output_size': 512}

def main(_=None):
    # Define working directories
    source_dir = os.path.dirname(os.path.abspath(__file__))
    save_dir = '/output/' if tf.flags.FLAGS.floyd_job else os.path.join(source_dir, 'models/hyperopt_models/')
    dataset_dir = '/input/' if tf.flags.FLAGS.floyd_job else os.path.join(source_dir, 'NYC_taxi_data_2016/')

    # Load and preprocess data
    features_len, (test_ids, testset), dataset, bucket_means = nyc_dnn.feature_engineering.load_data(dataset_dir,
                                                                                'train.csv',
                                                                                'test.csv',
                                                                                nyc_dnn.VALID_SIZE,
                                                                                HP_SPACE['output_size'],
                                                                                tf.flags.FLAGS.floyd_job)

    # Reduce trainset size (sample a subset of trainset)
    train_data, test_data, train_targets, test_targets, train_labels, test_labels = dataset
    train_data, train_targets, train_labels = resample(train_data, train_targets, train_labels,
                                                       replace=False, n_samples=int(SUB_TRAINSET_SIZE * len(train_data)))
    dataset = (train_data, test_data, train_targets, test_targets, train_labels, test_labels)

    # Define the objective function optimized by hyperopt
    eval_count = 0

    def _objective(hyperparameters):
        nonlocal eval_count
        eval_count += 1
        model_save_dir = save_dir + str(eval_count) + '/'
        print('\n\n' + '#' * 10 + ' TRYING HYPERPERPARAMETER SET #' + str(eval_count) + ' ' + '#' * 10)
        print(hyperparameters)
        # Reset default tensorflow graph
        tf.reset_default_graph()
        # Write hyperparameters to summary as text (once per session/model)
        hp_string = tf.placeholder(tf.string, name='hp')
        hp_summary_op = tf.summary.text('hyperparameters', hp_string, collections=['per_session'])
        with tf.Session(config=utils.tf_config(ALLOW_GPU_MEM_GROWTH)) as sess:
            summary_writer = tf.summary.FileWriter(model_save_dir, sess.graph)
            summary = sess.run(hp_summary_op, feed_dict={hp_string: 'Trial #' + str(eval_count) + ' hyperparameters:\n' + str(hyperparameters)})
            summary_writer.add_summary(summary, 0)
        # Build model
        model = nyc_dnn.build_graph(features_len, hyperparameters, bucket_means, summarize=False)
        # Train model
        test_rmse, predictions = nyc_dnn.train(model, dataset, hyperparameters, model_save_dir, testset)
        # Save predictions to csv file for Kaggle submission
        predictions = np.int32(np.round(np.exp(predictions))) - 1
        pd.DataFrame(np.column_stack([test_ids, predictions]), columns=['id', 'trip_duration']
                     ).to_csv(os.path.join(save_dir, str(eval_count), 'preds.csv'), index=False)
        return {'loss': test_rmse,  # TODO: put last batch average loss here?
                'true_loss': test_rmse,
                'status': ho.STATUS_OK,
                'eval_time': time.time()}

    # Run optimization algorithm
    trials = ho.Trials()
    best_parameters = ho.fmin(_objective,
                              space=HP_SPACE,
                              algo=OPT_ALGO,
                              max_evals=MAX_EVALS,
                              trials=trials)
    print('\n\n' + '#' * 20 + '  BEST HYPERPARAMETERS  ' + '#' * 20)
    print(best_parameters)  # TODO: translate ho.hp.choice hyperarameters from index to their actual value

if __name__ == '__main__':
    tf.logging.set_verbosity(tf.logging.INFO)  # Set log level to debug
    tf.flags.DEFINE_bool('floyd-job', False, 'Change working directories for training on Floyd.')
    tf.app.run()


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.benchmark;

import com.facebook.presto.testing.LocalQueryRunner;

import static com.facebook.presto.benchmark.BenchmarkQueryRunner.createLocalQueryRunner;

public class SqlHashJoinBenchmark
        extends AbstractSqlBenchmark
{
    public SqlHashJoinBenchmark(LocalQueryRunner localQueryRunner)
    {
        super(localQueryRunner,
                "sql_hash_join",
                4,
                5,
                "select lineitem.orderkey, lineitem.quantity, orders.totalprice, orders.orderkey from lineitem join orders using (orderkey)");
    }

    public static void main(String[] args)
    {
        new SqlHashJoinBenchmark(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out));
    }
}


text:
package net.blay09.mods.cookingbook.food;

import net.minecraft.item.ItemStack;

import java.util.List;

public abstract class FoodRecipe {

    protected List<FoodIngredient> craftMatrix;
    protected ItemStack outputItem;

    public List<FoodIngredient> getCraftMatrix() {
        return craftMatrix;
    }

    public ItemStack getOutputItem() {
        return outputItem;
    }

    public boolean isSmeltingRecipe() {
        return false;
    }

}


text:
package io.github.skepter.skepbot.modules;

public class Oodler extends Module {

	public Oodler() {
		super("oodle phrases", PatternType.STARTS_WITH, "oodle ");
	}

	@Override
	public String output() {
		return input.substring(6).replaceAll("[aeiou]", "oodle").replaceAll("[AEIOU]", "Oodle");
	}

}


text:
qx.Class.define("soap.RequestHeader", { extend: qx.core.Object
    ,properties: {
         _row : {check: "Integer", nullable: true, init: 0}
        ,_sort_key : {check: "String", nullable: true, init: null}
        ,_sort_ord : {check: "String", nullable: true, init: null}
    }
    ,statics: {
        TYPE_DEFINITION: {
            ns: 'soap'
        }
    }
});


text:
layout: post
microblog: true
audio:
photo:
date: 2013-11-23 07:48:45 -0600
guid: http://craigmcclellan.micro.blog/2013/11/23/t404245136743596032.html
---
Praying for all my friends headed to Guatemala and Thailand with @CRWorldwide this morning. Love you guys.


text:
import path from 'path';
import glob from 'glob';

const pkg = require('../../../package.json');
import Conf from '../../../tool/base.config';

const chrome = {
    title: `Welcome to ${pkg.name} v${pkg.version}`,
    description: pkg.description,
    links: {
        "site.webmanifest": "site.webmanifest",
        "apple-touch-icon": "apple-touch-icon.png"
    },
    scripts: glob.sync('**/*.js', { cwd: Conf.target.js_path }).map(s => path.join("js", s)),
    styles: glob.sync('**/*.css', { cwd: Conf.target.css_path }).map( s => path.join("css", s)),
    rel: '',
    gaKey: Conf.TRACK_ID
}

const page = {
    author: "Modesty",
    date: new Date(2019, 8, 1, 0, 0, 0)
};

export default { chrome, page };


text:
import numpy as np
from scipy.stats import scoreatpercentile
import matplotlib.pyplot as p

def rht(mask, radius, ntheta=180, background_percentile=25, verbose=False):
    '''

    Parameters
    ----------

    mask : numpy.ndarray
           Boolean or integer array. Transform performed at all
           non-zero points.

    radius : int
             Radius of circle used around each pixel.

    ntheta : int, optional
             Number of angles to use in transform.

    background_percentile : float, optional
                            Percentile of data to subtract off. Background is
                            due to limits on pixel resolution.

    verbose : bool, optional
        Enables plotting.

    Returns
    -------

    theta : numpy.ndarray
            Angles transform was performed at.

    R : numpy.ndarray
        Transform output.

    '''

    pad_mask = np.pad(mask.astype(float), radius, padwithnans)

    # The theta=0 case isn't handled properly
    theta = np.linspace(np.pi/2., 1.5*np.pi, ntheta)

    # Create a cube of all angle positions
    circle, mesh = circular_region(radius)
    circles_cube = np.empty((ntheta, circle.shape[0], circle.shape[1]))
    for posn, ang in enumerate(theta):
        diff = mesh[0]*np.sin(ang) - mesh[1]*np.cos(ang)
        diff[np.where(np.abs(diff) < 1.0)] = 0
        circles_cube[posn, :, :] = diff

    R = np.zeros((ntheta,))
    x, y = np.where(mask != 0.0)
    for i, j in zip(x, y):
        region = np.tile(circle * pad_mask[i:i+2*radius+1,
                                           j:j+2*radius+1], (ntheta, 1, 1))
        line = region * np.isclose(circles_cube, 0.0)

        if not np.isnan(line).all():
            R = R + np.nansum(np.nansum(line, axis=2), axis=1)

    # Check that the ends are close.
    if np.isclose(R[0], R[-1], rtol=1.0):
        R = R[:-1]
        theta = theta[:-1]
    else:
        raise ValueError("R(-pi/2) should equal R(pi/2). Check input.")

    # You're likely to get a somewhat constant background, so subtract it out
    R = R - np.median(R[R <= scoreatpercentile(R, background_percentile)])
    if (R < 0.0).any():
        R[R < 0.0] = 0.0  # Ignore negative values after subtraction

    # Return to [-pi/2, pi/2] interval and position to the correct zero point.
    theta -= np.pi
    R = np.fliplr(R[:, np.newaxis])

    mean_circ = circ_mean(theta, weights=R)
    twofive, sevenfive = circ_CI(theta, weights=R, u_ci=0.67)
    twofive = twofive[0]
    sevenfive = sevenfive[0]
    quantiles = (twofive, mean_circ, sevenfive)

    if verbose:
        p.subplot(1, 2, 1, polar=True)
        p.plot(2*theta, R, "rD")
        p.plot([2*mean_circ]*2, [0, R.max()], "k")
        p.plot([2*twofive]*2, [0, R.max()], "r")
        p.plot([2*sevenfive]*2, [0, R.max()], "r")
        p.subplot(1, 2, 2)
        p.imshow(mask, cmap="binary", origin='lower')
        p.show()

    return theta, R, quantiles

def circular_region(radius):
    '''
    Create a circle of a given radius.
    Values are NaNs outside of the circle.

    Parameters
    ----------
    radius : int
        Circle radius.

    Returns
    -------
    circle : numpy.ndarray
        Array containing the circle.
    [xx, yy] : numpy.ndarray
        Grids used to create the circle.
    '''
    xx, yy = np.mgrid[-radius:radius+1, -radius:radius+1]

    circle = xx**2. + yy**2.
    circle = circle < radius**2.

    circle = circle.astype(float)
    circle[np.where(circle == 0.)] = np.NaN

    return circle, [xx, yy]

def padwithnans(vector, pad_width, iaxis, kwargs):
    vector[:pad_width[0]] = np.NaN
    vector[-pad_width[1]:] = np.NaN
    return vector

def find_nearest(array, value):
    idx = (np.abs(array-value)).argmin()
    return array[idx]

def find_nearest_posn(array, value):
    idx = (np.abs(array-value)).argmin()
    return idx

def circ_mean(theta, weights=None):
    """
    Calculates the median of a set of angles on the circle and returns
    a value on the interval from (-pi, pi].  Angles expected in radians.

    Parameters
    ----------
    """

    if len(theta.shape) == 1:
        theta = theta[:, np.newaxis]

    if weights is None:
        weights = np.ones(theta.shape)

    medangle = np.arctan2(np.nansum(np.sin(2*theta) * weights),
                          np.nansum(np.cos(2*theta) * weights))

    medangle /= 2.0

    return medangle

def circ_CI(theta, weights=None, u_ci=0.67, axis=0):
    '''

    '''

    if len(theta.shape) == 1:
        theta = theta[:, np.newaxis]

    if weights is None:
        weights = np.ones(theta.shape)
    else:
        if len(weights.shape) == 1:
            weights = weights[:, np.newaxis]

    assert theta.shape == weights.shape

    # Normalize weights
    weights /= np.sum(weights, axis=axis)

    mean_ang = circ_mean(theta, weights=weights)

    # Now center the data around the mean to find the CI intervals
    mean_posn = find_nearest_posn(theta, mean_ang)

    diff_posn = -1 * (theta.shape[0]/2 - mean_posn)

    theta_copy = np.roll(theta, diff_posn)

    vec_length2 = np.sum(weights * np.cos(theta_copy), axis=axis)**2. + \
        np.sum(weights * np.sin(theta_copy), axis=axis)**2.

    alpha = np.sum(weights * np.cos(2*theta_copy), axis=axis)

    var_w = (1 - alpha) / (4 * vec_length2)

    # Make sure the CI stays within the interval. Otherwise assign it to
    # pi/2 (largest possible on interval of pi)
    sin_arg = u_ci * np.sqrt(2 * var_w)

    if sin_arg <= 1:
        ci = np.arcsin(sin_arg)
    else:
        ci = np.pi / 2.

    samp_cis = np.vstack([mean_ang - ci, mean_ang + ci])

    return samp_cis


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

public class objectRender : MonoBehaviour {

	GameObject myHam, myCube, mySphr, myPlane, mySteam;
	int objIndex;
	Vector2 startPosition;
	float startTime;

	void Start () {
		myHam = GameObject.Find ("HamEgg");
		myCube = GameObject.Find ("cube");
		mySphr = GameObject.Find ("sphere");
		mySteam = GameObject.Find ("WhiteSmoke");

		//myPlane = GameObject.Find ("ARplane");
		//start with case 3
		objIndex = 3;
	}

	// Update is called once per frame
	void Update () {

//			if (gesture ()) {
//				objIndex++;
//				Debug.Log ("Swipe Detected");
//			}

		if (Input.GetMouseButtonDown (0)) {
			objIndex++;
			Debug.Log ("Left Click");
		}

		if (Input.GetMouseButtonDown (1)) {
			objIndex--;
			Debug.Log ("Right Click");
		}

		if (objIndex == 4) {
			objIndex = 1;
		}

		if (objIndex == 0) {
			objIndex = 3;
		}

		switch (objIndex) {
		case 1:
			showHam (false);
			showCube (true);
			showSphr (false);
			showSteam (false);
			Debug.Log ("Case 1");
			break;
		case 2:
			showCube (false);
			showSphr (true);
			showHam (false);
			showSteam (false);
			Debug.Log ("Case 2");
			break;
		case 3:
			showSphr (false);
			showHam (true);
			showSteam (true);
			showCube (false);
			Debug.Log ("Case 3");
			break;
		}
	}

	void showHam(bool n){
		myHam.gameObject.GetComponent<Renderer> ().enabled = n;
	}

	void showCube(bool n){
		myCube.gameObject.GetComponent<Renderer> ().enabled = n;
	}

	void showSphr(bool n){
		mySphr.gameObject.GetComponent<Renderer> ().enabled = n;
	}

	void showSteam(bool n){
		mySteam.gameObject.GetComponent<Renderer> ().enabled = n;
	}

	// gestures
	bool gesture(){

		//Get initial touch location and time
		if (Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) {
			startPosition = Input.GetTouch(0).position;
			startTime = Time.time;
		}

		//Get final touch location and calculate swipe
		if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended) {
			Vector2 endPosition = Input.GetTouch(0).position;
			Vector2 delta = endPosition - startPosition;

			float dist = Mathf.Sqrt(Mathf.Pow(delta.x, 2) + Mathf.Pow (delta.y, 2));
			float angle = Mathf.Atan (delta.y/delta.x) * (180.0f/Mathf.PI);
			float duration = Time.time - startTime;
			float speed = dist/duration;

			// Left to right swipe
			if (startPosition.y < endPosition.y) {
				if (angle < 0) angle = angle * 1.0f;

				if (dist > 300 &&  angle < 10 && speed > 1000) {

					return true;

				}
			}
		}

		return false;

	}

}


text:
table = false;
tableDom = false;

var apiRoute = "https://prod-api.level-labs.com/api/v2/core/"
document.addEventListener('DOMContentLoaded', function() {
  var sample = "im in line 32";
  $('#transactions').click(function(e) {
    $('#tableTitle').text("Transactions");
    $('#tableDescription').text("See your transactions");
    getAllTransactions();
  })
  $('#accounts').click(function(e) {
    $('#tableTitle').text("Accounts");
    $('#tableDescription').text("See your accounts");
    getAccounts();
  })
  $('#projects').click(function(e) {
    $('#tableTitle').text("Projects");
    $('#tableDescription').text("See your projects");
    projectTransactions();
  })
  $('#balances').click(function(e) {
    $('#tableTitle').text("Balances");
    $('#tableDescription').text("See your balances");
    getHistoricalAndProjectedBalances();
  })
  $('#aggregate').click(function(e) {
    $('#tableTitle').text("Aggregate");
    $('#tableDescription').text("See your aggragation");
    aggregateTransaction();
  })

  $('#bankSubmit').click(function(e) {
    //debugger
    var transactionInfo = getAllTransactions();
    //debugger
  })

  var getAllTransactions = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/get-all-transactions", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var userTransac = parsed['transactions'];
        //showTable(getColumns(userTransac), getData(userTransac));

        var columns = [];
        var datarows = [];
        var fixedColumns = [];
        var fixedData = [];
        fixedColumns = [
          { name: 'amount', title:'Amount' },
          //{ name: 'is-pending', title:'Status' },
          { name: 'aggregation-time', title:'Time' },
          //{ name: 'account-id', title:'Account' },
          { name: 'transaction-id', title:'Transaction ID' },
          { name: 'raw-merchant', title:'Merchant' }
        ];

        for(var i=0; i<userTransac.length; i++) {
          var row = [];
          var fixedRow = [];
          for( column in fixedColumns) {
            fixedRow.push (userTransac[i][fixedColumns[column].name]);
          }
          for( property in userTransac[i] ) {
            if(i==0) {
              columns.push({ title: property });
            } else {
              row.push(userTransac[i][property]);
            }
          }

          if(i>0){
            //fixedData.push(fixedRow);
            fixedData.push([
                userTransac[i]['amount'],
                //userTransac[i]['is-pending'],
                formatDate(userTransac[i]['aggregation-time']),
                //userTransac[i]['account-id'],
                userTransac[i]['transaction-id'],
                userTransac[i]['raw-merchant']
              ]
            );
            datarows.push(row);
          }
        }

        showTable(fixedColumns, fixedData);
    };
    xhr.onerror = function(err) {
        //document.getElementById('outrpc28').textContent = "ugh an error. i can't handle this right now.";
        console.log("Error occured.");
    };

    args = {"args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
    xhr.send(JSON.stringify(args));

  }

  // FETCH ALL COLUMNS
  var getColumns = function (data){
    var columns = [];
    for( property in data[0] ) {
      columns.push({ title: property });
    }
    return columns;
  }

  // FETCH ALL DATA
  var getData = function (data){
    var datarows = [];
    for(var i=0; i<data.length; i++) {
      var row = [];
      for( property in data[i] ) {
          row.push(data[i][property]);
      }
        datarows.push(row);
    }
    return datarows;
  }

  var formatAmount = function(amount){

  }
  var formatDate = function(UNIX_timestamp){
    var a = new Date(UNIX_timestamp);
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
    return time;
  }

  var showTable = function(columns, datarows) {
    if (table == false) {
    } else {
      table.clear();
      table.destroy();
      tableDom.remove();
    }

    tableDom = $('#table').clone()
    tableDom = $('#table').after(tableDom);
    table = tableDom.DataTable({
      data: datarows,
      columns: columns,
      //responsive: true
    });

  }

  var projectTransactions = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/projected-transactions-for-month", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var jsonResponse = JSON.stringify(parsed, null, 2);
        console.log(jsonResponse);

        var transactions = parsed['transactions'];
        showTable(getColumns(transactions), getData(transactions));
        // document.getElementById('outrpc29').textContent = pretty;
    };
    xhr.onerror = function(err) {
        console.log("Error occured.");
        // document.getElementById('outrpc29').textContent = "ugh an error. i can't handle this right now.";
    };
    args = {"args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}, "year":  2015, "month":  3};
    xhr.send(JSON.stringify(args));
  }

  var getHistoricalAndProjectedBalances = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/balances", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var jsonResponse = JSON.stringify(parsed, null, 2);
        console.log(jsonResponse);
        // document.getElementById('outrpc30').textContent = pretty;

        var accounts = parsed['days'];
        showTable(getColumns(accounts), getData(accounts));
    };
    xhr.onerror = function(err) {
        console.log("error occured");
        // document.getElementById('outrpc30').textContent = "ugh an error. i can't handle this right now.";
    };
    args = {"args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
    xhr.send(JSON.stringify(args));
  }

  var getAccounts = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/get-accounts", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var jsonResponse = JSON.stringify(parsed, null, 2);

        var accounts = parsed['accounts'];
        showTable(getColumns(accounts), getData(accounts));

        console.log(jsonResponse);
        // document.getElementById('outrpc30').textContent = pretty;

    };
    xhr.onerror = function(err) {
        console.log("error occured");
        // document.getElementById('outrpc30').textContent = "ugh an error. i can't handle this right now.";
    };
    args = {"args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
    xhr.send(JSON.stringify(args));
  }

  var aggregateTransaction = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/aggregate-transactions", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var jsonResponse = JSON.stringify(parsed, null, 2);
        console.log(jsonResponse);
        // document.getElementById('outrpc30').textContent = pretty;
        var transactions = parsed['transactions'];
        showTable(getColumns(transactions), getData(transactions));

    };
    xhr.onerror = function(err) {
        console.log("error occured");
        // document.getElementById('outrpc30').textContent = "ugh an error. i can't handle this right now.";
    };
    args = {"args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
    xhr.send(JSON.stringify(args));
  }

var Login = function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/login", true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.setRequestHeader('Accept', 'application/json');
  xhr.onloadend = function() {
      var parsed = JSON.parse(this.response);
      var jsonResponse = JSON.stringify(parsed, null, 2);
      console.log(jsonResponse);
      //document.getElementById('outrpc34').textContent = pretty;
  };
  xhr.onerror = function(err) {
      //document.getElementById('outrpc34').textContent = "ugh an error. i can't handle this right now.";
  };
  args = {"email":  "level@example.com", "password":  "incorrect_password", "args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
  xhr.send(JSON.stringify(args));
}
  var Login = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://prod-api.level-labs.com/api/v2/core/login", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Accept', 'application/json');
    xhr.onloadend = function() {
        var parsed = JSON.parse(this.response);
        var jsonResponse = JSON.stringify(parsed, null, 2);
        console.log(jsonResponse);
        //document.getElementById('outrpc34').textContent = pretty;
    };
    xhr.onerror = function(err) {
        //document.getElementById('outrpc34').textContent = "ugh an error. i can't handle this right now.";
    };
    args = {"email":  "jsnx21@gmail.com", "password":  "incorrect_password", "args": {"uid":  1110881160, "token":  "4A7C75C97619AAE75614834BBDE2DE2F", "api-token":  "HackathonAPITokenDevweek4222"}};
    xhr.send(JSON.stringify(args));
  }
})


text:
<?php

namespace TonicHealthCheck\Incident\Siren\Subject;

use Cron\CronExpression;

/**
 * Class Subject.
 */
class Subject implements SubjectInterface
{
    /**
     * @var string;
     */
    private $target;

    /**
     * @var CronExpression ;
     */
    private $schedule;

    /**
     * Subject constructor.
     *
     * @param string              $target
     * @param null|CronExpression $schedule
     */
    public function __construct($target, CronExpression $schedule = null)
    {
        $this->setTarget($target);
        $this->setSchedule($schedule);
    }

    /**
     * @return string
     */
    public function getTarget()
    {
        return $this->target;
    }

    /**
     * @return CronExpression
     */
    public function getSchedule()
    {
        return $this->schedule;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getTarget();
    }

    /**
     * @param string $target
     */
    protected function setTarget($target)
    {
        $this->target = $target;
    }

    /**
     * @param null|CronExpression $schedule
     */
    protected function setSchedule(CronExpression $schedule = null)
    {
        $this->schedule = $schedule;
    }
}


text:
package gov.nasa.arc.spife.core.plan.rules.view;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;

public enum RuleIcons {

	RULE_ENFORCED("rule_enforced.png"),
	RULE_WAIVED("rule_waived.png"),

	;

	private final Image image;

	public Image getImage() {
		return image;
	}

	RuleIcons(String iconPath) {
		ImageDescriptor descriptor = Activator.getImageDescriptor("icons/"+iconPath);
		if (descriptor != null) {
			image = descriptor.createImage();
		} else {
			image = null;
		}
	}

}


text:
package com.chenlb.mmseg4j.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Set;
import java.util.TreeSet;

import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.Dictionary.FileLoading;
import com.chenlb.mmseg4j.example.DicTransform.WriterRow;

public class MergeDic {

	/**
	 * 尝试合并 sogou(去除了没有词性的) 与 rmmseg 的词库。
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		FileInputStream fis = new FileInputStream(new File("dic/word-with-attr.dic"));
		final Set<String> words = new TreeSet<String>();
		final int[] num = {0};
		FileLoading fl = new FileLoading() {

			public void row(String line, int n) {
				words.add(line.trim());
				num[0]++;
			}

		};

		Dictionary.load(fis, fl);

		fis = new FileInputStream(new File("dic/words-rmmseg.dic"));

		Dictionary.load(fis, fl);

		WriterRow wr = new WriterRow(new File("dic/words-marge-sogou-no-attr-and-rmmseg.dic"));
		for(String word : words) {
			wr.writerRow(word);
		}
		wr.close();
		System.out.println("rows="+num[0]+", size="+words.size()+", same="+(num[0]-words.size()));
	}

}


text:
@implementation TestSimpleHttpClientFilter

//----------------------------------------------------------------------------//
#pragma mark -- APIs --
//----------------------------------------------------------------------------//

- (void)test
{
    NSString *jsonHost = @"json.org";
    NSString *xmlHost  = @"xml.org";
    NSString *htmlHost = @"html.org";

    SimpleHttpClientFilter *filter = [
        [[SimpleHttpClientFilter alloc] init] autorelease
    ];

    [filter
        setFilter:SimpleHttpClientFilterJSON
          forHost:jsonHost
    ];

    [filter
        setFilter:SimpleHttpClientFilterXML
          forHost:xmlHost
    ];

    [filter
        setFilter:SimpleHttpClientFilterHTML
          forHost:htmlHost
    ];

    SimpleHttpClientFilterBase *jsonFilter = [filter filterObjectForHost:jsonHost];
    SimpleHttpClientFilterBase *xmlFilter  = [filter filterObjectForHost:xmlHost];
    SimpleHttpClientFilterBase *htmlFilter = [filter filterObjectForHost:htmlHost];

    NSAssert1(
        [jsonFilter isKindOfClass:[SimpleHttpClientFilterForJSON class]],
        @"jsonFilter is %@", jsonFilter
    );

    NSAssert1(
        [xmlFilter isKindOfClass:[SimpleHttpClientFilterForXML class]],
        @"xmlFilter is %@", xmlFilter
    );

    NSAssert1(
        [htmlFilter isKindOfClass:[SimpleHttpClientFilterForHTML class]],
        @"htmlFilter is %@", htmlFilter
    );
}

@end


text:
<link href="../../../../../concordion.css" rel="stylesheet" type="text/css" />
<title>Failures</title>

Failures

        Failures are indicated by adding a class="failure" attribute to the element,
        and replacing the contents with a <del> and <ins>
        elements containing the expected value and the actual value respectively.

Example

            The output of running this:

<p concordion:assertTrue="isPalindrome(#TEXT)">ABB</p>

Looks like this:

<p concordion:assertTrue="isPalindrome(#TEXT)" class="failure">
  <del class="expected">ABB</del>
  <ins class="actual">== false</ins>
</p>

Note: The underscores indicate line continuations for readability only. They are not output. In reality, it is all in one long line.


text:
#ifndef TENSORFLOW_COMPILER_XLA_PJRT_UTILS_H_
#define TENSORFLOW_COMPILER_XLA_PJRT_UTILS_H_

#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/client/executable_build_options.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/service/computation_placer.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/shape.h"
#include "tensorflow/compiler/xla/statusor.h"

namespace xla {

// Returns the num_replicas, num_partitions and device assignment given a
// ExecutableBuildOptions and whether we want a portable executable.
Status ParseDeviceAssignmentCompileOptions(
    bool compile_portable_executable, ExecutableBuildOptions* build_options,
    std::function<StatusOr<DeviceAssignment>(int, int)>
        GetDefaultDeviceAssignmentFunction,
    int* num_replicas, int* num_partitions,
    std::shared_ptr<DeviceAssignment>* device_assignment);

// Returns pointers to the argument layouts given an XlaComputation and
// ExecutableBuildOptions.
Status DetermineArgumentLayoutsFromCompileOptions(
    const XlaComputation& computation,
    std::function<StatusOr<Shape>(Shape)>
        choose_compact_layout_for_shape_function,
    absl::optional<std::vector<Shape>>& argument_layouts,
    ExecutableBuildOptions* build_options,
    std::vector<const Shape*>* argument_layout_pointers);

// Executables can donate buffers so that buffers can be aliased from inputs
// to outputs. This function returns the list of parameters that must be
// donated when executable is run. tuple_inputs reflects the option that
// executable was compiled with.
StatusOr<absl::flat_hash_set<int>> GetParametersThatMustBeDonated(
    const HloModule& module, bool tuple_inputs);

}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_PJRT_UTILS_H_


text:
package se.claremont.autotest.common;

import se.claremont.autotest.support.SupportMethods;

import java.text.SimpleDateFormat;

/**
 * This class represents the HTML based test case executon testCaseLog, as compared to the pure text testCaseLog that might be considered for some occasions.
 *
 * Created by jordam on 2016-08-27.
 */
class TestCaseHtmlExecutionLog {

    /**
     * Compiles and writes the test case HTML based execution testCaseLog.
     * @param testCase the test case
     */
    static void create(TestCase testCase){
        write(testCase);
    }

    /**
     * Enums for the class names of the HTML document to avoid orphan references.
     */
    enum HtmlLogStyleNames{
        knownerror,
        timestamp,
        striped,
        logrow,
        logpostslist,
        knownerrors,
        head,
        data,
        testcasedata,
        testcasedataparametername,
        testcasedatavalue
    }

    /**
     * Used to apped HTML style information to the HTML based testCaseLog
     * @return A HTML formatted string to incorporate in the style tag in the HTML testCaseLog
     */
    private static String styles(){
        StringBuilder sb = new StringBuilder();
        sb.append("      body                    { background-color: honeydew; }").append(LF);
        sb.append("      table                   { border: 1px solid black; margin-left: 10px;}").append(LF);
        sb.append("      img                     { border: 1px solid darkgrey; }").append(LF);
        sb.append("      table#").append(HtmlLogStyleNames.logpostslist.toString()).append("             { background-color: white; }").append(LF);
        sb.append("      table#").append(HtmlLogStyleNames.logpostslist.toString()).append(" tr:hover     { background-color: lightgrey; }").append(LF);
        sb.append("      table.").append(HtmlLogStyleNames.striped.toString()).append(" tr:nth-child(even)                 { background-color: #f2f2f2 }").append(LF);
        sb.append("      td.").append(HtmlLogStyleNames.timestamp.toString()).append("            { color: grey; }").append(LF);
        sb.append("      img                     { border: 0 none; width: 105px; background: #999; }").append(LF);
        sb.append("      img:hover               { margin: -1px -2px -2px -1px; width: 340px; }").append(LF);
        sb.append("      td.").append(LogLevel.VERIFICATION_PASSED.toString()).append("  { color: green; }").append(LF);
        sb.append("      td.").append(LogLevel.EXECUTED.toString()).append("             { color: black; }").append(LF);
        sb.append("      td.").append(LogLevel.VERIFICATION_FAILED.toString()).append("  { color: red; font-weight: bold; }").append(LF);
        sb.append("      td.").append(LogLevel.EXECUTION_PROBLEM.toString()).append("    { color: red; font-weight: bold; }").append(LF);
        sb.append("      td.").append(LogLevel.VERIFICATION_PROBLEM.toString()).append(" { color: red; font-weight: bold; }").append(LF);
        sb.append("      td.").append(LogLevel.FRAMEWORK_ERROR.toString()).append("      { color: red; font-weight: bold; }").append(LF);
        sb.append("      td.").append(HtmlLogStyleNames.knownerror.toString()).append("           { color: red; font-weight: bold; } ").append(LF);
        sb.append("      td.").append(LogLevel.INFO.toString()).append("                 { color: blue; }").append(LF);
        sb.append("      td.").append(LogLevel.DEBUG.toString()).append("                { color: Grey; }").append(LF);
        sb.append("      td.").append(LogLevel.DEVIATION_EXTRA_INFO.toString()).append(" { color: blue; }").append(LF);
        sb.append("      font.").append(HtmlLogStyleNames.data.toString()).append("               { color: blue; }").append(LF);
        return sb.toString();
    }

    /**
     * Prints the output of the test case to an HTML formatted text file
     */
    private static void write(TestCase testCase){
        boolean errorseEncountered = testCase.testCaseLog.hasEncounteredErrors();
        testCase.log(LogLevel.DEBUG, "Saving html report to '" + testCase.pathToHtmlLog + "'.");
        System.out.println("Saving html report to '" + testCase.pathToHtmlLog + "'.");
        StringBuilder html = new StringBuilder();
        html.append("").append(LF).append(LF);
        html.append("  ").append(LF).append(LF);
        html.append("    <title>Test testCaseLog ").append(testCase.testName).append("</title>").append(LF);
        html.append("    <meta charset=\"UTF-8\">").append(LF);
        html.append("    <meta name=\"description\" content=\"Test case result for test run for test case ").append(testCase.testName).append("\">").append(LF);
        html.append("    ").append(LF).append(LF);
        html.append("  ").append(LF).append(LF);
        html.append("  ").append(LF).append(LF);

        html.append("
").append(LF);
        html.append("      ").append(LF);
        html.append("
Test results for test case '").append(testCase.testName).append("'
").append(LF);
        html.append("
").append(LF);
        html.append("        Status: ").append(SupportMethods.enumCapitalNameToFriendlyString(testCase.resultStatus.toString())).append("
").append(LF);
        html.append("        Start time: ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(testCase.startTime)).append("
").append(LF);
        html.append("        Stop time:  ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(testCase.stopTime)).append(LF);
        html.append("
").append(LF);
        html.append("
").append(LF).append(LF);

        //If found errors are judged to be known errors, these are stated together here
        if(testCase.testCaseKnownErrorsList.size() > 0){
            html.append("
").append(LF);
            html.append("
Encountered known errors
").append(LF);
            html.append("
").append(LF);
            for(KnownError knownError : testCase.testCaseKnownErrorsList.knownErrors){
                html.append("
").append(knownError.description).append("
").append(LF);
            }
            html.append("
").append(LF);
            html.append("
").append(LF).append(LF);
        }

        //TestCaseLog section for test case data recorded during runtime
        if(testCase.testCaseData.size() > 0){
            html.append("
Test case data
").append(LF);
            html.append("
").append(LF);
            for(ValuePair valuePair : testCase.testCaseData){
                html.append("
").append(valuePair.parameter).append("	").append(valuePair.value).append("
").append(LF);
            }
            html.append("
").append(LF);
        }

        //TestCaseLog post list, with debug info filtered out if everything went well and no errors occured
        html.append("
Test case testCaseLog entries
").append(LF);
        html.append("
").append(LF);
        html.append("
Time	testCaseLog level	Message
").append(LF);
        for( LogPost logPost : testCase.testCaseLog.logPosts){
            if((!errorseEncountered && logPost.logLevel.equals(LogLevel.DEBUG))) continue;
            html.append("        ").append(logPost.toHtmlTableRow()).append(LF);
        }
        html.append("
").append(LF);

        html.append("  ").append(LF).append(LF);
        html.append("").append(LF);
        SupportMethods.saveToFile(html.toString(), testCase.pathToHtmlLog);
    }

    /**
     * Line feed/Form feed for relevant OS
     */
    private static final String LF = SupportMethods.LF;

}


text:
<?php

namespace Logular\Modules;

use Logular as Logular;

class ConsoleLogger extends Logular\Logger
{

    public function entry($message, $level = Logular\LogLevel::INFO, $variable = null)
    {

        try {
            $message = parent::entry($message, $level, $variable);
        } catch (\Exception $e) {
            return;
        }

        echo $message, PHP_EOL;

        return $message;
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MagicNetworkExplorer" >

    <TextView
		android:id="@+id/main_ipaddress_title"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignParentTop="true"
		style="?android:attr/listSeparatorTextViewStyle"
		android:text="@string/main_ipaddress_title"/>

    <TextView
        android:id="@+id/main_ipaddress"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="8dp"
        android:gravity="center_vertical"
        android:layout_below="@id/main_ipaddress_title"
        android:text="@string/main_ipaddress_error"/>

    <TextView
		android:id="@+id/main_scanner_status_title"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_marginTop="8dp"
		android:layout_below="@id/main_ipaddress"
		style="?android:attr/listSeparatorTextViewStyle"
		android:text="@string/main_scanner_status_title"/>

    <TextView
        android:id="@+id/main_scanner_status"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginLeft="8dp"
        android:gravity="center_vertical"
        android:layout_below="@id/main_scanner_status_title"
        android:text="@string/main_scanner_status_idle"/>

    <TextView
		android:id="@+id/main_scanner_found_title"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_marginTop="8dp"
		android:layout_below="@id/main_scanner_status"
		style="?android:attr/listSeparatorTextViewStyle"
		android:text="@string/main_scanner_found_title"/>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/main_scanner_found_title"/>

</RelativeLayout>


text: Termos de uso | Política de Privacidade


text:
namespace performance_manager {
namespace mechanism {

class MemoryPressureVoterOnUIThread;

// HighPMFMemoryPressureSignals is meant to be used by a
// HighPMFMemoryPressurePolicy to notify the global MemoryPressureMonitor when
// the total PMF of Chrome exceeds a threshold.
class HighPMFMemoryPressureSignals {
 public:
  using MemoryPressureLevel = base::MemoryPressureListener::MemoryPressureLevel;

  HighPMFMemoryPressureSignals();
  ~HighPMFMemoryPressureSignals();
  HighPMFMemoryPressureSignals(const HighPMFMemoryPressureSignals& other) =
      delete;
  HighPMFMemoryPressureSignals& operator=(const HighPMFMemoryPressureSignals&) =
      delete;

  // Should be called each time the memory pressure level computed by
  // HighPMFMemoryPressurePolicy changes.
  void SetPressureLevel(MemoryPressureLevel level);

 private:
  MemoryPressureLevel pressure_level_ =
      MemoryPressureLevel::MEMORY_PRESSURE_LEVEL_NONE;

  std::unique_ptr<MemoryPressureVoterOnUIThread> ui_thread_voter_;

  SEQUENCE_CHECKER(sequence_checker_);
};

}  // namespace mechanism
}  // namespace performance_manager

#endif  // CHROME_BROWSER_PERFORMANCE_MANAGER_MECHANISMS_HIGH_PMF_MEMORY_PRESSURE_SIGNALS_H_


text:
using namespace std;

namespace mtconnect::entity {
  using namespace mtconnect::printer;

  extern "C" void XMLCDECL entityXMLErrorFunc(void *ctx ATTRIBUTE_UNUSED, const char *msg, ...)
  {
    va_list args;

    char buffer[2048] = {0};
    va_start(args, msg);
    vsnprintf(buffer, 2046u, msg, args);
    buffer[2047] = '0';
    va_end(args);

    LOG(error) << "XML: " << buffer;
  }

  inline entity::QName nodeQName(xmlNodePtr node)
  {
    entity::QName qname((const char *)node->name);

    if (node->ns && node->ns->prefix &&
        strncmp((const char *)node->ns->href, "urn:mtconnect.org:MTConnectDevices", 34u))
    {
      qname.setNs((const char *)node->ns->prefix);
    }

    return qname;
  }

  inline void trim(string &s)
  {
    auto beg = s.find_first_not_of(" \t\n");
    if (beg > 0)
      s.erase(0, beg);
    if (!s.empty())
    {
      auto end = s.find_last_not_of(" \t\n");
      if (end < s.size() - 1)
        s.erase(end + 1);
    }
  }

  static Value parseRawNode(xmlNodePtr node)
  {
    stringstream str;
    for (xmlNodePtr child = node->children; child; child = child->next)
    {
      xmlBufferPtr buf;
      THROW_IF_XML2_NULL(buf = xmlBufferCreate());
      auto count = xmlNodeDump(buf, child->doc, child, 0, 0);
      if (count > 0)
      {
        str << (const char *)buf->content;
      }
      xmlBufferFree(buf);
    }
    Value content {nullptr};
    if (str.tellp() > 0)
      content = str.str();
    return content;
  }

  EntityPtr XmlParser::parseXmlNode(FactoryPtr factory, xmlNodePtr node, ErrorList &errors,
                                    bool parseNamespaces)
  {
    auto qname = nodeQName(node);
    auto ef = factory->factoryFor(qname);
    if (ef)
    {
      OrderMapPtr order;
      AttributeSet attrs;
      if (ef->isAny())
      {
        order = make_shared<OrderMap>();
      }

      Properties properties;
      EntityList *l {nullptr};
      if (ef->isList())
      {
        l = &properties["LIST"].emplace<EntityList>();
      }

      for (xmlAttrPtr attr = node->properties; attr; attr = attr->next)
      {
        if (attr->type == XML_ATTRIBUTE_NODE)
        {
          entity::QName qname((const char *)attr->name);
          if (attr->ns)
            qname.setNs((const char *)attr->ns->prefix);
          properties.insert({qname, string((const char *)attr->children->content)});
          if (!islower(qname.getName()[0]))
          {
            attrs.emplace(qname);
          }
        }
      }

      if (parseNamespaces && node->nsDef)
      {
        for (auto def = node->nsDef; def; def = def->next)
        {
          string name;
          if (def->prefix)
            name = {string("xmlns:") + (const char *)def->prefix};
          else
            name = "xmlns";

          properties.insert({name, string((const char *)def->href)});
        }
      }

      if (ef->hasRaw())
      {
        auto value = parseRawNode(node);
        if (holds_alternative<string>(value))
          properties.insert({"RAW", value});
      }
      else
      {
        int orderCount = 0;
        for (xmlNodePtr child = node->children; child; child = child->next)
        {
          if (child->type == XML_ELEMENT_NODE)
          {
            auto name = nodeQName(child);
            bool simple = ef->isSimpleProperty(name);
            if (order)
            {
              order->emplace(name, orderCount++);

              if (!simple && !ef->isProperty(name))
              {
                simple = child->children != nullptr && child->properties == nullptr &&
                         child->nsDef == nullptr && child->children->next == nullptr &&
                         child->children->type == XML_TEXT_NODE;
              }
            }

            if (simple)
            {
              if (child->children != nullptr && child->children->content != nullptr)
              {
                string s((const char *)child->children->content);
                trim(s);
                if (!s.empty())
                  properties.insert({nodeQName(child), s});
              }
            }
            else
            {
              auto ent = parseXmlNode(ef, child, errors);
              if (ent)
              {
                if (l != nullptr)
                {
                  l->emplace_back(ent);
                }
                else if (ef->isPropertySet(ent->getName()))
                {
                  auto res = properties.try_emplace(ent->getName(), EntityList {});
                  get<EntityList>(res.first->second).emplace_back(ent);
                }
                else
                {
                  properties.insert({ent->getName(), ent});
                }
              }
              else
              {
                LOG(warning) << "Unexpected element: " << nodeQName(child);
                errors.emplace_back(
                    new EntityError("Invalid element '" + nodeQName(child) + "'", qname));
              }
            }
          }
          else if (child->type == XML_TEXT_NODE)
          {
            string s((const char *)child->content);
            trim(s);
            if (!s.empty())
              properties.insert({"VALUE", s});
          }
        }
      }

      try
      {
        auto entity = ef->make(qname, properties, errors);
        if (entity)
        {
          if (order)
            entity->setOrder(order);
          if (!attrs.empty())
            entity->setAttributes(attrs);
        }
        return entity;
      }
      catch (EntityError &e)
      {
        e.setEntity(qname);
        errors.emplace_back(e.dup());
      }
    }

    return nullptr;
  }

  EntityPtr XmlParser::parse(FactoryPtr factory, const string &document, const string &version,
                             ErrorList &errors, bool parseNamespaces)
  {
    NAMED_SCOPE("entity.xml_parser");
    EntityPtr entity;
    try
    {
      xmlInitParser();
      xmlXPathInit();
      xmlSetGenericErrorFunc(nullptr, entityXMLErrorFunc);

      unique_ptr<xmlDoc, function<void(xmlDocPtr)>> doc(
          xmlReadMemory(document.c_str(), int32_t(document.length()), "document.xml", nullptr,
                        XML_PARSE_NOBLANKS),
          [](xmlDocPtr d) { xmlFreeDoc(d); });
      xmlNodePtr root = xmlDocGetRootElement(doc.get());
      if (root != nullptr)
        entity = parseXmlNode(factory, root, errors, parseNamespaces);
      else
        errors.emplace_back(new EntityError("Cannot parse asset"));
    }

    catch (EntityError e)
    {
      LOG(error) << "Cannot parse XML document: " << e.what();
      errors.emplace_back(e.dup());
      entity.reset();
    }

    catch (XmlError e)
    {
      LOG(error) << "Cannot parse XML document: " << e.what();
      errors.emplace_back(new EntityError(e.what()));
      entity.reset();
    }

    catch (...)
    {
      LOG(error) << "Cannot parse XML document: unknown error";
      errors.emplace_back(new EntityError("Unknown Error"));
      entity.reset();
    }

    return entity;
  }
}  // namespace mtconnect::entity


text:
import { HttpResponse } from 'common/http/http-client.types'

export function responseToBody<B>(response: HttpResponse<B>): B {
    return response.body
}


text:
INIT_EXCEPTION_MAIN(e)

int main(int argc, char* argv[])
{
  Stack  *stack = Read_Stack("/Users/zhaot/Data/neurolineage/2_to_5_lineages/medium-syn-d120-hs72-B10L.tif");
  Stack *grey_stack = Stack_Channel_Extraction(stack, 1, NULL);
  Stack *resample_stack = Resample_Stack_Depth(grey_stack, NULL, 0.255);
  Write_Stack("../data/fly_neuron4_org.tif", grey_stack);
  Write_Stack("../data/fly_neuron4.tif", resample_stack);

  return 1;
}


text:
if ENV['TRAVIS']
    require 'coveralls'
      Coveralls.wear!
end

require 'bundler/setup'
Bundler.require
require 'minitest/autorun'


text:
<?php
/**
 * Created by Szymon Szymański <szymon.szymanski@hotmail.com>
 * Date: 02.05.2017
 * Time: 19:36
 */

namespace Szyku\NLTK\Assertion;

use Assert\Assertion as BaseAssertion;
use Szyku\NLTK\Exception\NltkClientAssertionException;

class Assertion extends BaseAssertion
{
    protected static $exceptionClass = NltkClientAssertionException::class;
}


text:
SMTP(S)
^^^^^^^
Logs into an SMTP server and sends an email

`Uses Accounts`

Custom Properties:

.. list-table::
   :widths: 25 50

   * - touser
     - address that the email will be sent to
   * - subject
     - subject of the email
   * - body
     - body of the email


text:
class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!
  before_filter :authorize_admin
  respond_to :html, :xml, :json

  def index
    @articles = Article.all
    respond_with(@articles)
  end

  def show
    respond_with(@article)
  end

  def new
    @article = Article.new
    respond_with(@article)
  end

  def edit
  end

  def create
    @article = Article.new(article_params)
    @article.save
    respond_with(@article)
  end

  def update
    @article.update(article_params)
    respond_with(@article)
  end

  def destroy
    @article.destroy
    respond_with(@article)
  end

  private
    def set_article
      @article = Article.find(params[:id])
    end

    def article_params
      params.require(:article).permit(:title, :content, :image)
    end
end


text:
from contextlib import contextmanager

@contextmanager
def call_on_exit(obj, call, *args, **kwargs):
    """Get the attribute 'call' from 'obj' and call with the remaining
    arguments upon exiting the context manager.

    Upon entrance 'obj' is returned.

    """
    try:
        yield obj
    finally:
        fxn = getattr(obj, call)
        fxn(*args, **kwargs)


text:
var mapOperator = {
    puertoRico: {},
    pueblos: {},
    tooltip: {},
    youTubeAPIKey: 'AIzaSyA1H0afPg9KoZXsZKr6hTRfir22QwFGNHs',
    init: function() {
      this.tooltip = d3.select('#map').append('div').attr('class', 'tooltip');
      var config = {
      	node: $('#map')[0],
  		tiles: ['pueblos'],
  		size: 'medium',
 		on_ready: mapOperator.bindActions
      };
      this.puertoRico = new AtlasPR(config);
    },

    getPlayListItems: function(playListID) {
      var playListID = 'PL5Mlzwwjsgub3w0W18UFcIn3d998mPqXC'; // @todo -- bye bye once abstracted
      var url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=' +
      playListID +
      '&key=' +
      this.youTubeAPIKey;

      //return $.ajax({
      $.ajax({
          type: 'GET',
          url: url,
          async: false,
          contentType: "application/json",
          dataType: 'jsonp',
          success: function(res) {
            console.log(res);
          }
      });
    },

    bindActions: function() {
        mapOperator.getPlayListItems('ten');
        var pueblos = mapOperator.puertoRico.svg.selectAll('.pueblos');
        pueblos.on('mousemove', function(d,i){
            var mouse = d3.mouse(mapOperator.puertoRico.svg.node()).map(function(d) { return parseInt(d); });
            mapOperator.tooltip.html('Name: ' + d.properties.NAME + ''+
                '
' +
                '
' +
                '' +
                '
')
                .transition()
                .duration(300)
                .style('visibility', 'visible')
                .style('left', (mouse[0] + 25) + 'px')
                .style('top', mouse[1] + 'px');

        })
        .on('mouseover', function(d, i) {
            d3.select(this).style('stroke-width', 3).style('fill', 'red');
        })
        .on("mouseout",  function(d,i) {
            d3.select(this).style('stroke-width', 2).style('fill', 'white');
            mapOperator.tooltip.style('visibility', 'hidden').html('');
            // tooltip.classed("hidden", true)
        });

    }
}


text:
package org.apache.jackrabbit.oak.plugins.memory;

import static com.google.common.collect.Maps.newHashMap;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE;
import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.MISSING_NODE;

import java.util.HashMap;
import java.util.Map;

import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.spi.state.AbstractNodeState;
import org.apache.jackrabbit.oak.spi.state.ChildNodeEntry;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateDiff;
import org.jetbrains.annotations.NotNull;

/**
 * Basic in-memory node state implementation.
 */
class MemoryNodeState extends AbstractNodeState {

    private final Map<String, PropertyState> properties;

    private final Map<String, NodeState> nodes;

    /**
     * Creates a new node state with the given properties and child nodes.
     * The given maps are stored as references, so their contents and
     * iteration order must remain unmodified at least for as long as this
     * node state instance is in use.
     *
     * @param properties properties
     * @param nodes child nodes
     */
    public MemoryNodeState(
            Map<String, PropertyState> properties,
            Map<String, NodeState> nodes) {
        this.properties = properties;
        this.nodes = nodes;
    }

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

    @Override
    public boolean hasProperty(@NotNull String name) {
        return properties.containsKey(name);
    }

    @Override
    public PropertyState getProperty(@NotNull String name) {
        return properties.get(name);
    }

    @Override
    public long getPropertyCount() {
        return properties.size();
    }

    @NotNull
    @Override
    public Iterable<? extends PropertyState> getProperties() {
        return properties.values();
    }

    @Override
    public boolean hasChildNode(@NotNull String name) {
        return nodes.containsKey(name);
    }

    @NotNull
    @Override
    public NodeState getChildNode(@NotNull String name) {
        NodeState state = nodes.get(name);
        if (state == null) {
            checkValidName(name);
            state = MISSING_NODE;
        }
        return state;
    }

    @Override
    public long getChildNodeCount(long max) {
        return nodes.size();
    }

    @NotNull
    @Override
    public Iterable<ChildNodeEntry> getChildNodeEntries() {
        return MemoryChildNodeEntry.iterable(nodes.entrySet());
    }

    @NotNull
    @Override
    public NodeBuilder builder() {
        return new MemoryNodeBuilder(this);
    }

    /**
     * We don't keep track of a separate base node state for
     * {@link MemoryNodeState} instances, so this method will just do
     * a generic diff against the given state.
     */
    @Override
    public boolean compareAgainstBaseState(NodeState base, NodeStateDiff diff) {
        if (base == EMPTY_NODE || !base.exists()) {
            return EmptyNodeState.compareAgainstEmptyState(this, diff);
        }

        Map<String, PropertyState> newProperties =
                new HashMap<String, PropertyState>(properties);
        for (PropertyState before : base.getProperties()) {
            PropertyState after = newProperties.remove(before.getName());
            if (after == null) {
                if (!diff.propertyDeleted(before)) {
                    return false;
                }
            } else if (!after.equals(before)) {
                if (!diff.propertyChanged(before, after)) {
                    return false;
                }
            }
        }

        for (PropertyState after : newProperties.values()) {
            if (!diff.propertyAdded(after)) {
                return false;
            }
        }

        Map<String, NodeState> newNodes =
                new HashMap<String, NodeState>(nodes);
        for (ChildNodeEntry entry : base.getChildNodeEntries()) {
            String name = entry.getName();
            NodeState before = entry.getNodeState();
            NodeState after = newNodes.remove(name);
            if (after == null) {
                if (!diff.childNodeDeleted(name, before)) {
                    return false;
                }
            } else if (after != before) {
                if (!diff.childNodeChanged(name, before, after)) {
                    return false;
                }
            }
        }

        for (Map.Entry<String, NodeState> entry : newNodes.entrySet()) {
            if (!diff.childNodeAdded(entry.getKey(), entry.getValue())) {
                return false;
            }
        }

        return true;
    }

    static MemoryNodeState wrap(NodeState state) {
        if (state instanceof MemoryNodeState) {
            return (MemoryNodeState) state;
        }

        Map<String, PropertyState> properties = newHashMap();
        for (PropertyState property : state.getProperties()) {
            properties.put(property.getName(), property);
        }

        Map<String, NodeState> nodes = newHashMap();
        for (ChildNodeEntry child : state.getChildNodeEntries()) {
            nodes.put(child.getName(), child.getNodeState());
        }

        return new MemoryNodeState(properties, nodes);
    }
}


text:
package org.andengine.util.modifier;

import org.andengine.util.modifier.IModifier.IModifierListener;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 11:18:37 - 03.09.2010
 * @param <T>
 */
public class LoopModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
	// ===========================================================
	// Constants
	// ===========================================================

	public static final int LOOP_CONTINUOUS = -1;

	// ===========================================================
	// Fields
	// ===========================================================

	private float mSecondsElapsed;
	private final float mDuration;

	private final IModifier<T> mModifier;

	private ILoopModifierListener<T> mLoopModifierListener;

	private final int mLoopCount;
	private int mLoop;

	private boolean mModifierStartedCalled;
	private boolean mFinishedCached;

	// ===========================================================
	// Constructors
	// ===========================================================

	public LoopModifier(final IModifier<T> pModifier) {
		this(pModifier, LoopModifier.LOOP_CONTINUOUS);
	}

	public LoopModifier(final IModifier<T> pModifier, final int pLoopCount) {
		this(pModifier, pLoopCount, null, (IModifierListener<T>)null);
	}

	public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final IModifierListener<T> pModifierListener) {
		this(pModifier, pLoopCount, null, pModifierListener);
	}

	public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener) {
		this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener<T>)null);
	}

	public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener, final IModifierListener<T> pModifierListener) {
		super(pModifierListener);

		BaseModifier.assertNoNullModifier(pModifier);

		this.mModifier = pModifier;
		this.mLoopCount = pLoopCount;
		this.mLoopModifierListener = pLoopModifierListener;

		this.mLoop = 0;
		this.mDuration = (pLoopCount == LoopModifier.LOOP_CONTINUOUS) ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier

		this.mModifier.addModifierListener(this);
	}

	protected LoopModifier(final LoopModifier<T> pLoopModifier) throws DeepCopyNotSupportedException {
		this(pLoopModifier.mModifier.deepCopy(), pLoopModifier.mLoopCount);
	}

	@Override
	public LoopModifier<T> deepCopy() throws DeepCopyNotSupportedException {
		return new LoopModifier<T>(this);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public ILoopModifierListener<T> getLoopModifierListener() {
		return this.mLoopModifierListener;
	}

	public void setLoopModifierListener(final ILoopModifierListener<T> pLoopModifierListener) {
		this.mLoopModifierListener = pLoopModifierListener;
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public float getSecondsElapsed() {
		return this.mSecondsElapsed;
	}

	@Override
	public float getDuration() {
		return this.mDuration;
	}

	@Override
	public float onUpdate(final float pSecondsElapsed, final T pItem) {
		if(this.mFinished){
			return 0;
		} else {
			float secondsElapsedRemaining = pSecondsElapsed;

			this.mFinishedCached = false;
			while((secondsElapsedRemaining > 0) && !this.mFinishedCached) {
				secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem);
			}
			this.mFinishedCached = false;

			final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
			this.mSecondsElapsed += secondsElapsedUsed;
			return secondsElapsedUsed;
		}
	}

	@Override
	public void reset() {
		this.mFinished = false;
		this.mLoop = 0;
		this.mSecondsElapsed = 0;
		this.mModifierStartedCalled = false;

		this.mModifier.reset();
	}

	// ===========================================================
	// Methods
	// ===========================================================

	@Override
	public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
		if(!this.mModifierStartedCalled) {
			this.mModifierStartedCalled = true;
			this.onModifierStarted(pItem);
		}
		if(this.mLoopModifierListener != null) {
			this.mLoopModifierListener.onLoopStarted(this, this.mLoop, this.mLoopCount);
		}
	}

	@Override
	public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
		if(this.mLoopModifierListener != null) {
			this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount);
		}

		if(this.mLoopCount == LoopModifier.LOOP_CONTINUOUS) {
			this.mSecondsElapsed = 0;
			this.mModifier.reset();
		} else {
			this.mLoop++;
			if(this.mLoop >= this.mLoopCount) {
				this.mFinished = true;
				this.mFinishedCached = true;
				this.onModifierFinished(pItem);
			} else {
				this.mSecondsElapsed = 0;
				this.mModifier.reset();
			}
		}
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================

	public interface ILoopModifierListener<T> {
		public void onLoopStarted(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
		public void onLoopFinished(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
	}
}


text:
package com.dell.doradus.testprocessor.xmlreflector;

import org.w3c.dom.Node;

import com.dell.doradus.testprocessor.common.*;

import java.util.List;

@IXTypeReflector(name="control.statements", isLibrary=true)
public class ControlStmtReflector
{
    XMLReflector m_xmlReflector = null;

    @IXMLReflectorSetter
    public void setXMLReflector(XMLReflector xmlReflector) {
        m_xmlReflector = xmlReflector;
    }

    /*******************************************************************************
     *  FOR Statement
     *  <for index="ind" from="int" to="int" [step="int"]>
     *      ... ${ind} ...
     *  </for>
     *******************************************************************************/
    @IXTypeReflector(name="for", isFinal=true)
    public class XForStmt implements IXTask
    {
        @IXFieldReflector(name="index", required=true)
        public String m_index;

        @IXFieldReflector(name="from", required=true)
        public int m_from;

        @IXFieldReflector(name="to", required=true)
        public int m_to;

        @IXFieldReflector(name="step", required=false)
        private int m_step = 1;

        public void Run(Node xmlNode)
        throws Exception
        {
            try {
                for (int i = m_from; i <= m_to; i += m_step) {
                    m_xmlReflector.definitions().setInteger(m_index, i);
                    m_xmlReflector.process(xmlNode);
                }
            } catch(Exception ex) {
                throw ex;
            }
            finally {
                m_xmlReflector.definitions().remove(m_index);
            }
        }
    }

    /*******************************************************************************
     *  IF Statements
     *******************************************************************************/
    private void IFExecute(boolean condition, Node xmlNode)
    throws Exception
    {
        if (condition) {
            m_xmlReflector.process(xmlNode);
        }
    }

    public class TwoIntArgs
    {
        @IXFieldReflector(name="arg1", required=true)
        public int m_arg1;

        @IXFieldReflector(name="arg2", required=true)
        public int m_arg2;
    }

    /*******************************************************************************
     *  <IF.LT arg1="int" arg2="int">
     *      ...
     *  </IF.LT>
     *******************************************************************************/
    @IXTypeReflector(name="IF.LT", isFinal = true)
    public class IFLTStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 < m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.LE arg1="int" arg2="int">
     *      ...
     *  </IF.LE>
     *******************************************************************************/
    @IXTypeReflector(name="IF.LE", isFinal = true)
    public class IFLEStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 <= m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.EQ arg1="int" arg2="int">
     *      ...
     *  </IF.EQ>
     *******************************************************************************/
    @IXTypeReflector(name="IF.EQ", isFinal = true)
    public class IFEQStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 == m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.NE arg1="int" arg2="int">
     *      ...
     *  </IF.NE>
     *******************************************************************************/
    @IXTypeReflector(name="IF.NE", isFinal = true)
    public class IFNEStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 != m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.GE arg1="int" arg2="int">
     *      ...
     *  </IF.GE>
     *******************************************************************************/
    @IXTypeReflector(name="IF.GE", isFinal = true)
    public class IFGEStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 >= m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.GT arg1="int" arg2="int">
     *      ...
     *  </IF.GT>
     *******************************************************************************/
    @IXTypeReflector(name="IF.GT", isFinal = true)
    public class IFGTStmt extends TwoIntArgs implements IXTask
    {
        public void Run(Node xmlNode) throws Exception {
            IFExecute(m_arg1 > m_arg2, xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.DEF name="name">
     *      ...
     *  </IF.DEF>
     *******************************************************************************/
    @IXTypeReflector(name="IF.DEF", isFinal = true)
    public class IFDEFStmt implements IXTask
    {
        @IXFieldReflector(name = "name", required = true)
        public String m_name = null;

        public void Run(Node xmlNode) throws Exception  {
            IFExecute(m_xmlReflector.definitions().isDefined(m_name), xmlNode);
        }
    }
    /*******************************************************************************
     *  <IF.UNDEF name="name">
     *      ...
     *  </IF.UNDDEF>
     *******************************************************************************/
    @IXTypeReflector(name="IF.UNDEF", isFinal = true)
    public class IFUNDEFStmt implements IXTask
    {
        @IXFieldReflector(name = "name", required = true)
        public String m_name = null;

        public void Run(Node xmlNode) throws Exception {
            IFExecute(!m_xmlReflector.definitions().isDefined(m_name), xmlNode);
        }
    }

    /*******************************************************************************
     *  TRY-CATCH Statement
     *******************************************************************************/
    @IXTypeReflector(name="try", isFinal=true)
    public class XTry implements IXTask
    {
        public void Run(Node xmlNode)
        throws Exception
        {
            List<Node> catchNodes = XmlUtils.removeChildren(xmlNode, "catch", m_xmlReflector.ignoreCase());
            if (catchNodes.size() > 1) {
                String msg = "Try statement contains multiple catch-statements";
                throw new Exception(msg);
            }

            try {
                m_xmlReflector.process(xmlNode);
            }
            catch(Exception ex) {
                if (catchNodes.size() == 1) {
                    m_xmlReflector.definitions().setString("exception", Utils.unwind(ex));
                    m_xmlReflector.process(catchNodes.get(0));
                    m_xmlReflector.definitions().remove("exception");
                }
            }
        }
    }
}


text:
var Client = require('../')
var Server = require('../').Server
var test = require('tape')

var infoHash = '4cb67059ed6bd08362da625b3ae77f6f4a075705'
var peerId = new Buffer('01234567890123456789')
var peerId2 = new Buffer('12345678901234567890')
var torrentLength = 50000

function serverTest (t, serverType, serverFamily) {
  t.plan(26)

  var opts = serverType === 'http' ? { udp: false } : { http: false }
  var server = new Server(opts)
  var serverAddr = serverFamily === 'inet6' ? '[::1]' : '127.0.0.1'
  var clientAddr = serverFamily === 'inet6' ? '[::1]' : '127.0.0.1'
  var clientIp = serverFamily === 'inet6' ? '::1' : '127.0.0.1'

  server.on('error', function (err) {
    t.fail(err.message)
  })

  server.on('warning', function (err) {
    t.fail(err.message)
  })

  server.on('listening', function () {
    t.pass('server listening')
  })

  server.listen(function (port) {
    var announceUrl = serverType + '://' + serverAddr + ':' + port + '/announce'

    var client = new Client(peerId, 6881, {
      infoHash: infoHash,
      length: torrentLength,
      announce: [ announceUrl ]
    })

    client.start()

    server.once('start', function () {
      t.pass('got start message from client1')
    })

    client.once('update', function (data) {
      t.equal(data.announce, announceUrl)
      t.equal(data.complete, 0)
      t.equal(data.incomplete, 1)

      t.equal(Object.keys(server.torrents).length, 1)
      t.equal(server.getSwarm(infoHash).complete, 0)
      t.equal(server.getSwarm(infoHash).incomplete, 1)
      t.equal(Object.keys(server.getSwarm(infoHash).peers).length, 1)
      t.deepEqual(server.getSwarm(infoHash).peers[clientAddr + ':6881'], {
        ip: clientIp,
        port: 6881,
        peerId: peerId.toString('hex')
      })

      client.complete()

      client.once('update', function (data) {
        t.equal(data.announce, announceUrl)
        t.equal(data.complete, 1)
        t.equal(data.incomplete, 0)

        client.scrape()

        client.once('scrape', function (data) {
          t.equal(data.announce, announceUrl)
          t.equal(typeof data.complete, 'number')
          t.equal(typeof data.incomplete, 'number')
          t.equal(typeof data.downloaded, 'number')

          var client2 = new Client(peerId2, 6882, {
            infoHash: infoHash,
            length: torrentLength,
            announce: [ announceUrl ]
          })

          client2.start()

          server.once('start', function () {
            t.pass('got start message from client2')
          })

          client2.once('peer', function (addr) {
            t.equal(addr, clientAddr + ':6881')

            client2.stop()
            client2.once('update', function (data) {
              t.equal(data.announce, announceUrl)
              t.equal(data.complete, 1)
              t.equal(data.incomplete, 0)

              client.stop()
              client.once('update', function (data) {
                t.equal(data.announce, announceUrl)
                t.equal(data.complete, 0)
                t.equal(data.incomplete, 0)

                server.close(function () {
                  t.pass('server closed')
                })
              })
            })
          })
        })
      })
    })
  })
}

test('http ipv4 server', function (t) {
  serverTest(t, 'http', 'inet')
})

test('http ipv6 server', function (t) {
  serverTest(t, 'http', 'inet6')
})

test('udp server', function (t) {
  serverTest(t, 'udp', 'inet')
})


text:
monphoto
========

Scatter image files into month-based folder basing on the EXIF data.


text:
<?php
// this object expects an associative array (string keys)
// where the keys will become the column headers for
// a table of the array's values.
// (typically from a sql query)
// and it will convert that multidimensional array into
// a table with iterating (alternating colored) rows
// the array keys of dimension 2 of this multidimensional array
// will be used as the content

class TableOfData {
    /** @var  Table $table */
    var $table;
    var $row;
    var $cell;
    var $headCell;
    var $allRows;
    var $allHeadCells;
    /** @var  array $dataSet */
    var $dataSet;

    public function __construct($dataSet) {
        $this->setAllHeadCells($dataSet);
        $this->dataSet = $dataSet;
        $this->setHeadRow();
        //  echo $this->getHeadRow()->getElementString(); // this accesses the header row after the above setters complete
        $i=0;
        foreach($dataSet as $row) {
            $this->setAllTableCells($row, $i);
            $this->allRows .= $this->getRow($i)->getElementString();
            $i++;
        }
        $this->setTable($this->getHeadRow()->getElementString().$this->allRows);
    }

    // populate a row with the headcells for the header
    private function setHeadRow() {
    $this->setRow($this->allHeadCells,'head');
    }

    //  instantiate a new HeadCell object for each array key in dimension 2 of the multidimensional array $dataSet
    private function setAllHeadCells($dataSet) {
        $idx = 0;
        foreach(array_keys($dataSet[0]) as $key) { // header cells (using the array keys // string of Foo	Bar
        $this->setHeadCell($key, $idx);
        $this->allHeadCells .= $this->getHeadCell($idx)->getElementString();
            $idx++;
        }
    }
    private function setAllTableCells($row , $rowID) {
        $i = 0;
        $localArray = [];
        foreach($row as $cell) {
            $this->setCell($cell,$i);
            array_push($localArray,$this->getCell($i)->getElementString());
            $i++;
        }
        $this->setRow(implode($localArray), $rowID);
    }

    private function setTable($content) {
        $this->table = new Table($content,['cellpadding','cellspacing'],[3,1]);
    }
    private function setRow($content,$idx) {
        if($idx % 2 == 0) { $class = 'dtAlt-0'; } else { $class = 'dtAlt-1'; }
        $this->row[$idx] = new Row($content,array('class'),array($class));
    }
    private function setCell($content,$idx) {
        $this->cell[$idx] = new Cell($content);
    }
    private function setHeadCell($content,$idx) {
        $this->headCell[$idx] = new HeadCell(ucwords(strtolower(str_replace('_',' ',$content))),['class'],['dtHeading']);
    }

    private function getTable() {
        return $this->table;
    }
    private function getRow($idx) {
        return $this->row[$idx];
    }
    private function getCell($idx) {
        return $this->cell[$idx];
    }
    private function getHeadCell($idx) {
        return $this->headCell[$idx];
    }
    private function getAllHeadCells() {
        return $this->allHeadCells;
    }
    private function getHeadRow() {
        return $this->getRow('head');
    }
    public function getDataTable() {
        return $this->getTable();
    }

}