text:
Carbonado support
-----------------

Plugin page: [http://artifacts.griffon-framework.org/plugin/carbonado](http://artifacts.griffon-framework.org/plugin/carbonado)

The Carbonado plugin enables lightweight access to JDBC, BerkeleyDB or in-memory
datastores using [Carbonado][1]. This plugin does NOT provide domain classes nor
dynamic finders like GORM does.

Usage
-----
Upon installation the plugin will generate the following artifacts in
`$appdir/griffon-app/conf`:

 * CarbonadoConfig.groovy - contains the repository definitions.
 * BootstrapCarbonado.groovy - defines init/destroy hooks for data to be
   manipulated during app startup/shutdown.

A new dynamic method named `withCarbonado` will be injected into all controllers,
giving you access to a `com.amazon.carbonado.Repository` object, with which
you'll be able to make calls to the repository. Remember to make all repository
calls off the UI thread otherwise your application may appear unresponsive
when doing long computations inside the UI thread.

This method is aware of multiple repositories. If no repositoryName is specified
when calling it then the default repository will be selected. Here are two example
usages, the first queries against the default repository while the second queries
a repository whose name has been configured as 'internal'

    package sample
    class SampleController {
        def queryAllRepisitories = {
            withCarbonado { repositoryName, repository -> ... }
            withCarbonado('internal') { repositoryName, repository -> ... }
        }
    }

The following list enumerates all the variants of the injected method

 * `<R> R withCarbonado(Closure<R> stmts)`
 * `<R> R withCarbonado(CallableWithArgs<R> stmts)`
 * `<R> R withCarbonado(String repositoryName, Closure<R> stmts)`
 * `<R> R withCarbonado(String repositoryName, CallableWithArgs<R> stmts)`

These methods are also accessible to any component through the singleton
`griffon.plugins.carbonado.CarbonadoConnector`. You can inject these methods to
non-artifacts via metaclasses. Simply grab hold of a particular metaclass and
call `CarbonadoEnhancer.enhance(metaClassInstance, carbonadoProviderInstance)`.

Configuration
-------------
### CarbonadoAware AST Transformation

The preferred way to mark a class for method injection is by annotating it with
`@griffon.plugins.carbonado.CarbonadoAware`. This transformation injects the
`griffon.plugins.carbonado.CarbonadoContributionHandler` interface and default
behavior that fulfills the contract.

### Dynamic method injection

Dynamic methods will be added to controllers by default. You can
change this setting by adding a configuration flag in `griffon-app/conf/Config.groovy`

    griffon.carbonado.injectInto = ['controller', 'service']

Dynamic method injection will be skipped for classes implementing
`griffon.plugins.carbonado.CarbonadoContributionHandler`.

### Selecting a repository type

This plugin supports 3 types of repositories: JDBC, BerkeleyDB and in-memory. You can select which one to use by
configuring the selected type in the repository configuration (`CarbonadoConfig.groovy`).

This flag accepts the following values: `jdbc`, `bdb` and `map`. The last option is the default if no preference is specified.

### Events

The following events will be triggered by this addon

 * CarbonadoConnectStart[config, repositoryName] - triggered before connecting to the repository
 * CarbonadoConnectEnd[repositoryName, repository] - triggered after connecting to the repository
 * CarbonadoDisconnectStart[config, repositoryName, repository] - triggered before disconnecting from the repository
 * CarbonadoDisconnectEnd[config, repositoryName] - triggered after disconnecting from the repository

### Multiple Stores

The config file `CarbonadoConfig.groovy` defines a default repository block. As the name
implies this is the repository used by default, however you can configure named repositories
by adding a new config block. For example connecting to a repository whose name is 'internal'
can be done in this way

    repositories {
        internal {
            type = 'map'
        }
    }

This block can be used inside the `environments()` block in the same way as the
default repository block is used.

### Configuration Storage

The plugin will load and store the contents of `CarbonadoConfig.groovy` inside the
application's configuration, under the `pluginConfig` namespace. You may retrieve
and/or update values using

    app.config.pluginConfig.carbonado

### Connect at Startup

The plugin will attempt a connection to the default database at startup. If this
behavior is not desired then specify the following configuration flag in
`Config.groovy`

    griffon.carbonado.connect.onstartup = false

### Example

A trivial sample application can be found at [https://github.com/aalmiray/griffon_sample_apps/tree/master/persistence/carbonado][2]

Testing
-------

Dynamic methods will not be automatically injected during unit testing, because
addons are simply not initialized for this kind of tests. However you can use
`CarbonadoEnhancer.enhance(metaClassInstance, carbonadoProviderInstance)` where
`carbonadoProviderInstance` is of type `griffon.plugins.carbonado.CarbonadoProvider`.
The contract for this interface looks like this

    public interface CarbonadoProvider {
        <R> R withCarbonado(Closure<R> closure);
        <R> R withCarbonado(CallableWithArgs<R> callable);
        <R> R withCarbonado(String repositoryName, Closure<R> closure);
        <R> R withCarbonado(String repositoryName, CallableWithArgs<R> callable);
    }

It's up to you define how these methods need to be implemented for your tests.
For example, here's an implementation that never fails regardless of the
arguments it receives

    class MyCarbonadoProvider implements CarbonadoProvider {
        public <R> R withCarbonado(Closure<R> closure) { null }
        public <R> R withCarbonado(CallableWithArgs<R> callable) { null }
        public <R> R withCarbonado(String repositoryName, Closure<R> closure) { null }
        public <R> R withCarbonado(String repositoryName, CallableWithArgs<R> callable) { null }
    }

This implementation may be used in the following way

    class MyServiceTests extends GriffonUnitTestCase {
        void testSmokeAndMirrors() {
            MyService service = new MyService()
            CarbonadoEnhancer.enhance(service.metaClass, new MyCarbonadoProvider())
            // exercise service methods
        }
    }

On the other hand, if the service is annotated with `@CarbonadoAware` then usage
of `CarbonadoEnhancer` should be avoided at all costs. Simply set `carbonadoProviderInstance`
on the service instance directly, like so, first the service definition

    @griffon.plugins.carbonado.CarbonadoAware
    class MyService {
        def serviceMethod() { ... }
    }

Next is the test

    class MyServiceTests extends GriffonUnitTestCase {
        void testSmokeAndMirrors() {
            MyService service = new MyService()
            service.carbonadoProvider = new MyCarbonadoProvider()
            // exercise service methods
        }
    }

Tool Support
------------

### DSL Descriptors

This plugin provides DSL descriptors for Intellij IDEA and Eclipse (provided
you have the Groovy Eclipse plugin installed). These descriptors are found
inside the `griffon-carbonado-compile-x.y.z.jar`, with locations

 * dsdl/carbonado.dsld
 * gdsl/carbonado.gdsl

### Lombok Support

Rewriting Java AST in a similar fashion to Groovy AST transformations is
possible thanks to the [lombok][3] plugin.

#### JavaC

Support for this compiler is provided out-of-the-box by the command line tools.
There's no additional configuration required.

#### Eclipse

Follow the steps found in the [Lombok][3] plugin for setting up Eclipse up to
number 5.

 6. Go to the path where the `lombok.jar` was copied. This path is either found
    inside the Eclipse installation directory or in your local settings. Copy
    the following file from the project's working directory

         $ cp $USER_HOME/.griffon/<version>/projects/<project>/plugins/carbonado-<version>/dist/griffon-carbonado-compile-<version>.jar .

 6. Edit the launch script for Eclipse and tweak the boothclasspath entry so
    that includes the file you just copied

        -Xbootclasspath/a:lombok.jar:lombok-pg-<version>.jar:        griffon-lombok-compile-<version>.jar:griffon-carbonado-compile-<version>.jar

 7. Launch Eclipse once more. Eclipse should be able to provide content assist
    for Java classes annotated with `@CarbonadoAware`.

#### NetBeans

Follow the instructions found in [Annotation Processors Support in the NetBeans
IDE, Part I: Using Project Lombok][4]. You may need to specify
`lombok.core.AnnotationProcessor` in the list of Annotation Processors.

NetBeans should be able to provide code suggestions on Java classes annotated
with `@CarbonadoAware`.

#### Intellij IDEA

Follow the steps found in the [Lombok][3] plugin for setting up Intellij IDEA
up to number 5.

 6. Copy `griffon-carbonado-compile-<version>.jar` to the `lib` directory

         $ pwd
           $USER_HOME/Library/Application Support/IntelliJIdea11/lombok-plugin
         $ cp $USER_HOME/.griffon/<version>/projects/<project>/plugins/carbonado-<version>/dist/griffon-carbonado-compile-<version>.jar lib

 7. Launch IntelliJ IDEA once more. Code completion should work now for Java
    classes annotated with `@CarbonadoAware`.

[1]: http://carbonado.sourceforge.net/
[2]: https://github.com/aalmiray/griffon_sample_apps/tree/master/persistence/carbonado
[3]: /plugin/lombok
[4]: http://netbeans.org/kb/docs/java/annotations-lombok.html

### Building

This project requires all of its dependencies be available from maven compatible repositories.
Some of these dependencies have not been pushed to the Maven Central Repository, however you
can obtain them from [lombok-dev-deps][lombok-dev-deps].

Follow the instructions found there to install the required dependencies into your local Maven
repository before attempting to build this plugin.

[lombok-dev-deps]: https://github.com/aalmiray/lombok-dev-deps

redpajama_set_name: RedPajamaGithub


text:
@()
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=5.0, user-scalable=yes" />
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")" />
<link rel="stylesheet" media="screen" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/custom.css")" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="@routes.Assets.at("javascripts/config.js")"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.core.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/latest/jqm-datebox.mode.calbox.min.js"></script>
<script type="text/javascript" src="http://dev.jtsage.com/cdn/datebox/i18n/jquery.mobile.datebox.i18n.ja.utf8.js"></script>
<script type="text/javascript" src="@routes.Assets.at("javascripts/custom.js")"></script>


text:
using System.ComponentModel;

namespace abbSolutions.Communication.ThreadSafeObjects
{
   [Browsable(true), TypeConverter(typeof(ExpandableObjectConverter))]
   public interface ISupportsClear
   {
      void Clear();
   }
}


text:
#include "ADXL345.h"
#include <iostream>
#include <unistd.h>
#include <math.h>
#include <stdio.h>

using namespace std;

namespace exploringBB {

//From Table 19. of the ADXL345 Data sheet
#define DEVID          0x00   //Device ID
#define THRESH_TAP     0x1D   //Tap Threshold
#define OFSX           0x1E   //X-axis Offset
#define OFSY           0x1F   //Y-axis Offset
#define OFSZ           0x20   //Z-axis Offset
#define DUR            0x21   //Tap duration
#define LATENT         0x22   //Tap latency
#define WINDOW         0x23   //Tap window
#define THRESH_ACT     0x24   //Activity threshold
#define THRESH_INACT   0x25   //Threshold inactivity
#define TIME_INACT     0x26   //Inactivity time
#define ACT_INACT_CTL  0x27   //Axis enable control for activity and inactivity detection
#define THRESH_FF      0x28   //Free-fall threshold
#define TIME_FF        0x29   //Free-fall time
#define TAP_AXES       0x2A   //Axis control for single tap/double tap
#define ACT_TAP_STATUS 0x2B   //Source of single tap/double tap
#define BW_RATE        0x2C   //Data rate and power mode control
#define POWER_CTL      0x2D   //Power-saving features control
#define INT_ENABLE     0x2E   //Interrupt enable control
#define INT_MAP        0x2F   //Interrupt mapping control
#define INT_SOURCE     0x30   //Source of interrupts
#define DATA_FORMAT    0x31   //Data format control
#define DATAX0         0x32   //X-axis Data 0
#define DATAX1         0x33   //X-axis Data 1
#define DATAY0         0x34   //Y-axis Data 0
#define DATAY1         0x35   //Y-axis Data 1
#define DATAZ0         0x36   //Z-axis Data 0
#define DATAZ1         0x37   //Z-axis Data 1
#define FIFO_CTL       0x38   //FIFO control
#define FIFO_STATUS    0x39   //FIFO status

/**
 * Method to combine two 8-bit registers into a single short, which is 16-bits on the BBB. It shifts
 * the MSB 8-bits to the left and then ORs the result with the LSB.
 * @param msb an unsigned character that contains the most significant byte
 * @param lsb an unsigned character that contains the least significant byte
 */
short ADXL345::combineRegisters(unsigned char msb, unsigned char lsb){
   //shift the MSB right by 8 bits and OR with LSB
   return ((short)msb<<8)|(short)lsb;
}

/**
 * Method to calculate the pitch and roll state values. This calculation takes account of the scaling
 * factors due to the resolution and gravity range to determine gravity weighted values that are used
 * to calculate the angular pitch and roll values in degrees.
 */
void ADXL345::calculatePitchAndRoll(){
	float gravity_range;
	switch(ADXL345::range){
		case ADXL345::PLUSMINUS_16_G: gravity_range=32.0f; break;
		case ADXL345::PLUSMINUS_8_G: gravity_range=16.0f; break;
		case ADXL345::PLUSMINUS_4_G: gravity_range=8.0f; break;
		default: gravity_range=4.0f; break;
	}
    float resolution = 1024.0f;
    if (this->resolution==ADXL345::HIGH) resolution = 8192.0f; //13-bit resolution
    float factor = gravity_range/resolution;

    float accXg = this->accelerationX * factor;
    float accYg = this->accelerationY * factor;
    float accZg = this->accelerationZ * factor;
	float accXSquared = accXg * accXg ;
	float accYSquared = accYg * accYg ;
	float accZSquared = accZg * accZg ;
	this->pitch = 180 * atan(accXg/sqrt(accYSquared + accZSquared))/M_PI;
	this->roll = 180 * atan(accYg/sqrt(accXSquared + accZSquared))/M_PI;
}

/**
 * Method used to update the DATA_FORMAT register and any other registers that might be added
 * in the future.
 * @return 0 if the register is updated successfully
 */
int ADXL345::updateRegisters(){
   //update the DATA_FORMAT register
   char data_format = 0x00;  //+/- 2g with normal resolution
   //Full_resolution is the 3rd LSB
   data_format = data_format|((this->resolution)<<3);
   data_format = data_format|this->range; // 1st and 2nd LSB therefore no shift
   return this->device->writeRegister(DATA_FORMAT, data_format);
}

/**
 * The constructor for the ADXL345 accelerometer object. It passes the bus number and the
 * device address (with is 0x53 by default) to the constructor of I2CDevice. All of the states
 * are initialized and the registers are updated.
 * @param I2CBus The bus number that the ADXL345 device is on - typically 0 or 1
 * @param I2CAddress The address of the ADLX345 device (default 0x53, but can be altered)
 */

ADXL345::ADXL345(BusDevice *busDevice){
	//this->I2CAddress = I2CAddress;
	//this->I2CBus = I2CBus;
	this->device = busDevice;
	this->accelerationX = 0;
	this->accelerationY = 0;
	this->accelerationZ = 0;
	this->pitch = 0.0f;
	this->roll = 0.0f;
	this->registers = NULL;
	this->range = ADXL345::PLUSMINUS_16_G;
	this->resolution = ADXL345::HIGH;
	this->device->writeRegister(POWER_CTL, 0x08);
	this->updateRegisters();
}

/**
 * Read the sensor state. This method checks that the device is being correctly
 * read by using the device ID of the ADXL345 sensor. It will read in the accelerometer registers
 * and pass them to the combineRegisters() method to be processed.
 * @return 0 if the registers are successfully read and -1 if the device ID is incorrect.
 */
int ADXL345::readSensorState(){
	this->registers = this->device->readRegisters(BUFFER_SIZE, 0x00);
	if(*this->registers!=0xe5){
		perror("ADXL345: Failure Condition - Sensor ID not Verified");
		return -1;
	}
	this->accelerationX = this->combineRegisters(*(registers+DATAX1), *(registers+DATAX0));
	this->accelerationY = this->combineRegisters(*(registers+DATAY1), *(registers+DATAY0));
	this->accelerationZ = this->combineRegisters(*(registers+DATAZ1), *(registers+DATAZ0));
	this->resolution = (ADXL345::RESOLUTION) (((*(registers+DATA_FORMAT))&0x08)>>3);
	this->range = (ADXL345::RANGE) ((*(registers+DATA_FORMAT))&0x03);
	this->calculatePitchAndRoll();
	return 0;
}

/**
 * Set the ADXL345 gravity range according to the RANGE enumeration
 * @param range One of the four possible gravity ranges defined by the RANGE enumeration
 */
void ADXL345::setRange(ADXL345::RANGE range) {
	this->range = range;
	updateRegisters();
}

/**
 * Set the ADXL345 resolution according to the RESOLUTION enumeration
 * @param resolution either HIGH or NORMAL resolution. HIGH resolution is only available if the range is set to +/- 16g
 */
void ADXL345::setResolution(ADXL345::RESOLUTION resolution) {
	this->resolution = resolution;
	updateRegisters();
}

/**
 * Useful debug method to display the pitch and roll values in degrees on a single standard output line
 * @param iterations The number of 0.1s iterations to take place.
 */
void ADXL345::displayPitchAndRoll(int iterations){
	int count = 0;
	while(count < iterations){
	      cout << "Pitch:"<< this->getPitch() << " Roll:" << this->getRoll() << "     \r"<<flush;
	      usleep(100000);
	      this->readSensorState();
	      count++;
	}
}

ADXL345::~ADXL345() {}

} /* namespace exploringBB */


text:
'use strict';
const assert = require('chai').assert;
const rewire = require('rewire');
const _ = require('underscore');

const chalk = require('../lib/chalk');

describe('helper', function() {
  let h;

  before(function() {
    chalk.init();
  });

  beforeEach(function() {
    h = rewire('../lib/helper');
  });

  describe('#prettyState', function() {
    it('should ok w/ color', function() {
      chalk.enabled = true;

      assert.equal(h.prettyState('ac'), chalk.green('✔'));
      assert.equal(h.prettyState('notac'), chalk.red('✘'));
      assert.equal(h.prettyState('none'), ' ');
      assert.equal(h.prettyState(''), ' ');
      assert.equal(h.prettyState(null), ' ');
    });

    it('should ok w/o color', function() {
      chalk.enabled = false;

      assert.equal(h.prettyState('ac'), '✔');
      assert.equal(h.prettyState('notac'), '✘');
      assert.equal(h.prettyState('none'), ' ');
      assert.equal(h.prettyState(''), ' ');
      assert.equal(h.prettyState(null), ' ');
    });
  }); // #prettyState

  describe('#prettyText', function() {
    it('should ok w/ color', function() {
      chalk.enabled = true;

      assert.equal(h.prettyText(' text', true), chalk.green('✔ text'));
      assert.equal(h.prettyText(' text', false), chalk.red('✘ text'));
      assert.equal(h.prettyText('text'), 'text');
    });

    it('should ok w/o color', function() {
      chalk.enabled = false;

      assert.equal(h.prettyText(' text', true), '✔ text');
      assert.equal(h.prettyText(' text', false), '✘ text');
      assert.equal(h.prettyText('text'), 'text');
    });
  }); // #prettyText

  describe('#prettyLevel', function() {
    it('should ok w/ color', function() {
      chalk.enabled = true;

      assert.equal(h.prettyLevel('Easy'), chalk.green('Easy'));
      assert.equal(h.prettyLevel('Medium'), chalk.yellow('Medium'));
      assert.equal(h.prettyLevel('Hard'), chalk.red('Hard'));
      assert.equal(h.prettyLevel('easy  '), chalk.green('easy  '));
      assert.equal(h.prettyLevel('medium'), chalk.yellow('medium'));
      assert.equal(h.prettyLevel('hard  '), chalk.red('hard  '));
      assert.equal(h.prettyLevel('unknown'), 'unknown');
    });
  }); // #prettyLevel

  describe('#prettySize', function() {
    it('should ok', function() {
      assert.equal(h.prettySize(0), '0.00B');
      assert.equal(h.prettySize(512), '512.00B');
      assert.equal(h.prettySize(1024), '1.00K');
      assert.equal(h.prettySize(1024 * 1024), '1.00M');
      assert.equal(h.prettySize(1024 * 1024 * 1024), '1.00G');
    });
  }); // #prettySize

  describe('#prettyTime', function() {
    it('should ok', function() {
      assert.equal(h.prettyTime(30), '30 seconds');
      assert.equal(h.prettyTime(60), '1 minutes');
      assert.equal(h.prettyTime(2400), '40 minutes');
      assert.equal(h.prettyTime(3600), '1 hours');
      assert.equal(h.prettyTime(7200), '2 hours');
      assert.equal(h.prettyTime(86400), '1 days');
      assert.equal(h.prettyTime(86400 * 3), '3 days');
      assert.equal(h.prettyTime(86400 * 7), '1 weeks');
    });
  }); // #prettyTime

  describe('#levelToName', function() {
    it('should ok', function() {
      assert.equal(h.levelToName(0), ' ');
      assert.equal(h.levelToName(1), 'Easy');
      assert.equal(h.levelToName(2), 'Medium');
      assert.equal(h.levelToName(3), 'Hard');
      assert.equal(h.levelToName(4), ' ');
    });
  }); // #levelToName

  describe('#statusToName', function() {
    it('should ok', function() {
      assert.equal(h.statusToName(10), 'Accepted');
      assert.equal(h.statusToName(11), 'Wrong Answer');
      assert.equal(h.statusToName(12), 'Memory Limit Exceeded');
      assert.equal(h.statusToName(13), 'Output Limit Exceeded');
      assert.equal(h.statusToName(14), 'Time Limit Exceeded');
      assert.equal(h.statusToName(15), 'Runtime Error');
      assert.equal(h.statusToName(16), 'Internal Error');
      assert.equal(h.statusToName(20), 'Compile Error');
      assert.equal(h.statusToName(21), 'Unknown Error');
      assert.equal(h.statusToName(99), 'Unknown');
    });
  }); // #statusToName

  describe('#langToExt', function() {
    it('should ok', function() {
      assert.equal(h.langToExt('bash'), '.sh');
      assert.equal(h.langToExt('c'), '.c');
      assert.equal(h.langToExt('cpp'), '.cpp');
      assert.equal(h.langToExt('csharp'), '.cs');
      assert.equal(h.langToExt('golang'), '.go');
      assert.equal(h.langToExt('java'), '.java');
      assert.equal(h.langToExt('javascript'), '.js');
      assert.equal(h.langToExt('mysql'), '.sql');
      assert.equal(h.langToExt('php'), '.php');
      assert.equal(h.langToExt('python'), '.py');
      assert.equal(h.langToExt('python3'), '.py');
      assert.equal(h.langToExt('ruby'), '.rb');
      assert.equal(h.langToExt('rust'), '.rs');
      assert.equal(h.langToExt('scala'), '.scala');
      assert.equal(h.langToExt('swift'), '.swift');
    });
  }); // #langToExt

  describe('#extToLang', function() {
    it('should ok', function() {
      assert.equal(h.extToLang('/usr/bin/file.sh'), 'bash');
      assert.equal(h.extToLang('/home/skygragon/file.c'), 'c');
      assert.equal(h.extToLang('/var/log/file.cpp'), 'cpp');
      assert.equal(h.extToLang('./file.cs'), 'csharp');
      assert.equal(h.extToLang('../file.go'), 'golang');
      assert.equal(h.extToLang('file.java'), 'java');
      assert.equal(h.extToLang('c:/file.js'), 'javascript');
      assert.equal(h.extToLang('~/leetcode/../file.sql'), 'mysql');
      assert.equal(h.extToLang('~/leetcode/hello.php'), 'php');
      assert.equal(h.extToLang('c:/Users/skygragon/file.py'), 'python');
      assert.equal(h.extToLang('~/file.rb'), 'ruby');
      assert.equal(h.extToLang('~/leetcode/file.rs'), 'rust');
      assert.equal(h.extToLang('/tmp/file.scala'), 'scala');
      assert.equal(h.extToLang('~/leetcode/file.swift'), 'swift');
      assert.equal(h.extToLang('/home/skygragon/file.dat'), 'unknown');
    });
  }); // #extToLang

  describe('#langToCommentStyle', function() {
    it('should ok', function() {
      const C_STYLE = {start: '/*', line: ' *', end: ' */'};
      const RUBY_STYLE = {start: '#', line: '#', end: '#'};
      const SQL_STYLE = {start: '--', line: '--', end: '--'};

      assert.deepEqual(h.langToCommentStyle('bash'), RUBY_STYLE);
      assert.deepEqual(h.langToCommentStyle('c'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('cpp'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('csharp'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('golang'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('java'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('javascript'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('mysql'), SQL_STYLE);
      assert.deepEqual(h.langToCommentStyle('php'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('python'), RUBY_STYLE);
      assert.deepEqual(h.langToCommentStyle('python3'), RUBY_STYLE);
      assert.deepEqual(h.langToCommentStyle('ruby'), RUBY_STYLE);
      assert.deepEqual(h.langToCommentStyle('rust'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('scala'), C_STYLE);
      assert.deepEqual(h.langToCommentStyle('swift'), C_STYLE);
    });
  }); // #langToCommentStyle

  describe('#getSetCookieValue', function() {
    it('should ok', function() {
      const resp = {
        headers: {'set-cookie': [
          'key1=value1; path=/; Httponly',
          'key2=value2; path=/; Httponly']
        }
      };
      const respNoSetCookie = {
        headers: {}
      };

      assert.equal(h.getSetCookieValue(resp, 'key1'), 'value1');
      assert.equal(h.getSetCookieValue(resp, 'key2'), 'value2');
      assert.equal(h.getSetCookieValue(resp, 'key3'), null);
      assert.equal(h.getSetCookieValue(respNoSetCookie, 'key1'), null);
    });
  }); // #getSetCookieValue

  describe('#printSafeHTTP', function() {
    it('should hide sensitive info', function() {
      const raw = [
        "Cookie: 'xxxxxx'",
        "'X-CSRFToken': 'yyyyyy'",
        "'set-cookie': ['zzzzzz']"
      ].join('\r\n');

      const hide = [
        'Cookie: <hidden>',
        "'X-CSRFToken': <hidden>",
        "'set-cookie': <hidden>"
      ].join('\r\n');

      assert.equal(h.printSafeHTTP(raw), hide);
    });
  }); // #printSafeHTTP

  describe('#readStdin', function() {
    function hijackStdin(data) {
      const stream = require('stream');
      const rs = new stream.Readable();
      rs.push(data);
      rs.push(null);

      Object.defineProperty(process, 'stdin', {value: rs});
    }

    it('should ok', function(done) {
      hijackStdin('[1,2]\n3');

      h.readStdin(function(e, data) {
        assert.equal(data, '[1,2]\n3');
        done();
      });
    });

    it('should ok w/ empty input', function(done) {
      hijackStdin('');

      h.readStdin(function(e, data) {
        assert.equal(data, '');
        done();
      });
    });
  }); // #readStdin

  describe('#badge', function() {
    it('should ok', function() {
      chalk.enabled = true;
      assert.equal(h.badge('x'), chalk.white.bgBlue(' x '));
      assert.equal(h.badge('x', 'green'), chalk.black.bgGreen(' x '));
    });

    it('should ok with random', function() {
      const badges = _.values(h.__get__('COLORS'))
        .map(function(x) {
          return chalk[x.fg][x.bg](' random ');
        });

      const i = badges.indexOf(h.badge('random', 'random'));
      assert.equal(i >= 0, true);
    });
  }); // #badge
});


text:
package com.jetbrains.python.testing;

import com.google.common.collect.ObjectArrays;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.NlsSafe;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.psi.PsiDirectory;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.TextAccessor;
import com.intellij.ui.components.JBRadioButton;
import com.intellij.ui.components.JBTextField;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.util.ThreeState;
import com.intellij.util.ui.JBUI;
import com.jetbrains.PySymbolFieldWithBrowseButton;
import com.jetbrains.extensions.ContextAnchor;
import com.jetbrains.extensions.ModuleBasedContextAnchor;
import com.jetbrains.extensions.ProjectSdkContextAnchor;
import com.jetbrains.python.psi.types.TypeEvalContext;
import com.jetbrains.python.run.AbstractPyCommonOptionsForm;
import com.jetbrains.python.run.PyBrowseActionListener;
import com.jetbrains.python.run.PyCommonOptionsFormFactory;
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant;
import com.jetbrains.reflection.ReflectionUtilsKt;
import com.jetbrains.reflection.SimplePropertiesProvider;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Form to display run configuration.
 * It displays target type, target, additional arguments, custom options (if provided) and environment options
 * Create with {@link #create(PyAbstractTestConfiguration, PyTestCustomOption...)}}
 *
 * @author Ilya.Kazakevich
 */
public final class PyTestSharedForm implements SimplePropertiesProvider {

  private JPanel myPanel;
  /**
   * Panel for test targets
   */
  private JPanel myTargets;
  /**
   * Panel for environment options
   */
  private JPanel myOptionsPanel;
  /**
   * Panel for custom options, specific for runner and for "Additional Arguments"al;sop
   */
  private JPanel myCustomOptionsPanel;
  private JPanel myPanelForTargetFields;
  private final ButtonGroup myButtonGroup = new ButtonGroup();
  private AbstractPyCommonOptionsForm myOptionsForm;

  private final Map<String, OptionHolder> myCustomOptions = new LinkedHashMap<>(); // TDO: Linked -- order
  private final TextFieldWithBrowseButton myPathTarget;
  private final PySymbolFieldWithBrowseButton myPythonTarget;

  @NotNull
  JPanel getPanel() {
    return myPanel;
  }

  @NotNull
  @Override
  public List<String> getPropertyNames() {
    return new ArrayList<>(myCustomOptions.keySet());
  }

  @Override
  public void setPropertyValue(@NotNull final String propertyName, @Nullable final String propertyValue) {
    myCustomOptions.get(propertyName).myOptionValue.setText(propertyValue != null ? propertyValue : "");
  }

  @Nullable
  @Override
  public String getPropertyValue(@NotNull final String propertyName) {
    return myCustomOptions.get(propertyName).myOptionValue.getText();
  }

  private PyTestSharedForm(@Nullable final Module module,
                           @NotNull final PyAbstractTestConfiguration configuration) {
    myPathTarget = new TextFieldWithBrowseButton();
    final Project project = configuration.getProject();

    myPathTarget.addBrowseFolderListener(new PyBrowseActionListener(configuration));
    final TypeEvalContext context = TypeEvalContext.userInitiated(project, null);
    final ThreeState testClassRequired = configuration.isTestClassRequired();

    ContextAnchor contentAnchor = (module != null ? new ModuleBasedContextAnchor(module) : new ProjectSdkContextAnchor(project, configuration.getSdk()));
    myPythonTarget = new PySymbolFieldWithBrowseButton(contentAnchor,
                                                       element -> {
                                                         if (element instanceof PsiDirectory) {
                                                           // Folder is always accepted because we can't be sure
                                                           // if it is test-enabled or not
                                                           return true;
                                                         }
                                                         return PyTestsSharedKt.isTestElement(element, testClassRequired, context);
                                                       }, () -> {
      final String workingDirectory = configuration.getWorkingDirectory();
      if (StringUtil.isEmpty(workingDirectory)) {
        return null;
      }
      return LocalFileSystem.getInstance().findFileByPath(workingDirectory);
    });
  }

  /**
   * Titles border used among test run configurations
   */
  public static void setBorderToPanel(@NotNull final JPanel panel, @NotNull final @NlsSafe String title) {
    panel.setBorder(IdeBorderFactory.createTitledBorder(title, false));
  }

  /**
   * @param configuration configuration to configure form on creation
   * @param customOptions additional option names this form shall support. Make sure your configuration has appropriate properties.
   */
  @NotNull
  public static PyTestSharedForm create(@NotNull final PyAbstractTestConfiguration configuration,
                                        final PyTestCustomOption @NotNull ... customOptions) {
    final PyTestSharedForm form = new PyTestSharedForm(configuration.getModule(), configuration);

    for (final PyRunTargetVariant testTargetType : PyRunTargetVariant.values()) {
      final JBRadioButton button =
        new JBRadioButton(StringUtil.capitalize(testTargetType.getCustomName().toLowerCase(Locale.getDefault())));
      button.setActionCommand(testTargetType.name()); // NON-NLS
      button.addActionListener(o -> form.onTargetTypeChanged());
      form.myButtonGroup.add(button);
      form.myTargets.add(button);
    }
    form.myButtonGroup.getElements().nextElement().setSelected(true);

    form.myOptionsForm = PyCommonOptionsFormFactory.getInstance().createForm(configuration.getCommonOptionsFormData());
    final GridConstraints constraints = new GridConstraints();
    constraints.setFill(GridConstraints.FILL_BOTH);
    form.myOptionsPanel.add(form.myOptionsForm.getMainPanel(), constraints);

    setBorderToPanel(form.myPanel, configuration.getTestFrameworkName());

    form.addCustomOptions(
      ObjectArrays.concat(customOptions, new PyTestCustomOption(
        PyTestsSharedKt.getAdditionalArgumentsProperty(),
        PyRunTargetVariant.values()))
    );
    configuration.copyTo(ReflectionUtilsKt.getProperties(form, null, true));
    return form;
  }

  private void addCustomOptions(final PyTestCustomOption @NotNull ... customOptions) {
    if (customOptions.length == 0) {
      return;
    }
    final Map<String, JBTextField> optionValueFields = new HashMap<>();
    for (final PyTestCustomOption option : customOptions) {
      final JBTextField textField = new JBTextField();
      optionValueFields.put(option.getName(), textField);
    }

    final GridBagConstraints constraints = new GridBagConstraints();
    constraints.insets = JBUI.insets(3);
    constraints.gridy = 0;
    constraints.anchor = GridBagConstraints.LINE_START;

    for (final PyTestCustomOption option : customOptions) {
      final JBTextField textField = optionValueFields.get(option.getName());
      final JLabel label = new JLabel(option.getLocalizedName()); // NON-NLS
      label.setHorizontalAlignment(SwingConstants.LEFT);

      constraints.fill = GridBagConstraints.NONE;
      constraints.gridx = 0;
      constraints.weightx = 0;
      myCustomOptionsPanel.add(label, constraints);

      constraints.gridx = 1;
      constraints.weightx = 1.0;
      constraints.fill = GridBagConstraints.HORIZONTAL;
      myCustomOptionsPanel.add(textField, constraints);

      constraints.gridy++;

      myCustomOptions.put(option.getName(), new OptionHolder(option, label, textField));
    }
  }

  @NotNull
  AbstractPyCommonOptionsForm getOptionsForm() {
    return myOptionsForm;
  }

  @NotNull
  public String getTarget() {
    // We should always use system-independent path because only this type of path is processed correctly
    // when stored (folder changed to macros to prevent hard code)
    final String targetText = getActiveTextField().getText().trim();
    return getTargetType() == PyRunTargetVariant.PATH ? FileUtil.toSystemIndependentName(targetText) : targetText;
  }

  public void setTarget(@NotNull final String targetText) {
    getActiveTextField().setText(targetText);
  }

  private void onTargetTypeChanged() {
    final PyRunTargetVariant targetType = getTargetType();

    for (final OptionHolder optionHolder : myCustomOptions.values()) {
      optionHolder.setType(targetType);
    }

    Arrays.stream(myPanelForTargetFields.getComponents()).forEach(myPanelForTargetFields::remove);
    final GridBagConstraints cons = new GridBagConstraints();
    cons.fill = GridBagConstraints.HORIZONTAL;
    cons.weightx = 1;

    if (targetType == PyRunTargetVariant.PATH) {
      myPanelForTargetFields.add(myPathTarget, cons);
    }
    else if (targetType == PyRunTargetVariant.PYTHON) {
      myPanelForTargetFields.add(myPythonTarget, cons);
    }
  }

  @NotNull
  private TextAccessor getActiveTextField() {
    return (getTargetType() == PyRunTargetVariant.PATH ? myPathTarget : myPythonTarget);
  }

  @SuppressWarnings("WeakerAccess") // Accessor for property
  @NotNull
  public PyRunTargetVariant getTargetType() {
    return PyRunTargetVariant.valueOf(myButtonGroup.getSelection().getActionCommand());
  }

  @SuppressWarnings("unused") // Mutator for property
  public void setTargetType(@NotNull final PyRunTargetVariant target) {
    final Enumeration<AbstractButton> elements = myButtonGroup.getElements();
    while (elements.hasMoreElements()) {
      final AbstractButton button = elements.nextElement();
      if (PyRunTargetVariant.valueOf(button.getActionCommand()) == target) {
        myButtonGroup.setSelected(button.getModel(), true);
        break;
      }
    }
    onTargetTypeChanged();
  }

  private static final class OptionHolder {
    @NotNull
    private final PyTestCustomOption myOption;
    @NotNull
    private final JLabel myOptionLabel;
    @NotNull
    private final JTextField myOptionValue;

    private OptionHolder(@NotNull final PyTestCustomOption option,
                         @NotNull final JLabel optionLabel,
                         @NotNull final JTextField optionValue) {
      myOption = option;
      myOptionLabel = optionLabel;
      myOptionValue = optionValue;
    }

    private void setType(@NotNull final PyRunTargetVariant type) {
      final boolean visible = myOption.getMySupportedTypes().contains(type);
      myOptionLabel.setVisible(visible);
      myOptionValue.setVisible(visible);
    }
  }
}


text:
/**
 * A JS hierarchy tree viewer that works with checkboxes
 *
 * @version v0.0.1
 * @author GreenImp - greenimp.co.uk
 * @link https://github.com/GreenImp/tree-view
 */
;(function ($, window, document, undefined){
  "use strict";

  /**
   * Returns the jQuery object for the given `obj`.
   * `obj` can be any type that jQuery understands.
   * if `obj` is a jQuery object, it is returned.
   *
   * @param {*} obj
   * @returns {*}
   */
  var $Obj  = function(obj){
      return obj ? (obj.jQuery ? obj : $(obj)) : $();
    };

  /**
   * Create our component as an extension of the app
   *
   * @type {treeView}
   */
  window.treeView = new function(){
    var lib = this; // component scope

    this.namespace  = 'tree-view';  // component namespace

    /**
     * Returns the tree view root container
     * for the given element
     *
     * @param {*} elm
     * @returns {*}
     */
    var getContainer    = function(elm){
      return $Obj(elm).closest('[data-' + lib.namespace + ']');
    };

    /**
     * returns a list of child inputs for the given parent input
     *
     * @param {*} input
     * @returns {*}
     */
    var getChildren     = function(input){
      return $Obj(input)
        .closest('li')
        .children('ul')
        .find('> li > label :checkbox, > li > label :radio');
    };

    /**
     * Updates the children for the given parent input
     * By default, it also triggers the change event to update
     * their children too
     *
     * @param {*} input
     * @param {boolean=} recurse defaults to `true`
     */
    var updateChildren  = function(input, recurse){
      var $inp      = $Obj(input),
          $children = getChildren($inp), // 1st level children of the input
          isChecked = $inp.prop('checked');

      recurse = recurse !== false;

      if($children.length){
        // change their checked state to match the parent
        $children.prop('checked', isChecked).prop('indeterminate', false);

        // if we have a radio that is checked, we need to ensure other radios,
        // in the same group, have their children correctly unchecked
        if(isChecked && $inp.is(':radio')){
          // go up to the tree view root
          getContainer($inp)
            // find all radios with the same name
            .find(':radio[name="' + $inp.attr('name') + '"]')
            // except for the current one
            .not($inp)
            .prop('checked', false)
            .prop('indeterminate', false)
            // loop through and update their children
            .each(function(i, elm){
              updateChildren(elm, recurse);
            });
        }

        if(recurse){
          // recurse the update down the tree, to the children
          $children.each(function(i, elm){
            updateChildren(elm, recurse);
          });
        }
      }
    };

    /**
     * returns a the parent input for the given input
     *
     * @param {*} input
     * @returns {*}
     */
    var getParent       = function(input){
      var $inp  = $Obj(input);

      return $inp
        // get the closest UL within the root tree
        .closest('ul', getContainer($inp).get(0))
        // find the parent label
        .siblings('label')
        // find any checkbox or radio inside the label
        .find(':checkbox, :radio')
    };

    /**
     * Updates the parent input for the given input
     *
     * @param {*} input
     * @param {boolean=} recurse defaults to `true`
     */
    var updateParent    = function(input, recurse){
      var $inp            = $Obj(input),          // given input
          $childHolder    = $inp.closest('ul'),   // holder for the input and it's siblings
          $parent         = getParent($inp),      // parent input
          isChecked       = $inp.prop('checked'), // flag - whether the input is checked or not
          isIndeterminate = false;                // flag - whether the parent state is indeterminate or not

      if(!$parent.length){
        // no parent found - stop handling
        return;
      }

      // check the indeterminate state of the parent
      if(
        // input is checked and unchecked siblings exist OR input is unchecked and checked siblings exist
      $childHolder.find('input[type="checkbox"]' + (isChecked ? ':not(:checked)' : ':checked')).length  ||
        // parent has indeterminate children
      $childHolder.find('input[type="checkbox"]:indeterminate').length
      ){
        isIndeterminate = true;
      }

      if(isIndeterminate){
        // parent is indeterminate
        $parent.prop('indeterminate', true);
      }else{
        $parent
          .prop('checked', isChecked)
          .prop('indeterminate', false);
      }

      if(recurse !== false){
        // recurse into the parent's parent
        updateParent($parent);
      }
    };

    /**
     * Initialises the component.
     * This can be called when new elements are added to the page
     */
    this.init           = function(){
      /**
       * Ensure that only open branches are shown
       */
      $('[data-' + this.namespace + '] li:not(' + lib.namespace + '-open)').addClass(lib.namespace + '-closed');

      /**
       * Add handles to all branches that have children
       */
      $('[data-' + this.namespace + '] li:has(> ul)')
        // filter out any branches that already have a handle
        .not(':has(> [data-' + lib.namespace + '-handle])')
        // add a handle
        .prepend('<span data-' + lib.namespace + '-handle>></span>');
    };

    /**
     * Open and close trees when clicking on a handle
     */
    $(document).on('click.' + this.namespace, '[data-' + this.namespace + '] [data-' + this.namespace + '-handle]', function(e){
      var $handle     = $Obj(this),
          $container  = $handle.closest('li');

      e.preventDefault();

      if($container.hasClass(lib.namespace + '-open')){
        $container.removeClass(lib.namespace + '-open').addClass(lib.namespace + '-closed');
      }else{
        $container.removeClass(lib.namespace + '-closed').addClass(lib.namespace + '-open');
      }
    });

    /**
     * Handle checkbox state changes
     */
    $(document).on('change.' + this.namespace, '[data-' + this.namespace + '] :checkbox, [data-' + this.namespace + '] :radio', function(){
      var $inp    = $(this),
          checked = $inp.prop('checked');

      // update the child input states and trigger them recursively
      updateChildren($inp);

      // update the parent input states
      updateParent($inp);
    });

    // initialise the component
    this.init();
  };
}(jQuery, window, window.document));


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

Copyright (c) 2013, Sebastian J. Mielke
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * The names of its contributors may not be used to endorse or promote products
    derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-->
<ScrollView  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical"
  android:padding="15dp"
  android:gravity="center"
  >
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <TextView
      android:id="@+id/lbWelcome"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="10dp"
      android:text="@string/welcome"
      android:textAppearance="?android:attr/textAppearanceMedium"
      android:textSize="30sp"
      android:gravity="center"
      />
    <TextView
      android:id="@+id/lbAbout"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="5dp"
      android:text="@string/about"
      android:textAppearance="?android:attr/textAppearanceSmall"
      android:gravity="center"
      />
  </LinearLayout>

  <TextView
    android:id="@+id/lbHint"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hint"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:gravity="center"
    />
  <EditText
    android:id="@+id/edInput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:layout_marginBottom="25dp"
    android:hint="@string/input"
    />
  <!--########## Depending on Method: ##########-->
  <SeekBar
    android:id="@+id/sbShift"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="12dp"
    android:max="25"
    />
  <EditText
    android:id="@+id/edKey"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/key"
    android:inputType="text|textNoSuggestions|textCapCharacters|textVisiblePassword"
    />
  <!--########## Depending on Method END ##########-->
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    >
    <ToggleButton
      android:id="@+id/tgMethod"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:textOff="@string/caesar"
      android:textOn="@string/vigenere"
      />
    <ToggleButton
      android:id="@+id/tgMode"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      />
  </LinearLayout>
  <EditText
    android:id="@+id/edOutput"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="20dp"
    android:hint="@string/output"
    />
</LinearLayout>
</ScrollView>


text:
/*
 * This example was developed using the following STMicroelectronics
 * evaluation boards:
 *
 * - STEVAL_MKI109V3
 * - NUCLEO_F411RE
 * - DISCOVERY_SPC584B
 *
 * Used interfaces:
 *
 * STEVAL_MKI109V3    - Host side:   USB (Virtual COM)
 *                    - Sensor side: SPI(Default) / I2C(supported)
 *
 * NUCLEO_STM32F411RE - Host side: UART(COM) to USB bridge
 *                    - Sensor side: I2C(Default) / SPI(supported)
 *
 * DISCOVERY_SPC584B  - Host side: UART(COM) to USB bridge
 *                    - Sensor side: I2C(Default) / SPI(supported)
 *
 * If you need to run this example on a different hardware platform a
 * modification of the functions: `platform_write`, `platform_read`,
 * `tx_com` and 'platform_init' is required.
 *
 */

/* STMicroelectronics evaluation boards definition
 *
 * Please uncomment ONLY the evaluation boards in use.
 * If a different hardware is used please comment all
 * following target board and redefine yours.
 */

//#define STEVAL_MKI109V3  /* little endian */
//#define NUCLEO_F411RE    /* little endian */
//#define SPC584B_DIS      /* big endian */

/* ATTENTION: By default the driver is little endian. If you need switch
 *            to big endian please see "Endianness definitions" in the
 *            header file of the driver (_reg.h).
 */

#if defined(STEVAL_MKI109V3)
/* MKI109V3: Define communication interface */
#define SENSOR_BUS hspi2
/* MKI109V3: Vdd and Vddio power supply values */
#define PWM_3V3 915

#elif defined(NUCLEO_F411RE)
/* NUCLEO_F411RE: Define communication interface */
#define SENSOR_BUS hi2c1

#elif defined(SPC584B_DIS)
/* DISCOVERY_SPC584B: Define communication interface */
#define SENSOR_BUS I2CD1

#endif

/* Includes ------------------------------------------------------------------*/
#include <string.h>
#include <stdio.h>
#include "lis3de_reg.h"

#if defined(NUCLEO_F411RE)
#include "stm32f4xx_hal.h"
#include "usart.h"
#include "gpio.h"
#include "i2c.h"

#elif defined(STEVAL_MKI109V3)
#include "stm32f4xx_hal.h"
#include "usbd_cdc_if.h"
#include "gpio.h"
#include "spi.h"
#include "tim.h"

#elif defined(SPC584B_DIS)
#include "components.h"
#endif

/* Private macro -------------------------------------------------------------*/
#define TX_BUF_DIM          1000

/* Define number of byte for each sensor sample */
#define OUT_XYZ_SIZE        6

/* Define FIFO watermark to 10 samples */
#define FIFO_WATERMARK      10

/* Private variables ---------------------------------------------------------*/

static uint8_t tx_buffer[TX_BUF_DIM];

static float acceleration_mg[3];
static int16_t data_raw_acceleration[3];
static stmdev_ctx_t dev_ctx;

/* Extern variables ----------------------------------------------------------*/

/* Platform Functions --------------------------------------------------------*/
/*
 *   WARNING:
 *   Functions declare in this section are defined at the end of this file
 *   and are strictly related to the hardware platform used.
 *
 */
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
                              uint16_t len);
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
                             uint16_t len);
static void tx_com(uint8_t *tx_buffer, uint16_t len);
static void platform_delay(uint32_t ms);
static void platform_init(void);

/* Main Example --------------------------------------------------------------*/
void lis3de_fifo_read(void)
{
  uint8_t whoamI;
  dev_ctx.write_reg = platform_write;
  dev_ctx.read_reg = platform_read;
  dev_ctx.handle = &SENSOR_BUS;
  whoamI = 0;
  /* Initialize platform specific hardware */
  platform_init();

  lis3de_device_id_get(&dev_ctx, &whoamI);
  if ( whoamI != LIS3DE_ID )
    while (1); /*manage here device not found */

  /* Enable Block Data Update. */
  lis3de_block_data_update_set(&dev_ctx, PROPERTY_ENABLE);
  /* Set Output Data Rate to 100 hz. */
  lis3de_data_rate_set(&dev_ctx, LIS3DE_ODR_100Hz);
  /* Set full scale to 2 g. */
  lis3de_full_scale_set(&dev_ctx, LIS3DE_2g);
  /*
   * Set operating mode to high resolution.
   */
  lis3de_operating_mode_set(&dev_ctx, LIS3DE_LP);
  /* Set FIFO watermark to FIFO_WATERMARK samples. */
  lis3de_fifo_watermark_set(&dev_ctx, FIFO_WATERMARK);
  /*
   * Set FIFO mode to Stream mode: Accumulate samples and
   * override old data.
   */
  lis3de_fifo_mode_set(&dev_ctx, LIS3DE_DYNAMIC_STREAM_MODE);
  /* Enable FIFO. */
  lis3de_fifo_set(&dev_ctx, PROPERTY_ENABLE);

  while (1) {
    uint8_t flags;
    uint8_t num = 0;
    /* Check if FIFO level over threshold. */
    lis3de_fifo_fth_flag_get(&dev_ctx, &flags);

    if (flags) {
      /* Read number of sample in FIFO. */
      lis3de_fifo_data_level_get(&dev_ctx, &num);

      while (num-- > 0) {
        /* Read XL samples. */
        lis3de_acceleration_raw_get(&dev_ctx, data_raw_acceleration);
        acceleration_mg[0] = lis3de_from_fs2_to_mg(data_raw_acceleration[0]);
        acceleration_mg[1] = lis3de_from_fs2_to_mg(data_raw_acceleration[1]);
        acceleration_mg[2] = lis3de_from_fs2_to_mg(data_raw_acceleration[2]);
        sprintf((char *)tx_buffer,
                "Acceleration [mg]:%4.2f\t%4.2f\t%4.2f\r\n",
                acceleration_mg[0], acceleration_mg[1], acceleration_mg[2]);
        tx_com( tx_buffer, strlen( (char const *)tx_buffer ) );
      }
    }

    else {
      /* Force compiler to generate code, avoiding I2C polling stress. */
      for (volatile uint32_t i = 0; i < 10000; i++);
    }
  }
}

/*
 * @brief  Write generic device register (platform dependent)
 *
 * @param  handle    customizable argument. In this examples is used in
 *                   order to select the correct sensor bus handler.
 * @param  reg       register to write
 * @param  bufp      pointer to data to write in register reg
 * @param  len       number of consecutive register to write
 *
 */
static int32_t platform_write(void *handle, uint8_t reg, const uint8_t *bufp,
                              uint16_t len)
{
#if defined(NUCLEO_F411RE)
  /* Write multiple command */
  reg |= 0x80;
  HAL_I2C_Mem_Write(handle, LIS3DE_I2C_ADD_L, reg,
                    I2C_MEMADD_SIZE_8BIT, (uint8_t*) bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
  /* Write multiple command */
  reg |= 0x40;
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
  HAL_SPI_Transmit(handle, &reg, 1, 1000);
  HAL_SPI_Transmit(handle, (uint8_t*) bufp, len, 1000);
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
  /* Write multiple command */
  reg |= 0x80;
  i2c_lld_write(handle,  LIS3DE_I2C_ADD_L & 0xFE, reg, (uint8_t*) bufp, len);
#endif
  return 0;
}

/*
 * @brief  Read generic device register (platform dependent)
 *
 * @param  handle    customizable argument. In this examples is used in
 *                   order to select the correct sensor bus handler.
 * @param  reg       register to read
 * @param  bufp      pointer to buffer that store the data read
 * @param  len       number of consecutive register to read
 *
 */
static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp,
                             uint16_t len)
{
#if defined(NUCLEO_F411RE)
  /* Read multiple command */
  reg |= 0x80;
  HAL_I2C_Mem_Read(handle, LIS3DE_I2C_ADD_L, reg,
                   I2C_MEMADD_SIZE_8BIT, bufp, len, 1000);
#elif defined(STEVAL_MKI109V3)
  /* Read multiple command */
  reg |= 0xC0;
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_RESET);
  HAL_SPI_Transmit(handle, &reg, 1, 1000);
  HAL_SPI_Receive(handle, bufp, len, 1000);
  HAL_GPIO_WritePin(CS_up_GPIO_Port, CS_up_Pin, GPIO_PIN_SET);
#elif defined(SPC584B_DIS)
  /* Read multiple command */
  reg |= 0x80;
  i2c_lld_read(handle, LIS3DE_I2C_ADD_L & 0xFE, reg, bufp, len);
#endif
  return 0;
}

/*
 * @brief  Send buffer to console (platform dependent)
 *
 * @param  tx_buffer     buffer to transmit
 * @param  len           number of byte to send
 *
 */
static void tx_com(uint8_t *tx_buffer, uint16_t len)
{
#if defined(NUCLEO_F411RE)
  HAL_UART_Transmit(&huart2, tx_buffer, len, 1000);
#elif defined(STEVAL_MKI109V3)
  CDC_Transmit_FS(tx_buffer, len);
#elif defined(SPC584B_DIS)
  sd_lld_write(&SD2, tx_buffer, len);
#endif
}

/*
 * @brief  platform specific delay (platform dependent)
 *
 * @param  ms        delay in ms
 *
 */
static void platform_delay(uint32_t ms)
{
#if defined(NUCLEO_F411RE) | defined(STEVAL_MKI109V3)
  HAL_Delay(ms);
#elif defined(SPC584B_DIS)
  osalThreadDelayMilliseconds(ms);
#endif
}

/*
 * @brief  platform specific initialization (platform dependent)
 */
static void platform_init(void)
{
#if defined(STEVAL_MKI109V3)
  TIM3->CCR1 = PWM_3V3;
  TIM3->CCR2 = PWM_3V3;
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2);
  platform_delay(1000);
#endif
}


text:
<?php

namespace Fuel\Migrations;

class Create_useraccounts
{
	public function up()
	{
		\DBUtil::create_table('useraccounts', array(
			'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true, 'unsigned' => true),
			'email' => array('constraint' => 255, 'type' => 'varchar'),
			'password' => array('constraint' => 255, 'type' => 'varchar'),
			'active' => array('type' => 'boolean'),
			'UserGroup_id' => array('constraint' => 11, 'type' => 'int', 'null' => true),
			'created_at' => array('constraint' => 11, 'type' => 'int', 'null' => true),
			'updated_at' => array('constraint' => 11, 'type' => 'int', 'null' => true),

		), array('id'));
	}

	public function down()
	{
		\DBUtil::drop_table('useraccounts');
	}
}


text:
'use strict';

const GuildChannel = require('./GuildChannel');
const Webhook = require('./Webhook');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const Collection = require('../util/Collection');
const DataResolver = require('../util/DataResolver');
const MessageStore = require('../stores/MessageStore');

/**
 * Represents a guild text channel on Discord.
 * @extends {GuildChannel}
 * @implements {TextBasedChannel}
 */
class TextChannel extends GuildChannel {
  /**
   * @param {Guild} guild The guild the text channel is part of
   * @param {Object} data The data for the text channel
   */
  constructor(guild, data) {
    super(guild, data);
    /**
     * A collection containing the messages sent to this channel
     * @type {MessageStore<Snowflake, Message>}
     */
    this.messages = new MessageStore(this);
    this._typing = new Map();
  }

  _patch(data) {
    super._patch(data);

    /**
     * The topic of the text channel
     * @type {?string}
     */
    this.topic = data.topic;

    /**
     * If the guild considers this channel NSFW
     * @type {boolean}
     * @readonly
     */
    this.nsfw = data.nsfw || /^nsfw(-|$)/.test(this.name);

    /**
     * The ID of the last message sent in this channel, if one was sent
     * @type {?Snowflake}
     */
    this.lastMessageID = data.last_message_id;

    /**
     * The ratelimit per user for this channel
     * @type {number}
     */
    this.rateLimitPerUser = data.rate_limit_per_user || 0;

    /**
     * The timestamp when the last pinned message was pinned, if there was one
     * @type {?number}
     */
    this.lastPinTimestamp = data.last_pin_timestamp ? new Date(data.last_pin_timestamp).getTime() : null;

    if (data.messages) for (const message of data.messages) this.messages.add(message);
  }

  /**
   * Sets the rate limit per user for this channel.
   * @param {number} rateLimitPerUser The new ratelimit
   * @param {string} [reason] Reason for changing the channel's ratelimits
   * @returns {Promise<TextChannel>}
   */
  setRateLimitPerUser(rateLimitPerUser, reason) {
    return this.edit({ rateLimitPerUser }, reason);
  }

  /**
   * Sets whether this channel is flagged as NSFW.
   * @param {boolean} nsfw Whether the channel should be considered NSFW
   * @param {string} [reason] Reason for changing the channel's NSFW flag
   * @returns {Promise<TextChannel>}
   */
  setNSFW(nsfw, reason) {
    return this.edit({ nsfw }, reason);
  }

  /**
   * Fetches all webhooks for the channel.
   * @returns {Promise<Collection<Snowflake, Webhook>>}
   * @example
   * // Fetch webhooks
   * channel.fetchWebhooks()
   *   .then(hooks => console.log(`This channel has ${hooks.size} hooks`))
   *   .catch(console.error);
   */
  fetchWebhooks() {
    return this.client.api.channels[this.id].webhooks.get().then(data => {
      const hooks = new Collection();
      for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
      return hooks;
    });
  }

  /**
   * Creates a webhook for the channel.
   * @param {string} name The name of the webhook
   * @param {Object} [options] Options for creating the webhook
   * @param {BufferResolvable|Base64Resolvable} [options.avatar] Avatar for the webhook
   * @param {string} [options.reason] Reason for creating the webhook
   * @returns {Promise<Webhook>} webhook The created webhook
   * @example
   * // Create a webhook for the current channel
   * channel.createWebhook('Snek', {
   *   avatar: 'https://i.imgur.com/mI8XcpG.jpg',
   *   reason: 'Needed a cool new Webhook'
   * })
   *   .then(console.log)
   *   .catch(console.error)
   */
  async createWebhook(name, { avatar, reason } = {}) {
    if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
      avatar = await DataResolver.resolveImage(avatar);
    }
    return this.client.api.channels[this.id].webhooks.post({ data: {
      name, avatar,
    }, reason }).then(data => new Webhook(this.client, data));
  }

  // These are here only for documentation purposes - they are implemented by TextBasedChannel
  /* eslint-disable no-empty-function */
  get lastMessage() {}
  get lastPinAt() {}
  send() {}
  startTyping() {}
  stopTyping() {}
  get typing() {}
  get typingCount() {}
  createMessageCollector() {}
  awaitMessages() {}
  bulkDelete() {}
  acknowledge() {}
  _cacheMessage() {}
}

TextBasedChannel.applyToClass(TextChannel, true);

module.exports = TextChannel;


text:
package ai.verta.client.entities.utils

import ai.verta.client.entities.DummyArtifact

import org.scalatest.FunSuite
import org.scalatest.Assertions._

class TestValueType extends FunSuite {
  test("ListValueType should correctly infer type, and not accept wrong type") {
    val list: ValueType = List[ValueType](1, "abc", 4.5)
    val underlyingList = list.asList.get

    assert(underlyingList(0).asBigInt.get == BigInt(1))
    assert(underlyingList(1).asString.get == "abc")
    assert(underlyingList(2).asDouble.get == 4.5)

    val artifact = new DummyArtifact("hello")
    assertTypeError("val list: ValueType = List[ValueType](artifact)")
  }

  test("Converting ListValueType to GenericObject and back should not corrupt the values") {
    val list: ValueType = List[ValueType](1, "abc", 4.5)

    val convertedList = KVHandler.convertFromValueType(list, "conversion failed")
      .flatMap(obj => KVHandler.convertToValueType(obj, "conversion failed"))
      .get

    assert(list == convertedList)
  }
}


text:
package com.mta.tehreer.internal;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.mta.tehreer.collections.ByteList;
import com.mta.tehreer.collections.FloatList;
import com.mta.tehreer.collections.IntList;
import com.mta.tehreer.collections.PointList;
import com.mta.tehreer.internal.collections.JByteArrayList;

import java.util.Iterator;

public class Description {
    private static final String NULL = "null";

    public static @NonNull String forByteArray(@NonNull byte[] array) {
        return forByteList(new JByteArrayList(array, 0, array.length));
    }

    public static @NonNull String forByteList(@Nullable ByteList list) {
        if (list != null) {
            Description description = new Description();
            description.begin();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                description.append(String.valueOf(list.get(i)));
            }
            description.end();

            return description.toString();
        }

        return NULL;
    }

    public static @NonNull String forIntList(@Nullable IntList list) {
        if (list != null) {
            Description description = new Description();
            description.begin();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                description.append(String.valueOf(list.get(i)));
            }
            description.end();

            return description.toString();
        }

        return NULL;
    }

    public static @NonNull String forFloatList(@Nullable FloatList list) {
        if (list != null) {
            Description description = new Description();
            description.begin();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                description.append(String.valueOf(list.get(i)));
            }
            description.end();

            return description.toString();
        }

        return NULL;
    }

    public static @NonNull String forPointList(@Nullable PointList list) {
        if (list != null) {
            Description description = new Description();
            description.begin();
            int size = list.size();
            for (int i = 0; i < size; i++) {
                description.append(String.valueOf(list.getX(i)));
                description.append(String.valueOf(list.getY(i)));
            }
            description.end();

            return description.toString();
        }

        return NULL;
    }

    public static @NonNull <T> String forIterator(@Nullable Iterator<T> iterator) {
        if (iterator != null) {
            Description description = new Description();
            description.begin();
            while (iterator.hasNext()) {
                T element = iterator.next();
                description.append(element.toString());
            }
            description.end();

            return description.toString();
        }

        return NULL;
    }

    public static @NonNull <T> String forIterable(@NonNull Iterable<T> iterable) {
        return forIterator(iterable.iterator());
    }

    private final @NonNull StringBuilder builder = new StringBuilder();
    private boolean begun = false;

    private Description() {
    }

    private void begin() {
        builder.append("[");
        begun = true;
    }

    private void append(String value) {
        if (!begun) {
            builder.append(", ");
        }
        builder.append(value);
        begun = false;
    }

    private void end() {
        builder.append("]");
    }

    @Override
    public String toString() {
        return builder.toString();
    }
}


text:
void xfreopen(const char *path, const char *mode, FILE *stream);

void dump_hdr(const bam_hdr_t* hdr);

#endif


text:
/* global describe, it, before, after, JSON */
'use strict';

// A require to work on node or browser
function smartRequire(name, windowName) {
    var stripName = function(moduleName) {
        if (!moduleName) {
            return moduleName;
        }
        var strippedName = moduleName.match(/\/([^\/]+)$/);
        return strippedName ? strippedName[1] : moduleName;
    };
    if (typeof require === 'function') {
        return require(name);
    }
    return window[windowName || stripName(name)];
}

var assert = smartRequire('chai').assert,
    sinon = smartRequire('sinon'),
    jsonpipe = smartRequire('../lib/jsonpipe'),
    testUrl = 'https://github.com/eBay/jsonpipe'; // this is a dummy URL, the actual response will be simulated by sinon

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe('jsonpipe', function() {
    it('should check if jsonpipe API is present', function() {
        assert.isNotNull(jsonpipe, 'jsonpipe should not be null');
    });

    describe('verify the iterface', function() {
        var fakexhr;

        before(function() {
            fakexhr = sinon.useFakeXMLHttpRequest();
        });

        after(function() {
            fakexhr.restore();
        });

        it('should return undefined when called with no arguments', function() {
            assert.isUndefined(jsonpipe.flow());
        });

        it('should return undefined when called with a string url with no options', function() {
            assert.isUndefined(jsonpipe.flow(testUrl));
        });

        it('should return undefined when called with options object with no attributes', function() {
            assert.isUndefined(jsonpipe.flow({}));
        });

        it('should return undefined when called with options object with only url attribute', function() {
            assert.isUndefined(jsonpipe.flow({
                "url": testUrl
            }));
        });

        it('should return XMLHttpRequest object when called with url and success attributes', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {}
            });
            assert.isObject(xhr);
        });

        it('should return XMLHttpRequest object when called with url and error attributes', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "error": function() {}
            });
            assert.isObject(xhr);
        });

        it('should return object which is an instance of XMLHttpRequest', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {}
            });
            assert.instanceOf(xhr, XMLHttpRequest);
        });

        it('should return XMLHttpRequest object when called with url, success and onHeaders attributes', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {},
                "onHeaders": function() {}
            });
            assert.isObject(xhr);
        });

        it('should check if request headers are set right', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {},
                "headers": {
                    "x-test": "jsonpipe"
                }
            });
            assert.equal(xhr.requestHeaders['x-test'], 'jsonpipe');
        });

        it('should default withCredentials to true if not specified in options', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {}
            });
            assert.equal(xhr.withCredentials, true);
        });

        it('should set withCredentials baed on the supplied options', function() {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {},
                "withCredentials": false
            });
            assert.equal(xhr.withCredentials, false);
        });
    });

    describe('verify onHeaders scenarios', function() {
        var fakexhr;

        before(function() {
            fakexhr = sinon.useFakeXMLHttpRequest();
        });

        after(function() {
            fakexhr.restore();
        });

        it('should receive headers', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {},
                "onHeaders": function(statusText, header) {
                    assert.equal(statusText, 'OK');
                    assert.equal(header["x-example-test"], "test value");
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;

            xhr.respond(200, {
                "Content-Type": "application/json",
                "X-Example-Test": "test value"
            },
            JSON.stringify({
                "id": 7
            }));
        });
    });

    describe('verify success scenarios', function() {
        var fakexhr,
            headers = {
                "Content-Type": "application/json",
                "Transfer-Encoding": "chunked"
            };

        before(function() {
            fakexhr = sinon.useFakeXMLHttpRequest();
        });

        after(function() {
            fakexhr.restore();
        });

        it('should process a JSON response with no chunks', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function(data) {
                    assert.equal(data.id, 7);
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;

            xhr.respond(200, {
                "Content-Type": "application/json"
            },
            JSON.stringify({
                "id": 7
            }));
        });

        it('should process a JSON response with 1 chunk and ending with \\n\\n', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function(data) {
                    assert.equal(data.id, 7);
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;
            xhr.respond(200, headers,
                '{"id": 7}\n\n');
        });

        it('should process a JSON response with 1 chunk and starting with \\n\\n', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function(data) {
                    assert.equal(data.id, 7);
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;
            xhr.respond(200, headers,
                '\n\n{"id": 7}');
        });

        it('should process a JSON response with 1 chunk, starting and ending with \\n\\n', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function(data) {
                    assert.equal(data.id, 7);
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;
            xhr.respond(200, headers,
                '\n\n{"id": 7}\n\n');
        });

        it('should process a JSON response with 1 chunk, and JSON separated with \\n\\n', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 2) {
                            done();
                        }
                    }
                });

            // increase the chunkSize
            xhr.chunkSize = 20;
            xhr.respond(200, headers,
                '{"id": 0}\n\n{"id": 1}');
        });

        it('should process a JSON response with 1 chunk, and JSON separated with \\n\\n and ending with \\n\\n', function(done) { // eslint-disable-line max-len
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 2) {
                            done();
                        }
                    }
                });

            // increase the chunkSize
            xhr.chunkSize = 40;
            xhr.respond(200, headers,
                '{"id": 0}\n\n{"id": 1}\n\n');
        });

        it('should process a JSON response with multile chunks', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 3) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(200, headers,
                '{"id": 0}\n\n{"id": 1}\n\n{"id": 2}');
        });

        it('should process a JSON response with multile chunks and bigger buffer size', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 3) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 15;
            xhr.respond(200, headers,
                '{"id": 0}\n\n{"id": 1}\n\n{"id": 2}');
        });

        it('should process a JSON response with multile chunks, staring and ending with \\n\\n', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 3) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(200, headers,
                '\n\n{"id": 0}\n\n{"id": 1}\n\n{"id": 2}\n\n');
        });

        it('should process a JSON response with multile chunks, and a complete function', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                    },
                    "complete": function() {
                        done();
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(200, headers,
                '\n\n{"id": 0}\n\n{"id": 1}\n\n{"id": 2}\n\n');
        });

        it('should process a JSON response which has Array chunks', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.isArray(data);
                        if (++chunkCount === 2) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(200, headers,
                '[{"id": 0},{"id": 1}]\n\n[{"id": 2},{"id": 3}]');
        });

        it('should process a multi chunk JSON response separated with the provided option delimiter', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "delimiter": "\r\r",
                    "success": function(data) {
                        assert.equal(data.id, chunkCount++);
                        if (chunkCount === 3) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(200, headers,
                '\r\r{"id": 0}\r\r{"id": 1}\r\r{"id": 2}\r\r');
        });

        it('should process a JSON response which has a success code other than 200', function(done) {
            var chunkCount = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.isArray(data);
                        if (++chunkCount === 2) {
                            done();
                        }
                    }
                });

            // reduce the chunkSize
            xhr.chunkSize = 5;
            xhr.respond(205, headers,
                '[{"id": 0},{"id": 1}]\n\n[{"id": 2},{"id": 3}]');
        });
    });

    describe('vefiry error scenarios', function() {
        var fakexhr,
            headers = {
                "Content-Type": "application/json",
                "Transfer-Encoding": "chunked"
            };

        before(function() {
            fakexhr = sinon.useFakeXMLHttpRequest();
        });

        after(function() {
            fakexhr.restore();
        });

        it('should call error function on invalid JSON response', function(done) {
            var chunkSize = 0,
                xhr = jsonpipe.flow(testUrl, {
                    "error": function(msg) {
                        assert.equal(msg, 'parsererror');
                        if (++chunkSize === 2) {
                            done();
                        }
                    }
                });

            xhr.respond(200, headers, '{"id"\n\n}');
        });

        it('should call success function on valid chunk and error function on invalid JSON chunk', function(done) {
            var chunkSize = 0,
                callDone = function() {
                    if (++chunkSize === 2) {
                        done();
                    }
                },
                xhr = jsonpipe.flow(testUrl, {
                    "success": function(data) {
                        assert.equal(data.id, 1);
                        callDone();
                    },
                    "error": function(msg) {
                        assert.equal(msg, 'parsererror');
                        callDone();
                    }
                });

            xhr.respond(200, headers, '{"id"}\n\n{"id": 1}');
        });

        it('should call error function if timeout exceeded', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "error": function() {
                    assert.equal(xhr.status, 0);
                    done();
                },
                "timeout": 20
            });

            // Set auto response
            xhr.autoRespond = true;
            xhr.autoRespondAfter = 50;
        });

        it('should call error function on HTTP response code other than 200. e.g. 404', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "error": function(msg) {
                    assert.equal(xhr.status, '404');
                    assert.equal(msg, 'Not Found');
                    done();
                }
            });

            xhr.respond(404);
        });
    });

    describe('verify different Content-Type Headers', function() {
        var fakexhr;

        before(function() {
            fakexhr = sinon.useFakeXMLHttpRequest();
        });

        after(function() {
            fakexhr.restore();
        });

        it('should receive content-type header as set in the response', function(done) {
            var xhr = jsonpipe.flow(testUrl, {
                "success": function() {},
                "onHeaders": function(statusText, header) {
                    assert.equal(statusText, 'OK');
                    assert.equal(header["content-type"], "multipart/json");
                    done();
                }
            });

            // increase the chunkSize
            xhr.chunkSize = 20;

            xhr.respond(200, {
                "content-type": "multipart/json",
                "Transfer-Encoding": "chunked"
            },
            '{"id": 0}\n\n{"id": 1}\n\n');
        });
    });

    /* describe('verify a real server endpoint', function() {
        this.timeout(15000);
        it('should parse the response from a real server', function(done) {
            var chunkCount = 0;
            jsonpipe.flow('http://10.64.252.29/saas/SaasTest', {
                "success": function(data) {
                    assert.equal(typeof data, 'object');
                    if (++chunkCount === 3) {
                        done();
                    }
                },
                withCredentials: false
            });
        });
    }); */
});


