text:
var mongoClient = require("mongodb").MongoClient;

////////////////////////////////////////////////////////////////////////////////////////////////////////////
// EXAMPLE: CONNECT to mongodb
////////////////////////////////////////////////////////////////////////////////////////////////////////////

// we must connect to the mongodb server before we can do anything with it
var url = "mongodb://localhost:27017";
var connection = mongoClient.connect(url, function(error, db) {
    console.log("-----EXAMPLE: CONNECT to MongoDB------------------------------------------------------------------");
    if(error)
        console.log("ERROR! Failed to connect to mongodb at " + url);
    else
        console.log("Connected to mongodb at " + url);

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // EXAMPLE: CREATE single record
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var myCollection = "ExampleCollection";
    var jockRecord = { recordType: "User Account", name: "Jock", email: "jock@email.com", phone: "111-111-1111" };
    db.collection(myCollection).insertOne(jockRecord, function(error, result) {
        console.log("\n\n-----EXAMPLE: CREATE (single)---------------------------------------------------------------------");
        if(error)
            console.log("ERROR! Failed to create " + JSON.stringify(jockRecord) + " in collection " + myCollection);
        else
            console.log("Created " + JSON.stringify(jockRecord) + " in collection " + myCollection);
    });

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // EXAMPLE: CREATE multiple records
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    var aprilRecord = { recordType: "User Account", name: "April", email: "april@email.com", phone: "222-222-2222" };
    var tomRecord = { recordType: "User Account", name: "Tom", email: "tom@email.com", phone: "333-333-3333" };
    db.collection(myCollection).insertMany([aprilRecord, tomRecord], function(error, result) {
        console.log("\n\n-----EXAMPLE: CREATE (multiple)-------------------------------------------------------------------");
        if(error)
            console.log("ERROR! Failed to create " + JSON.stringify(aprilRecord) + " and " + JSON.stringify(tomRecord) + " in collection " + myCollection);
        else
            console.log("Created [" + JSON.stringify(aprilRecord) + ", " + JSON.stringify(tomRecord) + "] in collection " + myCollection);
    });

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // EXAMPLE: READ multiple records
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // Let's try to find ALL the user account records that we added in the previous step...
    var readFilter = { recordType: "User Account" };
    var queryResultSize = 5;    // Notice that we can limit the size of query result
    db.collection(myCollection).find(readFilter).limit(queryResultSize).toArray(function(error, records) {
        console.log("\n\n-----EXAMPLE: READ (multiple)---------------------------------------------------------------------");
        if(error) {
            console.log("ERROR! Failed to find records matching filter " + JSON.stringify(readFilter) + " in collection " + myCollection);
        }
        else {
            console.log("Found records matching filter " + JSON.stringify(readFilter) + " in collection " + myCollection + ":");
            console.log(records);
        }
    });

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // EXAMPLE: UPDATE single record
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // we will try to add a country field to Jock's user account only
    var newJockRecord = { recordType: "User Account", name: "Jock", email: "jock@email.com", phone: "111-111-1111", country: "United States" };
    db.collection(myCollection).updateOne(jockRecord, {$set: newJockRecord}, function(error, result) {
        console.log("\n\n-----EXAMPLE: UPDATE (single)---------------------------------------------------------------------");
        if(error)
            console.log("ERROR! Failed to update " + JSON.stringify(jockRecord) + " in collection " + myCollection);
        else
            console.log("Updated " + JSON.stringify(jockRecord) + " to " + JSON.stringify(newJockRecord) + " in collection " + myCollection);
    });

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // EXAMPLE: DELETE 1 or more records
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // we will try to delete all user account records
    var deleteFilter = { recordType: "User Account" };
    var options = { single: false };// if single is true, deletes only first record found
    db.collection(myCollection).deleteMany(deleteFilter, options, function(error, result) {
        console.log("\n\n-----EXAMPLE: DELETE (1 or more)------------------------------------------------------------------");
        if(error)
            console.log("ERROR! Failed to delete records matching filter " + JSON.stringify(deleteFilter) + " in collection " + myCollection);
        else
            console.log("Deleted records matching filter " + JSON.stringify(deleteFilter) + " in collection " + myCollection);
    });

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // BONUS EXAMPLE: Avoiding duplicate records in your database collection.
    // Please Note this uses many of the previous steps together
    // in one example.  Please make sure you understand the previous
    // steps before proceeding to this example.
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // First, let's demonstrate accidentally adding duplicate records into our database collection...
    db.collection(myCollection).insertOne(jockRecord, function(error, result) {
        console.log("\n\n-----EXAMPLE: Avoiding Duplicates-----------------------------------------------------------------");
        if(error)
            console.log("ERROR! Failed to create " + JSON.stringify(jockRecord) + " in collection " + myCollection);
        else
            console.log("Created " + JSON.stringify(jockRecord) + " in collection " + myCollection);
    });

    // Try adding Jock record again, however this time it will return error
    // as Jock record is already present in the database collection
    db.collection(myCollection).insertOne(jockRecord, function(error, result) {
        if(error){
            console.log("ERROR! Failed to create " + JSON.stringify(jockRecord) + " in collection " + myCollection);
            console.log(error);// we expect this second insert to return error
        }
        else {
            console.log("Created " + JSON.stringify(jockRecord) + " in collection " + myCollection);
        }
    });

    // If we query for all Jock records, we should find only one Jock record and no duplicates.
    var jockFilter = { recordType: "User Account", name: "Jock" };
    db.collection(myCollection).find(jockFilter).toArray(function(error, records) {
        if(error) {
            console.log("ERROR! Failed to find records matching filter " + JSON.stringify(jockFilter) + " in collection " + myCollection);
        }
        else {
            console.log("Found records matching filter " + JSON.stringify(jockFilter) + " in collection " + myCollection + ":");
            console.log(records);// should print out a single Josk user account record
        }
    });

    db.close();
});


