text:
(function (factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(["require", "exports", '../util/util', './recognizers', '../util/ui-event-manager', '../util/dom', '../util/debouncer'], factory);
    }
})(function (require, exports) {
    "use strict";
    var util_1 = require('../util/util');
    var recognizers_1 = require('./recognizers');
    var ui_event_manager_1 = require('../util/ui-event-manager');
    var dom_1 = require('../util/dom');
    var debouncer_1 = require('../util/debouncer');
    var PanGesture = (function () {
        function PanGesture(element, opts) {
            if (opts === void 0) { opts = {}; }
            this.element = element;
            this.events = new ui_event_manager_1.UIEventManager(false);
            this.started = false;
            this.captured = false;
            this.isListening = false;
            util_1.defaults(opts, {
                threshold: 20,
                maxAngle: 40,
                direction: 'x',
                zone: true,
                capture: false,
            });
            this.debouncer = (opts.debouncer)
                ? opts.debouncer
                : new debouncer_1.FakeDebouncer();
            this.gestute = opts.gesture;
            this.direction = opts.direction;
            this.eventsConfig = {
                element: this.element,
                pointerDown: this.pointerDown.bind(this),
                pointerMove: this.pointerMove.bind(this),
                pointerUp: this.pointerUp.bind(this),
                zone: opts.zone,
                capture: opts.capture
            };
            this.detector = new recognizers_1.PanRecognizer(opts.direction, opts.threshold, opts.maxAngle);
        }
        PanGesture.prototype.listen = function () {
            if (this.isListening) {
                return;
            }
            this.pointerEvents = this.events.pointerEvents(this.eventsConfig);
            this.isListening = true;
        };
        PanGesture.prototype.unlisten = function () {
            if (!this.isListening) {
                return;
            }
            this.gestute && this.gestute.release();
            this.events.unlistenAll();
            this.isListening = false;
        };
        PanGesture.prototype.destroy = function () {
            this.gestute && this.gestute.destroy();
            this.gestute = null;
            this.unlisten();
            this.element = null;
        };
        PanGesture.prototype.pointerDown = function (ev) {
            if (this.started) {
                return;
            }
            if (!this.canStart(ev)) {
                return false;
            }
            if (this.gestute) {
                this.gestute.release();
                if (!this.gestute.start()) {
                    return false;
                }
            }
            var coord = dom_1.pointerCoord(ev);
            this.detector.start(coord);
            this.started = true;
            this.captured = false;
            return true;
        };
        PanGesture.prototype.pointerMove = function (ev) {
            var _this = this;
            this.debouncer.debounce(function () {
                if (!_this.started) {
                    return;
                }
                if (_this.captured) {
                    _this.onDragMove(ev);
                    return;
                }
                var coord = dom_1.pointerCoord(ev);
                if (_this.detector.detect(coord)) {
                    if (_this.detector.pan() !== 0 &&
                        (!_this.gestute || _this.gestute.capture())) {
                        _this.onDragStart(ev);
                        _this.captured = true;
                        return;
                    }
                    _this.started = false;
                    _this.captured = false;
                    _this.pointerEvents.stop();
                    _this.notCaptured(ev);
                }
            });
        };
        PanGesture.prototype.pointerUp = function (ev) {
            this.debouncer.cancel();
            if (!this.started) {
                return;
            }
            this.gestute && this.gestute.release();
            if (this.captured) {
                this.onDragEnd(ev);
            }
            else {
                this.notCaptured(ev);
            }
            this.captured = false;
            this.started = false;
        };
        PanGesture.prototype.getNativeElement = function () {
            return this.element;
        };
        PanGesture.prototype.canStart = function (ev) { return true; };
        PanGesture.prototype.onDragStart = function (ev) { };
        PanGesture.prototype.onDragMove = function (ev) { };
        PanGesture.prototype.onDragEnd = function (ev) { };
        PanGesture.prototype.notCaptured = function (ev) { };
        return PanGesture;
    }());
    exports.PanGesture = PanGesture;
});
//# sourceMappingURL=drag-gesture.js.map


text:
namespace YAF.Pages;

using YAF.Types.Models;

/// <summary>
/// Class to communicate in Jabber.
/// </summary>
public partial class Jabber : ForumPage
{
    /// <summary>
    ///   Initializes a new instance of the <see cref = "Jabber" /> class.
    /// </summary>
    public Jabber()
        : base("IM_XMPP", ForumPages.Jabber)
    {
    }

    /// <summary>
    ///   Gets UserID.
    /// </summary>
    public int UserID =>
        this.Get<LinkBuilder>().StringToIntOrRedirect(this.Get<HttpRequestBase>().QueryString.GetFirstOrDefault("u"));