text:
module Chatrix
  module Api
    # Contains methods for accessing the media endpoints of a server.
    class Media < ApiComponent
      # API path for media operations.
      #
      # Because for some reason this one is different.
      MEDIA_PATH = '/_matrix/media/r0'.freeze

      # Initializes a new Media instance.
      # @param matrix [Matrix] The matrix API instance.
      def initialize(matrix)
        super
        @media_uri = @matrix.homeserver + MEDIA_PATH
      end

      # Download media from the server.
      # @param server [String] The server component of an `mxc://` URL.
      # @param id [String] The media ID of the `mxc://` URL (the path).
      # @return [HTTParty::Response] The HTTParty response object for the
      #   request. Use the response object to inspect the returned data.
      def download(server, id)
        make_request(
          :get,
          "/download/#{server}/#{id}",
          headers: { 'Accept' => '*/*' },
          base: @media_uri
        )
      end

      # Download the thumbnail for a media resource.
      # @param server [String] The server component of an `mxc://` URL.
      # @param id [String] The media ID of the `mxc://` URL (the path).
      # @param width [Fixnum] Desired width of the thumbnail.
      # @param height [Fixnum] Desired height of the thumbnail.
      # @param method ['scale', 'crop'] Desired resizing method.
      # @return [HTTParty::Response] The HTTParty response object for the
      #   request. Use the response object to inspect the returned data.
      def get_thumbnail(server, id, width, height, method = 'scale')
        make_request(
          :get,
          "/thumbnail/#{server}/#{id}",
          headers: { 'Accept' => 'image/jpeg, image/png' },
          params: { width: width, height: height, method: method },
          base: @media_uri
        )
      end

      # Uploads a new media file to the server.
      # @param type [String] The `Content-Type` of the media being uploaded.
      # @param path [String] Path to a file to upload.
      # @return [String] The MXC URL for the uploaded object (`mxc://...`).
      def upload(type, path)
        File.open(path, 'r') do |file|
          make_request(
            :post, '/upload',
            headers: {
              'Content-Type' => type, 'Content-Length' => file.size.to_s,
              'Transfer-Encoding' => 'chunked'
            },
            content: file, base: @media_uri
          )['content_uri']
        end
      end
    end
  end
