text:
package org.loader.liteplayer.utils;

import org.apache.http.HttpVersion;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

/**
 * liteplayer by loader
 * @author qibin
 */
public class HttpUtils {
	public static HttpParams getParams() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, 4000);
		HttpConnectionParams.setSoTimeout(params, 10000);
		ConnManagerParams.setTimeout(params, 4000);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
		HttpProtocolParams.setUseExpectContinue(params, true);
		HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1; WOW64)" +
				" AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1941.0 Safari/537.36");
		return params;
	}
}


text:
#include "woe32dll/export.h"

VARIABLE(argmatch_die)
#if GNULIB_DEFINED_ERROR
VARIABLE(rpl_error_message_count)
VARIABLE(rpl_error_one_per_line)
VARIABLE(rpl_error_print_progname)
#endif
VARIABLE(error_with_progname)
VARIABLE(exit_failure)
VARIABLE(gl_array_list_implementation)
VARIABLE(gl_linkedhash_list_implementation)
VARIABLE(program_name)
#if GNULIB_DEFINED_GETOPT
VARIABLE(rpl_optarg)
VARIABLE(rpl_optind)
#endif
VARIABLE(simple_backup_suffix)
VARIABLE(styled_ostream_typeinfo)

redpajama_set_name: RedPajamaGithub


text:
package org.apache.bcel.generic;

/**
 * Imnplement this interface if you're interested in changes to a FieldGen object
 * and register yourself with addObserver().
 *
 * @version $Id: FieldObserver.java 386056 2006-03-15 11:31:56Z tcurdt $
 * @author  M. Dahm
 */
public interface FieldObserver {

    public void notify( FieldGen field );
}


text:
namespace g2o {

  class G2O_SIMULATOR_API SensorPointXYOffset: public PointSensorParameters, public BinarySensor<Robot2D, EdgeSE2PointXYOffset, WorldObjectPointXY>{
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef PoseVertexType::EstimateType RobotPoseType;
    SensorPointXYOffset(const std::string& name_);
    virtual void sense();
    virtual void addNoise(EdgeType* e);
    virtual void addParameters();
  protected:
    bool isVisible(WorldObjectType* to);
    ParameterSE2Offset* _offsetParam;
    RobotPoseType _sensorPose;
  };

}

#endif


text:
""" GPTNeoX Japanese model configuration"""

from ...configuration_utils import PretrainedConfig
from ...utils import logging

logger = logging.get_logger(__name__)

GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP = {
    "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json",
}

class GPTNeoXJapaneseConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`GPTNeoXModelJapanese`]. It is used to instantiate
    a GPTNeoX model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the GPTNeoXJapanese
    [abeja/gpt-neox-japanese-2.7b](https://huggingface.co/abeja/gpt-neox-japanese-2.7b) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information. Default configs is set as 2.7B model

    Args:
        vocab_size (`int`, *optional*, defaults to 32000):
            Vocabulary size of the GPTNeoXJapanese model. Defines the number of different tokens that can be
            represented by the `inputs_ids` passed when calling [`GPTNeoXJapanese`].
        hidden_size (`int`, *optional*, defaults to 2560):
            Dimension of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 32):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 32):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_multiple_size (`int`, *optional*, defaults to 4):
            Dimension of the "intermediate" layer in the Transformer encoder is calculated by hidden_size *
            intermediate_multiple_size.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler.
        rotary_pct (`float`, *optional*, defaults to 1.00):
            percentage of hidden dimensions to allocate to rotary embeddings
        rotary_emb_base (`int`, *optional*, defaults to 10000)
            base for computing rotary embeddings frequency
        max_position_embeddings (`int`, *optional*, defaults to 2048):
            The maximum sequence length that this model might ever be used with.
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-5):
            The epsilon used by the layer normalization layers.
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models). Only
            relevant if `config.is_decoder=True`.
        weight_tying (`bool`, *optional*, defaults to `True`):
            Whhether or not use weight tying between input and output embedding weight
        attention_dropout (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention.
        hidden_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the hidden layer.
        Example:

    ```python
    >>> from transformers import GPTNeoXJapaneseConfig, GPTNeoXJapaneseModel

    >>> # Initializing a GPTNeoXJapanese gpt-neox-japanese-2.7b style configuration
    >>> configuration = GPTNeoXJapaneseConfig()

    >>> # Initializing a model (with random weights) from the gpt-neox-japanese-2.7b style configuration
    >>> model = GPTNeoXJapaneseModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```"""
    model_type = "gpt_neox_japanese"

    def __init__(
        self,
        vocab_size=32000,
        hidden_size=2560,
        num_hidden_layers=32,
        num_attention_heads=32,
        intermediate_multiple_size=4,
        hidden_act="gelu",
        rotary_pct=1.00,
        rotary_emb_base=10000,
        max_position_embeddings=2048,
        initializer_range=0.02,
        layer_norm_eps=1e-5,
        use_cache=True,
        bos_token_id=31996,
        eos_token_id=31999,
        weight_tying=True,
        attention_dropout=0.1,
        hidden_dropout=0.0,
        **kwargs
    ):
        super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_multiple_size = intermediate_multiple_size
        self.hidden_act = hidden_act
        self.rotary_pct = rotary_pct
        self.rotary_emb_base = rotary_emb_base
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.use_cache = use_cache
        self.weight_tying = weight_tying
        self.attention_dropout = attention_dropout
        self.hidden_dropout = hidden_dropout


text:
Getting Started with XGBoost4J
##############################
This tutorial introduces Java API for XGBoost.

**************
Data Interface
**************
Like the XGBoost python module, XGBoost4J uses DMatrix to handle data.
LIBSVM txt format file, sparse matrix in CSR/CSC format, and dense matrix are
supported.

* The first step is to import DMatrix:

  .. code-block:: java

    import ml.dmlc.xgboost4j.java.DMatrix;

* Use DMatrix constructor to load data from a libsvm text format file:

  .. code-block:: java

    DMatrix dmat = new DMatrix("train.svm.txt");

* Pass arrays to DMatrix constructor to load from sparse matrix.

  Suppose we have a sparse matrix

  .. code-block:: none

    1 0 2 0
    4 0 0 3
    3 1 2 0

  We can express the sparse matrix in `Compressed Sparse Row (CSR) <https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_(CSR,_CRS_or_Yale_format)>`_ format:

  .. code-block:: java

    long[] rowHeaders = new long[] {0,2,4,7};
    float[] data = new float[] {1f,2f,4f,3f,3f,1f,2f};
    int[] colIndex = new int[] {0,2,0,3,0,1,2};
    int numColumn = 4;
    DMatrix dmat = new DMatrix(rowHeaders, colIndex, data, DMatrix.SparseType.CSR, numColumn);

  ... or in `Compressed Sparse Column (CSC) <https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_column_(CSC_or_CCS)>`_ format:

  .. code-block:: java

    long[] colHeaders = new long[] {0,3,4,6,7};
    float[] data = new float[] {1f,4f,3f,1f,2f,2f,3f};
    int[] rowIndex = new int[] {0,1,2,2,0,2,1};
    int numRow = 3;
    DMatrix dmat = new DMatrix(colHeaders, rowIndex, data, DMatrix.SparseType.CSC, numRow);

* You may also load your data from a dense matrix. Let's assume we have a matrix of form

  .. code-block:: none

    1    2
    3    4
    5    6

  Using `row-major layout <https://en.wikipedia.org/wiki/Row-_and_column-major_order>`_, we specify the dense matrix as follows:

  .. code-block:: java

    float[] data = new float[] {1f,2f,3f,4f,5f,6f};
    int nrow = 3;
    int ncol = 2;
    float missing = 0.0f;
    DMatrix dmat = new DMatrix(data, nrow, ncol, missing);

* To set weight:

  .. code-block:: java

    float[] weights = new float[] {1f,2f,1f};
    dmat.setWeight(weights);

******************
Setting Parameters
******************
To set parameters, parameters are specified as a Map:

.. code-block:: java

  Map<String, Object> params = new HashMap<String, Object>() {
    {
      put("eta", 1.0);
      put("max_depth", 2);
      put("objective", "binary:logistic");
      put("eval_metric", "logloss");
    }
  };

**************
Training Model
**************
With parameters and data, you are able to train a booster model.

* Import Booster and XGBoost:

  .. code-block:: java

    import ml.dmlc.xgboost4j.java.Booster;
    import ml.dmlc.xgboost4j.java.XGBoost;

* Training

  .. code-block:: java

    DMatrix trainMat = new DMatrix("train.svm.txt");
    DMatrix validMat = new DMatrix("valid.svm.txt");
    // Specify a watch list to see model accuracy on data sets
    Map<String, DMatrix> watches = new HashMap<String, DMatrix>() {
      {
        put("train", trainMat);
        put("test", testMat);
      }
    };
    int nround = 2;
    Booster booster = XGBoost.train(trainMat, params, nround, watches, null, null);

* Saving model

  After training, you can save model and dump it out.

  .. code-block:: java

    booster.saveModel("model.bin");

* Generaing model dump with feature map

  .. code-block:: java

    // dump without feature map
    String[] model_dump = booster.getModelDump(null, false);
    // dump with feature map
    String[] model_dump_with_feature_map = booster.getModelDump("featureMap.txt", false);

* Load a model

  .. code-block:: java

    Booster booster = XGBoost.loadModel("model.bin");

**********
Prediction
**********
After training and loading a model, you can use it to make prediction for other data. The result will be a two-dimension float array ``(nsample, nclass)``; for ``predictLeaf()``, the result would be of shape ``(nsample, nclass*ntrees)``.

.. code-block:: java

  DMatrix dtest = new DMatrix("test.svm.txt");
  // predict
  float[][] predicts = booster.predict(dtest);
  // predict leaf
  float[][] leafPredicts = booster.predictLeaf(dtest, 0);


text:
#!/usr/bin/env node

/**
 * Clones several projects that are known to follow "JavaScript Standard Style" and runs
 * the `standard` style checker to verify that it passes without warnings. This helps
 * ensure we don't accidentally introduce new style rules that cause previously "good"
 * code to start failing with new warnings! (And if we do, then that needs to be a MAJOR
 * VERSION BUMP.)
 */

var crossSpawn = require('cross-spawn')
var fs = require('fs')
var minimist = require('minimist')
var mkdirp = require('mkdirp')
var os = require('os')
var parallelLimit = require('run-parallel-limit')
var path = require('path')
var standardPackages = require('standard-packages')
var test = require('tape')

var GIT = 'git'
var STANDARD = path.join(__dirname, 'lib', 'standard-cmd.js')
var TMP = path.join(__dirname, '..', 'tmp')
var PARALLEL_LIMIT = os.cpus().length

var argv = minimist(process.argv.slice(2), {
  boolean: [
    'disabled',
    'offline',
    'quick',
    'quiet'
  ]
})

var testPackages = argv.quick
  ? standardPackages.test.slice(0, 20)
  : standardPackages.test

testPackages.push({
  name: 'standard',
  repo: 'https://github.com/feross/standard'
})

var disabledPackages = []
testPackages = testPackages.filter(function (pkg) {
  if (pkg.disable) disabledPackages.push(pkg)
  return !pkg.disable
})

if (argv.disabled) {
  testPackages = disabledPackages
} else {
  test('Disabled Packages', function (t) {
    if (disabledPackages.length === 0) {
      t.pass('no disabled packages')
      t.end()
    } else {
      t.plan(disabledPackages.length)
      disabledPackages.forEach(function (pkg) {
        t.pass('DISABLED: ' + pkg.name + ': ' + pkg.disable + ' (' + pkg.repo + ')')
      })
    }
  })
}

test('test github repos that use `standard`', function (t) {
  t.plan(testPackages.length)

  mkdirp.sync(TMP)

  parallelLimit(testPackages.map(function (pkg) {
    var name = pkg.name
    var url = pkg.repo + '.git'
    var folder = path.join(TMP, name)
    return function (cb) {
      fs.access(path.join(TMP, name), fs.R_OK | fs.W_OK, function (err) {
        if (argv.offline) {
          if (err) {
            t.pass('SKIPPING (offline): ' + name + ' (' + pkg.repo + ')')
            return cb(null)
          }
          runStandard(cb)
        } else {
          downloadPackage(function (err) {
            if (err) return cb(err)
            runStandard(cb)
          })
        }

        function downloadPackage (cb) {
          if (err) gitClone(cb)
          else gitPull(cb)
        }

        function gitClone (cb) {
          var args = [ 'clone', '--depth', 1, url, path.join(TMP, name) ]
          spawn(GIT, args, { stdio: 'ignore' }, function (err) {
            if (err) err.message += ' (git clone) (' + name + ')'
            cb(err)
          })
        }

        function gitPull (cb) {
          var args = [ 'pull' ]
          spawn(GIT, args, { cwd: folder, stdio: 'ignore' }, function (err) {
            if (err) err.message += ' (git pull) (' + name + ')'
            cb(err)
          })
        }

        function runStandard (cb) {
          var args = [ '--verbose' ]
          if (pkg.args) args.push.apply(args, pkg.args)
          spawn(STANDARD, args, { cwd: folder }, function (err) {
            var str = name + ' (' + pkg.repo + ')'
            if (err) { t.fail(str) } else { t.pass(str) }
            cb(null)
          })
        }
      })
    }
  }), PARALLEL_LIMIT, function (err) {
    if (err) throw err
  })
})

function spawn (command, args, opts, cb) {
  if (!opts.stdio) opts.stdio = argv.quiet ? 'ignore' : 'inherit'

  var child = crossSpawn(command, args, opts)
  child.on('error', cb)
  child.on('close', function (code) {
    if (code !== 0) return cb(new Error('non-zero exit code: ' + code))
    cb(null)
  })
  return child
}


text:
BEGIN;

ALTER TABLE validez_nacional_solicitud ADD nro_expediente character varying(200);
-------------------------------------

INSERT INTO deltas_sql (numero, app, comentario) VALUES ('125', 'Validez Nacional', 'Número de expediente en Solicitud - #389');

COMMIT;


text:
PROFILES_HOME="/Users/cbrandt/profiles"

if [ "$1" == "" ]; then
	if [ "$PROFILE_CURRENT" != "" ]; then
		echo $PROFILE_CURRENT
	else
		echo "usage profile.sh name"
	fi

else
	source "$PROFILES_HOME/.$1"
	export PROFILE_CURRENT=$1

	# Print which profile is active
	alias pfc='echo $PROFILE_CURRENT'

	# Edit settings of the current profile
	alias pfe='txopen $PROFILES_HOME/.$PROFILE_CURRENT'

	# Open profile specific tmux session
	alias pfl='tmux new-session "tmux source-file $PROFILE_TMUX"'

	alias pfh='cd $PROFILE_HOME'
	alias pfx='cd $PROFILE_EXEC'
fi


text:
///////////////////////////////////////////////////////////
//  SingleTool.as
//  Macromedia ActionScript Implementation of the Class SingleTool
//  Created on:      2016-6-24 下午6:07:30
//  Original author: ww
///////////////////////////////////////////////////////////

/**
	 *
	 * @author ww
	 * @version 1.0
	 *
	 * @created  2016-6-24 下午6:07:30
	 */
	export class SingleTool
	{
		constructor(){
		}
		private static _instance:SingleTool;

		static get I():SingleTool{
			if(!SingleTool._instance){
				SingleTool._instance = new SingleTool();
			}
			return SingleTool._instance;
		}
		static set I(value){
			SingleTool._instance = value;
		}

		private _objDic:any={};
		getArr(sign:string):any[]
		{
			var dic:any;
			dic=this.getTypeDic("Array");
			if(!dic[sign]) dic[sign]=[];
			return dic[sign];
		}
		getObject(sign:string):any
		{
			var dic:any;
			dic=this.getTypeDic("Object");
			if(!dic[sign]) dic[sign]={};
			return dic[sign];
		}
		getByClass(sign:string,clzSign:string,clz:new()=>any):any
		{
			var dic:any;
			dic=this.getTypeDic(clzSign);
			if(!dic[sign]) dic[sign]=new clz();
			return dic[sign];
		}
		getTypeDic(type:string):any
		{
			if(!this._objDic[type]) this._objDic[type]={};
			return this._objDic[type];
		}
	}


text:
namespace {

// This class injects dummy "events" into the GLib loop. When "handled" these
// events can run tasks. This is intended to mock gtk events (the corresponding
// GLib source runs at the same priority).
class EventInjector {
 public:
  EventInjector() : processed_events_(0) {
    source_ = static_cast<Source*>(g_source_new(&SourceFuncs, sizeof(Source)));
    source_->injector = this;
    g_source_attach(source_, NULL);
    g_source_set_can_recurse(source_, TRUE);
  }

  ~EventInjector() {
    g_source_destroy(source_);
    g_source_unref(source_);
  }

  int HandlePrepare() {
    // If the queue is empty, block.
    if (events_.empty())
      return -1;
    base::TimeDelta delta = events_[0].time - base::Time::NowFromSystemTime();
    return std::max(0, static_cast<int>(ceil(delta.InMillisecondsF())));
  }

  bool HandleCheck() {
    if (events_.empty())
      return false;
    return events_[0].time <= base::Time::NowFromSystemTime();
  }

  void HandleDispatch() {
    if (events_.empty())
      return;
    Event event = events_[0];
    events_.erase(events_.begin());
    ++processed_events_;
    if (!event.callback.is_null())
      event.callback.Run();
    else if (!event.task.is_null())
      event.task.Run();
  }

  // Adds an event to the queue. When "handled", executes |callback|.
  // delay_ms is relative to the last event if any, or to Now() otherwise.
  void AddEvent(int delay_ms, const base::Closure& callback) {
    AddEventHelper(delay_ms, callback, base::Closure());
  }

  void AddDummyEvent(int delay_ms) {
    AddEventHelper(delay_ms, base::Closure(), base::Closure());
  }

  void AddEventAsTask(int delay_ms, const base::Closure& task) {
    AddEventHelper(delay_ms, base::Closure(), task);
  }

  void Reset() {
    processed_events_ = 0;
    events_.clear();
  }

  int processed_events() const { return processed_events_; }

 private:
  struct Event {
    base::Time time;
    base::Closure callback;
    base::Closure task;
  };

  struct Source : public GSource {
    EventInjector* injector;
  };

  void AddEventHelper(
      int delay_ms, const base::Closure& callback, const base::Closure& task) {
    base::Time last_time;
    if (!events_.empty())
      last_time = (events_.end()-1)->time;
    else
      last_time = base::Time::NowFromSystemTime();

    base::Time future = last_time + base::TimeDelta::FromMilliseconds(delay_ms);
    EventInjector::Event event = {future, callback, task};
    events_.push_back(event);
  }

  static gboolean Prepare(GSource* source, gint* timeout_ms) {
    *timeout_ms = static_cast<Source*>(source)->injector->HandlePrepare();
    return FALSE;
  }

  static gboolean Check(GSource* source) {
    return static_cast<Source*>(source)->injector->HandleCheck();
  }

  static gboolean Dispatch(GSource* source,
                           GSourceFunc unused_func,
                           gpointer unused_data) {
    static_cast<Source*>(source)->injector->HandleDispatch();
    return TRUE;
  }

  Source* source_;
  std::vector<Event> events_;
  int processed_events_;
  static GSourceFuncs SourceFuncs;
  DISALLOW_COPY_AND_ASSIGN(EventInjector);
};

GSourceFuncs EventInjector::SourceFuncs = {
  EventInjector::Prepare,
  EventInjector::Check,
  EventInjector::Dispatch,
  NULL
};

void IncrementInt(int *value) {
  ++*value;
}

// Checks how many events have been processed by the injector.
void ExpectProcessedEvents(EventInjector* injector, int count) {
  EXPECT_EQ(injector->processed_events(), count);
}

// Posts a task on the current message loop.
void PostMessageLoopTask(const tracked_objects::Location& from_here,
                         const base::Closure& task) {
  MessageLoop::current()->PostTask(from_here, task);
}

// Test fixture.
class MessagePumpGLibTest : public testing::Test {
 public:
  MessagePumpGLibTest() : loop_(NULL), injector_(NULL) { }

  virtual void SetUp() {
    loop_ = new MessageLoop(MessageLoop::TYPE_UI);
    injector_ = new EventInjector();
  }

  virtual void TearDown() {
    delete injector_;
    injector_ = NULL;
    delete loop_;
    loop_ = NULL;
  }

  MessageLoop* loop() const { return loop_; }
  EventInjector* injector() const { return injector_; }

 private:
  MessageLoop* loop_;
  EventInjector* injector_;
  DISALLOW_COPY_AND_ASSIGN(MessagePumpGLibTest);
};

}  // namespace

TEST_F(MessagePumpGLibTest, TestQuit) {
  // Checks that Quit works and that the basic infrastructure is working.

  // Quit from a task
  loop()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
  loop()->Run();
  EXPECT_EQ(0, injector()->processed_events());

  injector()->Reset();
  // Quit from an event
  injector()->AddEvent(0, MessageLoop::QuitClosure());
  loop()->Run();
  EXPECT_EQ(1, injector()->processed_events());
}

TEST_F(MessagePumpGLibTest, TestEventTaskInterleave) {
  // Checks that tasks posted by events are executed before the next event if
  // the posted task queue is empty.
  // MessageLoop doesn't make strong guarantees that it is the case, but the
  // current implementation ensures it and the tests below rely on it.
  // If changes cause this test to fail, it is reasonable to change it, but
  // TestWorkWhileWaitingForEvents and TestEventsWhileWaitingForWork have to be
  // changed accordingly, otherwise they can become flaky.
  injector()->AddEventAsTask(0, base::Bind(&base::DoNothing));
  base::Closure check_task =
      base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 2);
  base::Closure posted_task =
      base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
  injector()->AddEventAsTask(0, posted_task);
  injector()->AddEventAsTask(0, base::Bind(&base::DoNothing));
  injector()->AddEvent(0, MessageLoop::QuitClosure());
  loop()->Run();
  EXPECT_EQ(4, injector()->processed_events());

  injector()->Reset();
  injector()->AddEventAsTask(0, base::Bind(&base::DoNothing));
  check_task =
      base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 2);
  posted_task = base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
  injector()->AddEventAsTask(0, posted_task);
  injector()->AddEventAsTask(10, base::Bind(&base::DoNothing));
  injector()->AddEvent(0, MessageLoop::QuitClosure());
  loop()->Run();
  EXPECT_EQ(4, injector()->processed_events());
}

TEST_F(MessagePumpGLibTest, TestWorkWhileWaitingForEvents) {
  int task_count = 0;
  // Tests that we process tasks while waiting for new events.
  // The event queue is empty at first.
  for (int i = 0; i < 10; ++i) {
    loop()->PostTask(FROM_HERE, base::Bind(&IncrementInt, &task_count));
  }
  // After all the previous tasks have executed, enqueue an event that will
  // quit.
  loop()->PostTask(
      FROM_HERE,
      base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 0,
                 MessageLoop::QuitClosure()));
  loop()->Run();
  ASSERT_EQ(10, task_count);
  EXPECT_EQ(1, injector()->processed_events());

  // Tests that we process delayed tasks while waiting for new events.
  injector()->Reset();
  task_count = 0;
  for (int i = 0; i < 10; ++i) {
    loop()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&IncrementInt, &task_count),
        base::TimeDelta::FromMilliseconds(10*i));
  }
  // After all the previous tasks have executed, enqueue an event that will
  // quit.
  // This relies on the fact that delayed tasks are executed in delay order.
  // That is verified in message_loop_unittest.cc.
  loop()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&EventInjector::AddEvent, base::Unretained(injector()), 10,
                 MessageLoop::QuitClosure()),
      base::TimeDelta::FromMilliseconds(150));
  loop()->Run();
  ASSERT_EQ(10, task_count);
  EXPECT_EQ(1, injector()->processed_events());
}

TEST_F(MessagePumpGLibTest, TestEventsWhileWaitingForWork) {
  // Tests that we process events while waiting for work.
  // The event queue is empty at first.
  for (int i = 0; i < 10; ++i) {
    injector()->AddDummyEvent(0);
  }
  // After all the events have been processed, post a task that will check that
  // the events have been processed (note: the task executes after the event
  // that posted it has been handled, so we expect 11 at that point).
  base::Closure check_task =
      base::Bind(&ExpectProcessedEvents, base::Unretained(injector()), 11);
  base::Closure posted_task =
      base::Bind(&PostMessageLoopTask, FROM_HERE, check_task);
  injector()->AddEventAsTask(10, posted_task);

  // And then quit (relies on the condition tested by TestEventTaskInterleave).
  injector()->AddEvent(10, MessageLoop::QuitClosure());
  loop()->Run();

  EXPECT_EQ(12, injector()->processed_events());
}

namespace {

// This class is a helper for the concurrent events / posted tasks test below.
// It will quit the main loop once enough tasks and events have been processed,
// while making sure there is always work to do and events in the queue.
class ConcurrentHelper : public base::RefCounted<ConcurrentHelper>  {
 public:
  explicit ConcurrentHelper(EventInjector* injector)
      : injector_(injector),
        event_count_(kStartingEventCount),
        task_count_(kStartingTaskCount) {
  }

  void FromTask() {
    if (task_count_ > 0) {
      --task_count_;
    }
    if (task_count_ == 0 && event_count_ == 0) {
        MessageLoop::current()->Quit();
    } else {
      MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, this));
    }
  }

  void FromEvent() {
    if (event_count_ > 0) {
      --event_count_;
    }
    if (task_count_ == 0 && event_count_ == 0) {
        MessageLoop::current()->Quit();
    } else {
      injector_->AddEventAsTask(
          0, base::Bind(&ConcurrentHelper::FromEvent, this));
    }
  }

  int event_count() const { return event_count_; }
  int task_count() const { return task_count_; }

 private:
  friend class base::RefCounted<ConcurrentHelper>;

  ~ConcurrentHelper() {}

  static const int kStartingEventCount = 20;
  static const int kStartingTaskCount = 20;

  EventInjector* injector_;
  int event_count_;
  int task_count_;
};

}  // namespace

TEST_F(MessagePumpGLibTest, TestConcurrentEventPostedTask) {
  // Tests that posted tasks don't starve events, nor the opposite.
  // We use the helper class above. We keep both event and posted task queues
  // full, the helper verifies that both tasks and events get processed.
  // If that is not the case, either event_count_ or task_count_ will not get
  // to 0, and MessageLoop::Quit() will never be called.
  scoped_refptr<ConcurrentHelper> helper = new ConcurrentHelper(injector());

  // Add 2 events to the queue to make sure it is always full (when we remove
  // the event before processing it).
  injector()->AddEventAsTask(
      0, base::Bind(&ConcurrentHelper::FromEvent, helper.get()));
  injector()->AddEventAsTask(
      0, base::Bind(&ConcurrentHelper::FromEvent, helper.get()));

  // Similarly post 2 tasks.
  loop()->PostTask(
      FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));
  loop()->PostTask(
      FROM_HERE, base::Bind(&ConcurrentHelper::FromTask, helper.get()));

  loop()->Run();
  EXPECT_EQ(0, helper->event_count());
  EXPECT_EQ(0, helper->task_count());
}

namespace {

void AddEventsAndDrainGLib(EventInjector* injector) {
  // Add a couple of dummy events
  injector->AddDummyEvent(0);
  injector->AddDummyEvent(0);
  // Then add an event that will quit the main loop.
  injector->AddEvent(0, MessageLoop::QuitClosure());

  // Post a couple of dummy tasks
  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&base::DoNothing));
  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&base::DoNothing));

  // Drain the events
  while (g_main_context_pending(NULL)) {
    g_main_context_iteration(NULL, FALSE);
  }
}

}  // namespace

TEST_F(MessagePumpGLibTest, TestDrainingGLib) {
  // Tests that draining events using GLib works.
  loop()->PostTask(
      FROM_HERE,
      base::Bind(&AddEventsAndDrainGLib, base::Unretained(injector())));
  loop()->Run();

  EXPECT_EQ(3, injector()->processed_events());
}

namespace {

#if defined(TOOLKIT_USES_GTK)
void AddEventsAndDrainGtk(EventInjector* injector) {
  // Add a couple of dummy events
  injector->AddDummyEvent(0);
  injector->AddDummyEvent(0);
  // Then add an event that will quit the main loop.
  injector->AddEvent(0, MessageLoop::QuitClosure());

  // Post a couple of dummy tasks
  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&base::DoNothing));
  MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&base::DoNothing));

  // Drain the events
  while (gtk_events_pending()) {
    gtk_main_iteration();
  }
}
#endif

}  // namespace

#if defined(TOOLKIT_USES_GTK)
TEST_F(MessagePumpGLibTest, TestDrainingGtk) {
  // Tests that draining events using Gtk works.
  loop()->PostTask(
      FROM_HERE,
      base::Bind(&AddEventsAndDrainGtk, base::Unretained(injector())));
  loop()->Run();

  EXPECT_EQ(3, injector()->processed_events());
}
#endif

namespace {

// Helper class that lets us run the GLib message loop.
class GLibLoopRunner : public base::RefCounted<GLibLoopRunner> {
 public:
  GLibLoopRunner() : quit_(false) { }

  void RunGLib() {
    while (!quit_) {
      g_main_context_iteration(NULL, TRUE);
    }
  }

  void RunLoop() {
#if defined(TOOLKIT_USES_GTK)
    while (!quit_) {
      gtk_main_iteration();
    }
#else
    while (!quit_) {
      g_main_context_iteration(NULL, TRUE);
    }
#endif
  }

  void Quit() {
    quit_ = true;
  }

  void Reset() {
    quit_ = false;
  }

 private:
  friend class base::RefCounted<GLibLoopRunner>;

  ~GLibLoopRunner() {}

  bool quit_;
};

void TestGLibLoopInternal(EventInjector* injector) {
  // Allow tasks to be processed from 'native' event loops.
  MessageLoop::current()->SetNestableTasksAllowed(true);
  scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();

  int task_count = 0;
  // Add a couple of dummy events
  injector->AddDummyEvent(0);
  injector->AddDummyEvent(0);
  // Post a couple of dummy tasks
  MessageLoop::current()->PostTask(
      FROM_HERE, base::Bind(&IncrementInt, &task_count));
  MessageLoop::current()->PostTask(
      FROM_HERE, base::Bind(&IncrementInt, &task_count));
  // Delayed events
  injector->AddDummyEvent(10);
  injector->AddDummyEvent(10);
  // Delayed work
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&IncrementInt, &task_count),
      base::TimeDelta::FromMilliseconds(30));
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&GLibLoopRunner::Quit, runner.get()),
      base::TimeDelta::FromMilliseconds(40));

  // Run a nested, straight GLib message loop.
  runner->RunGLib();

  ASSERT_EQ(3, task_count);
  EXPECT_EQ(4, injector->processed_events());
  MessageLoop::current()->Quit();
}

void TestGtkLoopInternal(EventInjector* injector) {
  // Allow tasks to be processed from 'native' event loops.
  MessageLoop::current()->SetNestableTasksAllowed(true);
  scoped_refptr<GLibLoopRunner> runner = new GLibLoopRunner();

  int task_count = 0;
  // Add a couple of dummy events
  injector->AddDummyEvent(0);
  injector->AddDummyEvent(0);
  // Post a couple of dummy tasks
  MessageLoop::current()->PostTask(
      FROM_HERE, base::Bind(&IncrementInt, &task_count));
  MessageLoop::current()->PostTask(
      FROM_HERE, base::Bind(&IncrementInt, &task_count));
  // Delayed events
  injector->AddDummyEvent(10);
  injector->AddDummyEvent(10);
  // Delayed work
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&IncrementInt, &task_count),
      base::TimeDelta::FromMilliseconds(30));
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&GLibLoopRunner::Quit, runner.get()),
      base::TimeDelta::FromMilliseconds(40));

  // Run a nested, straight Gtk message loop.
  runner->RunLoop();

  ASSERT_EQ(3, task_count);
  EXPECT_EQ(4, injector->processed_events());
  MessageLoop::current()->Quit();
}

}  // namespace

TEST_F(MessagePumpGLibTest, TestGLibLoop) {
  // Tests that events and posted tasks are correctly executed if the message
  // loop is not run by MessageLoop::Run() but by a straight GLib loop.
  // Note that in this case we don't make strong guarantees about niceness
  // between events and posted tasks.
  loop()->PostTask(
      FROM_HERE,
      base::Bind(&TestGLibLoopInternal, base::Unretained(injector())));
  loop()->Run();
}

TEST_F(MessagePumpGLibTest, TestGtkLoop) {
  // Tests that events and posted tasks are correctly executed if the message
  // loop is not run by MessageLoop::Run() but by a straight Gtk loop.
  // Note that in this case we don't make strong guarantees about niceness
  // between events and posted tasks.
  loop()->PostTask(
      FROM_HERE,
      base::Bind(&TestGtkLoopInternal, base::Unretained(injector())));
  loop()->Run();
}


text:
This is a simple blynk HTTP/HTTPS API wrapper.

### Introduction
This library created for simple using [Blynk API](http://docs.blynkapi.apiary.io/#reference/0/pin-actions) and manage your project via python. It's simple one class lib which used `urllib2` for requests.

You can also:
  - Read/write pin value
  - Check hardware network status
  - Check application network status
  - Send push notification
  - Send email
  - Get pin history data
  - Get QR for project cloning
  - Get project info
  - Query API

### Installation

Install via pip
```bash
pip install blynkapi
```
after installation import it in your code
```python
from blynkapi import Blynk
```

Or simple copy `blynkapi/Blynk.py` to your main python program dir and import it
```python
from Blynk import *
```

### Using
```python
# if you install it from pip, else use `from Blynk import *`
from blynkapi import Blynk
# vars
auth_token = "sdjflksjflkdsjfkldsjfkldfkldjflk"

# create objects
room_light = Blynk(auth_token, pin = "V3")
kitchen_light = Blynk(auth_token, pin = "V4")
house_door = Blynk(auth_token, pin = "V5")
amp_power = Blynk(auth_token, pin = "V6")

# get current status
res = room_light.get_val()
print res

# set pin value (one)
amp_power.set_val(["120"])

# set pin value to 1
room_light.on()
# set pin value to 0
room_light.off()
```

### Available methods

All methods return values from API or error if it fixed. For detailed description of returning values and scheme read official [Blynk API guide] (http://docs.blynkapi.apiary.io/#reference)

Creating main object
```python
Blynk(token, server, protocol, port, pin, value)
```
  - `token` - Your project token
  - `server` - Blynk server for API requests, default "blynk-cloud.com"
  - `protocol` - http or https, default "http"
  - `port` - Your Blynk server API port, default "8080"
  - `pin` - Pin for working with, default "None"
  - `value` - Value for method get_val, default "None"

To turn pin on (set val "1" to pin)
```python
on()
```

To turn pin off (set val "0" to pin)
```python
off()
```

To set your value for pin
```python
set_val(value)
```
  - `value` - Custom value in list ["x"] or multiple values in list ["x", "y"]. [Details] (http://docs.blynkapi.apiary.io/#reference/0/write-pin-value-via-put/write-pin-value-via-put)

To get data from pin
```python
get_val()
```

Send push notification
```python
push(value)
```
  - `value` - String no more than 255 chars.

Send email
```python
email(to, title, subj)
```
  - `to` - String
  - `title` - String
  - `subj` - String

Check hardware status (connection to server)
```python
hw_status()
```

Check app status (connection to server)
```python
app_status()
```

Get pin history
```python
history()
```

Get QR image
```python
qr()
```

Get project info For details see [docs] (http://docs.blynkapi.apiary.io/#reference/0/get-project/get-project)
```python
get_project()
```

Query API. For details see [docs] (http://docs.blynkapi.apiary.io/#reference/0/query-api/query-api)
```python
query_api(groupBy, aggregation, pin, value)
```
  - `groupBy` - String
  - `aggregation` - String
  - `pin` - String
  - `value` - String

### Todos

 - Write Tests

License
----

MIT


text:
@interface FavoriteAppsTableViewController : UITableViewController

- (IBAction)editButtonAction:(id)sender;
- (IBAction)addButtonAction:(id)sender;
@end


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-travis]][link-travis]
[![Coverage Status][ico-scrutinizer]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]

This is where your description should go. Try and limit it to a paragraph or two, and maybe throw in a mention of what
PSRs you support to avoid any confusion with users and contributors.

## Install

Via Composer

``` bash
$ composer require acacha/profile
```

## Usage

``` php
$skeleton = new League\Skeleton();
echo $skeleton->echoPhrase('Hello, League!');
```

```
php artisan vendor:publish --tag=acacha-profile --force
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Security

If you discover any security related issues, please email sergiturbadenas@gmail.com instead of using the issue tracker.

## Credits

- [Sergi Tur Badenas][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/acacha/profile.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/acacha/profile/master.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/acacha/profile.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/acacha/profile.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/acacha/profile.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/acacha/profile
[link-travis]: https://travis-ci.org/acacha/profile
[link-scrutinizer]: https://scrutinizer-ci.com/g/acacha/profile/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/acacha/profile
[link-downloads]: https://packagist.org/packages/acacha/profile
[link-author]: https://github.com/acacha
[link-contributors]: ../../contributors


text:
using System.Collections.Generic;
using Microsoft.Xml;

namespace System.Runtime.Serialization
{
    /// <summary>
    /// Dummy documentation
    /// </summary>
    public class DataContractSerializerSettings
    {
        private int _maxItemsInObjectGraph = int.MaxValue;

        /// <summary>
        /// Gets or sets Dummy documentation
        /// </summary>
        public XmlDictionaryString RootName { get; set; }

        /// <summary>
        /// Gets or sets Dummy documentation
        /// </summary>
        public XmlDictionaryString RootNamespace { get; set; }

        /// <summary>
        /// Gets or sets Dummy documentation
        /// </summary>
        public IEnumerable<Type> KnownTypes { get; set; }

        /// <summary>
        /// Gets or sets Dummy documentation
        /// </summary>
        public int MaxItemsInObjectGraph
        {
            get { return _maxItemsInObjectGraph; }
            set { _maxItemsInObjectGraph = value; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether Dummy documentation
        /// </summary>
        public bool PreserveObjectReferences { get; set; }

        /// <summary>
        /// Gets or sets Dummy documentation
        /// </summary>
        public DataContractResolver DataContractResolver { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether Dummy documentation
        /// </summary>
        public bool SerializeReadOnlyTypes { get; set; }
    }
}


text:
var keystone = require('keystone');
var User = keystone.list('User');
var sanitizer = require('sanitizer');

exports = module.exports = function (req, res) {

  // If no one's logged in, disallow all of this
  if (!req.user) {
    return res.redirect('/account/log-in');
  }

  var view = new keystone.View(req, res);
  var locals = res.locals;
  locals.section = 'account';
  locals.formData = req.body || {};

  // sanitize form data for obvious reasons
  for (var key in locals.formData) {
    // skip loop if the property is from prototype
    if (!locals.formData.hasOwnProperty(key)) continue;
    if (typeof locals.formData[key] === 'string') {
      locals.formData[key] = sanitizer.sanitize(locals.formData[key]);
    }
  }

  // Turn off ads on this page
  locals.hideAds = true;

  view.on('init', function(next) {
    // Look up currently logged in user
    User.model.findOne().where('_id', req.user.id).exec(function(err, user) {
      if (err) {
        return next(err);
      }
      if (!user) {
        req.flash('error', { detail: 'Sorry, something went wrong while trying to update your profile. Please try again. Error #2' });
        return res.redirect('/account/profile');
      }

      locals.found = user;
      next();
    });

  });

  view.on('init', function(next) {
    // catch username conflicts
    User.model.findOne().where('userName', new RegExp(locals.formData.userUsername, 'i')).exec(function(err, foundUser) {
      locals.dupeUsername = false;
      if (err) {
        console.log(err);
        return next(err);
      }
      if (!foundUser) {
        return next();
      }
      if (foundUser.id != req.user.id) {
        locals.dupeUsername = true;
      }
      next();
    });
  });

  view.on('post', { action: 'edit-profile' }, function(next) {
    // Redirect dupes
    if (locals.dupeUsername) {
      req.flash('error', { detail: 'Sorry, that username already exists. Please try another one.' });
      return next();
    }

    // Build our user (ignoring blank required inputs by using saved values)
    locals.found.name.first =locals.formData.userFirstName || locals.found.name.first;
    locals.found.name.last = locals.formData.userLastName || locals.found.name.last;
    locals.found.userName = locals.formData.userUsername || locals.found.userName;
    locals.found.location = locals.formData.userLocation;
    locals.found.website = addhttp(locals.formData.userWebsite);
    locals.found.twitterUsername = removeAtSign(locals.formData.userTwitter);

    locals.found.save(function(err) {
      if (err) {
        req.flash('error', { detail: 'Sorry, something went wrong while trying to update your profile. Please try again. Error #4' });
        res.redirect('/account/profile');
      }
      req.flash('success', { detail: 'Changes Made!' });
      res.redirect('/account/profile');
    });

  });

  view.render('account/profile');

};

function addhttp(url) {
   if (url && !/^(f|ht)tps?:\/\//i.test(url)) {
      url = "http://" + url;
   }
   return url;
}

function removeAtSign(str) {
  if (str.charAt(0) === '@') {
    return str.slice(1, str.length);
  }
  return str
}


text:
Example of controller

```php
<?php

namespace Controller;

class ClientController
{
	protected $app;

	public function __construct(\Celtic\Application $app)
	{
		$this->app = $app;
	}

	public function index()
	{
		$results = $this->app->client->query();
		return $this->app->json($results);
	}

	public function view($id)
	{
		$result = $this->app->client->get($id);
		return $this->app->json($result);
	}

	public function add()
	{
		$form = $this->app->request;

		$result = $this->app->client->insert(
			$form->input('Name'),
			$form->input('Email')
		);

		if(!$result)
			throw new ValidationException('Error on save');

		return $this->app->json($result);
	}

	public function edit($id)
	{
		$form = $this->app->request;

		$result = $this->app->client->update(
			$id,
			$form->input('Name'),
			$form->input('Email')
		);

		if(!$result)
			throw new ValidationException('Error on save');

		return $this->app->json($result);
	}

	public function delete($id)
	{
		$result = $this->app->client->delete($id);
		if(!$result)
			throw new ValidationException('Error on delete');

		return $this->app->json($result);
	}
}
```

### Error Controller

Example

```php
<?php

namespace Controller;

class ErrorController
{
	protected $app;

	public function __construct(\Celtic\Application $app)
	{
		$this->app = $app;
	}

	public function json($code, $message)
	{
		$errors = [];
		$errors[400] = 'Bad Request';
		$errors[401] = 'Unauthorized';
		$errors[402] = 'Payment Required';
		$errors[403] = 'Forbidden';
		$errors[404] = 'Not Found';
		$errors[405] = 'Method Not Allowed';
		$errors[408] = 'Request Timeout';
		$errors[500] = 'Internal Server Error';

		header('HTTP/1.1 ' . $code . ' ' . $errors[$code]);
		$result = new \stdClass;
		$result->Code = $code;
		$result->Error = $message;

		return $app->json($result);
	}
}
```


text:
package com.wakaleo.gameoflife.webtests;

import com.wakaleo.gameoflife.webtests.requirements.GameOfLifeApplication;
import com.wakaleo.gameoflife.webtests.steps.PlayerSteps;
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.ManagedPages;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Story;
import net.thucydides.core.annotations.WithTag;
import net.thucydides.core.pages.Pages;
import net.thucydides.junit.runners.ThucydidesRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;

@RunWith(ThucydidesRunner.class)

@WithTag("Configuring a simulation")
public class WhenTheUserSpawnsTheNextGeneration {

    @Managed(uniqueSession = true)
    WebDriver driver;

    @ManagedPages(defaultUrl = "http://localhost:9090")
    public Pages pages;

    @Steps
    PlayerSteps player;

    final static String[][] EMPTY_GRID
            = new String[][]{{".", ".", "."},
            {".", ".", "."},
            {".", ".", "."}};

    @Test
    public void anEmptyGridShouldProduceAnEmptyGrid() {
        String[][] expectedGrid = new String[][]{{".", ".", "."},
                {".", ".", "."},
                {".", ".", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.starts_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);

    }

    @Test
    public void aGridWithOneCellShouldProduceAnEmptyGrid() {
        String[][] expectedGrid = new String[][]{{".", ".", "."},
                {".", ".", "."},
                {".", ".", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(1, 1);
        player.starts_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

    @Test
    public void aGridWithTwoCellsShouldProduceAnEmptyGrid() {
        String[][] expectedGrid = new String[][]{{".", ".", "."},
                {".", ".", "."},
                {".", ".", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(1, 1);
        player.clicks_on_cell_at(0, 1);
        player.starts_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

    @Test
    public void aStableCellSetShouldProduceTheSameSetOfCells() {
        String[][] expectedGrid = new String[][]{{"*", "*", "."},
                {"*", "*", "."},
                {".", ".", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(0, 0);
        player.clicks_on_cell_at(0, 1);
        player.clicks_on_cell_at(1, 0);
        player.clicks_on_cell_at(1, 1);
        player.starts_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

    @Test
    public void aRotatingCellSetShouldProduceTheExpectedNewSetOfCells() {
        String[][] expectedGrid = new String[][]{{".", ".", "."},
                {".", "*", "."},
                {".", "*", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(0, 0);
        player.clicks_on_cell_at(0, 1);
        player.clicks_on_cell_at(1, 0);
        player.clicks_on_cell_at(1, 1);
        player.clicks_on_cell_at(1, 2);
        player.starts_simulation();
        player.continues_simulation();
        player.continues_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

    @Test
    public void aRotatingCellSetShouldProduceTheOriginalSetOfCellsAfterTwoGenerations() {
        String[][] expectedGrid = new String[][]{{".", ".", "."},
                {"*", "*", "*"},
                {".", ".", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(1, 0);
        player.clicks_on_cell_at(1, 1);
        player.clicks_on_cell_at(1, 2);
        player.starts_simulation();
        player.continues_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

    @Test
    public void aRotatingCellSetShouldProduceTheOriginalSetOfCellsAfterThreeGenerations() {
        String[][] expectedGrid = new String[][]{{".", "*", "."},
                {".", "*", "."},
                {".", "*", "."}};

        player.opens_home_page();
        player.chooses_to_start_a_new_game();
        player.clicks_on_cell_at(1, 0);
        player.clicks_on_cell_at(1, 1);
        player.clicks_on_cell_at(1, 2);
        player.starts_simulation();
        player.continues_simulation();
        player.continues_simulation();
        player.continues_simulation();
        player.should_see_grid(expectedGrid);
    }

}


text:
import { node } from 'vidom';

import { inject } from 'example/store.js'

import {
  decrement
} from 'example/actions/counter.js';

export default inject(({ dispatch }) => {
  return node('button').attrs({onClick: (ev) => dispatch(decrement()), style: { height: '20px' }}).children('decrement');
});


text:
from django.shortcuts import redirect, get_object_or_404
from django.template import RequestContext, loader
from django.http import HttpResponse

from mig_main.utility import get_previous_page, Permissions, get_message_dict
from mig_main import messages
from mig_main.models import AcademicTerm
from bookswap.models import BookSwapPerson, BookSwapStatus, BookType, Book
from bookswap.forms import (
        StartTransactionForm,
        BookSwapPersonForm,
        BookSwapPersonFormNoProfile,
        BookSearchForm,
        BookTypeForm,
        ReceiveBookForm,
)
def get_permissions(user):
    return {
        'can_process':Permissions.can_process_bookswap(user),
    }

def get_common_context(request):
    context_dict = get_message_dict(request)
    context_dict.update({
        'main_nav': 'bookswap',
    })
    return context_dict

# Create your views here.
# These are for the admin site part
def admin_index(request):
    template = loader.get_template('bookswap/bookswap_admin_index.html')
    context_dict = {}
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))

def start_transaction(request):
    """ Just a simple form to receive the barcode, uniqname, or UMID
    Looks up the buyer or seller, redirects to form to confirm information
    """
    if not Permissions.can_process_bookswap(request.user): # TODO: create permission logic
        request.session['error_message'] = messages.BOOKSWAP_NO_PERM
        return get_previous_page(request, alternate='bookswap:admin_index')
    form = StartTransactionForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            user = form.get_user()
            uniqname = ''
            if user:
                request.session['success_message'] = ('User found, please '
                                                      'confirm details.')
                request.session['had_profile'] = True
                uniqname = user.user_profile.uniqname
                request.session['uniqname'] = uniqname
            else:
                request.session['error_message'] = ('User not found, please '
                                                    'create now.')
                request.session['UMID'] = form.cleaned_data['user_UMID']
                request.session['uniqname'] = form.cleaned_data['user_uniqname']
                request.session['barcode'] = form.cleaned_data['user_barcode']
                request.session['had_profile'] = False
            return redirect('bookswap:update_person')
        else:
            request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR
    template = loader.get_template('generic_form.html')
    context_dict = {
        'form': form,
        'subnav': 'admin',
        'has_files': False,
        'submit_name': 'Search for user',
        'form_title': 'Search for a user in the system',
        'help_text': ('You can search for a user by UMID, uniqname, or the '
                      'barcode on their MCard.'),
        'base': 'bookswap/base_bookswap.html',
        }
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))

def update_person(request):
    """ If person exists, pre-fill information
    If person has profile but not BS profile, pre-fill some of it, and on
    submit link together
    If person has nothing, will need to create and link everything on submit
    """
    if not Permissions.can_process_bookswap(request.user):
        request.session['error_message'] = messages.BOOKSWAP_NO_PERM
        return get_previous_page(request, alternate='bookswap:admin_index')
    had_profile = request.session.pop('had_profile', False)
    uniqname = request.session.pop('uniqname', '')
    if had_profile:
        bsp = BookSwapPerson.objects.get(user_profile__uniqname=uniqname)
        form = BookSwapPersonForm(request.POST or None, instance=bsp)
    else:
        initial = {
            'UMID': request.session.pop('UMID', ''),
            'uniqname': uniqname,
            'barcode': request.session.pop('barcode', ''),
        }
        form = BookSwapPersonFormNoProfile(request.POST or None, initial=initial)

    if request.method == 'POST':
        if form.is_valid():
            bsp = form.save()
            uniqname = bsp.user_profile.uniqname
            request.session['success_message'] = ('User created/updated.')
            if BookSwapStatus.can_receive(AcademicTerm.get_current_term()):
                return redirect('bookswap:receive_book_start', uniqname=uniqname)
            elif BookSwapStatus.can_sell(AcademicTerm.get_current_term()):
                return redirect('bookswap:sell_book_start', uniqname=uniqname)
            else:
                request.session['info_message'] = ('Book Swap not open for '
                                                   'receiving or selling')
                return redirect('bookswap:admin_index')
        else:
            request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR
            request.session['had_profile'] = had_profile
            request.session['uniqname'] = uniqname
    else:
        request.session['had_profile'] = had_profile
        request.session['uniqname'] = uniqname
    template = loader.get_template('generic_form.html')
    context_dict = {
        'form': form,
        'subnav': 'admin',
        'has_files': False,
        'submit_name': 'Create/update user',
        'form_title': 'Create/update the user information',
        'help_text': ('Please confirm that the following is correct and '
                      'update as necessary. Note that for sellers an address '
                      'is required.'),
        'base': 'bookswap/base_bookswap.html',
        }
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))

def receive_book_start(request, uniqname):
    """ Just show a form for the barcode
    On submit looks up the book type, if present redirects to receive_book
    If not saves the uniqname into request.session and redirects to
    create_book_type
    """
    if not Permissions.can_process_bookswap(request.user):
        request.session['error_message'] = messages.BOOKSWAP_NO_PERM
        return get_previous_page(request, alternate='bookswap:admin_index')
    if not BookSwapStatus.can_receive(AcademicTerm.get_current_term()):
        request.session['error_message'] = 'Book receiving not enabled'
        return get_previous_page(request, alternate='bookswap:admin_index')
    form = BookSearchForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            barcode = form.cleaned_data.get('book_barcode','')
            book_type = BookType.objects.filter(isbn=barcode)
            if book_type.exists():
                # TODO: If multiple give choice?
                book_type = book_type[0]
                request.session['success_message'] = ('Book found, please '
                                                      'enter sale details.')
                return redirect('bookswap:receive_book',
                                uniqname=uniqname,
                                book_type_id=book_type.id)

            else:
                request.session['warning_message'] = ('Book not found, please '
                                                      'enter details.')
                request.session['uniqname'] = uniqname
                request.session['isbn'] = barcode
                return redirect('bookswap:create_book_type')

        else:
            request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR
    template = loader.get_template('generic_form.html')
    context_dict = {
        'form': form,
        'subnav': 'admin',
        'has_files': False,
        'submit_name': 'Search for book by ISBN',
        'form_title': 'Search for a book in the system',
        'help_text': ('You can search for a book by its ISBN, which is the '
                      '13 digit code scanned by the barcode.'),
        'base': 'bookswap/base_bookswap.html',
        }
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))

def create_book_type(request):
    if not Permissions.can_process_bookswap(request.user):
        request.session['error_message'] = messages.BOOKSWAP_NO_PERM
        return get_previous_page(request, alternate='bookswap:admin_index')
    if not BookSwapStatus.can_receive(AcademicTerm.get_current_term()):
        request.session['error_message'] = 'Book receiving not enabled'
        return get_previous_page(request, alternate='bookswap:admin_index')
    isbn = request.session.get('isbn', '')
    form = BookTypeForm(request.POST or None, initial = {'isbn': isbn})
    if request.method == 'POST':
        if form.is_valid():
            book_type = form.save()
            request.session['success_message'] = ('Book type created! '
                                                  'Please continue.')
            uniqname = request.session.pop('uniqname', '')
            request.session.pop('isbn', '')
            if uniqname:
                return redirect('bookswap:receive_book',
                                uniqname=uniqname,
                                book_type_id=book_type.id)
            else:
                return redirect('bookswap:create_book_type')
        else:
            request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR
    template = loader.get_template('generic_form.html')
    context_dict = {
        'form': form,
        'subnav': 'admin',
        'has_files': False,
        'submit_name': 'Create book type',
        'form_title': 'Create a book type',
        'help_text': ('This creates a type of book, not an individual '
                      'physical book to sell.'),
        'base': 'bookswap/base_bookswap.html',
        }
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))

def receive_book(request, uniqname, book_type_id):
    if not Permissions.can_process_bookswap(request.user):
        request.session['error_message'] = messages.BOOKSWAP_NO_PERM
        return get_previous_page(request, alternate='bookswap:admin_index')
    if not BookSwapStatus.can_receive(AcademicTerm.get_current_term()):
        request.session['error_message'] = 'Book receiving not enabled'
        return get_previous_page(request, alternate='bookswap:admin_index')
    book_type = get_object_or_404(BookType, id=book_type_id)
    seller = get_object_or_404(BookSwapPerson, user_profile__uniqname=uniqname)
    instance = Book(
                seller=seller,
                book_type=book_type,
                term=AcademicTerm.get_current_term()
    )
    form = ReceiveBookForm(request.POST or None, instance=instance)
    if request.method == 'POST':
        if form.is_valid():
            book = form.save()
            request.session['success_message'] = ('Book added created! '
                                                  'Please continue.')
            return redirect('bookswap:receive_book_start',
                            uniqname=uniqname)
        else:
            request.session['error_message'] = messages.GENERIC_SUBMIT_ERROR
    template = loader.get_template('generic_form.html')
    context_dict = {
        'form': form,
        'subnav': 'admin',
        'has_files': False,
        'submit_name': 'Receive book',
        'form_title': 'Recieve a copy of: %s for %s' % (book_type.title, uniqname),
        'help_text': ('This receives a specific saleable book.'),
        'base': 'bookswap/base_bookswap.html',
        }
    context_dict.update(get_permissions(request.user))
    context_dict.update(get_common_context(request))
    context = RequestContext(request, context_dict)
    return HttpResponse(template.render(context))
    pass

def sell_book_start(request, uniqname):
    # Check permissions to sell

    # Just show a form for the barcode
    # On submit looks up the book type, redirects with a page to choose which one
    pass

def sell_book(request, uniqname, book_type_id):
    pass

# Should probably be ajax
def sell_individual_book(request,uniqname,book_id):
    pass

def manage_bookswap_settings(request):
    # Check appropriate permissions
    pass

# These are for the public front end
def view_faq(request):
    pass

def view_inventory(request):
    pass

def view_location(request):
    pass

def view_resources(request):
    pass


text:
function albums(){
    var request;
    var desc = new Array();
    var lang=getCookie('lang');
    if(window.XMLHttpRequest)
    {
      request=new XMLHttpRequest();
    } else {
      request=new ActiveXObject("Microsoft,XMLHTTP");
    }
    request.open('GET', 'json/pictures.json');
    request.onreadystatechange = function()
    {
      if((request.readyState===4)&&(request.status===200)){
        var items = JSON.parse(request.responseText);

        number=0;
        for(var key in items.pictureCon)
        {
            for(var key2 in items.pictureCon[key])
            {
                if(items.pictureCon[key][key2].alt){
                    var column = document.createElement('div');
                    var a = document.createElement('a');
                    a.setAttribute('href','fotog.php?udalost='+key);
                    column.setAttribute('class','column');
                    var udalostDiv = document.createElement('div');
                    udalostDiv.setAttribute("class", "udalDiv")
                    var img = document.createElement('img');
                    img.src=items.pictureCon[key][key2].src;
                    img.setAttribute("alt", items.pictureCon[key][key2].alt);
                    img.setAttribute("height", items.pictureCon[key][key2].height);
                    img.setAttribute("width", items.pictureCon[key][key2].width);
                    udalostDiv.appendChild(udalost);
                    a.appendChild(img);
                    a.appendChild(udalostDiv);
                    column.appendChild(a);
                    document.getElementById("row").appendChild(column);
                    break;
                }
                else{
                    if(lang=='sk')
                        udalost=document.createTextNode(items.pictureCon[key][key2].name_sk);
                    else
                        udalost=document.createTextNode(items.pictureCon[key][key2].name_en);
                }
        }

      }
    }
}
request.send();
}
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
function showImages(udalost){
    var request;
    var desc = new Array();
    if(window.XMLHttpRequest)
    {
      request=new XMLHttpRequest();
    } else {
      request=new ActiveXObject("Microsoft,XMLHTTP");
    }
    request.open('GET', 'json/pictures.json');
    request.onreadystatechange = function()
    {
      if((request.readyState===4)&&(request.status===200)){
        var items = JSON.parse(request.responseText);

        var images=document.getElementsByClassName("hover-shadow");

        number=0;
        for(var key in items.pictureCon[udalost])
        {
            if(items.pictureCon[udalost][key].alt){
            number++;
            var column = document.createElement('div');
            column.setAttribute('class','column');
            var img = document.createElement('img');
            img.src=items.pictureCon[udalost][key].src;
            img.setAttribute("alt", items.pictureCon[udalost][key].alt);
            img.setAttribute("height", items.pictureCon[udalost][key].height);
            img.setAttribute("width", items.pictureCon[udalost][key].width);
            img.setAttribute("onclick","openModal();currentSlide("+number+")");
            column.appendChild(img);
            document.getElementById("row").appendChild(column);
            desc[key]=items.pictureCon[udalost][key].desc;
            }
        }

            //var imgNum = document.getElementsByClassName("mySlide-img");

        for(var key in items.pictureCon[udalost])
        {
            if(items.pictureCon[udalost][key].alt){
            var slides = document.createElement('div');
            slides.className='mySlides';
            var img = document.createElement('img');
            img.className='mySlide-img';
            img.src=items.pictureCon[udalost][key].src;
            img.setAttribute("alt", items.pictureCon[udalost][key].alt);
            img.setAttribute("width", '100%');
            img.setAttribute("height", '600px');
            slides.appendChild(img);
            document.getElementById("modalContent").appendChild(slides);
            }
        }

        //var imgDemo = document.getElementsByClassName("demo");
        number=0;
        for(var key in items.pictureCon[udalost])
        {
            if(items.pictureCon[udalost][key].alt){
            number++;
           var slides = document.createElement('div');
            slides.className='column';
            var img = document.createElement('img');
            img.className='demo';
            img.src=items.pictureCon[udalost][key].src;
            img.setAttribute("alt", items.pictureCon[udalost][key].alt);
            img.setAttribute("width", '85%');
            img.setAttribute("height", '200px');
            img.setAttribute("onclick",'currentSlide('+number+')');
            slides.appendChild(img);
            document.getElementById("modalContent").appendChild(slides);
            }
        }
      }
    }
    request.send();
}

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
  start(0);
}

function start(value)
{
   var button=document.getElementById("start");
  if(value==1){
    myVar = setInterval(plusSlides, 1000,1);
    button.style.color="green";
  }
  if(value==0){
    clearInterval(myVar);
    button.style.color="white";
  }
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides= document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
}


text:
<plugin xmlns:gml = "http://www.opengis.net/gml" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:ogc = "http://www.opengis.net/ogc" xmlns = "pluginSchema" xsi:schemaLocation = "pluginSchema /data/capabilities/validate/pluginSchema.xsd" >
<name>Domain</name>
<description>Checks for domain existance.</description>
<class>org.geotools.validation.attributes.DomainValidation</class>
</plugin>


text:
import urllib2
import json
import logging
from django.http import HttpResponse
from django.utils.http import urlencode
from djangocms_store_locator.models import Location

logger = logging.getLogger('djangocms.storelocator')

def get_lat_long(request):
    args = urlencode({'address': request.GET.get('q', ''), 'sensor': 'false'})
    r = urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?%s" % args)
    data = json.loads(r.read())
    if data['status'] == 'OK':
        location = data['results'][0]['geometry']['location']
        latlong = location['lat'], location['lng']
    else:
        if data['status'] == 'OVER_QUERY_LIMIT':
            logger.error('Google Maps Geocoding over limit!')
        latlong = ('', '')
    return HttpResponse(','.join(map(str, latlong)))

def get_locations(request):
    try:
        latitude = float(request.GET.get('lat'))
        longitude = float(request.GET.get('long'))
        distance = int(request.GET.get('distance', 0))
        location_type = request.GET.get('location_type', '0')
    except:
        return HttpResponse('[]')

    locations = Location.objects.near(latitude, longitude, distance)
    if location_type:
        locations = [l for l in locations if location_type in [str(t[0]) for t in l.location_types.values_list('id')]]
    json_locations = []
    locations.sort(key=lambda loc: loc.distance)
    for location in locations:
        location_dict = dict()
        location_dict['id'] = location.id
        location_dict['name'] = location.name
        location_dict['address'] = location.address
        location_dict['latitude'] = location.latitude
        location_dict['longitude'] = location.longitude
        location_dict['distance'] = location.distance
        location_dict['description'] = location.description
        location_dict['url'] = location.url
        location_dict['phone'] = location.phone
        location_dict['image'] = location.get_image_url()
        json_locations.append(location_dict)
    return HttpResponse(json.dumps(json_locations), mimetype="application/json")


text:
package com.linkedin.mlease.regression.consumers;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.avro.generic.GenericData;

import com.linkedin.mapred.AvroConsumer;
import com.linkedin.mlease.utils.Util;

public class ReadLambdaMapConsumer implements AvroConsumer<Map<String, Float>>
{
  private Map<String, Float> _result = new HashMap<String, Float>();
  private boolean            _done   = false;

  @Override
  public void consume(Object value)
  {
    GenericData.Record record = (GenericData.Record) value;
    if (record.get("name") != null && record.get("value") != null)
    {
      String name;
      try
      {
        name = Util.getStringAvro(record, "name", false);
        String term = Util.getStringAvro(record, "term", true);
        if (!"".equals(term))
          name = name + "\u0001" + term;
        float lambda = (float) Util.getDoubleAvro(record, "value");
        _result.put(name, lambda);
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
  }

  @Override
  public void done()
  {
    _done = true;
  }

  @Override
  public Map<String, Float> get() throws IllegalStateException
  {
    if (_done)
    {
      return _result;
    }
    throw new IllegalStateException("Cannot call get before done");
  }
}


text:
ENV['ARMOR_ITER'] ||= "10"
ENV['CRYPT_KEEPER_IGNORE_LEGACY_DEPRECATION'] = "true"
require 'coveralls'
Coveralls.wear!
require 'crypt_keeper'

SPEC_ROOT           = Pathname.new File.expand_path File.dirname __FILE__
AR_LOG              = SPEC_ROOT.join('debug.log').to_s
ENCRYPTION_PASSWORD = "supermadsecretstring"

Dir[SPEC_ROOT.join('support/*.rb')].each{|f| require f }

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  config.after :each do
    ActiveRecord::Base.descendants.each do |model|
      model.method(:delete_all).call
    end
  end

  config.after :suite do
    if File.exist?(AR_LOG) && ENV['TRAVIS'].present?
      `grep \"#{ENCRYPTION_PASSWORD}\" #{AR_LOG}`

      if $?.exitstatus == 0
        raise StandardError, "\n\nERROR: The encryption password was found in the logs\n\n"
      end
    end
  end
end


text:
AdminHelp module for ProcessWire
================

Processwire helper modules for managing site documentation in [ProcessWire CMS](http://processwire.com/).

Currently beta state - please use with caution and report all errors or things that don't work as expected.

## Instructions

### Overview:
There are 3 modules included with this: the master module holds the settings for the other 2.

The Admin Help Setup module is capable of assisting in the creation of the fields, templates and pages needed for setting up documentation.

!Important
If you are planning on using the AdminHelpTab module, then you should install the FieldtypeTemplates prior to running setup.

### Getting Started

If you already setup a hidden part of your page tree for help documentation you can simply specify the templates and root page of the help section in the module settings.

Otherwise you can run the setup and it will auto-create the *template_select* field, *help-index* template and *help-doc* template, and the example help pages. Once created you can move those pages out of the root into any area you want, such as below a 'config' or 'settings' branch.

### Using the Help Tab

Once you have setup your docs template, template_select field and some help pages, you should install the AdminHelpTab module, then select the template(s) to show the docs on, as well as the root page of your docs.

At this point the 'Help' tab should show up for the relevant template (as specified with the template_select field), and show the help docs that have that template specified.

### Using the Process Admin Help

To have a global help page, which renders all of the help docs in an accordion view, you can install the ProcessAdminHelp module, which will setup a page to view the help docs, under setup.

## Help Setup Module (AdminHelp)

This is how the setup module looks before setup is completed:
![Desc](https://raw.githubusercontent.com/outflux3/AdminHelp/master/images/help_setup_new.jpg)

If you use the automated setup, it will create the field, templates and pages, and will auto-set the module configuration:
![Desc](https://raw.githubusercontent.com/outflux3/AdminHelp/master/images/help_setup_done.jpg)

## Example Help Tab (when using AdminHelpTab)

![Desc](https://raw.githubusercontent.com/outflux3/AdminHelp/master/images/help_tab.jpg)

## Admin Help page (ProcessAdminHelp)
This shows all help docs in accordion; it is capable of displaying child pages also but this is not currently implemented in the module;

![Desc](https://raw.githubusercontent.com/outflux3/AdminHelp/master/images/help_page_c.jpg)

Accordion opened:
![Desc](https://raw.githubusercontent.com/outflux3/AdminHelp/master/images/help_page_o.jpg)


text:
module Typekitter
  class ApiClient
    ENDPOINTS = {
      kits_index: 'https://typekit.com/api/v1/json/kits'
    }

    def kits_index
      kits = Typhoeus.get(
        ENDPOINTS[:kits_index],
        headers: { 'X-Typekit-Token' => Typekitter::Token.load.value }
      )

      if kits.success?
        JSON.parse(kits.body)
      else
        error_message(kits.body)
      end
    end

    def kits_create(options={})
      kit = Typhoeus.post(
        ENDPOINTS[:kits_index],
        headers: { 'X-Typekit-Token' => Typekitter::Token.load.value },
        body: {
          name: options[:name],
          domains: options[:domains],
          families: options[:families],
          segmented_names: options[:segmented_names]
        }
      )

      if kit.success?
        JSON.parse(kit.body)
      else
        error_message(kit.body)
      end
    end

    private

    def error_message(description)
      "An error occured: #{description}"
    end
  end
end


text:
Web Athletics

System for Handicapping, Event Recording and Processing of Athletics

Technology used: ISAPI with MFC

Last Build with: Microsoft Visual Studio 2005


text:
package azkaban.utils;

import static java.util.Objects.requireNonNull;

import azkaban.Constants;
import azkaban.Constants.ConfigurationKeys;
import azkaban.alert.Alerter;
import azkaban.executor.ExecutableFlow;
import azkaban.executor.Executor;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.ExecutorManagerException;
import azkaban.executor.mail.DefaultMailCreator;
import azkaban.executor.mail.MailCreator;
import azkaban.metrics.CommonMetrics;
import azkaban.sla.SlaOption;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimaps;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.mail.internet.AddressException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;

@Singleton
public class Emailer extends AbstractMailer implements Alerter {

  private static final String HTTPS = "https";
  private static final String HTTP = "http";
  private static final Logger logger = Logger.getLogger(Emailer.class);
  private final CommonMetrics commonMetrics;
  private final String scheme;
  private final String clientHostname;
  private final String clientPortNumber;
  private final String azkabanName;
  private final ExecutorLoader executorLoader;

  @Inject
  public Emailer(final Props props, final CommonMetrics commonMetrics,
      final EmailMessageCreator messageCreator, final ExecutorLoader executorLoader) {
    super(props, messageCreator);
    this.executorLoader = requireNonNull(executorLoader, "executorLoader is null.");
    this.commonMetrics = requireNonNull(commonMetrics, "commonMetrics is null.");
    this.azkabanName = props.getString("azkaban.name", "azkaban");

    final int mailTimeout = props.getInt("mail.timeout.millis", 30000);
    EmailMessage.setTimeout(mailTimeout);
    final int connectionTimeout = props.getInt("mail.connection.timeout.millis", 30000);
    EmailMessage.setConnectionTimeout(connectionTimeout);

    EmailMessage.setTotalAttachmentMaxSize(getAttachmentMaxSize());

    this.clientHostname = props.getString(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_HOSTNAME,
        props.getString("jetty.hostname", "localhost"));

    if (props.getBoolean("jetty.use.ssl", true)) {
      this.scheme = HTTPS;
      this.clientPortNumber = Integer.toString(props
          .getInt(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_SSL_PORT,
              props.getInt("jetty.ssl.port",
                  Constants.DEFAULT_SSL_PORT_NUMBER)));
    } else {
      this.scheme = HTTP;
      this.clientPortNumber = Integer.toString(
          props.getInt(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_PORT, props.getInt("jetty.port",
              Constants.DEFAULT_PORT_NUMBER)));
    }
  }

  public String getAzkabanURL() {
    return this.scheme + "://" + this.clientHostname + ":" + this.clientPortNumber;
  }

  /**
   * Send an email to the specified email list
   */
  public void sendEmail(final List<String> emailList, final String subject, final String body) {
    if (emailList != null && !emailList.isEmpty()) {
      final EmailMessage message = super.createEmailMessage(subject, "text/html", emailList);
      message.setBody(body);
      sendEmail(message, true, "email message " + body);
    }
  }

  @Override
  public void alertOnSla(final SlaOption slaOption, final String slaMessage) {
    final String subject =
        "SLA violation for " + getJobOrFlowName(slaOption) + " on " + getAzkabanName();
    final List<String> emailList =
        (List<String>) slaOption.getEmails();
    logger.info("Sending SLA email " + slaMessage);
    sendEmail(emailList, subject, slaMessage);
  }

  @Override
  public void alertOnFirstError(final ExecutableFlow flow) {
    final EmailMessage message = this.messageCreator.createMessage();
    final MailCreator mailCreator = getMailCreator(flow);
    final boolean mailCreated = mailCreator.createFirstErrorMessage(flow, message, this.azkabanName,
        this.scheme, this.clientHostname, this.clientPortNumber);
    sendEmail(message, mailCreated,
        "first error email message for execution " + flow.getExecutionId());
  }

  @Override
  public void alertOnError(final ExecutableFlow flow, final String... extraReasons) {
    final EmailMessage message = this.messageCreator.createMessage();
    final MailCreator mailCreator = getMailCreator(flow);
    List<ExecutableFlow> last72hoursExecutions = new ArrayList<>();

    if (flow.getStartTime() > 0) {
      final long startTime = flow.getStartTime() - Duration.ofHours(72).toMillis();
      try {
        last72hoursExecutions = this.executorLoader.fetchFlowHistory(flow.getProjectId(), flow
            .getFlowId(), startTime);
      } catch (final ExecutorManagerException e) {
        logger.error("unable to fetch past executions", e);
      }
    }

    final boolean mailCreated = mailCreator.createErrorEmail(flow, last72hoursExecutions, message,
        this.azkabanName, this.scheme, this.clientHostname, this.clientPortNumber, extraReasons);
    sendEmail(message, mailCreated, "error email message for execution " + flow.getExecutionId());
  }

  @Override
  public void alertOnSuccess(final ExecutableFlow flow) {
    final EmailMessage message = this.messageCreator.createMessage();
    final MailCreator mailCreator = getMailCreator(flow);
    final boolean mailCreated = mailCreator.createSuccessEmail(flow, message, this.azkabanName,
        this.scheme, this.clientHostname, this.clientPortNumber);
    sendEmail(message, mailCreated, "success email message for execution " + flow.getExecutionId());
  }

  /**
   * Sends as many emails as there are unique combinations of:
   *
   * [mail creator] x [failure email address list]
   *
   * Executions with the same combo are grouped into a single message.
   */
  @Override
  public void alertOnFailedUpdate(final Executor executor, List<ExecutableFlow> flows,
      final ExecutorManagerException updateException) {

    flows = flows.stream()
        .filter(flow -> flow.getExecutionOptions() != null)
        .filter(flow -> CollectionUtils.isNotEmpty(flow.getExecutionOptions().getFailureEmails()))
        .collect(Collectors.toList());

    // group by mail creator in case some flows use different creators
    final ImmutableListMultimap<String, ExecutableFlow> creatorsToFlows = Multimaps
        .index(flows, flow -> flow.getExecutionOptions().getMailCreator());

    for (final String mailCreatorName : creatorsToFlows.keySet()) {

      final ImmutableList<ExecutableFlow> creatorFlows = creatorsToFlows.get(mailCreatorName);
      final MailCreator mailCreator = getMailCreator(mailCreatorName);

      // group by recipients in case some flows have different failure email addresses
      final ImmutableListMultimap<List<String>, ExecutableFlow> emailsToFlows = Multimaps
          .index(creatorFlows, flow -> flow.getExecutionOptions().getFailureEmails());

      for (final List<String> emailList : emailsToFlows.keySet()) {
        sendFailedUpdateEmail(executor, updateException, mailCreator, emailsToFlows.get(emailList));
      }
    }
  }

  /**
   * Use the default mail creator to send a failed executor healthcheck message to the given list
   * of addresses. Message includes a list of flows impacted on the executor.
   */
  @Override
  public void alertOnFailedExecutorHealthCheck(Executor executor, List<ExecutableFlow> flows,
      ExecutorManagerException failureException, List<String> emailList) {
    if (emailList == null || emailList.isEmpty()) {
      // We should consider throwing an exception here. For now this follows the model of the rest
      // of the file and simply returns.
      logger.error("No email list specified for failed health check alert");
      return;
    }
    MailCreator mailCreator = DefaultMailCreator.getCreator(DefaultMailCreator.DEFAULT_MAIL_CREATOR);
    final EmailMessage message = this.messageCreator.createMessage();
    final boolean mailCreated = mailCreator
        .createFailedExecutorHealthCheckMessage(flows, executor, failureException, message,
            this.azkabanName, this.scheme, this.clientHostname, this.clientPortNumber, emailList);
    final List<Integer> executionIds = Lists.transform(flows, ExecutableFlow::getExecutionId);
    sendEmail(message, mailCreated, "failed health check message for executions " + executionIds);
  }

  /**
   * Sends a single email about failed updates.
   */
  private void sendFailedUpdateEmail(final Executor executor,
      final ExecutorManagerException exception, final MailCreator mailCreator,
      final ImmutableList<ExecutableFlow> flows) {
    final EmailMessage message = this.messageCreator.createMessage();
    final boolean mailCreated = mailCreator
        .createFailedUpdateMessage(flows, executor, exception, message,
            this.azkabanName, this.scheme, this.clientHostname, this.clientPortNumber);
    final List<Integer> executionIds = Lists.transform(flows, ExecutableFlow::getExecutionId);
    sendEmail(message, mailCreated, "failed update email message for executions " + executionIds);
  }

  private MailCreator getMailCreator(final ExecutableFlow flow) {
    final String name = flow.getExecutionOptions().getMailCreator();
    return getMailCreator(name);
  }

  private MailCreator getMailCreator(final String name) {
    final MailCreator mailCreator = DefaultMailCreator.getCreator(name);
    logger.debug("ExecutorMailer using mail creator:" + mailCreator.getClass().getCanonicalName());
    return mailCreator;
  }

  public void sendEmail(final EmailMessage message, final boolean mailCreated,
      final String operation) {
    if (mailCreated) {
      try {
        message.sendEmail();
        logger.info("Sent " + operation);
        this.commonMetrics.markSendEmailSuccess();
      } catch (final Exception e) {
        logger.error("Failed to send " + operation, e);
        if (!(e instanceof AddressException)) {
          this.commonMetrics.markSendEmailFail();
        }
      }
    }
  }

  private String getJobOrFlowName(final SlaOption slaOption) {
    if (org.apache.commons.lang.StringUtils.isNotBlank(slaOption.getJobName())) {
      return slaOption.getFlowName() + ":" + slaOption.getJobName();
    } else {
      return slaOption.getFlowName();
    }
  }
}


text:
package mypackage.numbers;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mypackage.types.MyNumber;

import org.apache.uima.UimaContext;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.descriptor.TypeCapability;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;

@TypeCapability(outputs = { "mypackage.types.MyNumber" })
public class NumbersEngine extends JCasAnnotator_ImplBase {

    @ConfigurationParameter(name = "allowFloats")
    private boolean allowFloats;

    private Pattern pattern;

    @Override
    public void initialize(UimaContext context)
            throws ResourceInitializationException {
        super.initialize(context);
        if (allowFloats) {
            pattern = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+");
        } else {
            pattern = Pattern.compile("[0-9]+");
        }
    }

    @Override
    public void process(JCas jCas) {

        Matcher m = pattern.matcher(jCas.getDocumentText());
        while (m.find()) {
            new MyNumber(jCas, m.start(), m.end()).addToIndexes();
        }
    }
}


text:
 package com.example;

import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;

public class BaseOwnerTable extends AbstractBaseTable<OwnerRecord> {

    private RowMapper<OwnerRecord> rm = new RowMapper<OwnerRecord>() {
        @Override
        public OwnerRecord mapRow(ResultSet rs, int rowNum) throws SQLException {
             return new OwnerRecord(rs, rowNum);
        }
    };

    public BaseOwnerTable(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public RowMapper<OwnerRecord> rowMapper() {
        return rm;
    }

    @Override
    public String tableName() {
        return "OWNER";
    }

    public Optional<OwnerRecord> findByPK(int ownerId) {
        String sql =
            selectStar() +
            "where OWNER_ID  = ? ";

        return optionalSingle(sql, ownerId);
    }

    public List<OwnerRecord> findByOwnerId(int ownerId) {
        String sql =
            selectStar() +
            "where OWNER_ID  = ? ";

        return query(sql, ownerId);
    }

}