text:
With ``-h `` or ``-help`` you will see all parameters.

# Supported databases

Following databases are supported:

* Mysql
* Posgre
* MongoDB
* CouchDB
* ElasticSearch 1.4
* Excel

## init a MySQL database with bsbm data

Start import data to a MySQL database. It will use sql files, which are generated by bsbm.

``-importToMysql -u root -p password  -urlMysql jdbc:mysql://localhost/benchmark ``

 If you want to use another file, you can use

``-importToMysql -u root -p password  -urlMysql jdbc:mysql://localhost/benchmark -file pathToFolder``

**Important**: The database in the jdbc muss exist. The loader have problems with large SQL files (above 5 MB)

## MongoDB
### parse to MongoDB
This will copy the RDBS tables to MongoDB. If the database not exist, it will be generate a new database.

``-parseToMongo -u root -p password  -urlMysql jdbc:mysql://localhost/benchmark -hostNosql localhost -portNosql 27017 -databaseName bsbm``

If you have this database and collections, you can use this :

``-parseToMongo -u root -p password  -urlMysql jdbc:mysql://localhost/benchmark -hostNosql localhost -portNosql 27017 -databaseName bsbm -d``

The collections will be removed.

### dematerialize n:1

This command dematerialize a simple N:1 relationship. It create a new collection target_mat and copy the new data in this collection.

``-materializeMongo -target offer -source product -fk product -pk nr -hostNosql localhost -portNosql 27017 -databaseName bsbm``

If you want to have only the ObjectID _id, the use :

``-materializeMongo -target offer -source product -fk product -pk nr -hostNosql localhost -portNosql 27017 -databaseName bsbm -objectId``

If exist a target_mat collection, you should run this command.

``-materializeMongo -target offer -source product -fk product -pk nr -hostNosql localhost -portNosql 27017 -databaseName bsbm -d``

This will delete the collection.

### demateriazile n:m

``-materializeMongo -hostNosql localhost -portNosql 27017 -databaseName bsbm -source product -fk productFeature -join productfeatureproduct -secondSource productfeature -pkSecond nr -pk nr -secondFkey product``

If you want to have only the ObjectID _id, the use :

``-materializeMongo -hostNosql localhost -portNosql 27017 -databaseName bsbm -source product -fk productFeature -join productfeatureproduct -secondSource productfeature -pkSecond nr -pk nr -secondFkey product -objectID``

## CouchDB
### parse to CouchDB
``-parseToMongo -u root -p password  -urlMysql jdbc:mysql://localhost/benchmark -hostNosql localhost -portMongo 27017 -databaseName bsbm``

### demateriazile n:1

``-materializeCouch -target offer -source product -fk product -pk nr -hostNosql localhost -portNosql 5986 -databaseName bsbm -userCouch admin  -passwordCouch password``

### demateriazile n:m
``-materializeCouch -hostNosql localhost -portNosql 5986 -databaseName bsbm -source product -fk productFeature -join productfeatureproduct -secondSource productfeature -pkSecond nr -pk nr -secondFkey product -userCouch admin  -passwordCouch password``

### get a row (CouchDB)
To get all ids

``curl -X GET http://username:password@host:port/table/_all_docs``

To get a value

``curl -X GET http://username:password@host:port/table/id``

## Excel
### parse to Excel

The excel file must exist.
``-parseToExcel -u root -p password -urlMysql jdbc:mysql://localhost/benchmark -excelFile  C:\Users\username\Desktop\Test.xlsx``

At the moment, bsbmloader does not support demateriazile an excel file.

## ElasticSearch
### parte to ElasticSearch

``-parseToElastic -u root -p password -urlMysql jdbc:mysql://localhost/benchmark -hostNosql localhost -portNosql 27017 -databaseName bsbm``

### Get 1000 rows
http://127.0.0.1:9200/bla/_search/?size=1000&pretty=1

## Build and execute
### Build

You can build this programm with :
``cd loader``
``mvn package -DskipTests``

You can see the result in the target folger.

## Parse to JDBC

You can parse the databast to MySQL or PostgeSQL

-parseToJdbc -u root -p password -urlMysql  jdbc:mysql://localhost/benchmark -hostNosql localhost -portNosql 9200 -databaseName bsbm -targetUrl  jdbc:postgresql://127.0.0.1:5432/postgres
-user postgres   -password password

## Run

You can run the loader with :
git add pom.xml
``java -jar bsbmloader-jar-with-dependencies.jar -parseToMongo -u root -p password -urlMysql jdbc:mysql://localhost/benchmark -hostNosql localhost -portNosql 27017 -databaseName bsbm``


text:
<wicket:panel>

	    []
	    <input wicket:id="nameField" class="form-control input-xs" name="nameField" type="text" size="40"/>

	    []
	    <input wicket:id="fileNameField" class="form-control input-xs" name="fileNameField" type="text" size="40"/>

</wicket:panel>

redpajama_set_name: RedPajamaGithub


text:
package Native;

/**
 * Package:Native
 * Author:20728
 * Created on 2017/1/30.
 */
public class NativeHelloWorld {
    public native void sayHello();

    static {
        System.loadLibrary("sayHello");
    }

    public static void main(String[] args) {
        new NativeHelloWorld().sayHello();
        String s = new String();
        s.equals("2");
    }
}


text:
import urllib
import zipfile
import os
import numpy as np
import nibabel as nb
import numpy.linalg as npl
import pandas as pd
from pybraincompare.mr.datasets import get_standard_mask

# Downloading microarray data
urls = ["http://human.brain-map.org/api/v2/well_known_file_download/178238387",
        "http://human.brain-map.org/api/v2/well_known_file_download/178238373",
        "http://human.brain-map.org/api/v2/well_known_file_download/178238359",
        "http://human.brain-map.org/api/v2/well_known_file_download/178238316",
        "http://human.brain-map.org/api/v2/well_known_file_download/178238266",
        "http://human.brain-map.org/api/v2/well_known_file_download/178236545"]

donor_ids = [""]
download_dir = "/ahba_data"
os.makedirs(download_dir)

for i, url in enumerate(urls):
    print "Downloading %s" % url
    urllib.urlretrieve(url, os.path.join(download_dir, "donor%d.zip" % (i + 1)))
    zipfile.ZipFile(os.path.join(download_dir, "donor%d.zip" % (i + 1)))

# Dowloading MNI coordinates
urllib.urlretrieve(
    "https://raw.githubusercontent.com/chrisfilo/alleninf/master/alleninf/data/corrected_mni_coordinates.csv",
    os.path.join(download_dir, "corrected_mni_coordinates.csv"))

samples = pd.read_csv(os.path.join(download_dir, "corrected_mni_coordinates.csv"), index_col=0)

mni = get_standard_mask(voxdim=4)

reduced_coord = []

for coord_mni in samples[['corrected_mni_x', 'corrected_mni_y', 'corrected_mni_z']].values:
    sample_counts = np.zeros(mni.shape, dtype=int)
    coord_data = [int(round(i)) for i in nb.affines.apply_affine(npl.inv(mni.get_affine()), coord_mni)]
    sample_counts[coord_data[0],
                  coord_data[1],
                  coord_data[2]] = 1
    out_vector = sample_counts[mni.get_data()!=0]
    idx = out_vector.argmax()
    if idx == (out_vector == 1.0).sum() == 0:
        idx = np.nan
    reduced_coord.append(idx)

samples["reduced_coordinate"] = reduced_coord

#Downloading gene selections list
urllib.urlretrieve(
    "http://science.sciencemag.org/highwire/filestream/631209/field_highwire_adjunct_files/2/Richiardi_Data_File_S2.xlsx",
    os.path.join(download_dir, "Richiardi_Data_File_S2.xlsx"))

donors = ["H0351.2001", "H0351.2002", "H0351.1009", "H0351.1012", "H0351.1015", "H0351.1016"]

with zipfile.ZipFile(os.path.join(download_dir, "donor1.zip")) as z:
    with z.open("Probes.csv") as f:
        probe_info_df = pd.read_csv(f, index_col=0)

# concatenating data from all donors
dfs = []
for i, donor_id in enumerate(donors):
    with zipfile.ZipFile(os.path.join(download_dir, "donor%d.zip" % (i + 1))) as z:
        with z.open("MicroarrayExpression.csv") as f:
            df = pd.read_csv(f, header=None, index_col=0)

        # Dropping probes without entrez_id
        df.drop(probe_info_df.index[probe_info_df['entrez_id'].isnull()], inplace=True)

        with z.open("SampleAnnot.csv") as f:
            sample_annot_df = pd.read_csv(f, index_col="well_id").join(samples, how="inner")

        df.columns = list(sample_annot_df["reduced_coordinate"])
        # removing out side of the brain coordinates
        df.drop(sample_annot_df.index[sample_annot_df.reduced_coordinate.isnull()], axis=1, inplace=True)
        # averaging measurements from similar locations
        df = df.groupby(level=0, axis=1).mean()

        df.columns = pd.MultiIndex.from_tuples([(donor_id, c,) for c in list(df.columns)],
                                               names=['donor_id', 'reduced_coordinate'])
        dfs.append(df)

expression_data = pd.concat(dfs, copy=False, axis=1)
del dfs

probe_info_df.drop(probe_info_df.index[probe_info_df['entrez_id'].isnull()], inplace=True)

multiindex = []
for index in expression_data.index:
    entrez_id = int(probe_info_df.loc[index]["entrez_id"])
    multiindex.append((entrez_id, index,))
expression_data.index = pd.MultiIndex.from_tuples(multiindex, names=['entrez_id', 'probe_id'])

means = expression_data.mean(axis=1)
idx_maxs = means.groupby(level=0).idxmax()
expression_data = expression_data.reindex(idx_maxs)

expression_data.index = expression_data.index.droplevel(1)

multiindex = []
for index in probe_info_df.index:
    entrez_id = int(probe_info_df.loc[index]["entrez_id"])
    multiindex.append((entrez_id, index,))
probe_info_df.index = pd.MultiIndex.from_tuples(multiindex, names=['entrez_id', 'probe_id'])
probe_info_df = probe_info_df.reindex(idx_maxs)
probe_info_df.index = probe_info_df.index.droplevel(1)
probe_info_df.to_csv(os.path.join(download_dir, 'probe_info_max1.csv'))

assert (expression_data.index[0] in list(probe_info_df.index))
assert (expression_data.shape == (20787, 3072))

with pd.HDFStore(os.path.join(download_dir, 'store_max1_reduced.h5'), 'w') as store:
    for donor_id in donors:
        store.append(donor_id.replace(".", "_"), expression_data[donor_id])

# Removing downloaded files
for i, url in enumerate(urls):
    os.remove(os.path.join(download_dir, "donor%d.zip" % (i + 1)))


text:
package com.sabertazimi.tao.analysis;

import java.io.CharArrayReader;
import java.io.Reader;
import java.io.IOException;
import java.util.List;
import java.util.LinkedList;
import java.util.HashMap;

import static com.sabertazimi.tao.analysis.Token.Type;

public class LexicalAnalysis {
    private final Reader reader;
    private Token endToken = null;

    private enum State {
        Normal,
        Identifier,
        Sign,
        Annotation,
        String,
        RegEx,
        Space;
    }

    public LexicalAnalysis(Reader reader) {
        this.reader = reader;
        this.state = State.Normal;
    }

    /*
     * Parser 不断调用 read() 获取 Token 对象, 直到 EndSymbol/异常 为止
     */
    Token read() throws IOException, LexicalAnalysisException {
        if (endToken != null) {
            return endToken;
        }

        while (tokenBuffer.isEmpty()) {
            int read = reader.read();
            char c = (read == -1 ? '\0' : (char) read);

            while (!readChar(c)) {
                ;
            }
        }

        Token token = tokenBuffer.removeLast();

        if (token.type == Type.EndSymbol) {
            endToken = token;
        }

        return token;
    }