end


text:
package utils

import (
	"math"
)

// this file contains pure go implementations of the min_max functions that are
// SIMD accelerated so that we can fallback to these if the cpu doesn't support
// AVX2 or SSE4 instructions.

func int8MinMax(values []int8) (min, max int8) {
	min = math.MaxInt8
	max = math.MinInt8

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func uint8MinMax(values []uint8) (min, max uint8) {
	min = math.MaxUint8
	max = 0

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func int16MinMax(values []int16) (min, max int16) {
	min = math.MaxInt16
	max = math.MinInt16

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func uint16MinMax(values []uint16) (min, max uint16) {
	min = math.MaxUint16
	max = 0

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func int32MinMax(values []int32) (min, max int32) {
	min = math.MaxInt32
	max = math.MinInt32

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func uint32MinMax(values []uint32) (min, max uint32) {
	min = math.MaxUint32
	max = 0

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func int64MinMax(values []int64) (min, max int64) {
	min = math.MaxInt64
	max = math.MinInt64

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

func uint64MinMax(values []uint64) (min, max uint64) {
	min = math.MaxUint64
	max = 0

	for _, v := range values {
		if min > v {
			min = v
		}
		if max < v {
			max = v
		}
	}
	return
}

var minmaxFuncs = struct {
	i8   func([]int8) (int8, int8)
	ui8  func([]uint8) (uint8, uint8)
	i16  func([]int16) (int16, int16)
	ui16 func([]uint16) (uint16, uint16)
	i32  func([]int32) (int32, int32)
	ui32 func([]uint32) (uint32, uint32)
	i64  func([]int64) (int64, int64)
	ui64 func([]uint64) (uint64, uint64)
}{}

// GetMinMaxInt8 returns the min and max for a int8 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxInt8(v []int8) (min, max int8) {
	return minmaxFuncs.i8(v)
}

// GetMinMaxUint8 returns the min and max for a uint8 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxUint8(v []uint8) (min, max uint8) {
	return minmaxFuncs.ui8(v)
}

// GetMinMaxInt16 returns the min and max for a int16 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxInt16(v []int16) (min, max int16) {
	return minmaxFuncs.i16(v)
}

// GetMinMaxUint16 returns the min and max for a uint16 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxUint16(v []uint16) (min, max uint16) {
	return minmaxFuncs.ui16(v)
}

// GetMinMaxInt32 returns the min and max for a int32 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxInt32(v []int32) (min, max int32) {
	return minmaxFuncs.i32(v)
}

// GetMinMaxUint32 returns the min and max for a uint32 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxUint32(v []uint32) (min, max uint32) {
	return minmaxFuncs.ui32(v)
}

// GetMinMaxInt64 returns the min and max for a int64 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxInt64(v []int64) (min, max int64) {
	return minmaxFuncs.i64(v)
}