text:
layout: post
title: "GSoC 2015: New NMatrix gems for advanced linear algebra features"
date: 2015-08-19 09:57
comments: true
author: Will Levine
categories: [GSOC,GSOC2015,Students,NMatrix,linear algebra]
---
My Google Summer of Code project was working on the [NMatrix project](https://github.com/SciRuby/nmatrix), moving
functionality that depends on external libraries from the core `nmatrix`
gem to optional plugin gems. NMatrix is a Ruby library for linear algebra,
used by many other projects.
In addition to the code that was part of
NMatrix proper, NMatrix previously required the [ATLAS library](http://math-atlas.sourceforge.net/), which
implemented fast versions of common matrix operations like multiplication
and inversion, as well as more advanced operations like eigenvalue
decomposition and Cholesky decomposition.

There were two separate but related motivations for my project. The
first was to simplify the NMatrix installation
process. ATLAS can be difficult to install, so the installation
process for NMatrix was complicated, especially on
OS X, and may have discouraged people from using NMatrix.
The second motivation was that by separating out the ATLAS code from the
main NMatrix code, it would be easier to add new linear algebra backends
which provide similar features. Indeed, I implemented a second backend this
summer.

The end result of my summer's work:

* The core `nmatrix` gem does not depend on any external linear matrix
libraries. It provides non-optimized implementations of common matrix
operations.
* All code that requires ATLAS has been moved into the new `nmatrix-atlas`
gem, so that
those who are only interested in the core functionality are not required to
install ATLAS. `nmatrix-atlas` provides optimized implementations of common matrix
operations, as well as advanced functions not available in `nmatrix`.
I wrote a blog post describing the setup for [releasing multiple gems from the same repository](http://wlevine.github.io/2015/06/15/releasing-multiple-gems-with-c-extensions-from-the-same-repository.html), which this required.
* A new gem `nmatrix-lapacke`, which provides the same features as
`nmatrix-atlas`, but instead of depending specifically on the ATLAS
library, requires any generic [LAPACK](https://en.wikipedia.org/wiki/LAPACK) and
[BLAS](https://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms)
implementation. This should be easier to use for many users as they may
already have LAPACK installed (it comes pre-installed with OS X and is
commonly used in Linux systems), but not ATLAS.
* The installation procedure is simplified, especially for those installing
just the `nmatrix` gem. Compare the [new installation instructions](https://github.com/SciRuby/nmatrix/wiki/Installation)
to the [old ones](https://github.com/SciRuby/nmatrix/wiki/Installation/2ac41c62d35c79468d3d8169be0ccba238c3c921).

The one deviation from my original proposal was that I originally intended to remove
all the ATLAS code and release only the `nmatrix-lapacke` plugin, so that we
would only have one interface to the advanced linear algebra functions, but I
decided to keep the ATLAS code, since the `nmatrix-lapacke` code is new and
has not had a chance to be thoroughly tested.

### Usage

```ruby
require 'nmatrix'
# create a 3-by-3 matrix
a = NMatrix.new([3,3], [1,2,3, 4,5,6, 7,8,9], dtype: :float64)
#invert it using non-optimized NMatrix-internal implementation
a.invert!
```

```ruby
require 'nmatrix'
require 'nmatrix/atlas' #or require 'nmatrix/lapacke'
# create a 3-by-3 matrix
a = NMatrix.new([3,3], [1,2,3, 4,5,6, 7,8,9], dtype: :float64)
#invert it using optimized implementation provided by ATLAS
a.invert!
```

For advanced functions not provided by the core `nmatrix` gem, for example
[`gesvd`](http://sciruby.com/nmatrix/docs/NMatrix.html#method-i-gesvd), `nmatrix-atlas` and `nmatrix-lapacke`
provide a common interface:

```ruby
require 'nmatrix'
require 'nmatrix/atlas'
a = NMatrix.new([4,5],[1,0,0,0,2, 0,0,3,0,0, 0,0,0,0,0, 0,4,0,0,0],
dtype: dtype)
u, s, vt = a.gesvd
```

```ruby
#Identical to the above, except for the require
require 'nmatrix'
require 'nmatrix/lapacke'
a = NMatrix.new([4,5],[1,0,0,0,2, 0,0,3,0,0, 0,0,0,0,0, 0,4,0,0,0],
dtype: dtype)
u, s, vt = a.gesvd
```

If the developer wants to use an advanced feature, but does not care
whether the user is using `nmatrix-atlas`
or `nmatrix-lapacke`, they can `require nmatrix/lapack_plugin`, which will
require whichever of the two is available, instead of being forced to
choose between the two.

As a fun test of the new gems, I did a very simple benchmark, just
testing how long it took to invert a
1500-by-1500 matrix in place using `NMatix#invert!`:

* `nmatrix` (no external libraries): 3.67s
* `nmatrix-atlas`: 0.96s
* `nmatrix-lapacke` with ATLAS: 0.99s
* `nmatrix-lapacke` with OpenBLAS (multithreading enabled): 0.39s
* `nmatrix-lapacke` with reference implementations of LAPACK and BLAS: 3.72s

This is not supposed to be a thorough or realistic benchmark (performance will
depend on your system, on how you built the libraries, and on the exact
functions that you use), but there
are still a few interesting conclusions we can draw from it:

* Performance is much better using the two highly optimized libraries
(ATLAS and OpenBLAS) than using either the NMatrix
internal implementation or the reference implementation.
* When using ATLAS, performance is similar whether using `nmatrix-atlas`
and `nmatrix-lapacke` (this means we could consider deprecating
the `nmatix-atlas` gem).

Overall, my summer has been productive. I implemented everything that I
proposed and feedback from testers so far has been positive.
I plan to stay involved with NMatrix, especially to follow up on any issues
related to my changes.
Although I won't be a student next summer, I would certainly consider
participating in Google Summer of Code in the future as a mentor.
I'd like to
thank my mentor John Woods and the rest of the SciRuby community for support
and feedback throughout the summer.

redpajama_set_name: RedPajamaGithub


text:
package com.intellij.openapi.components.impl.stores;

import com.intellij.util.messages.Topic;

public interface BatchUpdateListener {
  Topic<BatchUpdateListener> TOPIC = new Topic<>("batch update listener", BatchUpdateListener.class);

  void onBatchUpdateStarted();
  void onBatchUpdateFinished();
}


text:
using System.IO;

namespace Paket.Bootstrapper.HelperProxies
{
    public interface IWebRequestProxy
    {
        string DownloadString(string address);
        void DownloadFile(string url, string targetLocation);
        void DownloadFile(string url, Stream stream, int bufferSize);
    }
}


text:
#include "Slinky3D.h"

#define thisTTClass			Slinky3D
#define thisTTClassName		"slinky.3D"
#define thisTTClassTags		"audio, trajectory, 3D"

TT_AUDIO_CONSTRUCTOR
{
	addAttribute(A,	kTypeFloat64);
	addAttribute(B,	kTypeFloat64);
	addAttribute(C,	kTypeFloat64);
	setProcessMethod(processAudio);
//	setCalculateMethod(calculateValue);
}

Slinky3D::~Slinky3D()
{
	;
}

//TTErr Slinky3D::calculateValue(const TTFloat64& x, TTFloat64& y, TTPtrSizedInt data)
//{
//	y = x;
//	return kTTErrNone;
//}

TTErr Slinky3D::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs)
{
	TTAudioSignal&		out = outputs->getSignal(0);
	TTChannelCount		numOutputChannels = out.getNumChannelsAsInt();

	if (numOutputChannels != 3) {
		TTValue v = 3;
		out.setMaxNumChannels(v);
		out.setNumChannels(v);
	}

	TTAudioSignal&		in0 = inputs->getSignal(0);
	TTUInt16			 vs = in0.getVectorSizeAsInt();

	TTSampleValuePtr	inSampleX			= in0.mSampleVectors[0];
	TTSampleValuePtr	outSampleX    		= out.mSampleVectors[0];
	TTSampleValuePtr	outSampleY			= out.mSampleVectors[1];
    TTSampleValuePtr	outSampleZ			= out.mSampleVectors[2];

	TTFloat64 phi, temp;

	for (int i=0; i<vs; i++) {

		phi = inSampleX[i] * kTTTwoPi - kTTTwoPi; // -2Pi .. 2Pi
		temp = mB + mA*cos(phi);
		outSampleX[i] = temp*cos(phi);
		outSampleY[i] = temp*sin(phi);
		outSampleZ[i] = mC*(inSampleX[i]-1.0) + mA*sin(phi);

	}
return kTTErrNone;
}


text:
- Test overwrite of directory with file
- Test overwrite of file with directory
- Test writing out of symlink
- Test overwrite of symlink with file
- Test overwrite of file with symlink
- Test overwrite of symlink with directory
- Test overwrite of directory with symlink
- Test running of tasks
- Add environment variables to running of task:
   - PASK\_PACKAGE\_NAME
   - PASK\_PACKAGE\_VERSION
   - PASK\_TASK
   - PASK\_PROJECT\_BASE
- Test that those variables (and others) are getting through


text:
#ifndef _TS_LUA_TRANSFORM_H
#define _TS_LUA_TRANSFORM_H

#include "ts_lua_common.h"

int ts_lua_transform_entry(TSCont contp, TSEvent event, void *edata);

#endif


text:
Brain-free [syslog](http://en.wikipedia.org/wiki/Syslog)** logging for
[node.js](http://nodejs.org).

*Ain* is written with full compatibility with *node.js* `console` module. It
implements all `console` functions and formatting. Also *ain* supports UTF-8
(tested on Debian Testing/Sid).

*Ain* can send messages by UDP to `127.0.0.1:514` or to the a unix socket;
/dev/log on Linux and /var/run/syslog on Mac OS X.  Unix socket support is possible if [unix-dgram](https://npmjs.org/package/unix-dgram) can be built and installed.

*In the Phoenician alphabet letter "ain" indicates eye.

**All examples tested under Ubuntu `rsyslog`. On other operating
systems and logging daemons settings and paths may differ.

## Installation

You can install *ain* as usual - by copy the "ain" directory in your
`~/.node_modules` or via *npm*

    npm install ain2

## Usage

Usage of *ain* is very similar to the *node.js* console. The following example
demonstrates the replacement of the console:

```javascript

var SysLogger = require('ain2');
var console = new SysLogger();

console.log('notice: %d', Date.now());
console.info('info');
console.error('error');
```

After launch in `/var/log/user` you can see the following:

    Dec  5 06:45:26 localhost ex.js[6041]: notice: 1291513526013
    Dec  5 06:45:26 localhost ex.js[6041]: info
    Dec  5 06:45:26 localhost ex.js[6041]: error

Note: you need to ensure syslog is listening on UDP port 514 for this example to work.  On Ubuntu, for example, you would need to edit ```/etc/rsyslog.conf```, add/uncomment the following lines, and ensure rsyslog is restarted:

```
# provides UDP syslog reception
$ModLoad imudp
$UDPServerAddress 127.0.0.1
$UDPServerRun 514
```

## Singleton logger

If you want to have a singleton that points to the same object whenever you do a require, use the following:

```javascript
require('ain2').getInstance();
```

If you use this, please be beware of this:

```javascript
require('ain2').getInstance() ===  require('ain2').getInstance();
=> true
```

As opposed to:

```javascript
var SysLogger = require('ain2');
new SysLogger() === new SysLogger();
=> false
```

## Changing destinations

By default *ain* sets following destinations:

* `TAG` - `__filename`
* `Facility` - user (1)
* `HOSTNAME` - localhost
* `PORT` - 514
* `Transport` - UDP

You can change them by passing in the params to the constructor or by
using the `set` function. The `set` function is chainable.

```javascript
var SysLogger = require('ain2');
var logger = new SysLogger({tag: 'node-test-app', facility: 'daemon', hostname: 'devhost', port: 3000});

logger.warn('some warning');
```

... and in `/var/log/daemon.log`:

    Dec  5 07:08:58 devhost node-test-app[10045]: some warning

The `set` function takes one argument, a configuration object which can contain the following keys:
 * tag - defaults to __filename
 * facility - defaults to user
 * hostname - defaults to require('os').hostname()
 * port - defaults to 514
 * transport - defaults to 'UDP'
 * path - path to filesystem socket if using unix_dgram transport
 * messageComposer - a custom function to compose syslog messages

All of these are optional. If you provide a `hostname` transport is automatically set to UDP

`tag` and `hostname` arguments is just *RFC 3164* `TAG` and `HOSTNAME` of
your messages.

`facility` is little more than just name. Refer to *Section 4.1.1* of
[RFC 3164](http://www.faqs.org/rfcs/rfc3164.html) it can be:

    ##  String  Description
    -----------------------
     0  kern    kernel messages
     1  user    user-level messages
     2  mail    mail system
     3  daemon  system daemons
     4  auth    security/authorization messages
     5  syslog  messages generated internally by syslog daemon
     6  lpr     line printer subsystem
     7  news    network news subsystem
     8  uucp    UUCP subsystem
    16  local0  local use 0
    17  local1  local use 1
    18  local2  local use 2
    19  local3  local use 3
    20  local4  local use 4
    21  local5  local use 5
    22  local6  local use 6
    23  local7  local use 7

You can set the `facility` by `String` or `Number`:

    logger.set({tag: 'node-test-app', facility: 3});
    logger.set({tag: 'node-test-app', facility: 'daemon'});

Also you can set `TAG`, `Facility`, `HOSTNAME`, `PORT`, and `transport` separately by `setTag`,
`setFacility`, `setHostname`, `setPort`, `setTransport` and `setMessageComposer` functions. All of them are chainable too.

You can get all destinations by these properties:

* `tag` TAG
* `facility` Numerical representation of RFC 3164 facility
* `hostname` HOSTNAME
* `port` PORT

## Callbacks

Ain provides an optional callback after a message has been sent to the socket (udp and unix socket).
The callback is passed up unaltered from [node.](http://nodejs.org/api/dgram.html#dgram_socket_send_buf_offset_length_port_address_callback)
Because ain supports a simplified printf format, the callback has to be the last parameter.

```javascript
var SysLogger = require('ain2');
var console = new SysLogger();

console.info('info', function(err, bytes){
  // callback received
});
console.log('notice: %d', Date.now(), function(err, bytes){
  // callback received
});

```

## Custom message composer

```javascript
var SysLogger = require('ain2');
var console = new SysLogger();

console.setMessageComposer(function(message, severity){
    return new Buffer('<' + (this.facility * 8 + severity) + '>' +
            this.getDate() + ' ' + '[' + process.pid + ']:' + message);
});
```

The default implementation looks this:

```javascript
SysLogger.prototype.composeSyslogMessage = function(message, severity) {
    return new Buffer('<' + (this.facility * 8 + severity) + '>' +
            this.getDate() + ' ' + this.hostname + ' ' +
            this.tag + '[' + process.pid + ']:' + message);
}
```

## Logging

As noticed before *ain* implements all `console` functions. Severity level is
referenced to [RFC 3164](http://www.faqs.org/rfcs/rfc3164.html):

    #  String   Description
    -----------------------
    0  emerg    Emergency: system is unusable
    1  alert    Alert: action must be taken immediately
    2  crit     Critical: critical conditions
    3  err      Error: error conditions
    4  warn     Warning: warning conditions
    5  notice   Notice: normal but significant condition
    6  info     Informational: informational messages
    7  debug    Debug: debug-level messages

*Ain* `console`-like functions behaviour is fully compatible to *node.js* and
logs messages with different severity levels:

* `log` - notice (5)
* `info` - info (6)
* `warn` - warn (4)
* `error` - err (3)
* `dir` - notice (5)
* `time`, `timeEnd` - notice (5)
* `trace` - err (3)
* `assert` - err (3)

To log a message with the desired severity level you can use the `send` function:

```javascript
logger.send('message', 'alert');
```

The `send` function takes two arguments: message and optional severity level. By
default, the severity level is *notice*.

# Development

    npm install
    npm test


text:
var _ = require('lodash');
var expect = require('chai').expect;

var getReadableStream = require('../_utilities/getReadableStream.js');
var runBasicStreamTests = require('../_utilities/runBasicStreamTests.js');
var take = require('../../').take;

describe('[take]', function () {
  var data = ['item1', new Buffer('item2'), 'item3', 'item4'];
  var objData = [true, false, [1, 2, 3], 'string', 0, '11', 95.23, { obj: true }, _.noop];
  var expected = [new Buffer('item1'), new Buffer('item2')];
  var objExpected = [true, false];

  function runTest(stream, objectMode, done) {
    var actual = [];

    stream
      .pipe(take(2))
      .on('data', function (chunk) {
        actual.push(chunk);
      })
      .on('error', done)
      .on('end', function () {

        if (objectMode) {
          expect(actual).to.deep.equal(objExpected);
        } else {
          expect(actual).to.deep.equal(expected);
        }

        done();
      });
  }

  runBasicStreamTests(data, objData, runTest);

  it('emits an error if `n` is not an integer', function (done) {
    var readableStream = getReadableStream(data);

    readableStream
      .pipe(take(false))
      .on('error', function (err) {
        expect(err).to.be.an.instanceof(TypeError);
        expect(err.message).to.equal('Expected `n` to be an integer.');

        done();
      })
      .on('end', function () {
        throw new Error('end should not be called');
      })
      .resume();
  });
});


text:
package org.aesh.command.settings;

import org.aesh.command.activator.CommandActivator;
import org.aesh.command.activator.OptionActivator;
import org.aesh.command.completer.CompleterInvocation;
import org.aesh.command.converter.ConverterInvocation;
import org.aesh.command.invocation.CommandInvocation;
import org.aesh.command.validator.ValidatorInvocation;
import org.aesh.io.FileResource;
import org.aesh.io.Resource;
import org.aesh.readline.editing.EditMode;

import java.io.File;

/**
 * @author Ståle W. Pedersen
 */
public class RuntimeSettings {

    public static Settings<CommandInvocation, ConverterInvocation, CompleterInvocation, ValidatorInvocation, OptionActivator, CommandActivator> readRuntimeProperties(
                                      Settings<CommandInvocation, ConverterInvocation, CompleterInvocation, ValidatorInvocation,
                                                      OptionActivator, CommandActivator> settings) {
       SettingsBuilder<CommandInvocation, ConverterInvocation, CompleterInvocation,
                              ValidatorInvocation, OptionActivator, CommandActivator>
               builder = new SettingsBuilder<>(settings);

            String editMode = System.getProperty("aesh.editmode");
            if(editMode != null && editMode.length() > 0) {
                if(editMode.equalsIgnoreCase("VI"))
                    builder.mode(EditMode.Mode.VI);
                else if(editMode.equalsIgnoreCase("EMACS"))
                    builder.mode(EditMode.Mode.EMACS);
            }
            String readInputrc = System.getProperty("aesh.readinputrc");
            if(readInputrc != null && readInputrc.length() > 0)
                if(readInputrc.equalsIgnoreCase("true") ||
                        readInputrc.equalsIgnoreCase("false"))
                    builder.readInputrc(Boolean.parseBoolean(readInputrc));

            String inputrc = System.getProperty("aesh.inputrc");
            if(inputrc != null && inputrc.length() > 0)
                if(new File(inputrc).isFile())
                    builder.inputrc(new File(inputrc));

            String historyFile = System.getProperty("aesh.historyfile");
            if(historyFile != null && historyFile.length() > 0)
                if(new File(historyFile).isFile())
                    builder.historyFile(new File(historyFile));

            String historyPersistent = System.getProperty("aesh.historypersistent");
            if(historyPersistent != null && historyPersistent.length() > 0)
                if(historyPersistent.equalsIgnoreCase("true") ||
                        historyPersistent.equalsIgnoreCase("false"))
                    builder.persistHistory(Boolean.parseBoolean(historyPersistent));

            String historyDisabled = System.getProperty("aesh.historydisabled");
            if(historyDisabled != null && historyDisabled.length() > 0)
                if(historyDisabled.equalsIgnoreCase("true") ||
                        historyDisabled.equalsIgnoreCase("false"))
                    builder.disableHistory(Boolean.parseBoolean(historyDisabled));

            String historySize = System.getProperty("aesh.historysize");
            if(historySize != null && historySize.length() > 0)
                builder.historySize(Integer.parseInt(historySize));

            String doLogging = System.getProperty("aesh.logging");
            if(doLogging != null && doLogging.length() > 0)
                if(doLogging.equalsIgnoreCase("true") ||
                        doLogging.equalsIgnoreCase("false"))
                    builder.logging(Boolean.parseBoolean(doLogging));

            String logFile = System.getProperty("aesh.logfile");
            if(logFile != null && logFile.length() > 0)
                builder.logfile(logFile);

            String disableCompletion = System.getProperty("aesh.disablecompletion");
            if(disableCompletion != null && disableCompletion.length() > 0)
                if(disableCompletion.equalsIgnoreCase("true") ||
                        disableCompletion.equalsIgnoreCase("false"))
                    builder.disableCompletion(Boolean.parseBoolean(disableCompletion));

            String execute = System.getProperty("aesh.execute");
            if(execute != null && execute.length() > 0)
                builder.setExecuteAtStart(execute);

            String executeFile = System.getProperty("aesh.executefile");
            if(executeFile != null && executeFile.length() > 0) {
               Resource resourceFile =  new FileResource(executeFile);
                if(resourceFile.isLeaf())
                    builder.setExecuteFileAtStart(resourceFile);
            }

        return builder.build();
    }
}


text:
'use strict';

const mkdirp = require('mkdirp'),
    path = require('path'),
    haro = require('haro'),
    defer = require('tiny-defer'),
    utility = require(path.resolve(__dirname, 'utility.js')),
    commandLineArgs = require('command-line-args');

let cli = commandLineArgs([{
        name: 'city',
        alias: 'c',
        type: String,
        defaultValue: 'Ottawa'
    },
    {
        name: 'directory',
        alias: 'd',
        type: String,
        defaultValue: process.cwd()
    },
    {
        name: 'uid',
        alias: 'u',
        type: Number
    }]),
    options = cli.parse(),
    sites = haro(null, {id: 'sites', key: 'code', index:['nameEn'], versioning: false}),
    site;

// Dropping process if a uid is specified
if (options.uid) {
    process.setuid(options.uid);
}

// Handling relative paths
options.directory = path.resolve(options.directory);

// Ensuring target directory exists
mkdirp.sync(options.directory);

// Loading sites, finding site & retrieving data
utility.sites().then(data => {
    return sites.batch(data, 'set');
}).then(() => {
    let regex = new RegExp('^' + options.city.replace(/[\-\[\]{}()*+?.,\\\/\^\$|#\s]/g, "\\$&"), 'i'),
        results = sites.toArray(sites.search(regex), false),
        deferred, output;

    if (results.length > 0) {
        site = results.shift();

        if (results.length > 0) {
            console.log('Multiple cities found, using: ' + site.nameEn);
            console.log('Other potential cities:');

            results.forEach(s => {
                console.log('- ' + s.nameEn);
            });
        }

        output = utility.retrieve(site.code, site.provinceCode, options.directory);
    } else {
        deferred = defer();
        output = deferred.promise;
        deferred.reject(new Error('City not found'));
    }

    return output;
}).then(() => {
    console.log('Saved weather data for ' + site.nameEn + ' \'' + options.directory + '\'');
    process.exit(0);
}).catch(err => {
    console.error('Failed to retrieve weather data:\n' + err.stack);
    process.exit(1);
});


text:
namespace Code
{
    QString dest(QString mnemonic);
    QString jump(QString mnemonic);
    QString comp(QString mnemonic);
}

#endif // CODE_H


text:
An Assertion that checks that a SOAP fault was not returned

[![Build Status](https://travis-ci.org/testify/NotSOAPFaultAssertion.svg?branch=master)](https://travis-ci.org/testify/NotSOAPFaultAssertion)


text:
module Scais::Topology
end
require 'scais/renderer'
require 'scais/topology/validations'
require 'scais/topology/block'
require 'scais/topology/fint'
require 'scais/topology/funin'
require 'scais/topology/logate'
require 'scais/topology/logate_handler'
require 'scais/topology/convex'
require 'scais/topology/vmetodo'
require 'scais/topology/acelerator'
require 'scais/topology/files'
require 'scais/topology/topology'


text:
/**
 * Autor:    Ricardo Rodriguez
 * Objetivo: Métodos de atualização de informações de usuário.
 */

$( function() {
	jsProfile = {};

	jsProfile.EMAIL_FOUND = false;
	jsProfile.SHORTNAME_FOUND = false;

	jsProfile.INCLUDE = 0;
	jsProfile.DELETE  = 1;

	jsProfile.checkFields= function() {

		if (window.doCheckIsEmptyField("name", global.error.nameFormat)){
        	$("#name").focus();
        	return false;
        } else if (window.doCheckIsEmptyField("shortName", global.error.shortNameFormat)){
        	$("#shortName").focus();
        	return false;
        } else if (!window.docheckEmail(jsProfile.screenData.email,
        								 jsProfile.screenData.confirmEmail) ){
			$("#email").focus();
			return false;
		} else if (! pass.doVerifyPassword(jsProfile.screenData.password,
										   jsProfile.screenData.confirmPassword)){
			$("#password").focus();
			return false;
		} else if (!jsProfile.screenData.agree) {
			global.msgbox.data('messageBox').danger(window.important, global.error.confirmTerm);
			return false;
		}
		return true;
	};

	jsProfile.checkShortName = function() {
		// debugger

		var shortName = $("#shortName").val();
		var checkShortNamePath = $("#divCheckShortNamePath").attr("ajaxurl");
		var myData = {'shortName' : shortName};

		$.ajax({
			url: checkShortNamePath,
			data: myData,
			type: 'POST',
			cache: true,

			beforeSend: function( ) {
				 $("#shortName").css({'background-color' : '#fff'});
			},

			error: function(){

			},

			success: function(returned){
				//debugger;
				$(divPosicao).empty();
				var dataout = $.parseJSON(returned);
				jsProfile.SHORTNAME_FOUND = false;
				if($.trim(dataout.result) === global.recordFound){
					jsProfile.SHORTNAME_FOUND = true;
					 $("#shortName").css({'background-color' : '#fff'});
				} else
					 $("#shortName").css({'background-color' : '#5B1762'});

				return;
			},
			statusCode: {
				404: function() {
					global.msgbox.data('messageBox').danger(window.important,
							global.error.connection + checkShortNamePath + ". "+ global.error.tryagain);
				}
			}
		});

	};
	jsProfile.checkEmail = function() {
		var email 	   = $("#email").val();
		var checkEmailPath = $("#divCheckEmailPath").attr("ajaxurl");

		//debugger;

		var myData = {'email' : email};

		$.ajax({
			url: checkEmailPath,
			data: myData,
			type: 'POST',
			cache: true,

			beforeSend: function( ) {
				$("#email").css({'background-color' : '#ffffff'});			},

			error: function(){

			},

			success: function(returned){
				//debugger;
				var dataout = $.parseJSON(returned);
				jsProfile.EMAIL_FOUND = false;
				if($.trim(dataout.result) === global.recordFound){
					jsProfile.EMAIL_FOUND = true;
					$("#email").css({'background-color' : '#5B1762'});
				} else
					$("#email").css({'background-color' : '#ffffff'});

				return;
			},
			statusCode: {
				404: function() {
					global.msgbox.data('messageBox').danger(window.important,
							global.error.connection + checkEmailPath + ". "+ global.error.tryagain);
				}
			}
		});
	};

	jsProfile.saveNewUser = function() {
		jsProfile.checkShortName();
		jsProfile.checkEmail();
		//------------------------------------------
		var passMD5   = calcMD5($("#password").val());
		var cPassMD5  = calcMD5($("#confirmPassword").val());
		//------------------------------------------
		jsProfile.screenData = { 'name'           : $("#name").val(),
								 'shortName'      : $("#shortName").val(),
								 'password'       : passMD5,
								 'confirmPassword': cPassMD5,
								 'email'          : $("#email").val(),
								 'confirmEmail'   : $("#confirmEmail").val(),
								 'agree'          : $('#agree').is(":checked"),
								 'path'           : $("#divSaveNewProfile").attr("ajaxurl"),
								 'login'          : $("#divloginPath").attr("ajaxurl"),
				     			};
		if  (! jsProfile.checkFields())
			return false;

		/**
		 * Execute the call of save record
		 */
		window.ajaxLoading("show");
		$.ajax({
			url: jsProfile.screenData.path,
			data: jsProfile.screenData,
			type: 'POST',
			cache: true,

			success: function(returned){
				//debugger;
				window.ajaxLoading("hide");
				var dataout = $.parseJSON(returned);
				if($.trim(dataout.result) === global.recordSavedWithSuccess){
					location.href =jsProfile.screenData.login;
				} else
					alert('Erro no cadastro:');
				return;
			},
			statusCode: {
				404: function() {
					window.ajaxLoading("hide");
					global.msgbox.data('messageBox').danger(window.important,
							global.error.connection + jsProfile.screenData.path + ". "+ global.error.tryagain);
				}
			}
		});
	};

	jsProfile.checkLoginTagarelas = function(){
		//------------------------------------------
		var email 	  = $("#email").val();
		var passMD5   = calcMD5($("#password").val());

		//------------------------------------------
		jsProfile.screenData = { 'password'       : passMD5,
								 'email'          : $("#email").val(),
								 'checkLoginPath' : $("#divCheckLoginPath").attr("ajaxurl"),
								 'feedPath'       : $("#divFeedPath").attr("ajaxurl"),
				     			};
		/**
		 * Execute the call of save record
		 */
		window.ajaxLoading("show"); d
		$.ajax({
			url: jsProfile.screenData.checkLoginPath,
			data: jsProfile.screenData,
			type: 'POST',
			cache: true,

			success: function(returned){
				window.ajaxLoading("hide");
				var dataout = $.parseJSON(returned);
				if($.trim(dataout.result) === global.loginCorrect){
					location.href =jsProfile.screenData.feedPath;
				} else
					alert('Login Inválido. Tente de novo');
				return;
			},
			statusCode: {
				404: function() {
					window.ajaxLoading("hide");
					global.msgbox.data('messageBox').danger(window.important,
							global.error.connection + jsProfile.screenData.checkLoginPath + ". "+ global.error.tryagain);
				}
			}
		});
	};

	jsProfile.membersSelected = new Array();
	jsProfile.totalMembers = 0;

	jsProfile.hasMembers = function(){
		if ((jsProfile.membersSelected).length > 0) return true;
		global.msgbox.data('messageBox').danger(window.important,
												global.error.groupMemberNotFound);
		return false;
	}

	jsProfile.controlData = function(action,data){
		var totalRegistros = 0
		if (jsProfile.INCLUDE == action){
			jsProfile.totalMembers = jsProfile.membersSelected.push(data);

		} else {
			jsProfile.membersSelected = $.grep(jsProfile.membersSelected,function(item){
			             return (item.id !== data.id);
		     });
			jsProfile.totalMembers = jsProfile.membersSelected.length;
	    }

		$("#totalDeMembros").html(jsProfile.totalMembers);
		$("#totalDeMembrosHidden").val(jsProfile.totalMembers)
		jsProfile.controlTotals();
	};

	jsProfile.controlTotals = function (){
		$("#totalParticipantes").html(jsProfile.totalMembers+jsGroup.totalMembersGroups);
	};

	jsProfile.loadAllUsers = function() {
		/**
		 * Execute call to load all users
		 */
		if (window.ajaxLoading) window.ajaxLoading("show");
		var urlLoadAllUsers =  $("#divLoadAllUsers").attr("ajaxurl");
		$.ajax({
			url:  urlLoadAllUsers,
			data: [],
			type: 'POST',
			cache: false,

			error: function(){
				if (window.ajaxLoading)
					window.ajaxLoading("hide");

			},

			success: function(returned){
				if (window.ajaxLoading) window.ajaxLoading("hide");
				var dataout = $.parseJSON(returned);
				if(global.usersFound  ==$.trim(dataout.result)){
					$('#allMembers').magicsearch({
			            dataSource: dataout.users,
			            fields: ['realName', 'nickname'],
			            id: 'id',
			            format: '%realName% · %nickname%',
			            multiple: true,
			            multiField: 'realName',
			            dropdownBtn: true,
			            multiStyle: {
			                space: 5,
			                width: 80
			            },
			            success:function($imput,data){
			            	jsProfile.controlData(jsProfile.INCLUDE,data);
			            	return true;
			            },
			            afterDelete: function($input, data) {
			            	jsProfile.controlData(jsProfile.DELETE,data);
			            	return true;
			            },

					});

					return;
				}
			},
			statusCode: {
				404: function() {
					if (window.ajaxLoading) window.ajaxLoading("hide");
					global.msgbox.data('messageBox').danger(window.important,
							global.error.connection + urlLoadAllUsers + ". "+ global.error.tryagain);
				}
			},

		});

	};

	/**
	 * If exists $("#loadAllUsersDiv") - I'm in Group page then load all users.
	 */
	if ($("#pageGroup").length || $("#pageSession").length)
		jsProfile.loadAllUsers();

});


text:
<?php
    require "model.Attachment.php";

    class Attachments extends Modules {
        static function __install() {
            $sql = SQL::current();
            $sql->query("CREATE TABLE IF NOT EXISTS __attachments (
                             id INTEGER PRIMARY KEY AUTO_INCREMENT,
                             filename VARCHAR(100) DEFAULT '',
                             path VARCHAR(100) DEFAULT '',
                             entity_type VARCHAR(100) DEFAULT '',
                             entity_id INTEGER DEFAULT 0
                         ) DEFAULT CHARSET=utf8");
        }

        static function __uninstall($confirm) {
            if ($confirm) {
                foreach (Attachment::find() as $attachment)
                    @unlink(uploaded($attachment->path, true));

                SQL::current()->query("DROP TABLE __attachments");
            }
        }

        public function parse_urls(&$urls) {
            $urls["|/delete_attachment/([0-9]+)/|"] = '/?action=delete_attachment&id=$1';
        }

        public function parse_url($route) {
            if ($route->arg[0] == "delete_attachment" and is_numeric(@$route->arg[1])) {
                $_GET['id'] = $route->arg[1];
                $route->action = "delete_attachment";
            }
        }

        public function main_delete_attachment() {
            if (!isset($_GET['id']))
                error(__("No ID Specified"), __("An ID is required to delete an attachment.", "attachments"));

            $attachment = new Attachment($_GET['id']);
            if ($attachment->no_results)
                error(__("Error"), __("Invalid attachment ID specified.", "attachments"));

            if (!$attachment->deletable())
                show_403(__("Access Denied"), __("You do not have sufficient privileges to delete this attachment.", "attachments"));

            Attachment::delete($attachment->id);

            Flash::notice(__("Attachment deleted.", "attachments"), $_SESSION['redirect_to']);
        }
    }


text:
module Filemaker
  module Store
    class LayoutStore < Hash
      def initialize(server, database)
        @server = server
        @database = database
      end

      def [](name)
        super || self[name] = Filemaker::Layout.new(name, @server, @database)
      end

      def all
        args = { '-db' => @database.name }
        response, _params = @server.perform_request('-layoutnames', args)
        resultset = Filemaker::Resultset.new(@server, response.body)
        resultset.map do |record|
          record['LAYOUT_NAME']
        end
      end
    end
  end
end


text:
import numpy as np
import common
import os
labels = common.fetch_samples()

from sklearn.model_selection import train_test_split
np.random.seed(123)
y_train, y_test, sha256_train, sha256_test = train_test_split(
    list(labels.values()), list(labels.keys()), test_size=1000)

##################
# end-to-end model
# maximum number of bytes we allow per file = 512KB
max_file_length = int(2**19)
file_chunks = 8  # break file into this many chunks
file_chunk_size = max_file_length // file_chunks
batch_size = 8

import endtoend
import math
from keras.callbacks import LearningRateScheduler

# create_model(input_shape, byte_embedding_size=2, input_dropout=0.2, kernel_size=16, n_filters_per_layer=[64,256,1024], n_mlp_layers=2 )
model_e2e = endtoend.create_model(input_shape=(file_chunks, file_chunk_size))
train_generator = common.generator(list(zip(sha256_train, y_train)), batch_size, file_chunks, file_chunk_size)
test_generator = common.generator(list(zip(sha256_test, y_test)), 1, file_chunks, file_chunk_size)
model_e2e.fit_generator(train_generator,
                        steps_per_epoch=math.ceil(len(sha256_train) / batch_size),
                        epochs=20,
                        callbacks=[LearningRateScheduler(
                            lambda epoch: common.schedule(epoch, start=0.1, decay=0.5, every=1)
                            )
                        ],
                        validation_data=test_generator,
                        validation_steps=len(sha256_test))
y_pred = []
for sha256, lab in zip(sha256_test, y_test):
    y_pred.append(
        model_e2e.predict_on_batch(
            np.asarray([get_file_data(sha256, lab)]).reshape(
                (-1, file_chunks, file_chunk_size))
        )
    )
common.summarize_performance(np.asarray(
    y_pred).flatten(), y_test, "End-to-end convnet")
model_e2e.save('endtoend.h5')


text:
package egoscale

import (
	"context"
	"fmt"
	"net/url"

	"github.com/jinzhu/copier"
)

// Get loads the given Affinity Group
func (ag *AffinityGroup) Get(ctx context.Context, client *Client) error {
	if ag.ID == "" && ag.Name == "" {
		return fmt.Errorf("An Affinity Group may only be searched using ID or Name")
	}

	resp, err := client.RequestWithContext(ctx, &ListAffinityGroups{
		ID:   ag.ID,
		Name: ag.Name,
	})

	if err != nil {
		return err
	}

	ags := resp.(*ListAffinityGroupsResponse)
	count := len(ags.AffinityGroup)
	if count == 0 {
		return &ErrorResponse{
			ErrorCode: ParamError,
			ErrorText: fmt.Sprintf("AffinityGroup not found id: %s, name: %s", ag.ID, ag.Name),
		}
	} else if count > 1 {
		return fmt.Errorf("More than one Affinity Group was found. Query; id: %s, name: %s", ag.ID, ag.Name)
	}

	return copier.Copy(ag, ags.AffinityGroup[0])
}

// Delete removes the given Affinity Group
func (ag *AffinityGroup) Delete(ctx context.Context, client *Client) error {
	if ag.ID == "" && ag.Name == "" {
		return fmt.Errorf("An Affinity Group may only be deleted using ID or Name")
	}

	req := &DeleteAffinityGroup{
		Account:  ag.Account,
		DomainID: ag.DomainID,
	}

	if ag.ID != "" {
		req.ID = ag.ID
	} else {
		req.Name = ag.Name
	}

	return client.BooleanRequestWithContext(ctx, req)
}

// name returns the CloudStack API command name
func (*CreateAffinityGroup) name() string {
	return "createAffinityGroup"
}

func (*CreateAffinityGroup) asyncResponse() interface{} {
	return new(CreateAffinityGroupResponse)
}

// name returns the CloudStack API command name
func (*UpdateVMAffinityGroup) name() string {
	return "updateVMAffinityGroup"
}

func (*UpdateVMAffinityGroup) asyncResponse() interface{} {
	return new(UpdateVMAffinityGroupResponse)
}

func (req *UpdateVMAffinityGroup) onBeforeSend(params *url.Values) error {
	// Either AffinityGroupIDs or AffinityGroupNames must be set
	if len(req.AffinityGroupIDs) == 0 && len(req.AffinityGroupNames) == 0 {
		params.Set("affinitygroupids", "")
	}
	return nil
}

// name returns the CloudStack API command name
func (*DeleteAffinityGroup) name() string {
	return "deleteAffinityGroup"
}

func (*DeleteAffinityGroup) asyncResponse() interface{} {
	return new(booleanResponse)
}

// name returns the CloudStack API command name
func (*ListAffinityGroups) name() string {
	return "listAffinityGroups"
}

func (*ListAffinityGroups) response() interface{} {
	return new(ListAffinityGroupsResponse)
}

// name returns the CloudStack API command name
func (*ListAffinityGroupTypes) name() string {
	return "listAffinityGroupTypes"
}

func (*ListAffinityGroupTypes) response() interface{} {
	return new(ListAffinityGroupTypesResponse)
}


text:
package tabletmanager

import (
	"time"

	"github.com/youtube/vitess/go/vt/hook"
	"github.com/youtube/vitess/go/vt/logutil"
	"github.com/youtube/vitess/go/vt/mysqlctl/tmutils"
	"golang.org/x/net/context"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
	replicationdatapb "github.com/youtube/vitess/go/vt/proto/replicationdata"
	tabletmanagerdatapb "github.com/youtube/vitess/go/vt/proto/tabletmanagerdata"
	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
)

// RPCAgent defines the interface implemented by the Agent for RPCs.
// It is useful for RPC implementations to test their full stack.
type RPCAgent interface {
	// RPC calls

	// Various read-only methods

	Ping(ctx context.Context, args string) string

	GetSchema(ctx context.Context, tables, excludeTables []string, includeViews bool) (*tabletmanagerdatapb.SchemaDefinition, error)

	GetPermissions(ctx context.Context) (*tabletmanagerdatapb.Permissions, error)

	// Various read-write methods

	SetReadOnly(ctx context.Context, rdonly bool) error

	ChangeType(ctx context.Context, tabletType topodatapb.TabletType) error

	Sleep(ctx context.Context, duration time.Duration)

	ExecuteHook(ctx context.Context, hk *hook.Hook) *hook.HookResult

	RefreshState(ctx context.Context) error

	RunHealthCheck(ctx context.Context)

	IgnoreHealthError(ctx context.Context, pattern string) error

	ReloadSchema(ctx context.Context, waitPosition string) error

	PreflightSchema(ctx context.Context, changes []string) ([]*tabletmanagerdatapb.SchemaChangeResult, error)

	ApplySchema(ctx context.Context, change *tmutils.SchemaChange) (*tabletmanagerdatapb.SchemaChangeResult, error)

	ExecuteFetchAsDba(ctx context.Context, query []byte, dbName string, maxrows int, disableBinlogs bool, reloadSchema bool) (*querypb.QueryResult, error)

	ExecuteFetchAsAllPrivs(ctx context.Context, query []byte, dbName string, maxrows int, reloadSchema bool) (*querypb.QueryResult, error)

	ExecuteFetchAsApp(ctx context.Context, query []byte, maxrows int) (*querypb.QueryResult, error)

	// Replication related methods

	SlaveStatus(ctx context.Context) (*replicationdatapb.Status, error)

	MasterPosition(ctx context.Context) (string, error)

	StopSlave(ctx context.Context) error

	StopSlaveMinimum(ctx context.Context, position string, waitTime time.Duration) (string, error)

	StartSlave(ctx context.Context) error

	TabletExternallyReparented(ctx context.Context, externalID string) error

	GetSlaves(ctx context.Context) ([]string, error)

	WaitBlpPosition(ctx context.Context, blpPosition *tabletmanagerdatapb.BlpPosition, waitTime time.Duration) error

	StopBlp(ctx context.Context) ([]*tabletmanagerdatapb.BlpPosition, error)

	StartBlp(ctx context.Context) error

	RunBlpUntil(ctx context.Context, bpl []*tabletmanagerdatapb.BlpPosition, waitTime time.Duration) (string, error)

	// Reparenting related functions

	ResetReplication(ctx context.Context) error

	InitMaster(ctx context.Context) (string, error)

	PopulateReparentJournal(ctx context.Context, timeCreatedNS int64, actionName string, masterAlias *topodatapb.TabletAlias, pos string) error

	InitSlave(ctx context.Context, parent *topodatapb.TabletAlias, replicationPosition string, timeCreatedNS int64) error

	DemoteMaster(ctx context.Context) (string, error)

	PromoteSlaveWhenCaughtUp(ctx context.Context, replicationPosition string) (string, error)

	SlaveWasPromoted(ctx context.Context) error

	SetMaster(ctx context.Context, parent *topodatapb.TabletAlias, timeCreatedNS int64, forceStartSlave bool) error

	SlaveWasRestarted(ctx context.Context, parent *topodatapb.TabletAlias) error

	StopReplicationAndGetStatus(ctx context.Context) (*replicationdatapb.Status, error)

	PromoteSlave(ctx context.Context) (string, error)

	// Backup / restore related methods

	Backup(ctx context.Context, concurrency int, logger logutil.Logger) error

	RestoreFromBackup(ctx context.Context, logger logutil.Logger) error

	// HandleRPCPanic is to be called in a defer statement in each
	// RPC input point.
	HandleRPCPanic(ctx context.Context, name string, args, reply interface{}, verbose bool, err *error)
}


text:
const chai = require('chai')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')

const { syncConnector } = require('../../connector')
const job = require('../../src/job')

chai.use(sinonChai)

const { expect } = chai

describe('connector | syncConnector', () => {
  it('pushes job immediately', () => {
    const spy = sinon.spy()

    const newJob = job.of('job.name', { foo: 1 })
    const connector = syncConnector()
    connector.onJob(spy)
    connector.push(newJob)

    expect(spy).to.have.been.called // eslint-disable-line

    const spyArgs = spy.getCall(0).args

    expect(spyArgs[0].toJSON()).to.deep.equal(newJob.increment().toJSON())
  })

  it('releases job', () => {
    const stub = sinon.stub().callsFake(job => {
      if (job.attempts === 1) {
        job.release()
      }
    })

    const newJob = job.of('job.name')
    const connector = syncConnector()
    connector.onJob(stub)

    connector.push(newJob)

    expect(stub).to.have.been.calledTwice // eslint-disable-line
    expect(stub.getCall(1).args[0]).to.include({ attempts: 2 })
  })

  it('releases job with delay', () => {
    const clock = sinon.useFakeTimers()
    const stub = sinon.stub().callsFake(job => {
      if (job.attempts === 1) {
        job.release(30)
      }
    })

    const connector = syncConnector()
    connector.onJob(stub)

    connector.push(job.of('job.name'))

    expect(stub).to.have.been.calledOnce // eslint-disable-line

    clock.tick(30000)

    expect(stub).to.have.been.calledTwice // eslint-disable-line

    clock.restore()
  })
})


text:
require 'spec_helper'

describe "RSpec Configuration" do
  describe "configuring Capybara without Cucumber" do
    it "should not set the driver to selenium_with_firebug by default" do
      Capybara.current_driver.should_not == :selenium_with_firebug
    end

    it "should set the driver to selenium_with_firebug when tagged", :firebug => true do
      Capybara.current_driver.should == :selenium_with_firebug
    end
  end
end


text:
package org.wso2.carbon.apimgt.rest.api.admin.v1.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.SettingsKeyManagerConfigurationDTO;
import javax.validation.constraints.*;

import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;
import org.wso2.carbon.apimgt.rest.api.common.annotations.Scope;
import com.fasterxml.jackson.annotation.JsonCreator;

import javax.validation.Valid;

public class SettingsDTO   {

    private List<String> scopes = new ArrayList<String>();
    private List<SettingsKeyManagerConfigurationDTO> keyManagerConfiguration = new ArrayList<SettingsKeyManagerConfigurationDTO>();
    private Boolean analyticsEnabled = null;

  /**
   **/
  public SettingsDTO scopes(List<String> scopes) {
    this.scopes = scopes;
    return this;
  }

  @ApiModelProperty(value = "")
  @JsonProperty("scopes")
  public List<String> getScopes() {
    return scopes;
  }
  public void setScopes(List<String> scopes) {
    this.scopes = scopes;
  }

  /**
   **/
  public SettingsDTO keyManagerConfiguration(List<SettingsKeyManagerConfigurationDTO> keyManagerConfiguration) {
    this.keyManagerConfiguration = keyManagerConfiguration;
    return this;
  }

  @ApiModelProperty(value = "")
      @Valid
  @JsonProperty("keyManagerConfiguration")
  public List<SettingsKeyManagerConfigurationDTO> getKeyManagerConfiguration() {
    return keyManagerConfiguration;
  }
  public void setKeyManagerConfiguration(List<SettingsKeyManagerConfigurationDTO> keyManagerConfiguration) {
    this.keyManagerConfiguration = keyManagerConfiguration;
  }

  /**
   * To determine whether analytics is enabled or not
   **/
  public SettingsDTO analyticsEnabled(Boolean analyticsEnabled) {
    this.analyticsEnabled = analyticsEnabled;
    return this;
  }

  @ApiModelProperty(example = "false", value = "To determine whether analytics is enabled or not")
  @JsonProperty("analyticsEnabled")
  public Boolean isAnalyticsEnabled() {
    return analyticsEnabled;
  }
  public void setAnalyticsEnabled(Boolean analyticsEnabled) {
    this.analyticsEnabled = analyticsEnabled;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SettingsDTO settings = (SettingsDTO) o;
    return Objects.equals(scopes, settings.scopes) &&
        Objects.equals(keyManagerConfiguration, settings.keyManagerConfiguration) &&
        Objects.equals(analyticsEnabled, settings.analyticsEnabled);
  }

  @Override
  public int hashCode() {
    return Objects.hash(scopes, keyManagerConfiguration, analyticsEnabled);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class SettingsDTO {\n");

    sb.append("    scopes: ").append(toIndentedString(scopes)).append("\n");
    sb.append("    keyManagerConfiguration: ").append(toIndentedString(keyManagerConfiguration)).append("\n");
    sb.append("    analyticsEnabled: ").append(toIndentedString(analyticsEnabled)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
namespace SpriterEngine
{

	class StringVariableInfoReference : public UniversalObjectInterface
	{
	public:
		StringVariableInfoReference();

		std::string getStringValue() override;
		void setStringValue(std::string *newValue) override;

		void setToBlendedLinear(UniversalObjectInterface *aObject, UniversalObjectInterface *bObject, real t, real blendRatio, ObjectRefInstance *blendedRefInstance = 0) override;

	private:
		std::string *value;
	};

}

#endif // STRINGVARIABLEINFOREFERENCE_H


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>io.github.NavVasky</groupId>
	<artifactId>Vanillarizer</artifactId>
	<version>0.0.2-SNAPSHOT</version>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<repositories>
		<repository>
			<id>spigot-repo</id>
			<url>https://hub.spigotmc.org/nexus/content/groups/public/</url>
		</repository>
	</repositories>
	<!--Spigot-API -->
	<dependencies>
		<dependency>
			<groupId>org.spigotmc</groupId>
			<artifactId>spigot-api</artifactId>
			<version>1.8-R0.1-SNAPSHOT</version>
		</dependency>
	</dependencies>
</project>


text:
@interface PodsDummy_Pods_GifCameraController_Tests : NSObject
@end
@implementation PodsDummy_Pods_GifCameraController_Tests
@end


text:
set -e
# set time
timedatectl set-ntp true

sgdisk -o /dev/sda

sgdisk -n 1:$(sgdisk -f /dev/sda):+512M -t 1:ef00 /dev/sda
sgdisk -n 2:$(sgdisk -f /dev/sda):$(sgdisk -E /dev/sda) -t 2:8e00 /dev/sda
sgdisk -p /dev/sda

mkfs.fat -F32 /dev/sda1

cryptsetup luksFormat /dev/sda2
cryptsetup open /dev/sda2 cryptlvm

pvcreate /dev/mapper/cryptlvm
vgcreate TheDisk /dev/mapper/cryptlvm

lvcreate -L 8G TheDisk -n swap
lvcreate -L 50G TheDisk -n root
lvcreate -l 100%FREE TheDisk -n home

mkfs.ext4 /dev/mapper/TheDisk-root
mkfs.ext4 /dev/mapper/TheDisk-home
mkswap /dev/mapper/TheDisk-swap

mount /dev/mapper/TheDisk-root /mnt
mkdir /mnt/home
mount /dev/mapper/TheDisk-home /mnt/home
swapon /dev/mapper/TheDisk-swap

mkdir /mnt/boot
mount /dev/sda1 /mnt/boot

pacman-key --populate archlinux
pacman-key --refresh-keys

pacstrap /mnt base base-devel

genfstab -U /mnt >> /mnt/etc/fstab

arch-chroot /mnt

# here should start a new script...

ln -s /usr/share/zoneinfo/Europe/Berlin /etc/localtime

hwclock --systohc

#TODO: Uncomment en_US.UTF-8 UTF-8 and other needed localizations in /etc/locale.gen, and generate them with: AUTOMATIC
locale-gen

#TODO: Add the keyboard, encrypt and lvm2 hooks to mkinitcpio.conf: AUTOMATIC

mkinitcpio -p linux

passwd

bootctl --path=/boot install

#TODO create conf for bootctl
# in /boot/loader/loader.conf
#default  arch
#timeout  4

#TODO: create entry for boot loader
# in /boot/loader/entries/arch.conf
#title Arch Linux Encrypted
#linux /vmlinuz-linux
#initrd /initramfs-linux.img
#options cryptdevice=UUID=<UUID>:<mapped-name> root=/dev/mapper/<mapped-name> quiet rw