    /// <summary>
    /// The page_ load.
    /// </summary>
    /// <param name="sender">
    /// The sender.
    /// </param>
    /// <param name="e">
    /// The e.
    /// </param>
    protected void Page_Load([NotNull] object sender, [NotNull] EventArgs e)
    {
        if (this.User == null)
        {
            this.Get<LinkBuilder>().AccessDenied();
        }

        if (this.IsPostBack)
        {
            return;
        }

        // get user data...
        var userHe = this.GetRepository<User>().GetById(this.UserID);

        if (userHe == null)
        {
            // No such user exists
            this.Get<LinkBuilder>().AccessDenied();
        }

        if (!userHe.UserFlags.IsApproved)
        {
            this.Get<LinkBuilder>().AccessDenied();
        }

        this.PageBoardContext.PageLinks.AddRoot();
        this.PageBoardContext.PageLinks.AddUser(
            this.UserID,
            userHe.DisplayOrUserName());
        this.PageBoardContext.PageLinks.AddLink(this.GetText("TITLE"), string.Empty);

        if (this.UserID == this.PageBoardContext.PageUserID)
        {
            this.NotifyLabel.Text = this.GetText("SERVERYOU");
            this.Alert.Type = MessageTypes.warning;
        }
        else
        {
            // get full user data...
            var userDataHe = this.Get<IAspNetUsersHelper>().GetUser(userHe.ProviderUserKey);

            var serverHe = userDataHe.Profile_XMPP
                .Substring(userDataHe.Profile_XMPP.IndexOf("@", StringComparison.Ordinal) + 1).Trim();

            var serverMe = this.PageBoardContext.MembershipUser.Profile_XMPP
                .Substring(this.PageBoardContext.MembershipUser.Profile_XMPP.IndexOf("@", StringComparison.Ordinal) + 1).Trim();

            this.NotifyLabel.Text = serverMe == serverHe
                                        ? this.GetTextFormatted("SERVERSAME", userDataHe.Profile_XMPP)
                                        : this.GetTextFormatted("SERVEROTHER", $"http://{serverHe}");

            this.Alert.Type = MessageTypes.info;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import gflags
import json
import math
import networkx
import os
import random
import re
import sqlite3
import subprocess
import sys

# Global values
distributions_list = list()
experiment_file = ''
output_console_log = ''
output_results_db = None
agent_states = ['susceptible', 'exposed', 'infectious', 'recovered']

# gflag defn's and registration
FLAGS = gflags.FLAGS
# Input control values
gflags.DEFINE_string('distributions_file', '',
                     'JSON file containing a list of distribution specifications to be used. These should be hand '
                     'checked to produce sane values')
gflags.DEFINE_string('generators_file', '',
                     'JSON file containing a list of generator specifications to be used.')
gflags.DEFINE_string('kernel_file', '',
                     'JSON file that contains a list of kernel paths to be tested. '
                     'File is expected to contain one entry with a member "kernels" '
                     'that contains the list. This is required.')

# Generation control values
gflags.DEFINE_integer('events_start', 5000,
                      'Value to start the events count at, defaults to 2500',
                      1)
gflags.DEFINE_integer('events_end', 50000,
                      'Value to end the events count at, defaults to 50000',
                      1)
gflags.DEFINE_integer('seed', 1,
                      'Seed value for random number generator, defaults to 1')
gflags.DEFINE_boolean('dry_run', False,
                      'Print out what would have been written out to the '
                      'database, but doesn\'t actually write anything out.')

# Execution control values
gflags.DEFINE_integer('max_time', 60000,
                      'Max time to allow the application to run for in mS, '
                      'defaults to 1 minute.')
gflags.DEFINE_integer('max_mem', 0,
                      'Max memory to allow the application to use, in kB, '
                      'defaults to 0, which indicates no limit.')
gflags.DEFINE_integer('hertz', 120,
                      'Rate at which the running application status is sampled. Defaults to 120Hz.')
gflags.DEFINE_integer('iterations', 50,
                      'Number iterations to run of each test. Defaults to 50.')
gflags.DEFINE_integer('worker', 0,
                      'Which worker number is this instance. 0, '
                      'indicates it is the only worker/there is no need to '
                      'fan out the results.')
gflags.DEFINE_integer('num_workers', 1,
                      'Total number of workers. This is used to partition the '
                      'work set and fan out the results. Not setting this '
                      'correctly will not kill your job, but will give you a '
                      'mis-balanced workload.')
gflags.DEFINE_string('machine', 'None',
                     'Machine that experiments are being running on. This defaults '
                     'to "None", which means the analyzer will ignore these results.')

# Flag Validators
def validate_distributions_file(distributions_file):
    if distributions_file == '':
        print "distributions_file not specified"
        return False
    if not os.path.isfile(distributions_file):
        print "distributions_file, '{}', does not exist".format(distributions_file)
        print os.getcwd()
        return False
    if not os.access(distributions_file, os.R_OK):
        print "distributions_file, '{}', is not readable".format(distributions_file)
        return False
    return True

def validate_generators_file(generators_file):
    if generators_file == '':
        print "generators_file not specified"
        return False
    if not os.path.isfile(generators_file):
        print "generators_file, '{}', does not exist".format(generators_file)
        print os.getcwd()
        return False
    if not os.access(generators_file, os.R_OK):
        print "generators_file, '{}', is not readable".format(generators_file)
        return False
    return True

def validate_kernel_file(kernel_file):
    if kernel_file == '':
        print "kernel_file not specified"
        return False
    if not os.path.isfile(kernel_file):
        print "kernel_file, '{}', does not exist".format(kernel_file)
        print os.getcwd()
        return False
    if not os.access(kernel_file, os.R_OK):
        print "kernel_file, '{}', is not readable".format(kernel_file)
        return False
    return True

def validate_kernel(kernel):
    if kernel == '':
        print "kernel not specified"
        return False
    if not os.path.isfile(kernel):
        print "kernel, '{}', does not exist".format(kernel)
        print os.getcwd()
        return False
    if not os.access(kernel, os.X_OK):
        print "kernel_file, '{}', is not executable".format(kernel)
        return False
    return True

gflags.RegisterValidator('distributions_file', validate_distributions_file)
gflags.RegisterValidator('generators_file', validate_generators_file)
gflags.RegisterValidator('kernel_file', validate_kernel_file)
gflags.MarkFlagAsRequired('distributions_file')
gflags.MarkFlagAsRequired('generators_file')
gflags.MarkFlagAsRequired('kernel_file')

def generate_doubling_values(start, end):
    values = list()
    values.append(int(start))
    x = 2 * start
    while x < end:
        values.append(int(x))
        x *= 2
    if start != end:
        values.append(int(end))
    return values

def generate_connection_graph(graph_type, params, count):
    lower_type = graph_type.lower()
    if lower_type == 'complete':
        assert (len(params) == 0)
        return networkx.complete_graph(count)
    elif lower_type == 'complete-bipartite':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        n1 = int(round(count * float(params[0]) / float(params[1])))
        n2 = int(round(count * float(params[1]) / float(params[0])))
        n1 = 1 if n1 < 1 else n1
        n2 = 1 if n2 < 1 else n2
        return networkx.complete_bipartite_graph(n1, n2)
    elif lower_type == 'circular-ladder':
        assert (len(params) == 0)
        return networkx.circular_ladder_graph(count)
    elif lower_type == 'cycle':
        assert (len(params) == 0)
        return networkx.cycle_graph(count)
    elif lower_type == 'periodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, True)
    elif lower_type == 'nonperiodic-2grid':
        assert (len(params) == 2)
        assert (int(params[0]) > 0.0)
        assert (int(params[1]) > 0.0)
        width = int(round(math.sqrt(count * float(params[0]) / float(params[1]))))
        height = int(round(math.sqrt(count * float(params[1]) / float(params[0]))))
        width = 1 if width < 1 else width
        height = 1 if height < 1 else height
        return networkx.grid_2d_graph(width, height, False)
    elif lower_type == 'hypercube':
        assert (len(params) == 0)
        return networkx.hypercube_graph(int(round(math.log(count, 2))))
    elif lower_type == 'star':
        assert (len(params) == 0)
        return networkx.star_graph(count - 1)
    elif lower_type == 'wheel':
        assert (len(params) == 0)
        return networkx.wheel_graph(count)
    elif lower_type == 'erdos-reyni':
        assert (len(params) == 1)
        return networkx.erdos_renyi_graph(count, float(params[0]))
    elif lower_type == 'watts-strogatz':
        assert (len(params) == 2)
        if int(params[0]) >= count / 2:
            k = int(count / 2 - 1)
        else:
            k = int(params[0])
        return networkx.connected_watts_strogatz_graph(count, k, int(params[1]))
    else:
        print "Unknown graph type {}".format(lower_type)
        assert False

def create_result_table():
    global output_results_db
    if output_results_db is None:
        pass
    cmd_str = "CREATE TABLE IF NOT EXISTS raw_results (machine text, kernel text, type text, model text, " \
              "iteration long, event_count long, final_time long, cpu long, maxmem long, agents long, " \
              "connections long)"
    output_results_db.execute(cmd_str)

def write_result_entry(result):
    global output_results_db
    if output_results_db is None:
        pass
    cmd_str = "INSERT INTO raw_results " \
              "(machine, kernel, type, model, iteration, event_count, final_time, cpu, maxmem, agents, " \
              "connections) " \
              "VALUES ('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')"\
        .format(result.json["machine"], result.json["kernel"], result.json["type"], result.json["model"],
                result.json["iteration"], result.json["event_count"], result.json["final_time"], result.json["cpu"],
                result.json["maxmem"], result.json["agents"], result.json["connections"])
    output_results_db.execute(cmd_str)
    output_results_db.commit()

class ExperimentResults(object):
    """Parses and stores the raw results from an experiment run"""

    def __init__(self, console_log, iteration):
        self.json = dict()
        self.json["machine"] = FLAGS.machine
        self.json["iteration"] = iteration
        self.json["cpu"] = 0
        self.json["maxmem"] = 0
        self.console_log = console_log
        self.parse_console_log()
        print self.json

    # noinspection PyBroadException
    def parse_console_log(self):
        """Parse the raw results and store"""
        parsing_json = False
        json_string = ""
        for line in self.console_log.splitlines():
            match = re.search(r'JSONBEGIN.*', line)
            if not parsing_json and match:
                parsing_json = True
                continue
            match = re.search(r'JSONEND.*', line)
            if parsing_json and match:
                parsing_json = False

                json_string = json_string.replace('\\"', '"')
                json_string = json_string.replace('"{', '{')
                json_string = json_string.replace('}"', '}')

                try:
                    results_json = json.loads(json_string)
                    print results_json
                    for key, value in results_json.items():
                        self.json[key] = value
                except:
                    print "Failed to parse as JSON, {}".format(json_string)
                    sys.exit(1)
                continue
            match = re.search(r'CPU: (.*)', line)
            if match:
                self.json["cpu"] = int(match.group(1))
                continue
            match = re.search(r'MAXMEM: (.*)', line)
            if match:
                self.json["maxmem"] = int(match.group(1))
                continue
            if parsing_json:
                json_string += line
                continue

class ExperimentRunner(object):
    """Takes an experiment and kernel and performs an experimental run."""

    def __init__(self, experiment, kernel):
        self.experiment = experiment
        self.kernel = kernel
        self.results = None
        self.succeeded = False
        self.console_log = ""
        self.results_json = dict()

    def run(self, iteration):
        """Run requested experiment"""
        try:
            print "Trying '{} --experiment_file {}'".format(self.kernel,
                                                            self.experiment)
            if FLAGS.max_mem != 0:
                self.console_log = subprocess.check_output(['../../third_party/perl/timeout.pl',
                                                            '-t', str(FLAGS.max_time),
                                                            '-m', str(FLAGS.max_mem),
                                                            '-x', str(FLAGS.hertz),
                                                            self.kernel,
                                                            '--experiment_file',
                                                            self.experiment,
                                                            '--random_seed',
                                                            str(iteration)])
            else:
                self.console_log = subprocess.check_output(['../../third_party/perl/timeout.pl',
                                                            '-t', str(FLAGS.max_time),
                                                            '-x', str(FLAGS.hertz),
                                                            self.kernel,
                                                            '--experiment_file',
                                                            self.experiment,
                                                            '--random_seed',
                                                            str(iteration)])
            self.succeeded = True
        except subprocess.CalledProcessError as e:
            self.console_log = e.output
            self.succeeded = False

        self.results = ExperimentResults(self.console_log, iteration)
        return self.succeeded

    def print_results(self, iteration):
        """Print result of last run"""
        print "{} {} {}\n".format(os.path.basename(self.kernel),
                                  self.experiment,
                                  str(iteration))
        if self.succeeded:
            print "SUCCESS"
            print json.dumps(self.results.results_json, indent=4, separators=(',', ': '))
        else:
            print "FAILURE"
            print json.dumps(self.results.results_json, indent=4, separators=(',', ': '))
        print "{}\n".format(self.console_log)

    def write_results(self, iteration):
        """Write out the results of the last run to the console log, and results json list"""
        with open(output_console_log, "a") as f:
            f.write("{} {} {}\n".format(os.path.basename(self.kernel),
                                        self.experiment,
                                        str(iteration)))
            f.write("{}\n".format(self.console_log))
            if self.succeeded:
                write_result_entry(self.results)
            else:
                print "Skipping failed in json file"
                print self.console_log

def perform_experiment(experiment, kernel):
    """Execute experiment, print results and write them out """
    runner = ExperimentRunner(experiment,
                              kernel)
    for i in range(1, FLAGS.iterations + 1):
        if FLAGS.worker == 0 or (i % FLAGS.num_workers) + 1 == FLAGS.worker:
            print "Running {} iteration #{}".format(experiment, i)
            if not runner.run(i):
                print "Failed {} on iteration #{}".format(experiment, i)
                return False
            if FLAGS.dry_run:
                runner.print_results(i)
            else:
                runner.write_results(i)
    return True

def generate_model_file(generator, agent_count):
    global distributions_list
    num_distributions = int(round(random.uniform(1, len(distributions_list))))
    distributions = random.sample(distributions_list, num_distributions)

    model_doc = dict()
    model_doc["distributions"] = distributions
    model_doc["model_name"] = generator["base_name"] + "_" + str(agent_count)
    model_doc["agents"] = list()
    graph = generate_connection_graph(generator["generator_type"],
                                      generator["generator_params"],
                                      agent_count)
    total_connections = 0
    global agent_states
    for node in graph.nodes_iter():
        agent = dict()
        agent["label"] = "Agent_" + str(node).replace('(', '').replace(')', '').replace(',', '').replace(' ', '_')
        agent["state"] = random.sample(agent_states, 1)[0]
        agent["s2e"] = random.sample(distributions, 1)[0]["label"]
        agent["e2i"] = random.sample(distributions, 1)[0]["label"]
        agent["i2r"] = random.sample(distributions, 1)[0]["label"]
        if not ("is_looping" in generator) or generator["is_looping"] is False:
            agent["r2s"] = random.sample(distributions, 1)[0]["label"]
        agent["connections"] = list()
        for connection in graph.neighbors_iter(node):
            agent["connections"].append("Agent_" + str(connection)
                                        .replace('(', '').replace(')', '').replace(',', '').replace(' ', '_'))
            total_connections += 1
        model_doc["agents"].append(agent)
    model_doc["total_connections"] = total_connections
    model_filename = os.path.join(".", generator["base_name"] + "_model_" + str(agent_count) + ".json")
    with open(model_filename, 'w') as output_file:
        json.dump(model_doc, output_file, indent=4, separators=(',', ': '))
    print "Emitted model {} for agent_count {}".format(model_filename, str(agent_count))
    return model_filename

def generate_experiment_file(generator, event_limit, agent_count):
    experiment = dict()
    experiment["experiment_name"] = generator["base_name"]
    experiment["event_limit"] = event_limit
    experiment["type"] = generator["generator_type"]
    experiment["model_filename"] = generator["base_name"] + "_model_" + str(agent_count) + ".json"
    experiment_filename = os.path.join(".", generator["base_name"] + "_experiment_" + str(agent_count) + "_"
                                       + str(event_limit) + ".json")
    with open(experiment_filename, 'w') as output_file:
        json.dump(experiment, output_file, indent=4, separators=(',', ': '))
    print "Emitted experiment {} for agent_count {} & event_limit {}".format(experiment_filename, str(agent_count),
                                                                             str(event_limit))
    return experiment_filename

def main(argv):
    try:
        FLAGS(argv)  # parse flags
    except gflags.FlagsError, e:
        print '%s\nUsage: %s ARGS\n%s' % (e, sys.argv[0], FLAGS)
        sys.exit(1)

    if not FLAGS.dry_run:
        print "Clobbering existing output files"
        global output_console_log
        if FLAGS.worker == 0:
            output_console_log = os.path.join('.', 'run_console_{}.log'.format(FLAGS.machine))
        else:
            output_console_log = os.path.join('.', 'run_console_{}_{}.log'.format(FLAGS.machine, str(FLAGS.worker)))

        open(output_console_log, 'w').close()

        global output_results_db
        if FLAGS.worker == 0:
            db_path = os.path.join('.', 'run_results_{}.db'.format(FLAGS.machine))
        else:
            db_path = os.path.join('.', 'run_results_{}_{}.db'.format(FLAGS.machine, str(FLAGS.worker)))
        try:
            os.unlink(db_path)
        except OSError, e:
            print "Unable able to unlink {} due to {}".format(db_path, e)
            pass
        output_results_db = sqlite3.connect(db_path)
        create_result_table()

    with open(FLAGS.kernel_file, "r") as f:
        kernel_json = json.load(f)

    kernels = list()
    for kernel in kernel_json["kernels"]:
        if validate_kernel(kernel):
            kernels.append(kernel)

    with open(FLAGS.distributions_file, 'r') as f:
        distributions_json = json.load(f)
    global distributions_list
    distributions_list = distributions_json["distributions"]

    with open(FLAGS.generators_file, 'r') as f:
        generators_json = json.load(f)

    for generator in generators_json["generators"]:
        for agent_count in generate_doubling_values(generator["agents_start"], generator["agents_end"]):
            model_filename = generate_model_file(generator, agent_count)
            experiment_filenames = list()
            for event_limit in generate_doubling_values(FLAGS.events_start, FLAGS.events_end):
                experiment_filenames.append(generate_experiment_file(generator, event_limit, agent_count))
            for kernel in kernels:
                for experiment_filename in experiment_filenames:
                    if not perform_experiment(experiment_filename, kernel):
                        print "Failed run for {} on {}, skipping remaining for model".format(kernel,
                                                                                experiment_filename)
                        break
            for experiment_filename in experiment_filenames:
                try:
                    os.unlink(experiment_filename)
                    print "Unlinked experiment {}".format(experiment_filename)
                except OSError, e:
                    print "Unable able to unlink {} due to {}".format(experiment_filename, e)
            try:
                os.unlink(model_filename)
                print "Unlinked model {}".format(model_filename)
            except OSError, e:
                print "Unable able to unlink {} due to {}".format(model_filename, e)

    if output_results_db is not None:
        output_results_db.commit()
        output_results_db.close()

if __name__ == '__main__':
    main(sys.argv)


text:
"""
  This module contains the Adaptive Monte Carlo sampling strategy

  Created on Feb 20, 2020
  @author: ZHOUJ2

"""
import numpy as np

from ..Models.PostProcessors import factory as ppFactory
from ..utils import InputData, InputTypes
from .AdaptiveSampler import AdaptiveSampler
from .MonteCarlo import MonteCarlo

class AdaptiveMonteCarlo(AdaptiveSampler, MonteCarlo):
  """
    A sampler that will adaptively locate the limit surface of a given problem
  """
  bS = ppFactory.returnClass('BasicStatistics')
  statScVals = bS.scalarVals
  statErVals = bS.steVals
  usableStats = []
  for errMetric in statErVals:
    metric, _ = errMetric.split('_')
    if metric in statScVals:
      usableStats.append((metric, errMetric))

  @classmethod
  def getInputSpecification(cls):
    """
      Method to get a reference to a class that specifies the input data for
      class cls.
      @ In, cls, the class for which we are retrieving the specification
      @ Out, inputSpecification, InputData.ParameterInput, class to use for
        specifying input of cls.
    """
    inputSpecification = super(AdaptiveMonteCarlo, cls).getInputSpecification()
    # TODO this class should use MonteCarlo's "limit" definition, probably?
    convergenceInput = InputData.parameterInputFactory('Convergence')
    convergenceInput.addSub(InputData.parameterInputFactory('limit', contentType=InputTypes.IntegerType))
    convergenceInput.addSub(InputData.parameterInputFactory('forceIteration', contentType=InputTypes.BoolType))
    convergenceInput.addSub(InputData.parameterInputFactory('persistence', contentType=InputTypes.IntegerType))
    for metric, _ in cls.usableStats:
      statErSpecification = InputData.parameterInputFactory(metric, contentType=InputTypes.StringListType)
      statErSpecification.addParam("prefix", InputTypes.StringType)
      statErSpecification.addParam("tol", InputTypes.FloatType)
      convergenceInput.addSub(statErSpecification)
    inputSpecification.addSub(convergenceInput)
    targetEvaluationInput = InputData.parameterInputFactory("TargetEvaluation", contentType=InputTypes.StringType)
    targetEvaluationInput.addParam("type", InputTypes.StringType)
    targetEvaluationInput.addParam("class", InputTypes.StringType)
    inputSpecification.addSub(targetEvaluationInput)
    inputSpecification.addSub(InputData.parameterInputFactory("initialSeed", contentType=InputTypes.IntegerType))

    return inputSpecification

  @classmethod
  def getSolutionExportVariableNames(cls):
    """
      Compiles a list of acceptable SolutionExport variable options.
      @ In, None
      @ Out, ok, dict, {varName: manual description} for each solution export option
    """
    # cannot be determined before run-time due to variables and prefixes.
    ok = super(AdaptiveMonteCarlo, cls).getSolutionExportVariableNames()
    new = {'solutionUpdate': 'iteration (or step) number for convergence algorithm',
           '{PREFIX}_{VAR}': 'value of metric with given prefix {PREFIX} for variable {VAR} at current step in convergence',
           '{PREFIX}_ste_{VAR}': 'estimate of error in metric with given prefix {PREFIX} for variable {VAR} at current step in convergence',
          }
    ok.update(new)

    return ok

  def __init__(self):
    """
      Default Constructor that will initialize member variables with reasonable
      defaults or empty lists/dictionaries where applicable.
      @ In, None
      @ Out, None
    """
    MonteCarlo.__init__(self)
    AdaptiveSampler.__init__(self)
    self.persistence = 5          # this is the number of times the error needs to fell below the tolerance before considering the sim converged
    self.persistenceCounter = 0   # Counter for the persistence
    self.forceIteration = False   # flag control if at least a self.limit number of iteration should be done
    self.solutionExport = None    # data used to export the solution (it could also not be present)
    self.tolerance = {}           # dictionary stores the tolerance for each variables
    self.basicStatPP = None       # post-processor to compute the basic statistics
    self.converged = False        # flag that is set to True when the sampler converged
    self.printTag = 'SAMPLER ADAPTIVE MC'
    self.toDo = None              # BasicStatistics metrics to calculate

  def localInputAndChecks(self,xmlNode, paramInput):
    """
      Class specific xml inputs will be read here and checked for validity.
      @ In, xmlNode, xml.etree.ElementTree.Element, The xml element node that will be checked against the available options specific to this Sampler.
      @ In, paramInput, InputData.ParameterInput, the parsed parameters
      @ Out, None
    """
    self.toDo = {}
    for child in paramInput.subparts:
      if child.getName() == "Convergence":
        for grandchild in child.subparts:
          tag = grandchild.getName()
          if tag == "limit":
            self.limit = grandchild.value
          elif tag == "persistence":
            self.persistence = grandchild.value
            self.raiseADebug(f'Persistence is set at {self.persistence}')
          elif tag == "forceIteration":
            self.forceIteration = grandchild.value
          elif tag in self.statScVals:
            if 'prefix' not in grandchild.parameterValues:
              self.raiseAnError(IOError, f"No prefix is provided for node: {tag}")
            if 'tol' not in grandchild.parameterValues:
              self.raiseAnError(IOError, f"No tolerance is provided for metric: {tag}")
            prefix = grandchild.parameterValues['prefix']
            tol = grandchild.parameterValues['tol']
            if tag not in self.toDo:
              self.toDo[tag] = [] # list of {'targets':(), 'prefix':str}
            self.toDo[tag].append({'targets':set(grandchild.value),
                                   'prefix':prefix,
                                   'tol':tol
                                  })
          else:
            self.raiseAWarning(f'Unrecognized convergence node "{tag}" has been ignored!')
        assert (len(self.toDo) > 0), self.raiseAnError(IOError, ' No target have been assigned to convergence node')
      elif child.getName() == "initialSeed":
        self.initSeed = child.value
    for metric, infos in self.toDo.items():
      steMetric = metric + '_ste'
      if steMetric in self.statErVals:
        for info in infos:
          prefix = info['prefix']
          for target in info['targets']:
            metaVar = prefix + '_ste_' + target
            self.tolerance[metaVar] = info['tol']
    if self.limit is None:
      self.raiseAnError(IOError, f'{self.type} requires a <limit> to be specified!')

  def localInitialize(self, solutionExport=None):
    """
      Will perform all initialization specific to this Sampler. For instance,
      creating an empty container to hold the identified surface points, error
      checking the optionally provided solution export and other preset values,
      and initializing the limit surface Post-Processor used by this sampler.
      @ In, solutionExport, DataObjects, optional, a PointSet to hold the solution
      @ Out, None
    """
    self.converged = False
    self.basicStatPP = ppFactory.returnInstance('BasicStatistics')
    # check if solutionExport is actually a "DataObjects" type "PointSet"
    if self._solutionExport.type != "PointSet":
      self.raiseAnError(IOError, f'solutionExport type is not a PointSet. Got {self._solutionExport.type}!')

    self.basicStatPP.what = self.toDo.keys()
    self.basicStatPP.toDo = self.toDo
    self.basicStatPP.initialize({'WorkingDir': None}, [self._targetEvaluation], {'Output': []})
    self.raiseADebug('Initialization done')

  ###############
  # Run Methods #
  ###############

  def localFinalizeActualSampling(self, jobObject, model, myInput):
    """
      General function (available to all samplers) that finalize the sampling
      calculation just ended. In this case, The function is aimed to check if
      all the batch calculations have been performed
      @ In, jobObject, instance, an instance of a JobHandler
      @ In, model, model instance, it is the instance of a RAVEN model
      @ In, myInput, list, the generating input
      @ Out, None
    """
    if self.counter > 1:
      output = self.basicStatPP.run(self._targetEvaluation)
      output['solutionUpdate'] = np.asarray([self.counter - 1])
      self._solutionExport.addRealization(output)
      self.checkConvergence(output)

  def checkConvergence(self, output):
    """
      Determine convergence for Adaptive MonteCarlo
      @ In, output, dict, dictionary containing the results from Basic Statistic
      @ Out, None
    """
    if self.forceIteration:
      self.converged = False
    else:
      converged = all(abs(tol) > abs(output[metric][0]) for metric, tol in self.tolerance.items())
      if converged:
        self.raiseAMessage('Checking target convergence for standard error and tolerance')
        for metric, tol in self.tolerance.items():
          self.raiseAMessage(f'Target \"{"".join(metric.split("_ste"))}\" standard error {output[metric][0]:>2.2e} < tolerance {tol:>2.2e}')
        self.persistenceCounter += 1
        # check if we've met persistence requirement; if not, keep going
        if self.persistenceCounter >= self.persistence:
          self.raiseAMessage(f' ... {self.name} converged {self.persistenceCounter} times consecutively!')
          self.converged = True
        else:
          self.raiseAMessage(f' ... {self.name} converged {self.persistenceCounter} times, required persistence is {self.persistence}.')

  def localStillReady(self, ready):
    """
      first perform some check to understand what it needs to be done possibly perform an early return
      ready is returned
      @ In,  ready, bool, a boolean representing whether the caller is prepared for another input.
      @ Out, ready, bool, a boolean representing whether the caller is prepared for another input.
    """
    if self.converged:
      return False

    return ready

  def _formatSolutionExportVariableNames(self, acceptable):
    """
      Does magic formatting for variables, based on this class's needs.
      Extend in inheritors as needed.
      @ In, acceptable, set, set of acceptable entries for solution export for this entity
      @ Out, new, set, modified set of acceptable variables with all formatting complete
    """
    # remaking the list is easier than using the existing one
    acceptable = AdaptiveSampler._formatSolutionExportVariableNames(self, acceptable)
    new = []
    while acceptable:
      # populate each template
      template = acceptable.pop()
      # the only "magic" entries have PREFIX and VAR in them
      if '{VAR}' in template and '{PREFIX}' in template:
        for _, info in self.toDo.items():
          # each metric may have several entries (for different prefixes, tolerances, etc)
          for entry in info:
            prefix = entry['prefix']
            targets = entry['targets']
            for target in targets:
              new.append(template.format(PREFIX=prefix, VAR=target))
      # if not a "magic" entry, just carry it along
      else:
        new.append(template)
    return set(new)

  def flush(self):
    """
      Reset AdaptiveMonteCarlo attributes to allow rerunning a workflow
      @ In, None
      @ Out, None
    """
    super().flush()
    self.persistenceCounter = 0
    self.basicStatPP = None


text:
package example

import scala.language.implicitConversions

/**
  *  Conversions: http://dotty.epfl.ch/docs/reference/contextual/conversions.html
  */
object Conversion {

  case class IntWrapper(a: Int) extends AnyVal
  case class DoubleWrapper(b: Double) extends AnyVal

  def convert[T, U](x: T)(using converter: Conversion[T, U]): U = converter(x)

  given IntWrapperToDoubleWrapper: Conversion[IntWrapper, DoubleWrapper] = new Conversion[IntWrapper, DoubleWrapper] {
    override def apply(i: IntWrapper): DoubleWrapper = new DoubleWrapper(i.a.toDouble)
  }

  def useConversion(using f: Conversion[IntWrapper, DoubleWrapper]) = {
    val y: IntWrapper = new IntWrapper(4)
    val x: DoubleWrapper = y
    x
  }

  /* Not working anymore.
    def useConversion(implicit f: A => B) = {
      val y: A = ...
      val x: B = a    // error under Dotty
    }
   */

  def test: Unit = {
    println(useConversion)
    println(convert(new IntWrapper(42)))
  }

}


text:
"use strict";
// THIS CODE WAS AUTOMATICALLY GENERATED
// DO NOT EDIT THIS CODE BY HAND
// RUN THE FOLLOWING COMMAND FROM THE WORKSPACE ROOT TO REGENERATE:
// npx nx generate-lib @typescript-eslint/scope-manager
Object.defineProperty(exports, "__esModule", { value: true });
exports.webworker_importscripts = void 0;
exports.webworker_importscripts = {};
//# sourceMappingURL=webworker.importscripts.js.map


text:
<!--configuration -->
<configuration scan="true" scanPeriod="120 seconds" debug="false">

	<!-- make use of the jul-to-slf4j bridge -->
	<contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
		<resetJUL>false</resetJUL>
	</contextListener>
<!--  -->
	<appender name="JMS" class="ch.qos.logback.classic.net.JMSTopicAppender">
		<InitialContextFactoryName>org.apache.activemq.jndi.ActiveMQInitialContextFactory</InitialContextFactoryName>
    	<ProviderURL>tcp://localhost:61616</ProviderURL>
    	<TopicConnectionFactoryBindingName>ConnectionFactory</TopicConnectionFactoryBindingName>
    	<TopicBindingName>dynamicTopics/LogTopic.jms</TopicBindingName>
	</appender>

	<!-- potential log file target dirs might be ${java.io.tmpdir} or ${user.home} -->
	<appender name="FILE"
		class="ch.qos.logback.core.rolling.RollingFileAppender">
		<file>${catalina.base}/logs/IVCTtcRunner.log</file>
		<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!-- rollover daily -->
			<fileNamePattern>${catalina.base}/logs/LogSinkTest.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
			<timeBasedFileNamingAndTriggeringPolicy
				class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
				<!-- or whenever the file size reaches 100MB -->
				<maxFileSize>100MB</maxFileSize>
			</timeBasedFileNamingAndTriggeringPolicy>
			<!-- keep 30 days' worth of history -->
			<maxHistory>30</maxHistory>
		</rollingPolicy>

		<encoder>
			<pattern>%date %level [%logger{36}] [%file:%line] %X{testcase}: %msg%n</pattern>
		</encoder>
	</appender>
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
			by default -->
		<encoder>
			<!--pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern -->
			<!--pattern>%d{HH:mm:ss.SSS} %-5level %logger{10} - %msg%n</pattern -->
			<pattern>%date IVCTtcRunner %X{testcase}: %msg%n</pattern>
		</encoder>
	</appender>

	<!-- TRACE < DEBUG < INFO < WARN < ERROR - ALL,OFF,NULL(=INHERITED) -->
	<!--  configure root -->
	<root level="WARN">
		<appender-ref ref="FILE" />
		<appender-ref ref="STDOUT" />
	<!-- -->
		<appender-ref ref="JMS" />
	</root>
	<!--  configure special settings for own packages -->
	<logger name="de.fraunhofer.iosb" level="DEBUG" />
	<!-- Thirdparty Configuration, i.e. various common base packages -->

</configuration>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wiley.wrox.chapter10.cardboardglass" >

    <uses-permission android:name="android.permission.NFC" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-feature android:glEsVersion="0x00020000" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:screenOrientation="landscape"
            android:name="com.wiley.wrox.chapter10.cardboardglass.MyActivityPhone"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="com.wiley.wrox.chapter10.cardboardglass.DataLayerListenerServicePhone" >
            <intent-filter>
                <action android:name="com.google.android.gms.wearable.BIND_LISTENER" />
            </intent-filter>
        </service>

        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
    </application>

</manifest>


text:
aclocal
autoheader
automake --foreign
autoconf

./configure $*


text:
<?php

  namespace vume;

  class Session {

    /**
     * The original reference for the $_SESSION array.
     */
    private $reference;

    /**
     * Copy of $_SESSION. Need for check if key or value exists.
     */
    private $copy;

    /**
     * The keys you work with.
     */
    private $keys;

    /**
     * Need second variable with stored keys you work with.
     */
    private $keysForExists;

    /**
     * Need third variable with stored keys you work with.
     */
    private $keysForRemove;

    /**
     * Start session if required, get your keys and initialize the variables.
     */
    public function __construct($keys, $seperator)
    {
      if(session_status() == PHP_SESSION_NONE) session_start();

      $this->keys = $keys ? explode($seperator, $keys) : null;
      $this->keysForExists = $this->keys;
      $this->keysForRemove = $this->keys;

      $this->reference = & $_SESSION;
      $this->copy = $_SESSION;
    }

    /**
     * Get the requested session. If key does not exists, return a default value.
     * If no key are passed, return the complete $_SESSION array.
     */
    public function get($default = null)
    {
      if( ! $this->keys) {
        return $_SESSION;
      }

      if($this->exists()) {
        $this->createDeepSession();

        return $this->reference;
      }

      return $default;
    }

    /**
     * Set a value for a session.
     */
    public function set($value)
    {
      $this->createDeepSession();
      $this->reference = $value;
    }

    /**
     * Check if session value is equal to the parameter.
     */
    public function is($value)
    {
      if($this->exists()) {
        $this->createDeepSession();

        return $this->reference == $value;
      }
    }

    /**
     * Call the removeKey() method.
     */
    public function remove()
    {
      return $this->removeKey($_SESSION);
    }

    /**
     * Alias for remove().
     */
    public function delete()
    {
      return $this->remove();
    }

    /**
     * Check if requested key exists.
     */
    public function exists($array = null)
    {
      if( ! $array) $array = $this->copy;

      $_key = array_shift($this->keysForExists);

      foreach($array as $key => & $value) {
        if(is_array($value) && ! empty($value) && $key == $_key && ! empty($this->keysForExists)) {
          return $this->exists($value);
        }

        if($key == $_key && empty($this->keysForExists)) {
          return true;
        }
      }
    }

    /**
     * Use this method for flash messages.
     *
     * Stores the value of a session, delete the original session and return the save.
     * Useful for form validation and redirect back with messages.
     */
    public function message()
    {
      if($this->exists()) {
        $this->createDeepSession();

        $value = $this->reference;
        $this->remove();

        return $value;
      }
    }

    /**
     * Destroy complete session.
     *
     * http://stackoverflow.com/questions/3948230/best-way-to-completely-destroy-a-session-even-if-the-browser-is-not-closed
     */
    public function destroy()
    {
      $_SESSION = array();

      if(ini_get("session.use_cookies")) {
        $params = session_get_cookie_params();
        setcookie(session_name(), '', time() - 42000,
          $params["path"], $params["domain"],
          $params["secure"], $params["httponly"]
        );
      }

      session_destroy();
    }

    /**
     * Creates dynamic a deep session.
     */
    private function createDeepSession()
    {
      while($name = array_shift($this->keys)) {
        $this->reference = & $this->reference[$name];
      }
    }

    /**
     * Remove the key in session.
     */
    private function removeKey( & $array)
    {
      $_key = array_shift($this->keysForRemove);

      foreach($array as $key => & $value) {
        if(is_array($value) && $key == $_key && ! empty($this->keysForRemove)) {
          return $this->removeKey($value);
        }

        if($key == $_key) {
          unset($array[$key]);
        }
      }
    }
  }


text:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using TXM.Core;

namespace TXM.GUI.Dialogs
{
    /// <summary>
    /// Interaktionslogik für NewPlayerDialog.xaml
    /// </summary>
    public partial class NewPlayerDialog : Window, IPlayerDialog
    {
        private bool dialogResult = false;
        private bool changes = false;
        private Player CurrentPlayer;
        private bool nicknameRequiered = true;

        public NewPlayerDialog(AbstractRules rules)
        {
            InitializeComponent();
            TextBoxNickname.Focus();
            changes = false;
            //Noch steuern, welcher Spieler angelegt werden soll
            foreach (string s in rules.Factions)
                ComboBoxFaction.Items.Add(s);
        }

        public void SetPlayer(Player player)
        {
            CurrentPlayer = player;
            TextBoxForename.Text = CurrentPlayer.Forename;
            TextBoxName.Text = CurrentPlayer.Name;
            TextBoxNickname.Text = CurrentPlayer.Nickname;
            TextBoxTeam.Text = CurrentPlayer.Team;
            ComboBoxFaction.SelectedValue = CurrentPlayer.Faction;
            if(ComboBoxFaction.SelectedValue == null)
            {
                ComboBoxFaction.Items.Add(CurrentPlayer.Faction);
                ComboBoxFaction.SelectedValue = CurrentPlayer.Faction;
            }
            CheckboxFreeticket.IsChecked = ((Player)CurrentPlayer).WonBye;
            CheckboxPayed.IsChecked = CurrentPlayer.Paid;
            CheckboxSquadListGiven.IsChecked = CurrentPlayer.ListGiven;
            TextBoxNickname.IsEnabled = false;
            nicknameRequiered = false;
            TextBoxTableNR.Text = player.TableNo.ToString();
            CheckboxPresent.IsChecked = CurrentPlayer.Present;

        }

        public Player GetPlayer()
        {
            Player player = new Player(TextBoxNickname.Text, ComboBoxFaction.SelectedValue.ToString());
            player.Team = TextBoxTeam.Text;
            player.Name = TextBoxName.Text;
            player.Forename = TextBoxForename.Text;
            player.WonBye = CheckboxFreeticket.IsChecked == true;
            player.ListGiven = CheckboxSquadListGiven.IsChecked == true;
            player.Paid = CheckboxPayed.IsChecked == true;
            player.TableNo = TableNr;
            player.Present = CheckboxPresent.IsChecked == true;
            return player;
        }

        public bool GetDialogResult()
        {
            return dialogResult;
        }

        public bool IsChanged()
        {
            return changes;
        }

        public void SetButtonOKText(string text)
        {
            ButtonOK.Content = text;
        }

        public void SetTitle(string text)
        {
            Title = text;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            dialogResult = false;
            this.Close();
        }

        private void NewPlayer_Click(object sender, RoutedEventArgs e)
        {
            NewPlayer();
        }

        private void NewPlayer()
        {
            if (TextBoxNickname.Text == "" && nicknameRequiered)
                return;
            else if (ComboBoxFaction.SelectedIndex == -1)
                return;
            else
            {
                dialogResult = true;
                this.Close();
            }
        }

        private void ValueChanged(object sender, TextChangedEventArgs e)
        {
            changes = true;
            e.Handled = true;
        }

        private void ValueChanged(object sender, SelectionChangedEventArgs e)
        {
            changes = true;
            e.Handled = true;
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            if(e.Key == Key.Enter)
            {
                NewPlayer();
            }
        }

        private int TableNr
        {
            get
            {
                int t;
                try
                {
                    t = Int32.Parse(TextBoxTableNR.Text);
                }
                catch
                {
                    t = 0;
                }
                return t;
            }
        }

        private void TextBoxNickname_TextChanged(object sender, TextChangedEventArgs e)
        {
            changes = true;
            e.Handled = true;
        }

        private void IntegerUpDownTableNr_ValueChanged(object sender, TextChangedEventArgs e)
        {
            changes = true;
            e.Handled = true;
        }

        public new void ShowDialog()
        {
            base.ShowDialog();
        }
    }
}


text:
<?php
    require "lib/emoticons.php";

    class Emoticons extends Modules {
        public function __init() {
           $this->addAlias("markup_text", "emote");
           $this->addAlias("markup_post_text","emote");
           $this->addAlias("preview", "emote");
           $this->addAlias("preview_post", "emote");
        }
        public function emote($text) {
            return convertEmoticons($text);
        }
    }
?>


text:
#ifndef __CCEDITBOXIMPLANDROID_H__
#define __CCEDITBOXIMPLANDROID_H__

#include "cocos2d.h"
#include "ExtensionMacros.h"
#include "CCEditBoxImpl.h"

NS_CC_EXT_BEGIN

class CCEditBox;

class CCEditBoxImplAndroid : public CCEditBoxImpl
{
public:
    CCEditBoxImplAndroid(CCEditBox* pEditText);
    virtual ~CCEditBoxImplAndroid();

    virtual bool initWithSize(const CCSize& size);
    virtual void setFontColor(const ccColor3B& color);
    virtual void setPlaceholderFontColor(const ccColor3B& color);
    virtual void setInputMode(EditBoxInputMode inputMode);
    virtual void setInputFlag(EditBoxInputFlag inputFlag);
    virtual void setMaxLength(int maxLength);
    virtual int  getMaxLength();
    virtual void setReturnType(KeyboardReturnType returnType);
    virtual bool isEditing();

    virtual void setText(const char* pText);
    virtual const char* getText(void);
    virtual void setPlaceHolder(const char* pText);
    virtual void setPosition(const CCPoint& pos);
    virtual void setContentSize(const CCSize& size);
    virtual void visit(void);
    virtual void doAnimationWhenKeyboardMove(float duration, float distance);
    virtual void openKeyboard();
    virtual void closeKeyboard();

private:
    CCLabelTTF* m_pLabel;
    CCLabelTTF* m_pLabelPlaceHolder;
    EditBoxInputMode    m_eEditBoxInputMode;
    EditBoxInputFlag    m_eEditBoxInputFlag;
    KeyboardReturnType  m_eKeyboardReturnType;

    std::string m_strText;
    std::string m_strPlaceHolder;

    ccColor3B m_colText;
    ccColor3B m_colPlaceHolder;

    int   m_nMaxLength;
    CCSize m_EditSize;
};

NS_CC_EXT_END

#endif /* __CCEDITBOXIMPLANDROID_H__ */


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRID_TEMPLATE_AREAS_VALUE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRID_TEMPLATE_AREAS_VALUE_H_

#include "third_party/blink/renderer/core/css/css_value.h"
#include "third_party/blink/renderer/core/style/grid_area.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"

namespace blink {
namespace cssvalue {

class CSSGridTemplateAreasValue : public CSSValue {
 public:
  CSSGridTemplateAreasValue(const NamedGridAreaMap&,
                            wtf_size_t row_count,
                            wtf_size_t column_count);
  ~CSSGridTemplateAreasValue() = default;

  String CustomCSSText() const;

  const NamedGridAreaMap& GridAreaMap() const { return grid_area_map_; }
  wtf_size_t RowCount() const { return row_count_; }
  wtf_size_t ColumnCount() const { return column_count_; }

  bool Equals(const CSSGridTemplateAreasValue&) const;

  void TraceAfterDispatch(blink::Visitor* visitor) const {
    CSSValue::TraceAfterDispatch(visitor);
  }

 private:
  NamedGridAreaMap grid_area_map_;
  wtf_size_t row_count_;
  wtf_size_t column_count_;
};

}  // namespace cssvalue

template <>
struct DowncastTraits<cssvalue::CSSGridTemplateAreasValue> {
  static bool AllowFrom(const CSSValue& value) {
    return value.IsGridTemplateAreasValue();
  }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_CSS_CSS_GRID_TEMPLATE_AREAS_VALUE_H_


text:
var _ = require('lodash');

var BrestLimiter = {

    init: function(brest, callback){
        var self = this;
        var client = brest.attachment('redis').client();
        BrestLimiter.limiter = require('./limiter')(brest.getApp(), client);
        BrestLimiter.settings = brest.getSetting('limiter', {
             lookup: ['connection.remoteAddress'],
             total: 150,
             expire: 60*60
        });

        if (BrestLimiter.settings.global) {
            var settings = _.defaultsDeep({
                path: '*',
                method: 'all'
            }, BrestLimiter.settings);
            BrestLimiter.limiter(settings);
        }

        callback();
    },

    resource: {
        init: function(resource, callback) {
            if (resource.description.limiter) {
                var settings = _.defaultsDeep(resource.description.limiter, BrestLimiter.settings);
                settings.path = resource.getURI();
                settings.method = 'all';
                BrestLimiter.limiter(settings);
            }
            callback(null, BrestLimiter);
        }
    },

    method: {
        init: function(method, callback) {
            var settings = {};
            if (method.description.limiter) {
                settings = _.defaults(method.description.limiter, BrestLimiter.settings);
                settings.method = method.getMethod().toLowerCase();
                settings.path = method.getURI();
                BrestLimiter.limiter(settings);

            }
            if (BrestLimiter.settings.whenAuth && !method.description.noAuth) {
                settings = _.defaults(BrestLimiter.settings.whenAuth, BrestLimiter.settings);
                settings.method = method.getMethod().toLowerCase();
                settings.path = method.getURI();
                BrestLimiter.limiter(settings);
            }
            callback(null, BrestLimiter);
        }
    }
};

module.exports = BrestLimiter;


text:
#include "tilesetlayout.h"
#include "combinesmalltiles.h"
#include "tilesetinserter.h"
#include "tilesettype.hpp"
#include "models/common/errorlist.h"
#include "models/common/iterators.h"
#include "models/common/vectorset.h"
#include "models/metasprite/errorlisthelpers.h"

namespace UnTech::MetaSprite::Compiler {

namespace MS = UnTech::MetaSprite::MetaSprite;

static void addFrameToTileset(vectorset<Tile16>& tiles,
                              const MS::Frame& frame,
                              const SmallTileMap_t& smallTileMap)
{
    for (const auto& obj : frame.objects) {
        Tile16 t;
        if (obj.size == ObjectSize::LARGE) {
            t.largeTileId = obj.tileId;
        }
        else {
            t.smallTileIds = smallTileMap.at(obj.tileId);
        }
        tiles.insert(t);
    }
}

static vectorset<Tile16> fixedTilesetData(const std::vector<ExportIndex>& frames,
                                          const MS::FrameSet& frameSet,
                                          const SmallTileMap_t& smallTileMap)
{
    vectorset<Tile16> tiles;

    for (const auto& entry : frames) {
        addFrameToTileset(tiles, frameSet.frames.at(entry.fsIndex), smallTileMap);
    }

    return tiles;
}

struct DynamicTileset {
    vectorset<Tile16> tiles;
    std::vector<unsigned> frameIds;

    DynamicTileset(vectorset<Tile16>&& tiles, unsigned frameId)
        : tiles(std::move(tiles))
        , frameIds({ frameId })
    {
    }
};

static std::vector<DynamicTileset> tilesForEachFrame(const std::vector<ExportIndex>& frameEntries,
                                                     const MS::FrameSet& frameSet,
                                                     const SmallTileMap_t& smallTileMap)
{
    std::vector<DynamicTileset> ret;

    for (auto [frameId, entry] : const_enumerate(frameEntries)) {
        const auto frame = frameSet.frames.at(entry.fsIndex);

        vectorset<Tile16> tileset;
        addFrameToTileset(tileset, frame, smallTileMap);

        auto it = std::find_if(ret.begin(), ret.end(),
                               [&](auto& i) { return i.tiles == tileset; });

        if (it == ret.end()) {
            ret.emplace_back(std::move(tileset), frameId);
        }
        else {
            // tileset already exists
            it->frameIds.push_back(frameId);
        }
    }

    return ret;
}

static std::vector<std::pair<Tile16, unsigned>> countTileUsage(const std::vector<DynamicTileset>& ftVector)
{
    std::vector<std::pair<Tile16, unsigned>> ret;
    ret.reserve(128);

    for (const auto& ft : ftVector) {
        for (const Tile16& ftTile : ft.tiles) {
            auto it = std::find_if(ret.begin(), ret.end(),
                                   [&](const auto& i) { return i.first == ftTile; });
            if (it == ret.end()) {
                ret.emplace_back(ftTile, ft.frameIds.size());
            }
            else {
                it->second += ft.frameIds.size();
            }
        }
    }

    return ret;
}

static vectorset<Tile16> calculateStaticTiles(const std::vector<DynamicTileset>& ftVector,
                                              const TilesetType tilesetType)
{
    const unsigned tilesetType_nTiles = numberOfTilesetTiles(tilesetType);

    auto popularTiles = countTileUsage(ftVector);

    std::stable_sort(popularTiles.begin(), popularTiles.end(),
                     [](auto& l, auto& r) { return l.second > r.second; });

    if (popularTiles.size() > tilesetType_nTiles - 1) {
        popularTiles.resize(tilesetType_nTiles - 1);
    }

    while (popularTiles.size() > 0) {
        unsigned maxDynamicTiles = 0;

        for (const auto& ft : ftVector) {
            unsigned nDynamicTiles = ft.tiles.size();

            for (const auto& tc : popularTiles) {
                if (ft.tiles.contains(tc.first)) {
                    nDynamicTiles--;
                }
            }
            if (nDynamicTiles > maxDynamicTiles) {
                maxDynamicTiles = nDynamicTiles;
            }
        }

        if (maxDynamicTiles + popularTiles.size() <= tilesetType_nTiles) {
            break;
        }
        popularTiles.resize(popularTiles.size() - 1);
    }

    vectorset<Tile16> ret;
    ret.reserve(popularTiles.size());
    for (const auto& tc : popularTiles) {
        ret.insert(tc.first);
    }
    return ret;
}

static std::vector<Tile16> tile_difference(const vectorset<Tile16>& tiles,
                                           const vectorset<Tile16>& staticTiles)
{
    std::vector<Tile16> ret;
    ret.reserve(tiles.size());

    std::copy_if(tiles.begin(), tiles.end(),
                 std::back_inserter(ret),
                 [&](const Tile16& t) { return staticTiles.contains(t) == false; });

    return ret;
}

TilesetLayout layoutTiles(const MS::FrameSet& frameSet,
                          const std::vector<ExportIndex>& exportFrames,
                          ErrorList& errorList)
{
    const TilesetType tilesetType = frameSet.tilesetType;
    const unsigned tilesetType_nTiles = numberOfTilesetTiles(tilesetType);
    const bool tilesetType_isFixed = isFixedTilesetType(tilesetType);

    const auto smallTileMap = buildSmallTileMap(frameSet, exportFrames);
    const auto tiles = fixedTilesetData(exportFrames, frameSet, smallTileMap);

    TilesetLayout ret;
    ret.tilesetType = frameSet.tilesetType;
    ret.frameTilesets.resize(exportFrames.size(), -1);

    if (tiles.size() < tilesetType_nTiles || tilesetType_isFixed) {
        // Fixed tileset
        if (not tilesetType_isFixed) {
            errorList.addWarningString(u8"Tileset can be fixed, making it so.");
        }

        if (tiles.size() <= tilesetType_nTiles) {
            const TilesetType smallestType = smallestFixedTilesetType(tiles.size());
            if (numberOfTilesetTiles(smallestType) != tilesetType_nTiles) {
                errorList.addWarningString(u8"TilesetType shrunk to ", ttString(smallestType));
            }
            ret.tilesetType = smallestType;
            ret.staticTiles = std::move(tiles);
        }
        else {
            errorList.addErrorString(u8"Unable to fit ", tiles.size(), u8" Tile16 tiles inside a ", ttString(tilesetType));
        }
    }
    else {
        // Dynamic tileset
        const auto frameTiles = tilesForEachFrame(exportFrames, frameSet, smallTileMap);
        ret.staticTiles = calculateStaticTiles(frameTiles, tilesetType);

        for (const auto& ft : frameTiles) {
            auto dynamicTiles = tile_difference(ft.tiles, ret.staticTiles);
            if (dynamicTiles.empty() == false) {
                unsigned nTiles = dynamicTiles.size() + ret.staticTiles.size();

                if (nTiles <= tilesetType_nTiles) {
                    int tilesetId = ret.dynamicTiles.size();
                    ret.dynamicTiles.push_back(std::move(dynamicTiles));
                    for (unsigned frameId : ft.frameIds) {
                        ret.frameTilesets.at(frameId) = tilesetId;
                    }
                }
                else {
                    for (unsigned frameId : ft.frameIds) {
                        const unsigned frameIndex = exportFrames.at(frameId).fsIndex;
                        errorList.addError(frameError(
                            frameSet.frames.at(frameIndex), frameIndex,
                            u8"Too many tiles in frame (", nTiles, u8")", dynamicTiles.size(), u8" ", ret.staticTiles.size()));
                    }
                }
            }
        }
    }

    return ret;
}

}


text:
    <meta http-equiv="refresh" content="0; URL=../../doc/html/boost/random_device.html">

    Automatic redirection failed, please go to

      ../../doc/html/boost/random_device.html

Copyright (c) 2010 Steven Watanabe

Distributed under the Boost Software License, Version 1.0. (See accompanying file
      LICENSE_1_0.txt or copy at
      www.boost.org/LICENSE_1_0.txt).


text:
public final class C /* p.C*/ extends p.A {
  protected int af();//  af()

  protected int getAp();//  getAp()

  public  C();//  .ctor()

}


text:
class Category < ActiveRecord::Base
  has_and_belongs_to_many :microposts
end


text:
"""
Converts a cache into a TSV with one column per feature, a column for the
target label, and (optionally) a column for score document.

Usage:
    cache2feature_tsv.py <features> <label> [<model>] [<additional-field>]...
                         [--input=<path>] [--output=<path>]
                         [--verbose]
                         [--debug]

Options:
    -h --help               Prints this documentation
    <features>              Classpath to an list of features to use when
                            constructing the model
    <label>                 The name of the target label field
    <model>                 If set, include a column with score documents
                            generated by the model file.
    <additional-field>      Fields from the observations to include in the output
    --input=<path>          The location of the input cache file to read
                            [default: <stdin>]
    --output=<path>         The location of the output TSV file to write
                            [default: <stdout>]
    --verbose               Prints dots and stuff to indicate progress.
    --debug                 Print debug logging.
"""
import logging
import json
import sys
import traceback

import docopt
import mysqltsv
import yamlconf
from revscoring import Model
from revscoring.dependencies import solve
from revscoring.utilities.util import read_observations

def main(argv=None):
    args = docopt.docopt(__doc__, argv=argv)

    logging.basicConfig(
        level=logging.INFO if not args['--debug'] else logging.DEBUG,
        format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
    )

    sys.path.insert(0, ".")  # Search local directory first
    features = yamlconf.import_module(args['<features>'])
    label_name = args['<label>']
    if args['<model>'] is not None:
        model = Model.load(open(args['<model>']))
    else:
        model = None

    additional_fields = args['<additional-field>']

    if args['--input'] == "<stdin>":
        observations = read_observations(sys.stdin)
    else:
        observations = read_observations(open(args['--input']))

    if args['--output'] == "<stdout>":
        output = sys.stdout
    else:
        output = open(args['--output'], 'w')

    verbose = args['--verbose']

    run(observations, output, features, label_name, model, additional_fields,
        verbose)

def run(observations, output, features, label_name, model, additional_fields,
        verbose):
    headers = [str(f) for f in features] + [label_name]
    if model is not None:
        headers.append("score_doc")
    headers.extend(additional_fields)
    writer = mysqltsv.Writer(output, headers=headers)

    for ob in observations:
        try:
            feature_values = list(solve(features, cache=ob['cache']))
            row = feature_values + [ob[label_name]]
            if model is not None:
                score_doc = model.score(feature_values)
                row += [json.dumps(score_doc)]
            for field_name in additional_fields:
                row += [ob[field_name]]
            writer.write(row)
            if verbose:
                sys.stderr.write(".")
                sys.stderr.flush()
        except:  # noqa: E722
            # Naughty indiscriminate exception consumption.
            sys.stderr.write(traceback.format_exc())

    if verbose:
        sys.stderr.write("\n")

if __name__ == "__main__":
    main(sys.argv[1:])


text:
/
Exosite::Exosite(MQTT *client_ref)
{
    client = client_ref;
    client->setMaxPacketSize(5000);
}

Exosite::Exosite(MQTT *client_ref, char *token_ref)
{
    client = client_ref;
    client->setMaxPacketSize(5000);
    strncpy(token, token_ref, 41);
}

/*==============================================================================
*  provision
*
*  Provision on Exosite Platform, activate device and get cik.
*=============================================================================*/
bool Exosite::provision(const char *topic) {
    // Ensure TLS enabled for the MQTT-TLS client - required for communicating with Exosite
    client->enableTls(DIGICERT_GLOBAL_ROOT_CA_PEM, sizeof(DIGICERT_GLOBAL_ROOT_CA_PEM));

    timeout_time = 0;
    time_now = 0;
    timeout = 2000; // 2s

    if (!client->isConnected()) {
        Serial.print(F("No existing connection - opening one (to provision)... "));
        client->connect("");
    }

    if (client->isConnected()) {
        Serial.println(F("connected!"));

        #ifdef EXOSITEDEBUG
            Serial.printf("Publishing empty string to: %s\n", topic);
        #endif

        // Send provision request using Exosite MQTT Device API (provision)
        client->publish(topic, "");

        #ifdef EXOSITEDEBUG
            Serial.println(F("Provision publish complete..."));
        #endif

        // Provide time for response from server (auth token)
        timeout_time = millis() + timeout;
        while (timeout_time > time_now) {
            client->loop();
            time_now = millis();
        }
    }
    else {
        Serial.println(F("\nError: Failed to open connection to Exosite (to provision)..."));
        return false;
    }

    // Disconnect - connection parameters are unique for provisioning
    client->disconnect();

    #ifdef EXOSITEDEBUG
        Serial.println(F("End of provision sequence"));
    #endif

    return true;
}

/*==============================================================================
*  connect
*
*  Establish persistent connection
*=============================================================================*/
bool Exosite::connect() {
    // Ensure TLS enabled for the MQTT-TLS client - required for communicating with Exosite
    client->enableTls(DIGICERT_GLOBAL_ROOT_CA_PEM, sizeof(DIGICERT_GLOBAL_ROOT_CA_PEM));

    if (!client->isConnected()) {
        Serial.print(F("No existing connection - opening one... "));
        client->connect("", "", token);
    }

    if (client->isConnected()) {
        Serial.println(F("connected!"));
    }
    else {
        Serial.println(F("\nError: Failed to open connection to Exosite..."));
        return false;
    }

    return true;
}

/*==============================================================================
*  publish
*
*  Publish specified value to specified topic
*=============================================================================*/
bool Exosite::publish(const char *topic, const char *payload) {
    #ifdef EXOSITEDEBUG
        Serial.println(F("Attempting to publish message..."));
    #endif

    if (!client->isConnected()) {
        connect();
    }

    if (client->isConnected()) {
        #ifdef EXOSITEDEBUG
            Serial.printf("Topic (%i): %s\n", strlen(topic), topic);
            Serial.printf("Payload (%i): %s\n", strlen(payload), payload);
        #endif

        // Send request using Exosite MQTT Device API (general publish)
        client->publish(topic, payload);

        #ifdef EXOSITEDEBUG
            Serial.println(F("Data publish complete..."));
        #endif
    }
    else {
        Serial.println(F("\nError: Unable to publish message..."));
        return false;
    }
    return true;
}

/*==============================================================================
*  checkForMessage
*
*  Pull any queued subscription messages from NIC buffer
*=============================================================================*/
void Exosite::checkForMessage() {
    Serial.println(F("Checking for queued messages..."));
    if (!client->isConnected()) {
        connect();
    }

    if (client->isConnected()) {
        Serial.printf("Check-In Loop: %i\n", client->loop());
    }
    else {
        Serial.println(F("\nError: Unable to check for messages..."));
    }
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
*  Utility Procedures
*
/*==============================================================================
*  saveNVCIK
*
*  Write the CIK to EEPROM
*=============================================================================*/
bool Exosite::saveNVCIK() {
    #ifdef EXOSITEDEBUG
        Serial.printf("Storing token: %s\n", token);
    #endif

    EEPROM.put(TOKEN_EEPROM_ADDRESS, token);
    return true;
}

/*==============================================================================
*  fetchNVCIK
*
*  Fetch the CIK from EEPROM
*=============================================================================*/
bool Exosite::fetchNVCIK() {
    Serial.println(F("Checking for stored token..."));
    char temp[41];

    EEPROM.get(TOKEN_EEPROM_ADDRESS, temp);

    if (!isToken(temp)) {
        Serial.printf("Retrieved non-token data: %s\n", temp);
        return false;
    }
    strncpy(token, temp, 40);

    #ifdef EXOSITEDEBUG
        Serial.printf("Found token: %s\n", token);
    #endif

    return true;
}

/*==============================================================================
*  isProvisioned
*
*  Fetch the CIK from EEPROM
*=============================================================================*/
bool Exosite::isProvisioned() {
    return fetchNVCIK();
}

/*==============================================================================
*  isConnected
*
*  Verify current connections state
*=============================================================================*/
bool Exosite::isConnected() {
    return client->isConnected();
}

/*==============================================================================
*  isToken
*
*  Fetch the CIK from EEPROM
*=============================================================================*/
bool Exosite::isToken(char *val) {
    for(int i = 0; i < 40; i++) {
        if (!((val[i] >= '0' && val[i] <= '9') ||
              (val[i] >= 'A' && val[i] <= 'Z') ||
              (val[i] >= 'a' && val[i] <= 'z'))) {

            #ifdef EXOSITEDEBUG
                Serial.printf("Proposed token failed validation: %s\n", val);
                Serial.printf("Invalid character: %c\n", val[i]);
            #endif

            return false;
        }
    }
    return true;
}

/*==============================================================================
*  useAuth
*
*  Store valid token
*=============================================================================*/
bool Exosite::useAuth(char auth[41]) {
    if (isToken(auth)) {
        strcpy(token, auth);
        if (saveNVCIK()) {
            #ifdef EXOSITEDEBUG
                Serial.printf("Token (Stored): %s\n", token);
            #endif

            return true;
        }
        Serial.printf("Error: Failed to store token!");
    }
    return false;
}

/*==============================================================================
*  clearAuth
*
*  Clear EEPROM of any stored values (e.g. Auth Token)
*=============================================================================*/
void Exosite::clearAuth() {
    Serial.println(F("ALERT: CLEARING ALL EEPROM"));
    EEPROM.clear();
}


text:
package org.liquidengine.legui.listener;

import org.liquidengine.legui.event.WindowPosEvent;

/**
 * Created by ShchAlexander on 04.02.2017.
 */
public interface WindowPosEventListener extends EventListener<WindowPosEvent> {

    void process(WindowPosEvent event);
}


text:
--TEST--
Test trait_exists() function : basic functionality
--FILE--
<?php
/* Prototype  : proto bool trait_exists(string traitname [, bool autoload])
 * Description: Checks if the trait exists
 * Source code: Zend/zend_builtin_functions.c
 * Alias to functions:
 */

echo "*** Testing trait_exists() : basic functionality ***\n";

function __autoload($traitName) {
	echo "In __autoload($traitName)\n";
}

trait MyTrait {}

echo "Calling trait_exists() on non-existent trait with autoload explicitly enabled:\n";
var_dump( trait_exists('C', true) );
echo "\nCalling trait_exists() on existing trait with autoload explicitly enabled:\n";
var_dump( trait_exists('MyTrait', true) );

echo "\nCalling trait_exists() on non-existent trait with autoload explicitly enabled:\n";
var_dump( trait_exists('D', false) );
echo "\nCalling trait_exists() on existing trait with autoload explicitly disabled:\n";
var_dump( trait_exists('MyTrait', false) );

echo "\nCalling trait_exists() on non-existent trait with autoload unspecified:\n";
var_dump( trait_exists('E') );
echo "\nCalling trait_exists() on existing trait with autoload unspecified:\n";
var_dump( trait_exists('MyTrait') );

echo "Done";
?>
--EXPECTF--
*** Testing trait_exists() : basic functionality ***
Calling trait_exists() on non-existent trait with autoload explicitly enabled:
In __autoload(C)
bool(false)

Calling trait_exists() on existing trait with autoload explicitly enabled:
bool(true)

Calling trait_exists() on non-existent trait with autoload explicitly enabled:
bool(false)

Calling trait_exists() on existing trait with autoload explicitly disabled:
bool(true)

Calling trait_exists() on non-existent trait with autoload unspecified:
In __autoload(E)
bool(false)

Calling trait_exists() on existing trait with autoload unspecified:
bool(true)
Done


text:
typedef NS_ENUM(NSInteger, ArbiTrackState) {
    ARBI_PLACEMENT,
    ARBI_TRACKING,
};

@interface MarkerlessTrackingViewController () {

    ArbiTrackState __arbiButtonState;

    float __lastScale;
    float __lastPanX;
}

@property (nonatomic) ARModelNode *modelNode;
@property (nonatomic) InstructionLabel *label;

@end

@implementation MarkerlessTrackingViewController

- (void)setupContent
{
    [self setupModel];
    [self setupArbiTrack];
    [self setupLabel];

    // Add gesture recognisers.
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(arbiPinch:)];
    [self.cameraView addGestureRecognizer:pinchGesture];

    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(arbiPan:)];
    [self.cameraView addGestureRecognizer:panGesture];

    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(arbiTap:)];
    [self.cameraView addGestureRecognizer:tapGesture];
}

- (void)setupModel
{
    // Import model from file.
    ARModelImporter *importer = [[ARModelImporter alloc] initWithBundled:@"bloodhound.armodel"];
    ARModelNode *modelNode = [importer getNode];

    // Set up and add material to model.
    ARLightMaterial *material = [ARLightMaterial new];
    material.colour.texture = [[ARTexture alloc] initWithUIImage:[UIImage imageNamed:@"bloodhound.png"]];
    material.diffuse.value = [ARVector3 vectorWithValuesX:0.2 y:0.2 z:0.2];
    material.ambient.value = [ARVector3 vectorWithValuesX:0.8 y:0.8 z:0.8];
    material.specular.value = [ARVector3 vectorWithValuesX:0.3 y:0.3 z:0.3];
    material.shininess = 20;
    material.reflection.reflectivity = 0.15;

    for (ARMeshNode *meshNode in modelNode.meshNodes) {
        meshNode.material = material;
    }

    self.modelNode = modelNode;
}

- (void)setupArbiTrack
{
    // Initialise gyro placement. Gyro placement positions content on a virtual floor plane where the device is aiming.
    ARGyroPlaceManager *gyroPlaceManager = [ARGyroPlaceManager getInstance];
    [gyroPlaceManager initialise];

    // Set up the target node on which the model is placed.
    ARNode *targetNode = [ARNode nodeWithName:@"targetNode"];
    [gyroPlaceManager.world addChild:targetNode];

    // Add a visual reticule to the target node for the user.
    ARImageNode *targetImageNode = [[ARImageNode alloc] initWithImage:[UIImage imageNamed:@"target.png"]];
    [targetNode addChild:targetImageNode];

    // Scale and rotate the image to the correct transformation.
    [targetImageNode scaleByUniform:0.1];
    [targetImageNode rotateByDegrees:90 axisX:1 y:0 z:0];

    // Initialise the arbiTracker, do not start until user placement.
    ARArbiTrackerManager *arbiTrack = [ARArbiTrackerManager getInstance];
    [arbiTrack initialise];

    // Set the arbiTracker target node to the node moved by the user.
    arbiTrack.targetNode = targetNode;

    [arbiTrack.world addChild:_modelNode];
}

- (void)setupLabel
{
    // Add instructional label.
    dispatch_async(dispatch_get_main_queue(), ^{

        InstructionLabel *label = [[InstructionLabel alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];

        label.text = @"Tap the screen to place model on target.";

        [self.view addSubview:label];

        [label constrainInView:self.view];

        self.label = label;
    });
}

#pragma mark - Gesture Interactions.

- (void)arbiTap:(UITapGestureRecognizer *)gesture
{
    ARArbiTrackerManager *arbiTrack = [ARArbiTrackerManager getInstance];

    if (__arbiButtonState == ARBI_PLACEMENT) {

        [arbiTrack start];

        arbiTrack.targetNode.visible = NO;

        self.modelNode.scale = [ARVector3 vectorWithValuesX:1 y:1 z:1];

        __arbiButtonState = ARBI_TRACKING;

        self.label.text = @"Pinch and pan to scale and rotate.";

        return;
    }

    else if (__arbiButtonState == ARBI_TRACKING) {

        [arbiTrack stop];

        arbiTrack.targetNode.visible = YES;

        __arbiButtonState = ARBI_PLACEMENT;

        self.label.text = @"Tap the screen to place model on target.";

        return;
    }
}

- (void)arbiPinch:(UIPinchGestureRecognizer *)gesture
{
    float scaleFactor = gesture.scale;

    if (gesture.state == UIGestureRecognizerStateBegan) {
        __lastScale = 1;
    }

    scaleFactor = 1 - (__lastScale - scaleFactor);

    __lastScale = gesture.scale;

    @synchronized ([ARRenderer getInstance]) {
        [self.modelNode scaleByUniform:scaleFactor];
    }
}

- (void)arbiPan:(UIPanGestureRecognizer *)gesture
{
    float x = [gesture translationInView:self.cameraView].x;

    if (gesture.state == UIGestureRecognizerStateBegan) {
        __lastPanX = x;
    }

    float diff = x - __lastPanX;

    float deg = diff * 0.5;

    @synchronized ([ARRenderer getInstance]) {
        [self.modelNode rotateByDegrees:deg axisX:0 y:1 z:0];
    }

    __lastPanX = x;
}

#pragma mark - Example IDs

+ (NSString *)getExampleName
{
    return @"MARKERLESS TRACKING";
}

+ (NSInteger)getExampleImportance
{
    return 5;
}

@end


text:
module Kanaveral
  module Extensions
    refine String do
      def camelize
        split('_'.freeze).map(&:capitalize).join
      end
    end
  end
end


text:
/*	$NetBSD: inflate9.h,v 1.1.1.1 2006/01/14 20:10:51 christos Exp $	*/

/* inflate9.h -- internal inflate state definition
 * Copyright (C) 1995-2003 Mark Adler
 * For conditions of distribution and use, see copyright notice in zlib.h
 */

/* WARNING: this file should *not* be used by applications. It is
   part of the implementation of the compression library and is
   subject to change. Applications should only use zlib.h.
 */

/* Possible inflate modes between inflate() calls */
typedef enum {
        TYPE,       /* i: waiting for type bits, including last-flag bit */
        STORED,     /* i: waiting for stored size (length and complement) */
        TABLE,      /* i: waiting for dynamic block table lengths */
            LEN,        /* i: waiting for length/lit code */
    DONE,       /* finished check, done -- remain here until reset */
    BAD         /* got a data error -- remain here until reset */
} inflate_mode;

/*
    State transitions between above modes -

    (most modes can go to the BAD mode -- not shown for clarity)

    Read deflate blocks:
            TYPE -> STORED or TABLE or LEN or DONE
            STORED -> TYPE
            TABLE -> LENLENS -> CODELENS -> LEN
    Read deflate codes:
                LEN -> LEN or TYPE
 */

/* state maintained between inflate() calls.  Approximately 7K bytes. */
struct inflate_state {
        /* sliding window */
    unsigned char FAR *window;  /* allocated sliding window, if needed */
        /* dynamic table building */
    unsigned ncode;             /* number of code length code lengths */
    unsigned nlen;              /* number of length code lengths */
    unsigned ndist;             /* number of distance code lengths */
    unsigned have;              /* number of code lengths in lens[] */
    code FAR *next;             /* next available space in codes[] */
    unsigned short lens[320];   /* temporary storage for code lengths */
    unsigned short work[288];   /* work area for code table building */
    code codes[ENOUGH];         /* space for code tables */
};


text:
<?php

namespace Sabre\CalDAV;
use Sabre\DAV;

interface ICalendar extends DAV\ICollection {

    /**
     * Performs a calendar-query on the contents of this calendar.
     *
     * The calendar-query is defined in RFC4791 : CalDAV. Using the
     * calendar-query it is possible for a client to request a specific set of
     * object, based on contents of iCalendar properties, date-ranges and
     * iCalendar component types (VTODO, VEVENT).
     *
     * This method should just return a list of (relative) urls that match this
     * query.
     *
     * The list of filters are specified as an array. The exact array is
     * documented by \Sabre\CalDAV\CalendarQueryParser.
     *
     * @param array $filters
     * @return array
     */
    public function calendarQuery(array $filters);

}


text:
package io.grpc.examples.helloworld;

import static org.junit.Assert.assertEquals;
import static org.mockito.AdditionalAnswers.delegatesTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import io.grpc.ManagedChannel;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.StreamObserver;
import io.grpc.testing.GrpcCleanupRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;

/**
 * Unit tests for {@link HelloWorldClient}.
 * For demonstrating how to write gRPC unit test only.
 * Not intended to provide a high code coverage or to test every major usecase.
 *
 * <p>For more unit test examples see {@link io.grpc.examples.routeguide.RouteGuideClientTest} and
 * {@link io.grpc.examples.routeguide.RouteGuideServerTest}.
 */
@RunWith(JUnit4.class)
public class HelloWorldClientTest {
  /**
   * This rule manages automatic graceful shutdown for the registered servers and channels at the
   * end of test.
   */
  @Rule
  public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();

  private final GreeterGrpc.GreeterImplBase serviceImpl =
      mock(GreeterGrpc.GreeterImplBase.class, delegatesTo(new GreeterGrpc.GreeterImplBase() {}));
  private HelloWorldClient client;

  @Before
  public void setUp() throws Exception {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();

    // Create a server, add service, start, and register for automatic graceful shutdown.
    grpcCleanup.register(InProcessServerBuilder
        .forName(serverName).directExecutor().addService(serviceImpl).build().start());

    // Create a client channel and register for automatic graceful shutdown.
    ManagedChannel channel = grpcCleanup.register(
        InProcessChannelBuilder.forName(serverName).directExecutor().build());

    // Create a HelloWorldClient using the in-process channel;
    client = new HelloWorldClient(channel);
  }

  /**
   * To test the client, call from the client against the fake server, and verify behaviors or state
   * changes from the server side.
   */
  @Test
  public void greet_messageDeliveredToServer() {
    ArgumentCaptor<HelloRequest> requestCaptor = ArgumentCaptor.forClass(HelloRequest.class);

    client.greet("test name");

    verify(serviceImpl)
        .sayHello(requestCaptor.capture(), Matchers.<StreamObserver<HelloReply>>any());
    assertEquals("test name", requestCaptor.getValue().getName());
  }
}


text:
package com.ettrema.httpclient;

/**
 *
 * @author mcevoy
 */
public interface FolderListener {

    void onChildAdded( Folder parent, Resource child );

    void onChildRemoved( Folder parent, Resource child );
}


text:
layout: page
title: "Liên hệ"
meta_title: "Liên hệ"
teaser: "Bạn có thông tin muốn chia sẻ với tôi?"
permalink: "/contact/"
---

Vui lòng gửi email cho tôi tới địa chỉ **quangnd.edu@gmail.com**. Mỗi ý kiến đóng góp của bạn sẽ giúp tôi xây dựng nội dung website để phục vụ bạn tốt hơn.

Follow me trên Twitter [@quangndedu](http://twitter.com/quangndedu)

Hoặc tham gia nhóm học tập [FreeCodeCamp Hà Nội](https://www.facebook.com/groups/free.code.camp.hanoi/) trên Facebook.

Trân trọng cám ơn!

--

My name is Nguyen Dang Quang.

I am Runner, Programmer, Reader and...Learner!

[Give me five minutes ^^..][give-me-five-minutes]

[give-me-five-minutes]: https://signalvnoise.com/posts/3124-give-it-five-minutes