// GetMinMaxUint64 returns the min and max for a uint64 slice, using AVX2 or
// SSE4 cpu extensions if available, falling back to a pure go implementation
// if they are unavailable or built with the noasm tag.
func GetMinMaxUint64(v []uint64) (min, max uint64) {
	return minmaxFuncs.ui64(v)
}


text:
package com.palantir.atlasdb.keyvalue.impl;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.palantir.atlasdb.keyvalue.api.KeyValueService;
import com.palantir.exception.NotInitializedException;
import java.time.Duration;
import org.awaitility.Awaitility;
import org.junit.Test;

public class AsyncInitializeableInMemoryKvsTest {

    @Test
    public void createSyncIgnoresEventuallySucceed() {
        KeyValueService kvs = AsyncInitializeableInMemoryKvs.createAndStartInit(false, false);
        assertThat(kvs.isInitialized()).isTrue();
        assertThat(kvs.getAllTableNames()).isEmpty();
    }

    @Test
    public void createAsyncCanEventuallySucceed() {
        KeyValueService kvs = AsyncInitializeableInMemoryKvs.createAndStartInit(true, true);
        assertThat(kvs.isInitialized()).isFalse();
        assertThatThrownBy(kvs::getAllTableNames).isInstanceOf(NotInitializedException.class);

        Awaitility.await().atMost(Duration.ofSeconds(2)).until(kvs::isInitialized);
        assertThat(kvs.isInitialized()).isTrue();
        assertThat(kvs.getAllTableNames()).isEmpty();
    }