    private State state;
    private final LinkedList<Token> tokenBuffer = new LinkedList<>();
    private StringBuilder readBuffer = null;
    private static final char[] FilterChar = new char[]{'\b', '\f', '\r'};
    private static final char[] Space = new char[]{' ', '\t'};
    private static final char[] IdentifierRearSign = new char[]{'?', '!'};
    private static final HashMap<Character, Character> StringTMMap = new HashMap<>();
    private boolean transferredMeaningSign;

    static {
        StringTMMap.put('\"', '\"');
        StringTMMap.put('\'', '\'');
        StringTMMap.put('\\', '\\');
        StringTMMap.put('b', '\b');
        StringTMMap.put('f', '\f');
        StringTMMap.put('t', '\t');
        StringTMMap.put('r', '\r');
        StringTMMap.put('n', '\n');
    }

    private boolean inIdentifierSetButNotRear(char c) {
        return (c >= 'a' && c <= 'z')
                | (c >= 'A' && c <= 'Z')
                | (c >= '0' && c <= '9')
                | (c == '_');
    }

    private boolean include(char[] range, char c) {
        boolean include = false;

        for (int i = 0; i < range.length; ++i) {
            if (range[i] == c) {
                include = true;
                break;
            }
        }

        return include;
    }

    private void refreshBuffer(char c) {
        readBuffer = new StringBuilder();
        readBuffer.append(c);
    }

    private void createToken(Type type) {
        Token token = new Token(type, readBuffer.toString());
        tokenBuffer.addFirst(token);
        readBuffer = null;
    }

    private void createToken(Type type, String value) {
        Token token = new Token(type, value);
        tokenBuffer.addFirst(token);
        readBuffer = null;
    }