    @Test
    public void createAsyncCanAlwaysFail() {
        KeyValueService kvs = AsyncInitializeableInMemoryKvs.createAndStartInit(true, false);
        assertThat(kvs.isInitialized()).isFalse();
        assertThatThrownBy(kvs::getAllTableNames).isInstanceOf(NotInitializedException.class);

        Awaitility.await().during(Duration.ofSeconds(2)).until(() -> !kvs.isInitialized());
    }
}


text:
System.config({
    baseURL: '/',
    warnings: true,
    map: {
        'src': 'src',
        '@angular/core': 'node_modules/@angular/core/bundles/core.umd.js',
        '@angular/common': 'node_modules/@angular/common/bundles/common.umd.js',
        '@angular/compiler': 'node_modules/@angular/compiler/bundles/compiler.umd.js',
        '@angular/platform-browser': 'node_modules/@angular/platform-browser/bundles/platform-browser.umd.js',
        '@angular/platform-browser-dynamic': 'node_modules/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
        '@angular/http': 'node_modules/@angular/http/bundles/http.umd.js',
        '@angular/router': 'node_modules/@angular/router/bundles/router.umd.js',
        'rxjs': 'node_modules/rxjs'
    },
    packages: {
        '': { defaultExtension: 'js', main: 'index.js' },
        'src': { defaultExtension: 'js' },
        'rxjs': { defaultExtension: 'js' },
        '@angular/common': { defaultExtension: 'js' },
        '@angular/compiler': { defaultExtension: 'js' },
        '@angular/core': { defaultExtension: 'js' },
        '@angular/http': { defaultExtension: 'js' },
        '@angular/platform-browser': { defaultExtension: 'js' },
        '@angular/platform-browser-dynamic': { defaultExtension: 'js' },
        '@angular/router': { defaultExtension: 'js' }
    }
});
//# sourceMappingURL=systemjs.config.js.map