    /*
     * readBuffer.append(c) 不断缓存读入字符
     * 在合适时机(由状态机决定)调用 createToken() 生成 Token 并返回给 Parser 使用
     */
    private boolean readChar(char c) throws LexicalAnalysisException {
        // Finite State Machine
        boolean moveCursor = true;
        Type createType = null;

        if (!include(FilterChar, c)) {

            if (state == State.Normal) {
                if (inIdentifierSetButNotRear(c)) {
                    state = State.Identifier;
                } else if (SignParser.inCharSet(c)) {
                    state = State.Sign;
                } else if (c == '#') {
                    state = State.Annotation;
                } else if (c == '\"' | c == '\'') {
                    state = State.String;
                    transferredMeaningSign = false;
                } else if (c == '`') {
                    state = State.RegEx;
                    transferredMeaningSign = false;
                } else if (include(Space, c)) {
                    state = State.Space;
                } else if (c == '\n') {
                    createType = Type.NewLine;
                } else if (c == '\0') {
                    createType = Type.EndSymbol;
                } else {
                    throw new LexicalAnalysisException(c);
                }

                refreshBuffer(c);
            } else if (state == State.Identifier) {
                if (inIdentifierSetButNotRear(c)) {
                    readBuffer.append(c);
                } else if (include(IdentifierRearSign, c)) {
                    createType = Type.Identifier;
                    readBuffer.append(c);
                    state = State.Normal;
                } else {
                    createType = Type.Identifier;
                    state = State.Normal;
                    moveCursor = false;
                }
            } else if (state == State.Sign) {
                if (SignParser.inCharSet(c)) {
                    readBuffer.append(c);
                } else {
                    List<String> list = SignParser.parse(readBuffer.toString());

                    for (String signStr : list) {
                        createToken(Type.Sign, signStr);
                    }

                    // tokens have been created in above foreach loop
                    createType = null;
                    state = State.Normal;
                    moveCursor = false;
                }
            } else if (state == State.Annotation) {
                if (c != '\n' && c != '\0') {
                    readBuffer.append(c);
                } else {
                    createType = Type.Annotation;
                    state = State.Normal;
                    moveCursor = false;
                }
            } else if (state == State.String) {
                if (c == '\n') {
                    throw new LexicalAnalysisException(c);
                } else if (c == '\0') {
                    throw new LexicalAnalysisException(c);
                } else if (transferredMeaningSign) {
                    Character tms = (Character) StringTMMap.get(c);

                    if (tms == null) {
                        throw new LexicalAnalysisException(c);
                    }

                    readBuffer.append(tms);
                    transferredMeaningSign = false;
                } else if (c == '\\') {
                    transferredMeaningSign = true;
                } else {
                    readBuffer.append(c);
                    char firstChar = readBuffer.charAt(0);

                    // seperator matching
                    if (firstChar == c) {
                        createType = Type.String;
                        state = State.Normal;
                    }
                }
            } else if (state == State.RegEx) {
                if (transferredMeaningSign) {
                    if (c != '`') {
                        throw new LexicalAnalysisException(c);
                    }

                    readBuffer.append(c);
                } else if (c == '\\') {
                    transferredMeaningSign = true;
                } else if (c == '\0') {
                    throw new LexicalAnalysisException(c);
                } else if (c == '`') {
                    readBuffer.append(c);
                    createType = Type.RegEx;
                    state = State.Normal;
                } else {
                    readBuffer.append(c);
                }
            } else if (state == State.Space) {
                if (include(Space, c)) {
                    readBuffer.append(c);
                } else {
                    createType = Type.Space;
                    state = State.Normal;
                    moveCursor = false;
                }
            }

        }

        if (createType != null) {
            createToken(createType);
        }

        return moveCursor;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Valsa trichospora Cooke & Peck

### Remarks
null


text:
"""Train and evaluate a melody RNN model."""

import os
import time

# internal imports
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('run_dir', '/tmp/melody_rnn/logdir/run1',
                           'Path to the directory where checkpoints and '
                           'summary events will be saved during training and '
                           'evaluation. Separate subdirectories for training '
                           'events and eval events will be created within '
                           '`run_dir`. Multiple runs can be stored within the '
                           'parent directory of `run_dir`. Point TensorBoard '
                           'to the parent directory of `run_dir` to see all '
                           'your runs.')
tf.app.flags.DEFINE_string('sequence_example_file', '',
                           'Path to TFRecord file containing '
                           'tf.SequenceExample records for training or '
                           'evaluation.')
tf.app.flags.DEFINE_string('hparams', '{}',
                           'String representation of a Python dictionary '
                           'containing hyperparameter to value mapping. This '
                           'mapping is merged with the default '
                           'hyperparameters.')
tf.app.flags.DEFINE_integer('num_training_steps', 0,
                            'The the number of global training steps your '
                            'model should take before exiting training. '
                            'During evaluation, the eval loop will run until '
                            'the `global_step` Variable of the model being '
                            'evaluated has reached `num_training_steps`. '
                            'Leave as 0 to run until terminated manually.')
tf.app.flags.DEFINE_integer('summary_frequency', 10,
                            'A summary statement will be logged every '
                            '`summary_frequency` steps during training or '
                            'every `summary_frequency` seconds during '
                            'evaluation.')
tf.app.flags.DEFINE_boolean('eval', False,
                            'If True, this process only evaluates the model '
                            'and does not update weights.')
tf.app.flags.DEFINE_string('log', 'INFO',
                           'The threshold for what messages will be logged '
                           'DEBUG, INFO, WARN, ERROR, or FATAL.')

def run_training(graph, train_dir, num_training_steps=None,
                 summary_frequency=10):
  """Runs the training loop.

  Args:
    graph: A tf.Graph object containing the model.
    train_dir: The path to the directory where checkpoints and summary events
        will be written to.
    num_training_steps: The number of steps to train for before exiting.
    summary_frequency: The number of steps between each summary. A summary is
        when graph values from the last step are logged to the console.
  """
  global_step = graph.get_collection('global_step')[0]
  learning_rate = graph.get_collection('learning_rate')[0]
  loss = graph.get_collection('loss')[0]
  perplexity = graph.get_collection('perplexity')[0]
  accuracy = graph.get_collection('accuracy')[0]
  train_op = graph.get_collection('train_op')[0]

  sv = tf.train.Supervisor(graph=graph, logdir=train_dir, save_model_secs=30,
                           global_step=global_step)

  with sv.managed_session() as sess:
    global_step_ = sess.run(global_step)
    if num_training_steps and global_step_ >= num_training_steps:
      tf.logging.info('This checkpoint\'s global_step value is already %d, '
                      'which is greater or equal to the specified '
                      'num_training_steps value of %d. Exiting training.',
                      global_step_, num_training_steps)
      return
    tf.logging.info('Starting training loop...')
    while not num_training_steps or global_step_ < num_training_steps:
      if sv.should_stop():
        break
      if (global_step_ + 1) % summary_frequency == 0:
        (global_step_, learning_rate_, loss_, perplexity_, accuracy_, _
        ) = sess.run([global_step, learning_rate, loss, perplexity, accuracy,
                      train_op])
        tf.logging.info('Global Step: %d - '
                        'Learning Rate: %.5f - '
                        'Loss: %.3f - '
                        'Perplexity: %.3f - '
                        'Accuracy: %.3f',
                        global_step_, learning_rate_, loss_, perplexity_,
                        accuracy_)
      else:
        global_step_, _ = sess.run([global_step, train_op])
    sv.saver.save(sess, sv.save_path, global_step=sv.global_step)
    tf.logging.info('Training complete.')

def run_eval(graph, train_dir, eval_dir, num_training_steps=None,
             summary_frequency=10):
  """Runs the training loop.

  Args:
    graph: A tf.Graph object containing the model.
    train_dir: The path to the directory where checkpoints will be loaded
        from for evaluation.
    eval_dir: The path to the directory where the evaluation summary events
        will be written to.
    num_training_steps: When the `global_step` from latest checkpoint loaded
        from for `train_dir` has reached `num_training_steps`, the evaluation
        loop will be stopped.
    summary_frequency: The number of seconds between each summary. A summary is
        when evaluation data is logged to the console and evaluation
        summary events are written to `eval_dir`.
  """
  global_step = graph.get_collection('global_step')[0]
  loss = graph.get_collection('loss')[0]
  perplexity = graph.get_collection('perplexity')[0]
  accuracy = graph.get_collection('accuracy')[0]
  summary_op = graph.get_collection('summary_op')[0]

  with graph.as_default():
    saver = tf.train.Saver()
    with tf.Session() as sess:
      summary_writer = tf.train.SummaryWriter(eval_dir, sess.graph)
      coord = tf.train.Coordinator()
      threads = tf.train.start_queue_runners(sess=sess, coord=coord)
      global_step_ = 0
      last_global_step = None
      tf.logging.info('Starting eval loop...')
      try:
        while not num_training_steps or global_step_ < num_training_steps:
          checkpoint_path = tf.train.latest_checkpoint(train_dir)
          if not checkpoint_path:
            tf.logging.info('Waiting for checkpoint file in directory %s.',
                            train_dir)
          else:
            saver.restore(sess, checkpoint_path)

            global_step_, loss_, perplexity_, accuracy_, summary_op_ = sess.run(
                [global_step, loss, perplexity, accuracy, summary_op])

            tf.logging.info('Global Step: %d - '
                            'Loss: %.3f - '
                            'Perplexity: %.3f - '
                            'Accuracy: %.3f',
                            global_step_, loss_, perplexity_, accuracy_)

            if global_step_ != last_global_step:
              summary_writer.add_summary(summary_op_, global_step=global_step_)
              summary_writer.flush()
              last_global_step = global_step_

          time.sleep(summary_frequency)

      except tf.errors.OutOfRangeError as e:
        tf.logging.warn('Got error reported to coordinator: %s', e)
      finally:
        coord.request_stop()
        summary_writer.close()

      coord.join(threads)

def run(melody_encoder_decoder, build_graph):
  """Runs the training or evaluation loop.

  Args:
    melody_encoder_decoder: A melodies_lib.MelodyEncoderDecoder object specific
        to your model.
    build_graph: A function that when called, returns the tf.Graph object for
        your model. The function will be passed the parameters:
        (mode, hparams_string, input_size, num_classes, sequence_example_file).
        For an example usage, see models/basic_rnn/basic_rnn_graph.py.
  """
  tf.logging.set_verbosity(FLAGS.log)

  if not FLAGS.run_dir:
    tf.logging.fatal('--run_dir required')
    return
  if not FLAGS.sequence_example_file:
    tf.logging.fatal('--sequence_example_file required')
    return

  FLAGS.sequence_example_file = os.path.expanduser(FLAGS.sequence_example_file)
  FLAGS.run_dir = os.path.expanduser(FLAGS.run_dir)

  mode = 'eval' if FLAGS.eval else 'train'
  graph = build_graph(mode,
                      FLAGS.hparams,
                      melody_encoder_decoder,
                      FLAGS.sequence_example_file)

  train_dir = os.path.join(FLAGS.run_dir, 'train')
  if not os.path.exists(train_dir):
    tf.gfile.MakeDirs(train_dir)
  tf.logging.info('Train dir: %s', train_dir)

  if FLAGS.eval:
    eval_dir = os.path.join(FLAGS.run_dir, 'eval')
    if not os.path.exists(eval_dir):
      tf.gfile.MakeDirs(eval_dir)
    tf.logging.info('Eval dir: %s', eval_dir)
    run_eval(graph, train_dir, eval_dir, FLAGS.num_training_steps,
             FLAGS.summary_frequency)

  else:
    run_training(graph, train_dir, FLAGS.num_training_steps,
                 FLAGS.summary_frequency)


text:
package quark_ffi_signatures_md;

public class classes_test_split_that_Method extends quark.reflect.Method implements io.datawire.quark.runtime.QObject {
    public classes_test_split_that_Method() {
        super("classes.test_split", "that", new java.util.ArrayList(java.util.Arrays.asList(new Object[]{"quark.String"})));
    }
    public Object invoke(Object object, java.util.ArrayList<Object> args) {
        classes.test_split obj = (classes.test_split) (object);
        return (obj).that((String) ((args).get(0)));
    }
    public String _getClass() {
        return (String) (null);
    }
    public Object _getField(String name) {
        return null;
    }
    public void _setField(String name, Object value) {}
}


text:
module Encosion

  class Playlist

    attr_reader :id, :name, :short_description, :reference_id, :videos

    def initialize(obj)
      @id = obj['id']
      @name = obj['name']
      @short_description = obj['shortDescription']
      @videos = obj['videos'].collect { |video| Video.new(video) }
    end

    def to_json
      { :id => @id,
        :name => @name,
        :short_description => @short_description,
        :reference_id => @reference_id,
        :videos => @videos }.to_json
    end

  end

end


text:
TODO: Write description here

## Installation

Add this line to your application's Gemfile:

    gem 'rails_sub_sessions'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install rails_sub_sessions

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
require 'spec_helper'

describe Adhearsion::Event::Ringing do
  it 'registers itself' do
    expect(Adhearsion::Rayo::RayoNode.class_from_registration(:ringing, 'urn:xmpp:rayo:1')).to eq(described_class)
  end

  describe "from a stanza" do
    let :stanza do
      <<-MESSAGE
<ringing xmlns='urn:xmpp:rayo:1'>
  <!-- Signaling (e.g. SIP) Headers -->
  <header name="X-skill" value="agent" />
  <header name="X-customer-id" value="8877" />
</ringing>
      MESSAGE
    end

    subject { Adhearsion::Rayo::RayoNode.from_xml parse_stanza(stanza).root, '9f00061', '1' }

    it { is_expected.to be_instance_of described_class }

    it_should_behave_like 'event'

    describe '#headers' do
      subject { super().headers }
      it { is_expected.to eq({ 'X-skill' => 'agent', 'X-customer-id' => '8877' }) }
    end

    context "with no headers provided" do
      let(:stanza) { '<ringing xmlns="urn:xmpp:rayo:1"/>' }

      describe '#headers' do
        subject { super().headers }
        it { is_expected.to eq({}) }
      end
    end
  end

  describe "when setting options in initializer" do
    subject { described_class.new headers: { 'X-skill' => 'agent', 'X-customer-id' => '8877' } }

    describe '#headers' do
      subject { super().headers }
      it { is_expected.to eq({ 'X-skill' => 'agent', 'X-customer-id' => '8877' }) }
    end
  end
end


text:
@interface SettingsTableViewController : UITableViewController

@end


text:
__author__ = 'Irwan Fathurrahman <irwan@kartoza.com>'
__date__ = '17/05/17'
import json
from campaign_manager.insights_functions._abstract_overpass_insight_function \
    import AbstractOverpassInsightFunction

class FeatureAttributeCompleteness(AbstractOverpassInsightFunction):
    function_name = "Feature completeness"
    tags_capitalizaition_checks = ['name']
    icon = 'list'
    _function_good_data = None  # cleaned data
    nodes = {}

    # attribute of insight function
    need_feature = True
    need_required_attributes = True

    def get_ui_html_file(self):
        """ Get ui name in templates
        :return: string name of html
        :rtype: str
        """
        return "feature_completeness"

    def get_summary_html_file(self):
        """ Get summary name in templates
        :return: string name of html
        :rtype: str
        """
        return ""

    def get_details_html_file(self):
        """ Get summary name in templates
        :return: string name of html
        :rtype: str
        """
        return ""

    def process_data(self, raw_data):
        """ Get geometry of campaign.
        :param raw_data: Raw data that returns by function provider
        :type raw_data: dict

        :return: list good data
        :rtype: dict
        """
        list_good_data = []
        self._function_good_data = []

        if not raw_data or not self.feature_type:
            return []
        try:
            required_attributes = self.get_required_attributes()
            for value in raw_data:

                if 'tags' not in value:
                    continue

                feature_key = self.feature.split('=')[0]
                feature_key_found_in_tags = False

                for key, tag in value['tags'].items():
                    if key == feature_key:
                        feature_key_found_in_tags = True

                if not feature_key_found_in_tags:
                    continue

                self._function_good_data.append(value)
                self.check_feature_completeness(
                    value, required_attributes)

                if value['error'] == 'False':
                    list_good_data.append(value)
        except KeyError:
            pass

        return list_good_data

    def check_capitalization(self, key, value):
        # Check all uppercase or lowercase
        if value.isupper():
            return '%s value is all uppercase' % key
        elif value.islower():
            return '%s value is all lowercase' % key

        # Check mixed case
        for index, name in enumerate(value.split()):
            if name[0].islower() and not self.is_string_int(name[0]):
                # e.g : name of Feature
                return '%s value is mixed case' % key

        return None

    def check_feature_completeness(
            self, feature_data, required_attributes):
        """Check feature completeness.

        :param feature_data: Feature data
        :type feature_data: dict

        :param required_attributes: Required attributes
        :type required_attributes: dict
        """
        warning_message = []
        error_message = []

        tags = feature_data['tags']

        if isinstance(required_attributes, str):
            return

        for required_attribute, survey_values in required_attributes.items():
            if required_attribute not in tags:
                error_message.append(
                    '%s not found' % required_attribute)
            else:
                value_in_tag = tags[required_attribute]
                if survey_values:
                    if value_in_tag not in survey_values:
                        error_message.append(
                            '%s is not allowed as value %s' %
                            (value_in_tag, required_attribute))
                if required_attribute in self.tags_capitalizaition_checks:
                    warning = self.check_capitalization(
                        required_attribute, value_in_tag)
                    if warning:
                        warning_message.append(warning)

        feature_data['error'] = 'False'
        feature_data['warning'] = 'False'

        if warning_message or error_message:
            feature_data['error'] = 'True'

        if not error_message and warning_message:
            feature_data['warning'] = 'True'

        feature_data['error_message'] = ', '.join(error_message)
        feature_data['warning_message'] = ', '.join(warning_message)
        feature_data['completeness'] = \
            (len(error_message) / len(required_attribute)) * 100

    def is_string_int(self, text):
        """Check whether the text is int or not."""
        try:
            int(text)
        except ValueError:
            return False

        return True

    def post_process_data(self, data):
        """Process data regarding output.
        This needed for processing data for counting or grouping.

        :param data: Data that received from open street map
        :type data: dict

        :return: Processed data
        :rtype: dict
        """
        percentage = '0.0'
        if len(self._function_good_data) > 0:
            percentage = '%.1f' % (
                (len(data) / len(self._function_good_data)) * 100
            )

        output = {
            'attributes': self.get_required_attributes(),
            'data': self._function_good_data,
            'percentage': percentage,
            'complete': len(data),
            'total': len(self._function_good_data),
            'last_update': self.last_update,
            'updating': self.is_updating,
            'raw_data': self.get_function_raw_data()
        }
        return output


text:
// The MIT License (MIT)
// Copyright © 2015 AppsLandia. All rights reserved.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.appslandia.plum.base;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appslandia.common.base.JsonProcessor;
import com.appslandia.common.utils.AssertUtils;
import com.appslandia.common.utils.ExceptionUtils;
import com.appslandia.common.utils.TypeUtils;

/**
 *
 * @author Loc Ha
 *
 */
public abstract class RequestExecutor extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public abstract RemoteClientFilter getRemoteClientFilter();

	public abstract CorsPolicyHandler getCorsPolicyHandler();

	public abstract ControllerProvider getControllerProvider();

	public abstract ActionInvoker getActionInvoker();

	public abstract JsonProcessor getJsonProcessor();

	protected void doRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// ActionContext
			ActionContext actionContext = (ActionContext) request.getAttribute(ServletUtils.REQUEST_ATTRIBUTE_ACTION_CONTEXT);
			AssertUtils.assertNotNull(actionContext, "actionContext is required.");

			// Filter client
			if (getRemoteClientFilter().filter(request) == false) {
				throw new HttpException(HttpServletResponse.SC_FORBIDDEN, actionContext.getMessage(ServletUtils.ERROR_MSGKEY_FORBIDDEN, request.getRequestURI()));
			}

			// TRACE
			if (request.getMethod().equals(HttpMethod.TRACE)) {
				throw new HttpException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, actionContext.getMessage(ServletUtils.ERROR_MSGKEY_METHOD_NOT_ALLOWED));
			}

			// OPTIONS
			if (request.getMethod().equals(HttpMethod.OPTIONS)) {
				doOptions(request, response, actionContext);
				return;
			}

			// Allow Method?
			if (actionContext.getActionDesc().allowActionVerb(request.getMethod()) == false) {
				throw new HttpException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, actionContext.getMessage(ServletUtils.ERROR_MSGKEY_METHOD_NOT_ALLOWED));
			}

			// AJAX?
			if (actionContext.getActionDesc().getAjax() != null) {
				if (ServletUtils.isAjaxRequest(request) == false) {
					throw new HttpException(HttpServletResponse.SC_FORBIDDEN, actionContext.getMessage(ServletUtils.ERROR_MSGKEY_FORBIDDEN, request.getRequestURI()));
				}
			}

			// HTTPS
			if (request.isSecure() == false) {
				if (actionContext.getActionDesc().isEnableHttps()) {
					askHttps(request, response, actionContext);
					return;
				}
			}

			// Authorize
			if (actionContext.getActionDesc().getAuthorize() != null) {
				if (actionContext.getUserData() == null) {
					askLogin(request, response, actionContext);
					return;
				}
				if (actionContext.getActionDesc().getAuthorize().reLogin()) {
					if (isReLogin(request, response, actionContext) == false) {
						return;
					}
				}
				if (actionContext.getActionDesc().getAuthorize().userRoles().length != 0) {
					if (isUserInRole(request, actionContext.getActionDesc().getAuthorize().userRoles()) == false) {
						throw new ForbiddenException(actionContext.getMessage(ServletUtils.ERROR_MSGKEY_FORBIDDEN, request.getRequestURI()));
					}
				}
			}

			// controller
			Object controller = getControllerProvider().getController(actionContext.getControllerDesc().getControllerClass(), actionContext.getControllerDesc().getQualifiers());

			// onActionExecuting
			onActionExecuting(request, response, actionContext);

			// Invoke Action
			Object result = getActionInvoker().invoke(request, response, actionContext, controller);

			// AsyncStarted?
			if (request.isAsyncStarted()) {
				AssertUtils.assertNotNull(actionContext.getActionDesc().getAsync(), "@Async is required.");
			}

			// onResultExecuting
			onResultExecuting(request, response, actionContext);

			// Execute Result
			if (result instanceof ActionResult) {
				((ActionResult) result).execute(request, response, actionContext);

			} else if (result != null) {
				writeNonActionResult(response, result);
			}

			// onResultExecuted
			onResultExecuted(request, response, actionContext);

		} catch (RuntimeException ex) {
			throw ex;
		} catch (ServletException | IOException ex) {
			throw ex;
		} catch (Exception ex) {
			throw new ServletException(ExceptionUtils.getMessage(ex), ex);
		}
	}

	protected boolean isUserInRole(HttpServletRequest request, String[] userRoles) {
		for (String role : userRoles) {
			if (request.isUserInRole(role)) {
				return true;
			}
		}
		return false;
	}

	protected void writeNonActionResult(HttpServletResponse response, Object result) throws Exception {
		if (writeToString(result.getClass())) {
			response.setContentType(ActionResult.TYPE_TEXT_PLAIN);
			response.getWriter().write(String.valueOf(result));
		} else {
			response.setContentType(ActionResult.TYPE_APPLICATION_JSON);
			response.setCharacterEncoding(StandardCharsets.UTF_8.name());
			getJsonProcessor().write(response.getWriter(), result);
		}
	}

	private static boolean writeToString(Class<?> resultType) {
		if (resultType.isPrimitive()) {
			return true;
		}
		if (TypeUtils.isWrapperType(resultType)) {
			return true;
		}
		if ((resultType == BigInteger.class) || (resultType == BigDecimal.class)) {
			return true;
		}
		if ((resultType == String.class) || (resultType.isEnum())) {
			return true;
		}
		if ((resultType == Calendar.class) || (java.util.Date.class.isAssignableFrom(resultType))) {
			return true;
		}
		if (java.time.temporal.Temporal.class.isAssignableFrom(resultType)) {
			return true;
		}
		if ((resultType == URL.class)) {
			return true;
		}
		return false;
	}

	protected void doOptions(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception {
		if (actionContext.getActionDesc().getCorsPolicy() != null) {
			getCorsPolicyHandler().handle(request, response, actionContext);
		} else {
			throw new HttpException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, actionContext.getMessage(ServletUtils.ERROR_MSGKEY_METHOD_NOT_ALLOWED));
		}
	}

	protected abstract void askHttps(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception;

	protected abstract void askLogin(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception;

	protected abstract boolean isReLogin(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception;

	protected void onActionExecuting(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception {
	}

	protected void onResultExecuting(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception {
	}

	protected void onResultExecuted(HttpServletRequest request, HttpServletResponse response, ActionContext actionContext) throws Exception {
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	@Override
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	@Override
	protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	@Override
	protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	@Override
	protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}
}


text:
'use strict';

const DocWriteUseAudit = require('../../../audits/dobetterweb/no-document-write.js');
const assert = require('assert');

const URL = 'https://example.com';

/* eslint-env jest */

describe('Page does not use document.write()', () => {
  it('passes when document.write() is not used', () => {
    const auditResult = DocWriteUseAudit.audit({
      ConsoleMessages: [],
      URL: {finalUrl: URL},
    });
    assert.equal(auditResult.score, 1);
    assert.equal(auditResult.details.items.length, 0);
  });

  it('fails when document.write() is used', () => {
    const text = 'Do not use document.write';
    const auditResult = DocWriteUseAudit.audit({
      URL: {finalUrl: URL},
      ConsoleMessages: [
        {entry: {source: 'violation', url: 'https://example.com/', text}},
        {entry: {source: 'violation', url: 'https://example2.com/two', text}},
        {entry: {source: 'violation', url: 'http://abc.com/', text: 'Long event handler!'}},
        {entry: {source: 'deprecation', url: 'https://example.com/two'}},
      ],
    });
    assert.equal(auditResult.score, 0);
    assert.equal(auditResult.details.items.length, 2);
  });
});


text:
<?php

namespace Deblan\PowerDNS\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Propel\Runtime\ActiveQuery\Criteria;
use Deblan\PowerDNS\Model\RecordQuery;
use Deblan\PowerDNS\Model\DomainQuery;
use Deblan\PowerDNS\Model\Record;

class ZonePushCommand extends AbstractZoneCommand
{
    protected function configure()
    {
        parent::configure();

        $this
            ->setName('zone:push')
            ->setDescription('Push activated zones to PowerDNS tables')
            ->setHelp("<info>%command.name%</info>

After editing zone versions, you have to push all modifications by using <info>%command.name%</info>.

The PDNS records will be replaced with your activated zones versions.");
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        parent::execute($input, $output);

        $domains = DomainQuery::create()->filterByZoneId(null, Criteria::NOT_EQUAL)->find();

        foreach ($domains as $domain) {
            RecordQuery::create()->filterByDomain($domain)->find()->delete();
            $zoneVersion = $domain->getZone()->getActiveZoneVersion();

            if ($zoneVersion === null) {
                continue;
            }

            foreach ($zoneVersion->getZoneRecords() as $zoneRecord) {
                $record = new Record();
                $record->hydrateFromZoneRecord($zoneRecord, $domain);
                $record->save();
            }
        }
    }
}


text:
@interface RACOperatorTableViewController : UITableViewController

@end


text:
#pragma strict

var inputMoveDirection:Vector3;
var inputJump=false;
var grounded=false;
var downmovement=0.1;
var velocity:Vector3;
public var max_speed=0.1;
public var max_speed_air=0.13;
public var max_speed_ground=0.1;
public var acceleration=10;
public var acceleration_air=10;
public var gravity=-0.18;
public var friction=0.8;
public var cameraObject:GameObject;
private var controller : CharacterController;
public var groundNormal:Vector3;
public var jumpspeed=0.16;
public var stopmovingup=false;
public var fallkillspeed=-0.38;
public var collisionFlags : CollisionFlags;

public var ground_gameobject:GameObject=null;
public var last_ground_pos:Vector3;
private var jumpcommand=0;
public var floating=false;

public var autowalk:int=0;
public var inhibit_autowalk=1;
public var reload_once:int=0;

public var enableGroundCollision = true; //want this on except for the character controller demo test for VR

function Awake () {
    controller = GetComponent (CharacterController);
    //Debug.Log("Controller Slopelimit"+controller.slopeLimit);
}

function toggle_autowalk(){

    if (autowalk==0)autowalk=1;
    else autowalk=0;

}

function JumpUp(){

    jumpcommand=1;

}

function Start () {

    reload_once=0;

}

function OnControllerColliderHit (hit : ControllerColliderHit) {

    if (hit.normal.y > 0 && hit.moveDirection.y < 0) {

        groundNormal = hit.normal;
        grounded=true;
        ground_gameobject=hit.gameObject;

        //print("Landed on: ground"+ground_gameobject.name);
        stopmovingup=false;

    }

}

    var fadeduration = 2.0; // fade duration in seconds

    function Die(){
        // create a GUITexture:
        var fade: GameObject = new GameObject();
        fade.AddComponent(GUITexture);
        // and set it to the screen dimensions:
        fade.guiTexture.pixelInset = Rect(0, 0, Screen.width, Screen.height);
        // set its texture to a black pixel:
        var tex = new Texture2D(1, 1);
        tex.SetPixel(0, 0, Color.black);
        tex.Apply();
        fade.guiTexture.texture = tex;
        // then fade it during duration seconds
        for (var alpha:float = 0.0; alpha < 1.0; ){
          alpha += Time.deltaTime / fadeduration;
          fade.guiTexture.color.a = alpha;
          yield;
        }
    // finally, reload the current level:
    if (reload_once==0){
        reload_once =1;
        //var async : AsyncOperation = Application.LoadLevelAsync(Application.loadedLevel);
        //yield async;

        Application.LoadLevelAsync(Application.loadedLevel);

    }

}

function Update () {

    if (velocity.y < fallkillspeed)Die();

    Debug.DrawLine (transform.position, transform.position+groundNormal, Color.red);
    //print("GroundNormal y" +groundNormal.y);

    var directionVector = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
    if (autowalk==1)directionVector=Vector3(0,0,1*inhibit_autowalk);
    if (directionVector != Vector3.zero) {
        // Get the length of the directon vector and then normalize it
        // Dividing by the length is cheaper than normalizing when we already have the length anyway
        var directionLength = directionVector.magnitude;
        directionVector = directionVector / directionLength;

        // Make sure the length is no bigger than 1
        directionLength = Mathf.Min(1, directionLength);

        // Make the input vector more sensitive towards the extremes and less sensitive in the middle
        // This makes it easier to control slow speeds when using analog sticks
        directionLength = directionLength * directionLength;

        // Multiply the normalized direction vector by the modified length
        directionVector = directionVector * directionLength;
    }
    // Apply the direction to the CharacterMotor
    inputMoveDirection =  directionVector;
    inputJump = Input.GetButton("Jump");

    if(jumpcommand==1){
        inputJump=true;
        jumpcommand=0;
    }

    if(enableGroundCollision) grounded=(collisionFlags & CollisionFlags.Below); //THIS SHIT WAS FUCKING UP THE COLLISION WITH THE GROUND SHIT YO

    if (floating){
        velocity.y=0.1;
    }
    if (inputJump&&grounded){
        velocity.y+=jumpspeed;
        velocity.z*=1.5;

        //print ("Jump");
        grounded=false;
    }

    if (grounded){
        velocity+=inputMoveDirection*acceleration*Time.deltaTime;
    }
    else
    {
        velocity+=inputMoveDirection*acceleration_air*Time.deltaTime;
    }

    var translation=Vector3(velocity.x,0,velocity.z);

    translation=Vector3.Lerp(Vector3(0,0,0),translation,friction);

    velocity.x=translation.x;
    velocity.z=translation.z;
    velocity.y = velocity.y+gravity*Time.deltaTime;
    //print ("Time deltatime "+Time.deltaTime);

    if (grounded)velocity.y=0;
    //print ("Vel y "+velocity.y);

    if (grounded)max_speed=max_speed_ground;
    if (!grounded)max_speed=max_speed_air;

    if (translation.magnitude>max_speed){
        translation=translation/translation.magnitude;
        translation=translation*max_speed;
    }
    velocity.x=translation.x;
    velocity.z=translation.z;
    translation.y=velocity.y;

    var yrotation_camera= Quaternion.Euler(0, cameraObject.transform.rotation.eulerAngles.y, 0);
    //transform.position+=yrotation_camera*translation;

    var platformdelta:Vector3;

    if(ground_gameobject!=null) {
        //print("ground object ungleich null");
        platformdelta=ground_gameobject.transform.position-last_ground_pos;
    }

    if (!grounded)platformdelta=Vector3.zero;

    //MAKE A MOVE!
    collisionFlags=controller.Move(yrotation_camera*translation+platformdelta);

    if (collisionFlags & CollisionFlags.CollidedAbove)
    {

        if (stopmovingup==false){
            //print ("ControllerColliderHit");
            velocity.y=0;
            stopmovingup=true;
        }

    }

    if (ground_gameobject!=null && !grounded){
        ground_gameobject=null;
    }

    if(ground_gameobject!=null)last_ground_pos=ground_gameobject.transform.position;

}

function LateUpdate () {
    //groundNormal=Vector3.zero;
}

function OnGUI () {
    //	GUI.Label (Rect (10, 10, 400, 20), "isgrounded "+grounded+   " velocity.y "+velocity.y+" collsionbelow "+ (collisionFlags & CollisionFlags.Below) );

    var e : Event = Event.current;
    if (e.isKey) {
        //Debug.Log("Detected key code: " + e.keyCode);
        GUI.Label (Rect (10, 10, 400, 20), "Keycode ="+ e.keyCode );

    }

}

function OnTriggerEnter( other : Collider ) {

    if (other.name == "Float") {

        floating=true;
        inhibit_autowalk=0.1;

    }

}

    function OnTriggerExit( other : Collider ) {

        if (other.name == "Float") {

            floating=false;
            inhibit_autowalk=1;

        }

    }

        function ActivateAutoWalk(){
            autowalk = 1;
        }

        function DeactivateAutoWalk(){
            autowalk = 0;
        }

        function jumpAndSpin()
        {
            grounded=true;
            JumpUp();
        }

        function enableC(){
            enableGroundCollision = true;
        }

        function disableC(){
            enableGroundCollision = false;
        }

    @script RequireComponent (CharacterController)


text:
@extends('layouts.auth')
@section('title','Login')
@section('content')

HEBASHOP

Sign in

           <form role="form" method="POST" action="{{ url('/login') }}">
                        {{ csrf_field() }}

has('email') ? ' has-error' : '' }}  has-feedback">
                                <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email">

        @if ($errors->has('email'))

                                        {{ $errors->first('email') }}

                                @endif

has('password') ? ' has-error' : '' }} has-feedback">
                                <input id="password" type="password" class="form-control" name="password" placeholder="Password">

        @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                                @endif

              <input type="checkbox" name="remember"> Remember Me

          <button type="submit" class="btn btn-primary btn-block btn-flat">
            Sign In</button>

 </form>

- OR -

       Sign in using
        Facebook
       Sign in using
        Google+

    I forgot my password

    Register a new member

      Go to HebaShop Home

@endsection
@section('scripts')

@endsection


text:
$packageName = 'easytag'
$installerType = 'exe'
$silentArgs = '/S'
$url = 'https://download.gnome.org/binaries/win32/easytag/2.4/easytag-2.4.1-setup.exe'
$checksum = '39230dbc7b2ab022109dd9c6d7f4c7e7864efdec'
$checksumType = 'sha1'
$validExitCodes = @(0)

Install-ChocolateyPackage -PackageName "$packageName" `
                          -FileType "$installerType" `
                          -SilentArgs "$silentArgs" `
                          -Url "$url" `
                          -ValidExitCodes $validExitCodes `
                          -Checksum "$checksum" `
                          -ChecksumType "$checksumType"


text:
/** @file Default implementation of IOSystem using the standard C file functions */

#include <assimp/StringComparison.h>

#include <assimp/DefaultIOSystem.h>
#include <assimp/DefaultIOStream.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/ai_assert.h>
#include <stdlib.h>

#ifdef __unix__
#include <sys/param.h>
#include <stdlib.h>
#endif

#ifdef _WIN32
#include <windows.h>
#endif

using namespace Assimp;

// maximum path length
// XXX http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html
#ifdef PATH_MAX
#   define PATHLIMIT PATH_MAX
#else
#   define PATHLIMIT 4096
#endif

// ------------------------------------------------------------------------------------------------
// Tests for the existence of a file at the given path.
bool DefaultIOSystem::Exists( const char* pFile) const
{
#ifdef _WIN32
    wchar_t fileName16[PATHLIMIT];

#ifndef WindowsStore
    bool isUnicode = IsTextUnicode(pFile, static_cast<int>(strlen(pFile)), NULL) != 0;
    if (isUnicode) {

        MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, pFile, -1, fileName16, PATHLIMIT);
        struct __stat64 filestat;
        if (0 != _wstat64(fileName16, &filestat)) {
            return false;
        }
    } else {
#endif
        FILE* file = ::fopen(pFile, "rb");
        if (!file)
            return false;

        ::fclose(file);
#ifndef WindowsStore
    }
#endif
#else
    FILE* file = ::fopen( pFile, "rb");
    if( !file)
        return false;

    ::fclose( file);
#endif
    return true;
}