text:
{% extends "microblogging/base.html" %}

{% load i18n %}
{% load avatar_tags %}

{% block head_title %}{% blocktrans %}Followers of {{ other_user }}{% endblocktrans %}{% endblock %}

{% block body %}

{% blocktrans %}Followers of {{ other_user }}{% endblocktrans %}

    {% url profiles.views.profile other_user.username as other_user_url %}

{% blocktrans %}Followers of {{ other_user }}'s tweets:{% endblocktrans %}

    {% if other_user.followers.all %}
        {% for following in other_user.followers.all %}
            {# @@@ this is common code from all profiles list -- refactor #}

                {# @@@ factor out style into css file #}

{% avatar following.follower 40 %}

{{ following.follower }}

        {% endfor %}
    {% else %}

{% trans 'No followers.' %}

    {% endif %}

    {% url tweet_following other_user.username as tweet_following_url %}

{% blocktrans %}Also see who {{ other_user }} is following.{% endblocktrans %}
{% endblock %}


text:
using NUnit.Framework.Internal;

namespace NUnit.Framework.Constraints.Tests
{
    [TestFixture]
    public class UniqueItemsTests : ConstraintTestBase
    {
        [SetUp]
        public void SetUp()
        {
            theConstraint = new UniqueItemsConstraint();
            stringRepresentation = "<uniqueitems>";
            expectedDescription = "all items unique";
        }

        internal object[] SuccessData = new object[] { new int[] { 1, 3, 17, -2, 34 }, new object[0] };
        internal object[] FailureData = new object[] { new object[] { new int[] { 1, 3, 17, 3, 34 }, "< 1, 3, 17, 3, 34 >" } };
    }
}


text:
<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;

class ChargeApproveType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('amount', MoneyType::class, [ 'currency' => 'GBP' ])
            ->add('paymentType', EntityType::class, [ 'class' => 'AppBundle:PaymentType', 'choice_label' => 'type' ])
            ->add('reference')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Charge'
        ));
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Twilio;

namespace best_vethack3.Service
{
    public class TwilioService
    {
        public static string SendMessage(string phoneNumberTo, string messageBody)
        {
            var accountSid = "AC975eb1a653a4fc23e5d7c59373414b00";
            var accountToken = "f242cda9f67746da4ad0409e70a87edb";

            var twilio = new TwilioRestClient(accountSid, accountToken);
            var message = twilio.SendMessage(
                "+13104395418"
                , phoneNumberTo
                , messageBody
                );

            return message.Status;
        }
    }
}