// ------------------------------------------------------------------------------------------------
// Open a new file with a given path.
IOStream* DefaultIOSystem::Open( const char* strFile, const char* strMode)
{
    ai_assert(NULL != strFile);
    ai_assert(NULL != strMode);
    FILE* file;
#ifdef _WIN32
    wchar_t fileName16[PATHLIMIT];
#ifndef WindowsStore
    bool isUnicode = IsTextUnicode(strFile, static_cast<int>(strlen(strFile)), NULL) != 0;
    if (isUnicode) {
        MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, strFile, -1, fileName16, PATHLIMIT);
        std::string mode8(strMode);
        file = ::_wfopen(fileName16, std::wstring(mode8.begin(), mode8.end()).c_str());
    } else {
#endif
        file = ::fopen(strFile, strMode);
#ifndef WindowsStore
    }
#endif
#else
    file = ::fopen(strFile, strMode);
#endif
    if (nullptr == file)
        return nullptr;

    return new DefaultIOStream(file, (std::string) strFile);
}

// ------------------------------------------------------------------------------------------------
// Closes the given file and releases all resources associated with it.
void DefaultIOSystem::Close( IOStream* pFile)
{
    delete pFile;
}

// ------------------------------------------------------------------------------------------------
// Returns the operation specific directory separator
char DefaultIOSystem::getOsSeparator() const
{
#ifndef _WIN32
    return '/';
#else
    return '\\';
#endif
}

// ------------------------------------------------------------------------------------------------
// IOSystem default implementation (ComparePaths isn't a pure virtual function)
bool IOSystem::ComparePaths (const char* one, const char* second) const
{
    return !ASSIMP_stricmp(one,second);
}

// ------------------------------------------------------------------------------------------------
// Convert a relative path into an absolute path
inline static void MakeAbsolutePath (const char* in, char* _out)
{
    ai_assert(in && _out);
#if defined( _MSC_VER ) || defined( __MINGW32__ )
#ifndef WindowsStore
    bool isUnicode = IsTextUnicode(in, static_cast<int>(strlen(in)), NULL) != 0;
    if (isUnicode) {
        wchar_t out16[PATHLIMIT];
        wchar_t in16[PATHLIMIT];
        MultiByteToWideChar(CP_UTF8, MB_PRECOMPOSED, in, -1, out16, PATHLIMIT);
        wchar_t* ret = ::_wfullpath(out16, in16, PATHLIMIT);
        if (ret) {
            WideCharToMultiByte(CP_UTF8, MB_PRECOMPOSED, out16, -1, _out, PATHLIMIT, nullptr, nullptr);
        }
        if (!ret) {
            // preserve the input path, maybe someone else is able to fix
            // the path before it is accessed (e.g. our file system filter)
            ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in));
            strcpy(_out, in);
        }

    } else {
#endif
        char* ret = :: _fullpath(_out, in, PATHLIMIT);
        if (!ret) {
            // preserve the input path, maybe someone else is able to fix
            // the path before it is accessed (e.g. our file system filter)
            ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in));
            strcpy(_out, in);
        }
#ifndef WindowsStore
    }
#endif
#else
    // use realpath
    char* ret = realpath(in, _out);
    if(!ret) {
        // preserve the input path, maybe someone else is able to fix
        // the path before it is accessed (e.g. our file system filter)
        ASSIMP_LOG_WARN_F("Invalid path: ", std::string(in));
        strcpy(_out,in);
    }
#endif
}

// ------------------------------------------------------------------------------------------------
// DefaultIOSystem's more specialized implementation
bool DefaultIOSystem::ComparePaths (const char* one, const char* second) const
{
    // chances are quite good both paths are formatted identically,
    // so we can hopefully return here already
    if( !ASSIMP_stricmp(one,second) )
        return true;

    char temp1[PATHLIMIT];
    char temp2[PATHLIMIT];

    MakeAbsolutePath (one, temp1);
    MakeAbsolutePath (second, temp2);

    return !ASSIMP_stricmp(temp1,temp2);
}

// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::fileName( const std::string &path )
{
    std::string ret = path;
    std::size_t last = ret.find_last_of("\\/");
    if (last != std::string::npos) ret = ret.substr(last + 1);
    return ret;
}

// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::completeBaseName( const std::string &path )
{
    std::string ret = fileName(path);
    std::size_t pos = ret.find_last_of('.');
    if(pos != ret.npos) ret = ret.substr(0, pos);
    return ret;
}

// ------------------------------------------------------------------------------------------------
std::string DefaultIOSystem::absolutePath( const std::string &path )
{
    std::string ret = path;
    std::size_t last = ret.find_last_of("\\/");
    if (last != std::string::npos) ret = ret.substr(0, last);
    return ret;
}

// ------------------------------------------------------------------------------------------------

#undef PATHLIMIT


text:
bool GetImportName ( const ASTElement * ImportStatementElement, std :: u32string & FileName, std :: string & ParseError );

bool OakResolveImports ( const ASTElement * FileRootElement, const std :: string & SourceFileName, const std :: vector <std :: string> & SearchPaths, FileTable & GlobalFileTable, std :: vector <CompilationUnit *> & UnitsOut, const std :: u32string * CompilationConditions, uint32_t CompilationConditionCount )
{

	uint64_t SubElementCount = FileRootElement -> GetSubElementCount ();
	uint64_t I = 0;

	std :: vector <const OilDecoratorTag *> ConditionalTags;

	while ( I < SubElementCount )
	{

		const ASTElement * SubElement = FileRootElement -> GetSubElement ( I );

		if ( SubElement -> GetTag () == OakASTTags :: kASTTag_DecoratorTag )
		{

			OilDecoratorTag * Tag = OakTranslateDecoratorTagToOil ( SubElement );

			if ( Tag == NULL )
			{

				for ( uint32_t I = 0; I < ConditionalTags.size (); I ++ )
					delete ConditionalTags [ I ];

				return false;

			}

			ConditionalTags.push_back ( Tag );

		}
		else if ( SubElement -> GetTag () == OakASTTags :: kASTTag_ImportStatement )
		{

			std :: u32string FileName;
			std :: string ParseError;

			if ( ! GetImportName ( SubElement, FileName, ParseError ) )
			{

				const Token * FirstToken = SubElement -> GetToken ( 0, 0 );

				if ( FirstToken == NULL )
					LOG_ERROR ( "Null first token for import statement" );

				LOG_ERROR_NOFILE ( ParseError );
				LOG_ERROR_NOFILE ( SourceFileName + " Line " + std :: to_string ( FirstToken -> GetSourceRef ().GetLine () ) + ", Char " + std :: to_string ( FirstToken -> GetSourceRef ().GetChar () ) + ": " + ParseError );

				return false;

			}

			if ( TestConditionalCompilationDecorators ( & ConditionalTags [ 0 ], ConditionalTags.size (), CompilationConditions, CompilationConditionCount ) )
			{

				std :: string UTF8FileName = CodeConversion :: ConvertUTF32ToUTF8 ( FileName );

				std :: string OutPath;

				if ( ! FindFirstMatchingFileInDirectories ( UTF8FileName, SearchPaths, OutPath ) )
				{

					LOG_FATALERROR_NOFILE ( "File not found: " + UTF8FileName );

					return false;

				}

				CompilationUnit * FileUnit = GlobalFileTable.GetUnit ( OutPath );

				if ( FileUnit == NULL )
				{

					FileUnit = new CompilationUnit ( OutPath );

					if ( ! FileUnit -> RunIndependantCompilationSteps ( GlobalFileTable, SearchPaths, CompilationConditions, CompilationConditionCount ) )
						return false;

				}

				UnitsOut.push_back ( FileUnit );

			}

			for ( uint32_t I = 0; I < ConditionalTags.size (); I ++ )
				delete ConditionalTags [ I ];

			ConditionalTags.clear ();

		}
		else
		{

			for ( uint32_t I = 0; I < ConditionalTags.size (); I ++ )
				delete ConditionalTags [ I ];

			ConditionalTags.clear ();

		}

		I ++;

	}

	return true;

}

bool GetImportName ( const ASTElement * ImportStatementElement, std :: u32string & FileName, std :: string & ParseError )
{

	const OakImportStatementConstructor :: ElementData * ImportData = reinterpret_cast <const OakImportStatementConstructor :: ElementData *> ( ImportStatementElement -> GetData () );

	return OakParseStringLiteral ( ImportData -> ImportFilenameLiteral, FileName, ParseError );

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">

 <!-- Marker-File for CDI -->

</beans>


text:
file(REMOVE_RECURSE
  "CMakeFiles/stddeque_overload_2.dir/stddeque_overload.cpp.o"
  "stddeque_overload_2.pdb"
  "stddeque_overload_2"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/stddeque_overload_2.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


text:
from __future__ import print_function

from future.standard_library import install_aliases

from topic_model_hdp import get_answer

install_aliases()
import logging
from twitter_data_fetcher import DataFetcher

from flask import Flask
from flask import request
from flask import make_response

from configparser import ConfigParser
from tweepy import OAuthHandler

import json

# Flask app should start in global layout
app = Flask(__name__)

########################################################################
# Twitter API credentials
########################################################################
config = ConfigParser()
config.read('credentials.ini')

CONSUMER_KEY = config['credentials']['consumer_key']
CONSUMER_SECRET = config['credentials']['consumer_secret']
ACCESS_TOKEN = config['credentials']['access_token']
ACCESS_SECRET = config['credentials']['access_secret']

auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)

datafetcher = DataFetcher('twitter.ini', auth)

@app.route('/', methods=['GET', 'POST'])
def hello():
    a = {'name': 'captibot'}
    req = request.get_json(silent=True, force=True)

    print("Request:")
    print(json.dumps(req, indent=4))

    res = makeWebhookResult(req)

    res = json.dumps(res, indent=4)
    # print(res)
    r = make_response(res)
    r.headers['Content-Type'] = 'application/json'
    return r

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500

def makeWebhookResult(req):
    datafetcher.download_friends_timeline(req.get('result').get('parameters').get('given-name'))

    parsed_twitter_account_name = 'Honda'
    ans = get_answer(parsed_twitter_account_name)

    return {
        "speech": "Hi, I am the backend, this is the name I have received: " + req.get('result').get('parameters').get(
            'given-name'),
        "displayText": "tyest diplay text",
        # "data": data,
        # "contextOut": [],
        "source": "captify bot"
    }

# [END app]


text:
import sys
import traceback
import os
from PyQt5.QtWidgets import (QWidget, QFileDialog, QPushButton, QTextEdit,
                             QGridLayout, QApplication, QLabel, QComboBox,
                             QCheckBox, QLineEdit, QStatusBar, QMainWindow)
# files for this package
import loss_analysis

class Measurement(QWidget):

    def __init__(self, grid, meas_name, default_file, row):
        super().__init__()

        self.meas_name = meas_name

        self.start_dir = os.path.join(os.pardir, 'example_cell')
        self.filepath = os.path.join(self.start_dir, default_file)

        _, self.file_ext = os.path.splitext(default_file)

        self._add_objects(grid, row)

    def _add_objects(self, grid,  row):
        '''
        Builds and binds the boxes.
        '''
        self.btn = QPushButton('Load {0}'.format(self.meas_name))
        self.btn.clicked.connect(self._get)

        filename = os.path.basename(self.filepath)

        self.label = QLabel(filename, self)
        grid.addWidget(self.btn, row, 0)
        grid.addWidget(self.label, row, 1)

    def _get(self):
        '''
        Gets and sets the label with the new file name
        '''
        filter_str = '{0} file (*{1})'.format(self.meas_name, self.file_ext)
        self.filepath = QFileDialog.getOpenFileName(self,
                                                    'Choose {0} file'.format(
                                                        self.meas_name),
                                                    self.start_dir, filter_str)[0]
        filename = os.path.basename(self.filepath)
        self.label.setText(filename)

    def file(self):
        return {self.meas_name + '_fname': self.filepath}

class LossAnalysisGui(QWidget):

    def __init__(self, parent):
        # super(LossAnalysisGui, self).__init__(parent)
        super().__init__()
        self.parent = parent

        self.initUI()

    def initUI(self):

        grid = QGridLayout()
        # grid.setSpacing(10)
        self.output_dir = os.path.join(os.pardir, 'example_cell')
        self.start_dir = os.path.join(os.pardir, 'example_cell')
        self.save_fig_bool = False

        # select starting directory
        self.btn_start_dir = QPushButton("Select start directory")
        self.btn_start_dir.clicked.connect(self.select_start_dir)
        grid.addWidget(self.btn_start_dir, 0, 0)
        self.label_start_dir = QLabel(os.path.basename(self.start_dir), self)
        grid.addWidget(self.label_start_dir, 0, 1)

        # select output directory
        self.btn_output_dir = QPushButton("Select output directory")
        self.btn_output_dir.clicked.connect(self.select_output_dir)
        grid.addWidget(self.btn_output_dir, 1, 0)
        self.label_output_dir = QLabel(os.path.basename(self.output_dir), self)
        grid.addWidget(self.label_output_dir, 1, 1)

        boxes = [['reflectance', 'example_reflectance.csv'],
                 ['EQE', 'example_EQE.txt'],
                 ['light IV', 'example_lightIV.lgt'],
                 ['suns Voc', 'example_sunsVoc.xlsm'],
                 ['dark IV', 'example_darkIV.drk']
                 ]

        self.measurement = []

        for box, row_num in zip(boxes, range(len(boxes))):
            self.measurement.append(Measurement(grid, box[0], box[1],
                                                row_num + 3))

        # save figures checkbox
        self.cb_save_fig = QCheckBox('Save figures', self)
        self.cb_save_fig.stateChanged.connect(self.save_fig_toggle)
        grid.addWidget(self.cb_save_fig, 9, 0)

        # cell name input
        self.cell_name_input = QLineEdit(self)
        self.cell_name_input.setPlaceholderText('cell name')
        grid.addWidget(self.cell_name_input, 9, 1)

        # process all data
        self.btn_process = QPushButton("Process data")
        self.btn_process.clicked.connect(self.process_data)
        grid.addWidget(self.btn_process, 10, 0)

        # self.statusBar = QStatusBar()
        # self.setStatusBar(self.statusBar)

        self.setLayout(grid)

        self.show()

    def select_start_dir(self):
        self.start_dir = QFileDialog.getExistingDirectory(self,
                                                          'Choose start directory', self.start_dir)
        self.label_start_dir.setText(os.path.basename(self.start_dir))
        for m in self.measurement:
            m.start_dir = self.start_dir

        self.output_dir = self.start_dir
        self.label_output_dir.setText(os.path.basename(self.start_dir))

    def select_output_dir(self):
        self.output_dir = QFileDialog.getExistingDirectory(self,
                                                           'Choose output directory', self.output_dir)
        self.label_output_dir.setText(os.path.basename(self.output_dir))

    def save_fig_toggle(self, state):
        if self.cb_save_fig.isChecked():
            self.save_fig_bool = True
        else:
            self.save_fig_bool = False

    def process_data(self):

        files = {}
        for i in self.measurement:
            files.update(i.file())

        # pass the file names, and let the next thing handle them.
        self.parent.statusBar().showMessage('loading files')

        # a check on the data
        # if the data is bad, a message is returned in the gui
        try:
            la = loss_analysis.Cell(**files)
        except Exception as e:
            self.parent.statusBar().showMessage('Error:' + str(e))
            # print(str(e))
        else:
            self.parent.statusBar().showMessage('Calculating losses')

        la.process_all(self.save_fig_bool, self.output_dir,
                       self.cell_name_input.text())
        self.parent.statusBar().showMessage('Done!')

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'Loss analysis'
        self.left = 100
        self.top = 100
        self.width = 400
        self.height = 500
        self.initUI()

    def initUI(self):

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.statusBar().showMessage('All clear, ready to roll')

        self.form_widget = LossAnalysisGui(self)
        self.setCentralWidget(self.form_widget)

        self.show()

if __name__ == '__main__':

    # logfile = open('traceback.log', 'w')
    app = QApplication(sys.argv)
    # try:
    lag = App()
    # except:
    # traceback.print_exc(file=logfile)

    lag.show()
    # logfile.close()
    sys.exit(app.exec_())


text:
require "test_helper"
require "models"

class StyleTest < Test::Unit::TestCase

  context "An Attachment with style rules" do

    setup do
      @dir = File.dirname(__FILE__) + '/fixtures'
      @image = File.open("#{@dir}/baboon.jpg", 'r')
      @options = {
        :styles=>{
          :thumb => "50x50#"
        }
      }

      @doc = DocNoAttachment.create
      @attachment = Griddle::Attachment.for(:image, @doc, @options)
    end

    context "and a file" do

      setup do
        @attachment.assign(@image)
      end

      should "have a styles hash" do
        assert_kind_of Hash, @attachment.styles
      end

      should ":thumb be a type of Griddle::Style" do
        assert_kind_of Griddle::Style, @attachment.styles[:thumb]
      end

      should "have an #attachment for a style" do
        assert_equal @attachment, @attachment.styles[:thumb].attachment
      end

      should "have a geometry for a style" do
        assert_equal @options[:styles][:thumb], @attachment.styles[:thumb][:geometry]
      end

      should "have a #geometry for a style" do
        assert_equal @options[:styles][:thumb], @attachment.styles[:thumb].geometry
      end

      should "save styles with the attachment" do
        @attachment.save
        options = {:name => @attachment.name, :owner_id => @attachment.owner_id, :owner_type => @attachment.owner_type }
        record = Griddle::Attachment.collection.find_one(options)
        attachment = Griddle::Attachment.new record
        assert_equal  @attachment.styles[:thumb][:geometry], attachment.styles[:thumb][:geometry]
      end

    end

  end

end


text:
import { config } from '../src/config';
import { registerBidder } from '../src/adapters/bidderFactory';
import * as utils from '../src/utils';
import { BANNER } from '../src/mediaTypes';

const SUPPORTED_AD_TYPES = [BANNER];
const BIDDER_CODE = 'openxoutstream';
const BIDDER_CONFIG = 'hb_pb_ym';
const BIDDER_VERSION = '1.0.0';
const CURRENCY = 'USD';
const NET_REVENUE = true;
const TIME_TO_LIVE = 300;
const YM_SCRIPT = `!function(e,t){if(void 0===t._ym){var a=Math.round(5*Math.random()/3)+'';t._ym='';var m=e.createElement('script');m.type='text/javascript',m.async=!0,m.src='//static.yieldmo.com/ym.'+a+'.js',(e.getElementsByTagName('head')[0]||e.getElementsByTagName('body')[0]).appendChild(m)}else t._ym instanceof String||void 0===t._ym.chkPls||t._ym.chkPls()}(document,window);`;
const PLACEMENT_ID = '1986307928000988495';
const PUBLISHER_ID = '1986307525700126029';
const CR_ID = '2052941939925262540';
const AD_ID = '1991358644725162800';

export const spec = {
  code: BIDDER_CODE,
  supportedMediaTypes: SUPPORTED_AD_TYPES,
  isBidRequestValid: function(bidRequest) {
    return !!(bidRequest.params.delDomain && bidRequest.params.unit)
  },
  buildRequests: function(bidRequests, bidderRequest) {
    if (bidRequests.length === 0) {
      return [];
    }
    let requests = [];
    bidRequests.forEach(bid => {
      requests.push(buildOXBannerRequest(bid, bidderRequest));
    })
    return requests;
  },
  interpretResponse: function(bid, serverResponse) {
    return handleVastResponse(bid, serverResponse.payload)
  },
};

function getViewportDimensions(isIfr) {
  let width;
  let height;
  let tWin = window;
  let body;

  if (isIfr) {
    let tDoc;
    try {
      tWin = window.top;
      tDoc = window.top.document;
    } catch (e) {
      return;
    }
    body = tDoc.body;

    width = tWin.innerWidth || docEl.clientWidth || body.clientWidth;
    height = tWin.innerHeight || docEl.clientHeight || body.clientHeight;
  } else {
    width = tWin.innerWidth || docEl.clientWidth;
    height = tWin.innerHeight || docEl.clientHeight;
  }

  return `${width}x${height}`;
}

function buildCommonQueryParamsFromBids(bid, bidderRequest) {
  const isInIframe = utils.inIframe();
  let defaultParams;
  defaultParams = {
    ju: config.getConfig('pageUrl') || utils.getTopWindowUrl(),
    jr: utils.getTopWindowReferrer(),
    ch: document.charSet || document.characterSet,
    res: `${screen.width}x${screen.height}x${screen.colorDepth}`,
    ifr: isInIframe,
    tz: new Date().getTimezoneOffset(),
    tws: getViewportDimensions(isInIframe),
    be: 1,
    bc: bid.params.bc || `${BIDDER_CONFIG}_${BIDDER_VERSION}`,
    auid: bid.params.unit,
    dddid: bid.transactionId,
    openrtb: '%7B%22mimes%22%3A%5B%22video%2Fmp4%22%5D%7D',
    nocache: new Date().getTime(),
    vht: bid.params.height || bid.sizes[0][1],
    vwd: bid.params.width || bid.sizes[0][0]
  };

  if (utils.deepAccess(bidderRequest, 'gdprConsent')) {
    let gdprConsentConfig = bidderRequest.gdprConsent;

    if (gdprConsentConfig.consentString !== undefined) {
      defaultParams.gdpr_consent = gdprConsentConfig.consentString;
    }

    if (gdprConsentConfig.gdprApplies !== undefined) {
      defaultParams.gdpr = gdprConsentConfig.gdprApplies ? 1 : 0;
    }

    if (config.getConfig('consentManagement.cmpApi') === 'iab') {
      defaultParams.x_gdpr_f = 1;
    }
  }

  return defaultParams;
}

function buildOXBannerRequest(bid, bidderRequest) {
  let queryParams = buildCommonQueryParamsFromBids(bid, bidderRequest);
  queryParams.aus = utils.parseSizesInput(bid.sizes).join(',');

  if (bid.params.doNotTrack) {
    queryParams.ns = 1;
  }

  if (bid.params.coppa) {
    queryParams.tfcd = 1;
  }

  let url = `https://${bid.params.delDomain}/v/1.0/avjp`
  return {
    method: 'GET',
    url: url,
    data: queryParams,
    payload: {'bid': bid}
  };
}

function handleVastResponse(response, serverResponse) {
  const body = response.body
  let bidResponses = [];
  if (response !== undefined && body.vastUrl !== '' && body.pub_rev && body.pub_rev > 0) {
    const openHtmlTag = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
    const closeHtmlTag = '';
    const sdkScript = createSdkScript().outerHTML;
    const placementDiv = createPlacementDiv();
    placementDiv.dataset.pId = PUBLISHER_ID;
    const placementDivString = placementDiv.outerHTML;
    const adResponse = getTemplateAdResponse(body.vastUrl);
    const adResponseString = JSON.stringify(adResponse);
    const ymAdsScript = '';

    let bidResponse = {};
    bidResponse.requestId = serverResponse.bid.bidId;
    bidResponse.bidderCode = BIDDER_CODE;
    bidResponse.netRevenue = NET_REVENUE;
    bidResponse.currency = CURRENCY;
    bidResponse.cpm = Number(body.pub_rev) / 1000;
    bidResponse.creativeId = body.adid;
    bidResponse.height = body.height;
    bidResponse.width = body.width;
    bidResponse.vastUrl = body.vastUrl;
    bidResponse.ttl = TIME_TO_LIVE;
    bidResponse.mediaType = BANNER;
    bidResponse.ad = openHtmlTag + placementDivString + ymAdsScript + sdkScript + closeHtmlTag;

    bidResponses.push(bidResponse);
  }
  return bidResponses;
}
registerBidder(spec);

// HELPER FUNCTIONS
function createSdkScript() {
  const script = document.createElement('script');
  script.innerHTML = YM_SCRIPT;
  return script;
}
function createPlacementDiv() {
  const div = document.createElement('div');
  div.id = `ym_${PLACEMENT_ID}`;
  div.classList.add('ym');
  div.dataset.lfId = CR_ID;
  return div
}

/**
 * Create a nativeplay template with the placement id and vastURL.
 * @param vastUrl
 */
const getTemplateAdResponse = (vastUrl) => {
  return {
    availability_zone: 'us-east-1a',
    data: [
      {
        ads: [
          {
            actions: {},
            adv_id: AD_ID,
            configurables: {
              cta_button_copy: 'Learn More',
              vast_click_tracking: 'true',
              vast_url: vastUrl,
            },
            cr_id: CR_ID,
          }
        ],
        column_count: 1,
        configs: {
          allowable_height: '248',
          header_copy: 'You May Like',
          ping: 'true',
        },
        creative_format_id: 40,
        css: '',
        placement_id: PLACEMENT_ID,
      }
    ],
    nc: 0,
  };
};


text:
require File.expand_path('spec_helper', File.dirname(__FILE__))

describe FontAwesome do
  it 'does not cause an error' do
    actual = require('bundle/bundler/setup')
    expect(actual).to be false
  end

  describe '.to_character_reference' do
    it 'returns the character reference' do
      actual = FontAwesome.to_character_reference('f000')
      expect(actual).to eq('')

      actual = FontAwesome.to_character_reference('f17b')
      expect(actual).to eq('')
    end

    it 'does not returns the character reference' do
      actual = FontAwesome.to_character_reference('f001')
      expect(actual).not_to eq('')
    end
  end

  describe '#icons' do
    let(:icons) { FontAwesome.new.icons }

    it 'returns 409' do
      expect(icons.size).to eq(409)
    end

    it 'returns "adjust"' do
      expect(icons.first.id).to eq('adjust')
    end

    it 'returns "youtube-square"' do
      expect(icons.last.id).to eq('youtube-square')
    end

    it 'includes these icons' do
      icon_ids = icons.map { |icon| icon.id }
      Fixtures.icon_ids.each { |icon| expect(icon_ids).to be_include(icon) }
    end

    it 'includes these icons (reverse)' do
      icons.each { |icon| expect(Fixtures.icon_ids).to be_include(icon.id) }
    end

    it 'does not includes these icons' do
      expectation = %w(icon awesome)
      expectation.each { |icon| expect(icons).not_to be_include(icon) }
    end
  end

  describe '#select!' do
    context 'with "hdd"' do
      let(:icons) { FontAwesome.new.select!(%w(hdd)) }

      it 'returns 1' do
        expect(icons.size).to eq(1)
      end

      it 'must equal icon name' do
        icon_ids = icons.map { |icon| icon.id }
        expect(icon_ids).to eq(%w(hdd-o))
      end
    end

    context 'with "left arr"' do
      let(:icons) { FontAwesome.new.select!(%w(left arr)) }

      it 'returns 4' do
        expect(icons.size).to eq(4)
      end

      it 'must equal icon names' do
        icon_ids = icons.map { |icon| icon.id }
        expectation = %w(
          arrow-circle-left
          arrow-circle-o-left
          arrow-left long-arrow-left
        )
        expect(icon_ids).to eq(expectation)
      end
    end

    context 'with "arr left" (reverse)' do
      let(:icons) { FontAwesome.new.select!(%w(arr left)) }

      it 'returns 4' do
        expect(icons.size).to eq(4)
      end

      it 'must equal icon names' do
        icon_ids = icons.map { |icon| icon.id }
        expectation = %w(
          arrow-circle-left
          arrow-circle-o-left
          arrow-left long-arrow-left
        )
        expect(icon_ids).to eq(expectation)
      end
    end

    context 'with "icon" (does not match)' do
      let(:icons) { FontAwesome.new.select!(%w(icon)) }

      it 'returns a empty array' do
        expect(icons).to eq([])
      end
    end

    context 'with unknown arguments' do
      let(:icons) { FontAwesome.new.select!([]) }

      it 'returns 409' do
        expect(icons.size).to eq(409)
      end

      it 'must equal icon names' do
        icon_ids = icons.map { |icon| icon.id }
        expect(icon_ids).to eq(Fixtures.icon_ids)
      end
    end
  end

  describe '#item_hash' do
    let(:item_hash) do
      icon = FontAwesome::Icon.new('apple')
      FontAwesome.new.item_hash(icon)
    end

    it 'returns 6' do
      expect(item_hash.size).to eq(6)
    end

    it 'must equal hash values' do
      expect(item_hash[:uid]).to eq('')
      expect(item_hash[:title]).to eq('apple')
      expect(item_hash[:subtitle]).to eq('Paste class name: fa-apple')
      expect(item_hash[:arg]).to eq('apple|||f179')
      expect(item_hash[:icon][:type]).to eq('default')
      expect(item_hash[:icon][:name]).to eq('./icons/fa-apple.png')
      expect(item_hash[:valid]).to eq('yes')
    end
  end

  describe '#item_xml' do
    let(:item_xml) do
      icon = FontAwesome::Icon.new('apple')
      item_hash = FontAwesome.new.item_hash(icon)
      FontAwesome.new.item_xml(item_hash)
    end

    it 'returns the XML' do
      expectation = <<-XML
<item arg="apple|||f179" uid="">
  <title>apple</title>
  <subtitle>Paste class name: fa-apple</subtitle>
  <icon>./icons/fa-apple.png</icon>
</item>
      XML
      expect(item_xml).to eq(expectation)
    end
  end

  describe '#to_alfred' do
    let(:doc) do
      queries = ['bookmark']
      xml = FontAwesome.new(queries).to_alfred
      REXML::Document.new(xml)
      # TODO: mute puts
    end

    it 'returns 2' do
      expect(doc.elements['items'].elements.size).to eq(2)
    end

    it 'must equal XML elements' do
      expect(doc.elements['items/item[1]'].attributes['arg']).to \
        eq('bookmark|||f02e')
      expect(doc.elements['items/item[1]/title'].text).to eq('bookmark')
      expect(doc.elements['items/item[1]/icon'].text).to \
        eq('./icons/fa-bookmark.png')
      expect(doc.elements['items/item[2]'].attributes['arg']).to \
        eq('bookmark-o|||f097')
      expect(doc.elements['items/item[2]/title'].text).to eq('bookmark-o')
      expect(doc.elements['items/item[2]/icon'].text).to \
        eq('./icons/fa-bookmark-o.png')
    end

    it 'must equal $stdout (test for puts)' do
      expectation = <<-XML
<?xml version='1.0'?>
<items>
<item arg="bookmark|||f02e" uid="">
  <title>bookmark</title>
  <subtitle>Paste class name: fa-bookmark</subtitle>
  <icon>./icons/fa-bookmark.png</icon>
</item>
<item arg="bookmark-o|||f097" uid="">
  <title>bookmark-o</title>
  <subtitle>Paste class name: fa-bookmark-o</subtitle>
  <icon>./icons/fa-bookmark-o.png</icon>
</item>
</items>
      XML

      actual = capture(:stdout) { FontAwesome.new(['bookmark']).to_alfred }
      expect(actual).to eq(expectation)
    end
  end

  describe '::Icon' do
    describe '#initialize' do
      context 'star-half-o (#detect_unicode_from_id)' do
        let(:icon) { FontAwesome::Icon.new('star-half-o') }

        it 'returns "star-half-o"' do
          expect(icon.id).to eq('star-half-o')
        end

        it 'returns "f123"' do
          expect(icon.unicode).to eq('f123')
        end
      end

      context 'star-half-empty (#detect_unicode_from_aliases)' do
        let(:icon) { FontAwesome::Icon.new('star-half-empty') }

        it 'returns "star-half-o"' do
          expect(icon.id).to eq('star-half-empty')
        end

        it 'returns "f123"' do
          expect(icon.unicode).to eq('f123')
        end
      end

      it 'includes these icons' do
        Fixtures.icon_ids.each do |id|
          icon = FontAwesome::Icon.new(id)
          expect(icon.id).to eq(id)
          expect(icon.unicode).not_to be_nil
        end
      end
    end
  end
end


text:
package chord

import (
	"encoding/binary"
	"fmt"
	"log"
	"time"
)

type Vnode struct {
	Id   []byte
	Host string
}

func (vn *Vnode) String() string {
	return fmt.Sprintf("%x", vn.Id)
}

// Initializes a local vnode
func (vn *localVnode) init(idx int) {
	// Generate an ID
	vn.genId(uint16(idx))

	// Set our host
	vn.Host = vn.ring.config.Hostname

	// Initialize all state
	vn.successors = make([]*Vnode, vn.ring.config.NumSuccessors)
	vn.finger = make([]*Vnode, vn.ring.config.hashBits)

	// Register with the RPC mechanism
	vn.ring.transport.Register(&vn.Vnode, vn)
}

// Schedules the Vnode to do regular maintenence
func (vn *localVnode) schedule() {
	// Setup our stabilize timer
	vn.timer = time.AfterFunc(randStabilize(vn.ring.config), vn.stabilize)
}

// Generates an ID for the node
func (vn *localVnode) genId(idx uint16) {
	// Use the hash funciton
	conf := vn.ring.config
	hash := conf.HashFunc()
	hash.Write([]byte(conf.Hostname))
	binary.Write(hash, binary.BigEndian, idx)

	// Use the hash as the ID
	vn.Id = hash.Sum(nil)
}

// Called to periodically stabilize the vnode
func (vn *localVnode) stabilize() {
	// Clear the timer
	vn.timer = nil

	// Check for shutdown
	if vn.ring.shutdown != nil {
		vn.ring.shutdown <- true
		return
	}

	// Setup the next stabilize timer
	defer vn.schedule()

	// Check for new successor
	if err := vn.checkNewSuccessor(); err != nil {
		log.Printf("[ERR] Error checking for new successor: %s", err)
	}

	// Notify the successor
	if err := vn.notifySuccessor(); err != nil {
		log.Printf("[ERR] Error notifying successor: %s", err)
	}

	// Finger table fix up
	if err := vn.fixFingerTable(); err != nil {
		log.Printf("[ERR] Error fixing finger table: %s", err)
	}

	// Check the predecessor
	if err := vn.checkPredecessor(); err != nil {
		log.Printf("[ERR] Error checking predecessor: %s", err)
	}

	// Set the last stabilized time
	vn.stabilized = time.Now()
}

// Checks for a new successor
func (vn *localVnode) checkNewSuccessor() error {
	// Ask our successor for it's predecessor
	trans := vn.ring.transport

CHECK_NEW_SUC:
	succ := vn.successors[0]
	if succ == nil {
		panic("Node has no successor!")
	}
	maybe_suc, err := trans.GetPredecessor(succ)
	if err != nil {
		// Check if we have succ list, try to contact next live succ
		known := vn.knownSuccessors()
		if known > 1 {
			for i := 0; i < known; i++ {
				if alive, _ := trans.Ping(vn.successors[0]); !alive {
					// Don't eliminate the last successor we know of
					if i+1 == known {
						return fmt.Errorf("All known successors dead!")
					}

					// Advance the successors list past the dead one
					copy(vn.successors[0:], vn.successors[1:])
					vn.successors[known-1-i] = nil
				} else {
					// Found live successor, check for new one
					goto CHECK_NEW_SUC
				}
			}
		}
		return err
	}

	// Check if we should replace our successor
	if maybe_suc != nil && between(vn.Id, succ.Id, maybe_suc.Id) {
		// Check if new successor is alive before switching
		alive, err := trans.Ping(maybe_suc)
		if alive && err == nil {
			copy(vn.successors[1:], vn.successors[0:len(vn.successors)-1])
			vn.successors[0] = maybe_suc
		} else {
			return err
		}
	}
	return nil
}

// RPC: Invoked to return out predecessor
func (vn *localVnode) GetPredecessor() (*Vnode, error) {
	return vn.predecessor, nil
}

// Notifies our successor of us, updates successor list
func (vn *localVnode) notifySuccessor() error {
	// Notify successor
	succ := vn.successors[0]
	succ_list, err := vn.ring.transport.Notify(succ, &vn.Vnode)
	if err != nil {
		return err
	}

	// Trim the successors list if too long
	max_succ := vn.ring.config.NumSuccessors
	if len(succ_list) > max_succ-1 {
		succ_list = succ_list[:max_succ-1]
	}

	// Update local successors list
	for idx, s := range succ_list {
		if s == nil {
			break
		}
		// Ensure we don't set ourselves as a successor!
		if s == nil || s.String() == vn.String() {
			break
		}
		vn.successors[idx+1] = s
	}
	return nil
}

// RPC: Notify is invoked when a Vnode gets notified
func (vn *localVnode) Notify(maybe_pred *Vnode) ([]*Vnode, error) {
	// Check if we should update our predecessor
	if vn.predecessor == nil || between(vn.predecessor.Id, vn.Id, maybe_pred.Id) {
		// Inform the delegate
		conf := vn.ring.config
		old := vn.predecessor
		vn.ring.invokeDelegate(func() {
			conf.Delegate.NewPredecessor(&vn.Vnode, maybe_pred, old)
		})

		vn.predecessor = maybe_pred
	}

	// Return our successors list
	return vn.successors, nil
}

// Fixes up the finger table
func (vn *localVnode) fixFingerTable() error {
	// Determine the offset
	hb := vn.ring.config.hashBits
	offset := powerOffset(vn.Id, vn.lastFinger, hb)

	// Find the successor
	nodes, err := vn.FindSuccessors(1, offset)
	if nodes == nil || len(nodes) == 0 || err != nil {
		return err
	}
	node := nodes[0]

	// Update the finger table
	vn.finger[vn.lastFinger] = node

	// Try to skip as many finger entries as possible
	for {
		next := vn.lastFinger + 1
		if next >= hb {
			break
		}
		offset := powerOffset(vn.Id, next, hb)

		// While the node is the successor, update the finger entries
		if betweenRightIncl(vn.Id, node.Id, offset) {
			vn.finger[next] = node
			vn.lastFinger = next
		} else {
			break
		}
	}

	// Increment to the index to repair
	if vn.lastFinger+1 == hb {
		vn.lastFinger = 0
	} else {
		vn.lastFinger++
	}

	return nil
}

// Checks the health of our predecessor
func (vn *localVnode) checkPredecessor() error {
	// Check predecessor
	if vn.predecessor != nil {
		res, err := vn.ring.transport.Ping(vn.predecessor)
		if err != nil {
			return err
		}

		// Predecessor is dead
		if !res {
			vn.predecessor = nil
		}
	}
	return nil
}

// Finds next N successors. N must be <= NumSuccessors
func (vn *localVnode) FindSuccessors(n int, key []byte) ([]*Vnode, error) {
	// Check if we are the immediate predecessor
	if betweenRightIncl(vn.Id, vn.successors[0].Id, key) {
		return vn.successors[:n], nil
	}

	// Try the closest preceeding nodes
	cp := closestPreceedingVnodeIterator{}
	cp.init(vn, key)
	for {
		// Get the next closest node
		closest := cp.Next()
		if closest == nil {
			break
		}

		// Try that node, break on success
		res, err := vn.ring.transport.FindSuccessors(closest, n, key)
		if err == nil {
			return res, nil
		}
		log.Printf("[ERR] Failed to contact %s. Got %s", closest.String(), err)
	}

	// Determine how many successors we know of
	successors := vn.knownSuccessors()

	// Check if the ID is between us and any non-immediate successors
	for i := 1; i <= successors-n; i++ {
		if betweenRightIncl(vn.Id, vn.successors[i].Id, key) {
			remain := vn.successors[i:]
			if len(remain) > n {
				remain = remain[:n]
			}
			return remain, nil
		}
	}

	// Checked all closer nodes and our successors!
	return nil, fmt.Errorf("Exhausted all preceeding nodes!")
}

// Instructs the vnode to leave
func (vn *localVnode) leave() error {
	// Inform the delegate we are leaving
	conf := vn.ring.config
	pred := vn.predecessor
	succ := vn.successors[0]
	vn.ring.invokeDelegate(func() {
		conf.Delegate.Leaving(&vn.Vnode, pred, succ)
	})

	// Notify predecessor to advance to their next successor
	var err error
	trans := vn.ring.transport
	if vn.predecessor != nil {
		err = trans.SkipSuccessor(vn.predecessor, &vn.Vnode)
	}

	// Notify successor to clear old predecessor
	err = mergeErrors(err, trans.ClearPredecessor(vn.successors[0], &vn.Vnode))
	return err
}

// Used to clear our predecessor when a node is leaving
func (vn *localVnode) ClearPredecessor(p *Vnode) error {
	if vn.predecessor != nil && vn.predecessor.String() == p.String() {
		// Inform the delegate
		conf := vn.ring.config
		old := vn.predecessor
		vn.ring.invokeDelegate(func() {
			conf.Delegate.PredecessorLeaving(&vn.Vnode, old)
		})
		vn.predecessor = nil
	}
	return nil
}

// Used to skip a successor when a node is leaving
func (vn *localVnode) SkipSuccessor(s *Vnode) error {
	// Skip if we have a match
	if vn.successors[0].String() == s.String() {
		// Inform the delegate
		conf := vn.ring.config
		old := vn.successors[0]
		vn.ring.invokeDelegate(func() {
			conf.Delegate.SuccessorLeaving(&vn.Vnode, old)
		})

		known := vn.knownSuccessors()
		copy(vn.successors[0:], vn.successors[1:])
		vn.successors[known-1] = nil
	}
	return nil
}

// Determine how many successors we know of
func (vn *localVnode) knownSuccessors() (successors int) {
	for i := 0; i < len(vn.successors); i++ {
		if vn.successors[i] != nil {
			successors = i + 1
		}
	}
	return
}