text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Transform" version="4.0">
	<brief_description>
		3D transformation (3×4 matrix).
	</brief_description>
	<description>
		3×4 matrix (3 rows, 4 columns) used for 3D linear transformations. It can represent transformations such as translation, rotation, or scaling. It consists of a [member basis] (first 3 columns) and a [Vector3] for the [member origin] (last column).
		For more information, read the "Matrices and transforms" documentation article.
	</description>
	<tutorials>
		<link title="Math tutorial index">https://docs.godotengine.org/en/latest/tutorials/math/index.html</link>
		<link title="Matrices and transforms">https://docs.godotengine.org/en/latest/tutorials/math/matrices_and_transforms.html</link>
		<link title="Using 3D transforms">https://docs.godotengine.org/en/latest/tutorials/3d/using_transforms.html</link>
	</tutorials>
	<methods>
		<method name="Transform">
			<return type="Transform">
			</return>
			<argument index="0" name="x_axis" type="Vector3">
			</argument>
			<argument index="1" name="y_axis" type="Vector3">
			</argument>
			<argument index="2" name="z_axis" type="Vector3">
			</argument>
			<argument index="3" name="origin" type="Vector3">
			</argument>
			<description>
				Constructs a Transform from four [Vector3] values (matrix columns). Each axis corresponds to local basis vectors (some of which may be scaled).
			</description>
		</method>
		<method name="Transform">
			<return type="Transform">
			</return>
			<argument index="0" name="basis" type="Basis">
			</argument>
			<argument index="1" name="origin" type="Vector3">
			</argument>
			<description>
				Constructs a Transform from a [Basis] and [Vector3].
			</description>
		</method>
		<method name="Transform">
			<return type="Transform">
			</return>
			<argument index="0" name="from" type="Transform2D">
			</argument>
			<description>
				Constructs a Transform from a [Transform2D].
			</description>
		</method>
		<method name="Transform">
			<return type="Transform">
			</return>
			<argument index="0" name="from" type="Quat">
			</argument>
			<description>
				Constructs a Transform from a [Quat]. The origin will be [code]Vector3(0, 0, 0)[/code].
			</description>
		</method>
		<method name="Transform">
			<return type="Transform">
			</return>
			<argument index="0" name="from" type="Basis">
			</argument>
			<description>
				Constructs the Transform from a [Basis]. The origin will be Vector3(0, 0, 0).
			</description>
		</method>
		<method name="affine_inverse">
			<return type="Transform">
			</return>
			<description>
				Returns the inverse of the transform, under the assumption that the transformation is composed of rotation, scaling and translation.
			</description>
		</method>
		<method name="interpolate_with">
			<return type="Transform">
			</return>
			<argument index="0" name="transform" type="Transform">
			</argument>
			<argument index="1" name="weight" type="float">
			</argument>
			<description>
				Interpolates the transform to other Transform by weight amount (on the range of 0.0 to 1.0).
			</description>
		</method>
		<method name="inverse">
			<return type="Transform">
			</return>
			<description>
				Returns the inverse of the transform, under the assumption that the transformation is composed of rotation and translation (no scaling, use affine_inverse for transforms with scaling).
			</description>
		</method>
		<method name="is_equal_approx">
			<return type="bool">
			</return>
			<argument index="0" name="transform" type="Transform">
			</argument>
			<description>
				Returns [code]true[/code] if this transform and [code]transform[/code] are approximately equal, by calling [code]is_equal_approx[/code] on each component.
			</description>
		</method>
		<method name="looking_at">
			<return type="Transform">
			</return>
			<argument index="0" name="target" type="Vector3">
			</argument>
			<argument index="1" name="up" type="Vector3">
			</argument>
			<description>
				Returns a copy of the transform rotated such that its -Z axis points towards the [code]target[/code] position.
				The transform will first be rotated around the given [code]up[/code] vector, and then fully aligned to the target by a further rotation around an axis perpendicular to both the [code]target[/code] and [code]up[/code] vectors.
				Operations take place in global space.
			</description>
		</method>
		<method name="orthonormalized">
			<return type="Transform">
			</return>
			<description>
				Returns the transform with the basis orthogonal (90 degrees), and normalized axis vectors.
			</description>
		</method>
		<method name="rotated">
			<return type="Transform">
			</return>
			<argument index="0" name="axis" type="Vector3">
			</argument>
			<argument index="1" name="phi" type="float">
			</argument>
			<description>
				Rotates the transform around the given axis by the given angle (in radians), using matrix multiplication. The axis must be a normalized vector.
			</description>
		</method>
		<method name="scaled">
			<return type="Transform">
			</return>
			<argument index="0" name="scale" type="Vector3">
			</argument>
			<description>
				Scales basis and origin of the transform by the given scale factor, using matrix multiplication.
			</description>
		</method>
		<method name="translated">
			<return type="Transform">
			</return>
			<argument index="0" name="offset" type="Vector3">
			</argument>
			<description>
				Translates the transform by the given offset, relative to the transform's basis vectors.
				Unlike [method rotated] and [method scaled], this does not use matrix multiplication.
			</description>
		</method>
		<method name="xform">
			<return type="Variant">
			</return>
			<argument index="0" name="v" type="Variant">
			</argument>
			<description>
				Transforms the given [Vector3], [Plane], [AABB], or [PackedVector3Array] by this transform.
			</description>
		</method>
		<method name="xform_inv">
			<return type="Variant">
			</return>
			<argument index="0" name="v" type="Variant">
			</argument>
			<description>
				Inverse-transforms the given [Vector3], [Plane], [AABB], or [PackedVector3Array] by this transform.
			</description>
		</method>
	</methods>
	<members>
		<member name="basis" type="Basis" setter="" getter="" default="Basis( 1, 0, 0, 0, 1, 0, 0, 0, 1 )">
			The basis is a matrix containing 3 [Vector3] as its columns: X axis, Y axis, and Z axis. These vectors can be interpreted as the basis vectors of local coordinate system traveling with the object.
		</member>
		<member name="origin" type="Vector3" setter="" getter="" default="Vector3( 0, 0, 0 )">
			The translation offset of the transform (column 3, the fourth column). Equivalent to array index [code]3[/code].
		</member>
	</members>
	<constants>
		<constant name="IDENTITY" value="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
			[Transform] with no translation, rotation or scaling applied. When applied to other data structures, [constant IDENTITY] performs no transformation.
		</constant>
		<constant name="FLIP_X" value="Transform( -1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
			[Transform] with mirroring applied perpendicular to the YZ plane.
		</constant>
		<constant name="FLIP_Y" value="Transform( 1, 0, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0 )">
			[Transform] with mirroring applied perpendicular to the XZ plane.
		</constant>
		<constant name="FLIP_Z" value="Transform( 1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0 )">
			[Transform] with mirroring applied perpendicular to the XY plane.
		</constant>
	</constants>
</class>


text:
#if !defined(__has_feature) || !__has_feature(objc_arc)
#error "This file requires ARC support."
#endif

#import "Splash3ViewController.h"
#import "Constants.h"

@implementation Splash3ViewController

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(Splash3ViewController *)sender {
  UINavigationController *nextController = segue.destinationViewController;
  if ([nextController isKindOfClass:[UINavigationController class]]) {
    NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    if (![standardUserDefaults boolForKey:kHideSplashScreenKey]) {
      [standardUserDefaults setBool:YES forKey:kHideSplashScreenKey];
      [standardUserDefaults synchronize];
    }
  }
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Incenteev\DynamicParametersBundle\Tests\DependencyInjection;

use Incenteev\DynamicParametersBundle\DependencyInjection\IncenteevDynamicParametersExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class IncenteevDynamicParametersExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadEmptyConfig()
    {
        $container = new ContainerBuilder();
        $extension = new IncenteevDynamicParametersExtension();

        $extension->load(array(), $container);

        $this->assertTrue($container->hasParameter('incenteev_dynamic_parameters.parameters'));
        $this->assertSame(array(), $container->getParameter('incenteev_dynamic_parameters.parameters'));

        $this->assertTrue($container->hasDefinition('incenteev_dynamic_parameters.retriever'));
    }

    public function testLoadParameters()
    {
        $container = new ContainerBuilder();
        $extension = new IncenteevDynamicParametersExtension();

        $config = array(
            'parameters' => array(
                'foo' => 'FOO',
                'bar' => 'SYMFONY__BAR',
            ),
        );

        $extension->load(array($config), $container);

        $expected = array(
            'foo' => array('variable' => 'FOO', 'yaml' => false),
            'bar' => array('variable' => 'SYMFONY__BAR', 'yaml' => false),
        );

        $this->assertTrue($container->hasParameter('incenteev_dynamic_parameters.parameters'));
        $this->assertSame($expected, $container->getParameter('incenteev_dynamic_parameters.parameters'));
    }
}


text:
<list>
  <group>
    <name>Group Name 0</name>
    Group Header 0
    Group Footer 0
  </group>
  <group>
    <name>Group Name 1</name>
    Group Header 1
    Group Footer 1
  </group>
  <group>
    <name>Group Name 2</name>
    Group Header 2
    Group Footer 2
  </group>
</list>


text:
Website
======
- My Website


text:
<?php

/**
 * A thing what can save data across requests and sessions.
 * It knows about APC, and one day might know about memcache.
 */
class DataCache {
	const CACHE_APC      = 1;
	const CACHE_MEMCACHE = 2;
	const CACHE_TMPFILE  = 0;

	private $method = DataCache::CACHE_TMPFILE;
	private $tmpfilename = NULL;

	private $id = NULL;
	private $loaded = FALSE;
	private $data = NULL;
	private $default_data = NULL;

	public function __construct($id, $default_data=NULL) {
		$this->id = $id;
		$this->default_data = $default_data;

		if (extension_loaded('apc') && ini_get('apc.enabled')) {
			$this->method = DataCache::CACHE_APC;
#		} elseif (extension_loaded('memdata')) {
#			$this->method = DataCache::CACHE_MEMCACHE;
		} else {
			#$this->tmpfilename = tempnam('/tmp', $id); // idiot Matty
			$this->tmpfilename = '/tmp/datacache-'.$id.'.dat';
		}
	}

	public function load() {
		switch ($this->method) {
		case DataCache::CACHE_APC:
			$data = apc_fetch($this->id, $joy);
			if ($joy) {
				$this->loaded = TRUE;
				$this->data = $data;
			} else {
				return FALSE;
			}
			break;
		case DataCache::CACHE_TMPFILE:
			if (is_file($this->tmpfilename)) {
				$data = file_get_contents($this->tmpfilename);
				$this->loaded = TRUE;
				$this->data = unserialize($data);
			} else {
				return FALSE;
			}
			break;
		default:
			throw new Exception("invalid cache method {$this->method}");
		}
		return TRUE;
	}

	public function save() {
		switch ($this->method) {
		case DataCache::CACHE_APC:
			return apc_store($this->id, $this->data());
		case DataCache::CACHE_TMPFILE:
			$data = serialize($this->data());
			$result = file_put_contents($this->tmpfilename, $data);
			return ($result !== FALSE);
		default:
			throw new Exception("invalid cache method {$this->method}");
		}
	}

	/**
	 * Gets (or sets) the cached data.
	 */
	public function data($value=NULL) {
		// set (and save) data
		if (func_num_args() > 0) {
			$this->data = $value;
			$this->save();
		// (maybe) load data, with fallback
		} elseif (! $this->loaded) {
			if (! $this->load()) {
				$this->data = $this->default_data;
			}
		}
		return $this->data;
	}
}


text:
'use strict';

const express = require('express');
const bodyParser = require('body-parser');
const compression = require('compression');
const dbDown = require('../app/utils/dbDown.server.utils');
const v2router = require('../app/v2');

module.exports = () => {
	const app = express();

	app.use('/newsletters', v2router);

	app.use(compression());

	app.use(bodyParser.urlencoded({
		extended: true,
		limit: '50mb'
	}));

	app.use(bodyParser.json({
		limit: '50mb'
	}));

	// NOTE: we expose the public folder before adding basic authentication!
	app.use(express.static('./public'));

	// NOTE: we expose the health and gtg endpoints folder before adding basic authentication!
	require('../app/routes/__health.server.routes')(app);
	require('../app/routes/__gtg.server.routes')(app);

	app.use(dbDown);
	app.use(require('express-bearer-token')());
	app.use(require('../app/middleware/create-decorated-logger'));
	app.use(require('../app/middleware/authenticator'));

	require('../app/routes/metadata.server.routes.js')(app);
	require('../app/routes/users.server.routes.js')(app);
	require('../app/routes/lists.server.routes.js')(app);
	require('../app/routes/listsByUser.server.routes.js')(app);
	require('../app/routes/usersByList.server.routes.js')(app);
	require('../app/routes/api/oneClick/v1')(app);

	return app;
};


text:
"""Module for CLI output styling.

This module sets the style of the CLI output
"""

class CLIStyle(object):
    """Class for styling CLI output

    This class defines some constants for styling the output of CLI-Scripts
    To use this class, simply use the constants in your print() functions.
    e.g.: print(CLIStyle.COLOR_GREEN + "Hello World" + CLIStyle.STYLE_RESET)
    """

    STYLE_RESET = '\033[0m'
    CLEAR_SCREEN = '\033[2J'

    STYLE_BOLD = '\033[1m'
    STYLE_UNDERLINE = '\033[4m'

    COLOR_GREEN = '\033[32m'
    COLOR_RED = '\033[31m'
    COLOR_YELLOW = '\033[33m'

    META_H1 = CLEAR_SCREEN + STYLE_RESET + STYLE_BOLD + STYLE_UNDERLINE
    META_OK = COLOR_GREEN
    META_ERR = COLOR_RED
    META_INPUT = COLOR_YELLOW


text:
package com.softmotions.ncms.asm.events;

import javax.annotation.Nullable;

import com.softmotions.ncms.events.BasicEvent;

/**
 * @author Adamansky Anton (adamansky@softmotions.com)
 */
public class AsmUnlockedEvent extends BasicEvent {

    final Long id;

    public Long getId() {
        return id;
    }

    public AsmUnlockedEvent(Object source, Long id, @Nullable String user) {
        super(source, AsmUnlockedEvent.class.getSimpleName(), user);
        this.id = id;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>lib/pool.js - Casson API</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 0.2.0

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

casson

Delete

Frame

Insert

KeySpace

List

Map

Parser

Pool

Pool.Connector

Select

Set

Table

Update

Uuid

casson

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: lib/pool.js

var net = require('net'),
    util = require('util'),
    events = require('events'),
    Frame = require('./frame'),
    Table = require('./table'),
    UUID = require('./uuid'),
    KeySpace = require('./keyspace'),
    Parser = require('./parser');

// var DEFAULT_CONNECTION_IDLE_TIMEOUT = 300000;      // 5 min
var DEFAULT_CONNECTIONS_PER_HOST = 2;
var DEFAULT_RESPONSE_TIMEOUT = 3000;
var DEFAULT_RETRY_INTERVAL = 1000;
var DEFAULT_SELECT_POLICY = 'round-robin'; // or 'random

var consoleErrorData = function(err, data) {

  console.log ((err) ? err : data);
}

var available_stream_ids = [];

for (var i = 255; i > 0; i--) {
  available_stream_ids.push(i);
}

var pendingActiviy = {};

var getStreamID = function(conn, time, callback) {

  var t_out = time || DEFAULT_RESPONSE_TIMEOUT;
  var id = available_stream_ids.pop();
  pendingActiviy[id] = {};
  pendingActiviy[id]['connector'] = conn;
  pendingActiviy[id]['callback'] = callback;
  pendingActiviy[id]['timer'] = setTimeout(
    function() {
    if (callback) {
      callback(new Error('Request timed out'));
    }
    returnStreamID(id);
  }, t_out);
  return id;
};

var returnStreamID = function(id) {

  clearTimeout(pendingActiviy[id]['timer']);
  delete pendingActiviy[id];
  available_stream_ids.push(id);
};

/**
 * Create a pool of connections to Cassandra. Only one instance with a
 * single keyspace is assumed. The keyspace can changed after intialization.
 * @class Pool
 * @constructor
 * @param {key/value} config parameters
 * @example
 *        { 'hosts'                    : ['localhost:9042'] ,
 *          'username'                 : <db_username>      ,
 *          'password'                 : <db_password>      ,
 *          'keyspace'                 : <keyspace_name>    ,
 *          'connection_per_host'      : 2                  ,
 *          'select_policy'            : round-robin        ,
 *          'retry_internal'           : 1000               ,
 *          'respnse_timeout'          : 2000               }
 *
 * The default hostname is `localhost` when it is not specified as `:9042`,
 * and port 9042 (the default CQL 3 native port). There can be mulitple hosts.
 * `hosts`, `username` and `password` are required, and others are optional.
 * The select_policy can be `round-robin` or `random`.
 */
Pool = function(config) {

  var _one = null;
  var connectors = {};
  var keyspace_name = config['keyspace'];
  var keyspace;

  if (!_one) {
    _one = this;
  } else {
    return _one;
  };

  this.username = config['username'];
  this.password = config['password'];
  this.hostspec = null;
  this.n_connect = config['connection_per_host'] ||
    DEFAULT_CONNECTIONS_PER_HOST;
  this.retry_t = config['retry_interval'] ||
    DEFAULT_RETRY_INTERVAL;
  this.respnse_t = config['response_timeout'] ||
    DEFAULT_RESPONSE_TIMEOUT;
  this.select_policy = config['select_policy'] ||
    DEFAULT_SELECT_POLICY;
  this.selected_c = 0;

  var available_connections = {};
  if (config['hosts']) {
    this.hostspec = [];
    for (i in config['hosts']) {
      var hp = config['hosts'][i].split(':');
      if (hp.length == 1) {hp[1] = 9042;}
      if (hp[0] === '') {hp[0] = 'localhost'}
      if (hp[0].match(/^[\w\.]+$/) || hp[0].match(/[\d+\.]+/)) {
        if (String(hp[1]).match(/^\d+$/)) {
          this.hostspec.push({'host' : hp[0], 'port' : hp[1]});
        } else {
          return new Error('port number = ', hp[1]);
        }
      } else {
        return new Error('Host name = ', hp[0]);
      }
    }
  } else {
    return new Error('No Host speicified');
  }

  /**
   * Get connection from the pool
   * @method getConnection
   * @return {Pool.Connector}
   */
  this.getConnection = function() {

    /* If total available number of available connection is
     * add one more from random host spec.
     */
    var uids = Object.keys(connectors);
    if (uids.length < this.hostspec.length * this.n_connects) {
      var i = Math.floor(Math.random() * this.hostspec.length);
      this.setConnector(this.hostspec[i]);
    }

    var c = null;
    if (uids.length) {
      if (this.select_policy === 'round-robin') {
        c = uids[this.selected_c];
        this.selected_c = (this.selected_c + 1) % uids.length;
      } else if (this.select_policy === 'random') {
        c = uids[Math.floor(Math.random() * uids.length)];
      }
    }
    if (!c) {
      console.log(new Error('No Connector available'));
    }
    return connectors[c];
  };

  /**
   * Frame an outgoing message
   * @async
   * @method frameMesg
   * @param {Frame} frame
   * @param {Function} callback
   * @param {Pool.Connectors} conn send through a specified connector
   */
  this.frameMesg = function (frame, callback, conn) {

    var c = conn || _one.getConnection();
    var id = getStreamID(c, 0, callback);
    frame.send(id, c);
  };

  /**
   * Listener for the result event from connections
   * @method resultListener
   * @param {short} opcode Code sent outgoing message to Cassandra
   * @param {key/value} result  Parsed results including error
   */
  this.resultListener = function(data) {

    var p = new Parser();
    p.write(new Buffer(data));
    // console.log(this.uuid.hex_uuid + ' [' + p.vars.stream + '] ' + Object.keys(p.result));
    var ans = pendingActiviy[p.vars.stream];
    if (p.result['ready']) {
      ans['connector'].ready = true;
      _one.sendForOptions(this);
      _one.setKeyspace(null, this);
    } else if (p.result['supported']) {
      // console.log('Supported: ' + Frame.checkSupported(p.result['supported']));
    } else if (p.result['authenticator']) {
      _one.sendCredentials(this);
    } else {
      if (ans['callback']) {
        ans.callback(p.result['error'], p.result);
      }
    }
    returnStreamID(p.vars.stream);
  }

  /**
   * Set Pool.Connector and receive events from connection
   * @method setConnector
   * @param {key/value} spec
   */
  this.setConnector = function(spec) {

    var c = new Pool.Connector(spec);
    connectors[c.uuid.hex_uuid] = c;
    c.on('connect', function() {
      var id = getStreamID(this, 0, consoleErrorData);
      new Frame('Startup').send(id, this.conn);
    });
    c.on('result', _one.resultListener);
    c.on('end', function() {
      console.log('Connector' + c.uuid.hex_uuid + ' dissconnected');
      delete connectors[c.uuid.hex_uuid] });
  };

  // ***
  // More initialization code down here -- need setConnector
  // ***
  for (i in this.hostspec) {
    for (var j = 0; j < this.n_connect; j++) {
      _one.setConnector(_one.hostspec[i]);
    }
  }
  // ***

  /**
   * get the options served by Cassandra
   * @method sendForOptions
   * @param {Pool.Connectors} conn send through a specified connector
   */
  this.sendForOptions = function(conn) {

    _one.frameMesg(new Frame('Options'), consoleErrorData, conn);
  };

  /**
   * Set keyspace to use
   * @method setKeyspace
   * @param {String|KeySpace} name/keyspace
   * @param {Pool.Connectors} [conn] send through a specified connector. If not given, set the keyspace for all connections
   * @param {KeySpace}
   */
  this.setKeyspace = function(keyspace, conn) {

    var name;
    if (keyspace instanceof KeySpace) {
      _one.keyspace = keyspace;
      name = keyspace.name;
    } else if (typeof(keyspace) === 'string') {
      name = keyspace;
      _one.keyspace = new KeySpace(name);
    } else if (keyspace_name) {
      name = keyspace_name;
      _one.keyspace = new KeySpace(name);
    }
    if (_one.keyspace) {
      var f = new Frame('Query', _one.keyspace.dbUse());
      if (conn) {
        _one.frameMesg(f, function(err, data) {
          if (!err) {_one.keyspace.activate();}
        }, conn);
      } else {
        var kc = Object.keys(connectors);
        var rc = 0;
        for (var k in kc) {
          _one.frameMesg(f, function(err, data) {
            if (!err) {
              rc++;
              if (rc == kc.length) {_one.keyspace.activate();}
            }
          }, connectors[kc[0]]);
        }
      }
    }
    return _one.keyspace;
  };

  /**
   * Send user/pw credentials
   * @method sendCredentials
   * @param {Pool.Connectors} conn send through a specified connector
   */
  this.sendCredentials = function(conn) {

    var f = new Frame('Credentials', {
      'username' : this.username, 'password' : this.password});
    _one.frameMesg(f, consoleErrorData, conn);
  };

  /**
   * Send a query. Although, query is usaully a object of specified kind, it
   * can be used to send raw queries as well.
   * @method sendQuery
   * @async
   * @param {string|Select|Insert|Update|Delete|Table} query if it is a Table, dbCreate() method is invoked. if it is a query object, query() method is invoked. Otherwise, query string is sent directly.
   * @param {Function} [callback]
   * @param {short} [consistency]
   * @param {boolean} [raw] Send back raw result instead of array of Table instances for Select.
   */
  this.sendQuery = function(query, callback, consistency, raw) {

    callback = callback || consoleErrorData;
    var framed;
    if (typeof(query) === 'string') {
      framed = new Frame('Query', query, consistency);
    } else if (Object.keys(query).indexOf('query') >= 0) {
      framed = new Frame('Query', query.query(), consistency);
    } else if (Object.keys(query).indexOf('dbCreate') >= 0) {
      framed = new Frame('Query', query.dbCreate(), consistency);
    }
    var wrapped_cb = function(err, result) {
      if (!err) {
        var instable = null;
        if (result.colspec && !raw) {
          var i, j, t, cs = [];
          var nc = result.colspec.length;
          for (i = 0; i < nc; i++) {
            if (i == 0) {
              t = result.colspec[0]['table'];
            }
            cs.push(result['colspec'][i]['name']);
          }

          var tb, rc;
          instable = [];
          for (i = 0; i < result['row_count']; i++) {
            tb = Table.construct(t);
            rc = result.rows[i];
            for (j = 0; j < nc; j++) {
              tb[cs[j]] = rc[j];
            }
            instable.push(tb);
          }
        }
        callback(null, (instable) ? instable : result);
      } else {
        callback(err);
      }
    }
    if (framed) {
      _one.frameMesg(framed, wrapped_cb);
    } else {
      callback(new Error('Incompatitible query'));
    }
  };

  this.close = function() {
    for (var k in connectors) {
      connectors[k].conn.end();
    }
  }
};

/**
 * Connector encapsulate each connection
 * @class Pool.Connector
 * @for Pool
 * @constructor
 * @param {key/value} options
 * @example
 *    options = {'host' : host-name, 'port' : port#, 'retry_t' : retry-interval}
 */
Pool.Connector = function(options) {

  var MAX_ATTEMPTS = 3;

  this.ready = false;
  this.rt = options['retry_t'];
  this.attempts = 0;

  this.uuid = new UUID();
  var ctor = this;
  this.conn = net.connect(options, function() {
                // console.log('conn connected');
                ctor.emit('connect', ctor.uuid.hex_uuid);

              });
  this.conn.on('data', function(data) {
    // console.log('data received');
    // console.log(new Buffer(data).toString('hex'));
    ctor.emit('result', data);
  });
  this.conn.on('end', function() {
    ctor.ready = false;
    ctor.emit('end');
  });
  this.conn.on('error', function (err) {
    ctor.ready = false;
    console.log('error: ' + ctor.uuid + " ; attempting reopen.");
    if (ctor.rt || ctor.attempts < MAX_ATTEMPTS) {
      setTimeout(net.connect, ctor.rt, options);
      ctor.attempts++;
      ctor.rt = ctor.rt << ctor.attempts;
    }
  });

  /**
   * write Pass through
   * @method write
   * @for Pool.Connector
   * @param {Buffer} data
   */
  this.write = function(data) {
    this.conn.write(data);
  };
  // this.conn.setTimeout(this.conn.end, DEFAULT_CONNECTION_IDLE_TIMEOUT);
};

util.inherits(Pool.Connector, events.EventEmitter);

module.exports = Pool;


text:
<ehcache  xsi:noNamespaceSchemaLocation="ehcache.xsd"
	updateCheck="true" monitoring="autodetect" dynamicConfig="true"
	maxBytesLocalHeap="150M">
	<diskStore path="java.io.tmpdir" />

<cache name="service_modules"
           maxEntriesLocalDisk="1000"
           eternal="false"
           diskSpoolBufferSizeMB="20"
           timeToIdleSeconds="30000"
           timeToLiveSeconds="60000"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>


text:
from datetime import datetime
from tapiriik.services.interchange import ActivityStatisticUnit
from tapiriik.services.api import UserException

class ActivityRecord:
    def __init__(self, dbRec=None):
        self.StartTime = None
        self.EndTime = None
        self.Name = None
        self.Notes = None
        self.Type = None
        self.Distance = None
        self.Stationary = None
        self.Private = None
        self.UIDs = []
        self.PresentOnServices = {}
        self.NotPresentOnServices = {}
        self.FailureCounts = {}

        # It's practically an ORM!
        if dbRec:
            self.__dict__.update(dbRec)

    def __repr__(self):
        return "<ActivityRecord> " + str(self.__dict__)

    def __deepcopy__(self, x):
        return ActivityRecord(self.__dict__)

    def FromActivity(activity):
        record = ActivityRecord()
        record.SetActivity(activity)
        return record

    def SetActivity(self, activity):
        self.StartTime = activity.StartTime
        self.EndTime = activity.EndTime
        self.Name = activity.Name
        self.Notes = activity.Notes
        self.Type = activity.Type
        self.Distance = activity.Stats.Distance.asUnits(ActivityStatisticUnit.Meters).Value
        self.Stationary = activity.Stationary
        self.Private = activity.Private
        self.UIDs = activity.UIDs

    def MarkAsPresentOn(self, serviceRecord):
        if serviceRecord.Service.ID not in self.PresentOnServices:
            self.PresentOnServices[serviceRecord.Service.ID] = ActivityServicePrescence(listTimestamp=datetime.utcnow())
        else:
            self.PresentOnServices[serviceRecord.Service.ID].ProcessedTimestamp = datetime.utcnow()
        if serviceRecord.Service.ID in self.NotPresentOnServices:
            del self.NotPresentOnServices[serviceRecord.Service.ID]

    def MarkAsSynchronizedTo(self, serviceRecord):
        if serviceRecord.Service.ID not in self.PresentOnServices:
            self.PresentOnServices[serviceRecord.Service.ID] = ActivityServicePrescence(syncTimestamp=datetime.utcnow())
        else:
            self.PresentOnServices[serviceRecord.Service.ID].SynchronizedTimestamp = datetime.utcnow()
        if serviceRecord.Service.ID in self.NotPresentOnServices:
            del self.NotPresentOnServices[serviceRecord.Service.ID]

    def MarkAsNotPresentOtherwise(self, userException):
        self.MarkAsNotPresentOn(None, userException)

    def MarkAsNotPresentOn(self, serviceRecord, userException):
        rec_id = serviceRecord.Service.ID if serviceRecord else None
        if rec_id not in self.NotPresentOnServices:
            self.NotPresentOnServices[rec_id] = ActivityServicePrescence(listTimestamp=datetime.utcnow(), userException=userException)
        else:
            record = self.NotPresentOnServices[rec_id]
            record.ProcessedTimestamp = datetime.utcnow()
            record.UserException = userException

    # Only unexpected, "active" failures increment this count
    #
    # Exceptions in the sync core (activity type unsupported, etc) cost nothing => don't count towards this, to keep things simple
    # Trapped errors inside Services use...
    #  - Activity exclusions, which either...
    #    a) permanently blacklist that activity => don't count towards this, to avoid duplication
    #    b) temporarily exclude it, where there's a finite horizon for success (activiteies being live-tracked, generally) => don't count toward this
    #  - APIExceptions, Exceptions => DO increment this
    #
    # These are stored seperately from the prescences, since the efficiency gained with how MarkAsNotPresentOtherwise works
    # would prevent keeping track of activity download failures (couldn't determine which service to blame after the fact)
    #
    # We don't store the error that originated the failure - that's already being stored in the service record
    # When it comes time to reset these counts once a widespread issue is solved, one can determine the appropriate users from that
    #
    # Also, we don't track the Step here - I can probably reverse-engineer it from the prescence (famous last words) if reqd

    def GetFailureCount(self, serviceRecord):
        return self.FailureCounts[serviceRecord.Service.ID] if serviceRecord.Service.ID in self.FailureCounts else 0

    def IncrementFailureCount(self, serviceRecord):
        self.FailureCounts[serviceRecord.Service.ID] = self.GetFailureCount(serviceRecord) + 1

    def ResetFailureCount(self, serviceRecord):
        if serviceRecord.Service.ID in self.FailureCounts:
            del self.FailureCounts[serviceRecord.Service.ID]

class ActivityServicePrescence:
    def __init__(self, listTimestamp=None, syncTimestamp=None, userException=None):
        self.ProcessedTimestamp = listTimestamp
        self.SynchronizedTimestamp = syncTimestamp
        # If these is a UserException then this object is actually indicating the abscence of an activity from a service.
        if userException is not None and not isinstance(userException, UserException):
            raise ValueError("Provided UserException %s is not a UserException" % userException)
        self.UserException = userException


text:
using System;
using System.Runtime.Serialization;

namespace TweetSharp
{
#if !SILVERLIGHT
    /// <summary>
    /// Represents a delivery device for receiving updates from Twitter.
    /// </summary>
    [Serializable]
#endif
#if !Smartphone && !NET20
    [DataContract]
#endif
    public enum TwitterDeliveryDevice
    {
#if !Smartphone && !NET20
        /// <summary>
        /// No delivery device is used.
        /// </summary>
        [EnumMember] None,
        /// <summary>
        /// An SMS-capable delivery device is used.
        /// </summary>
        [EnumMember] Sms
#else
        None,
        Sms
#endif
    }
}


text:
package org.ccci.gto.android.common.util.view;

import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import android.view.Menu;
import android.view.MenuItem;

public class MenuUtils {
    public static void setGroupVisibleRecursively(@Nullable final Menu menu, @IdRes final int group,
                                                  final boolean visible) {
        // short-circuit if there isn't a menu to process
        if (menu == null) {
            return;
        }

        // set direct items visible
        menu.setGroupVisible(group, visible);

        // cascade group visibility into submenus
        final int size = menu.size();
        for (int i = 0; i < size; i++) {
            final MenuItem item = menu.getItem(i);
            if (item.hasSubMenu()) {
                setGroupVisibleRecursively(item.getSubMenu(), group, visible);
            }
        }
    }
}


text:
<?php

namespace Doctrine\MongoDB\Tests\Event;

use Doctrine\MongoDB\Event\DistinctEventArgs;

class DistinctEventArgsTest extends \PHPUnit_Framework_TestCase
{
    public function testDistinctEventArgs()
    {
        $invoker = new \stdClass();
        $field = 'x';
        $query = array('y' => 1);

        $distinctEventArgs = new DistinctEventArgs($invoker, $field, $query);

        $this->assertSame($invoker, $distinctEventArgs->getInvoker());
        $this->assertSame($field, $distinctEventArgs->getField());
        $this->assertSame($query, $distinctEventArgs->getQuery());

        $field2 = 'y';
        $query2 = array('y' => 2);

        $distinctEventArgs->setQuery($query2);
        $distinctEventArgs->setField($field2);

        $this->assertSame($field2, $distinctEventArgs->getField());
        $this->assertSame($query2, $distinctEventArgs->getQuery());
    }
}


text:
(function() {
  function Room($firebaseArray) {
    var Room = {};

    var ref = firebase.database().ref().child("rooms");
    var rooms = $firebaseArray(ref);

    Room.all = rooms;

    Room.add = function(room){
        if (!room) {
            alert("Please enter a room name!");
            return;
        }
        rooms.$add(room);
    };

    return Room;
  }

  angular
    .module('blocChat')
    .factory('Room', ['$firebaseArray', Room]);
})();


text:
package seedu.taskell.logic.commands.list;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import seedu.taskell.logic.commands.Command;
import seedu.taskell.logic.commands.CommandResult;
import seedu.taskell.model.task.Task;
import seedu.taskell.model.task.TaskDate;

public class ListDateCommand extends Command {

    public static final String COMMAND_WORD = "list-date";

    public static final String MESSAGE_SUCCESS = "Listed all tasks on a given date";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Lists tasks on 1 specific date only.\n"
            + "Parameters: DATE (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 8-8-2016 ";

    private Set<String> keywordSet;

    public ListDateCommand(TaskDate date) {
        keywordSet = new HashSet<>(Arrays.asList(date.taskDate, Task.EVENT_TASK));
    }

    @Override
    public CommandResult execute() {
        model.updateFilteredtaskListDate(keywordSet);
        return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size()));
    }
}
// @@author


text:
<!DOCTYPE html>

 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
	<base href="<?php echo base_url() ?>" >
 <link href="<?php echo base_url();?>css/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
 <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
 <link href="<?php echo base_url();?>css/frontcss/style.css" rel="stylesheet" />
 <link href="<?php echo base_url();?>css/frontcss/responsive.css" rel="stylesheet" />
 <link rel='stylesheet' href='<?php echo base_url();?>css/frontcss/material.cyan-light_blue.min.css'>
 <link href="<?php echo base_url();?>css/css/datepicker.css" rel="stylesheet" type="text/css" />
 <link href="<?php echo base_url();?>calculator.css" rel="stylesheet" type="text/css" />
 <link rel='stylesheet' href='<?php echo base_url(); ?>css/fonts.css'>
	  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css'>
	<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.2.4/assets/owl.carousel.min.css'>

	  <div data-ng-include="'<?php echo base_url();?>template/User/header.html'" data-ng-controller="HeaderController" >

		<input type="hidden" id="state" value="<?php echo $state; ?>">


text:
/**
 * Autogenerated by Thrift Compiler (0.9.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.cloudera.impala.thrift;

import java.util.Map;
import java.util.HashMap;
import org.apache.thrift.TEnum;

public enum THdfsSeqCompressionMode implements org.apache.thrift.TEnum {
  RECORD(0),
  BLOCK(1);

  private final int value;

  private THdfsSeqCompressionMode(int value) {
    this.value = value;
  }

  /**
   * Get the integer value of this enum value, as defined in the Thrift IDL.
   */
  public int getValue() {
    return value;
  }

  /**
   * Find a the enum type by its integer value, as defined in the Thrift IDL.
   * @return null if the value is not found.
   */
  public static THdfsSeqCompressionMode findByValue(int value) {
    switch (value) {
      case 0:
        return RECORD;
      case 1:
        return BLOCK;
      default:
        return null;
    }
  }
}


text:
<?php

namespace Bitrix24;

use \Bitrix24\Im\Attach\Item\Link;
use \Psr\Log\NullLogger;

/**
 * Class LinkTest
 * @package Bitrix24
 */
class LinkTest extends \PHPUnit_Framework_TestCase
{
	/**
	 * @covers \Bitrix24\Im\Attach\Item\Link::getAttachTypeCode
	 */
	public function testLinkTypeCode()
	{
		$obItem = new Link(null, null, null, null);
		$this->assertSame($obItem->getAttachTypeCode(), 'LINK');
	}
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Global design: Apple à en vomir</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Hanging around, having a cigarette.
">
        <link rel="canonical"
        href="http://www.dilettantitude.de/long/2007/05/14/global-design-apple-a-en-vomir/">

        <link rel="stylesheet" type="text/css" href="/assets/css/main.css">

Dilettantitude

Hanging around, having a cigarette.

Global design: Apple à en vomir

      long
       |

    	May 14, 2007

S'il existe un pôle économique important à Berlin, c'est bien celui des agences de communication et de publicité. Cette ville jeune, alternative, carrefour de deux mondes, mémoire de deux dictatures, bon marché, créative, c'est un terreau fertile pour ces agences décontractées et branchées: depuis la chute du mur, nombre d'entre elles sont venues s'installer ici. On compte probablement dans Mitte, Prenzl'berg, F'hain et X'Berg plus d'agences que de boulangeries (en deuxième place tout de même derrière les vendeurs de Kebab...).

Cette semaine c'est l'effervescence pour la branche. Les "je-suis-un-artiste-du-digital-et-du-marketing" se donnent en festival. Ça s'appelle Designmai et promis ce sera passionnant, interactif, hyper-créatif -- illisible, fouillis comme leur site internet? Je ne sais pas encore, je ne me suis pas encore déplacé cette année pour ce RDV.

En discutant hier avec ma femme, qui malgré elle baigne dans ce milieu, nous nous amusions bruyamment de ce microcosme (marketcosme?). Je soutenais l'idée que ces prétendus créateurs sont en fait des hommes bien plus formatés que la moyenne, complètement manipulés par l'hégémonie conceptuelle mode Apple.

Il suffit de traîner quelques heures dans les couloirs de l'UDK -- université des arts de Berlin -- pour le constater. Une tenue vestimentaire très colorée, ne va point sans les deux écouteurs blanc suspendus aux lobes de l'oreille. Dans une petite pochette de laine -- tricotée par des vietnamiennes au service de Steve -- floqué d'une pomme, se cache le i-pod au courbes arrondies et au touché suave. Il y a d'ailleurs à mon avis quelque chose de sexuellement conformiste dans la manipulation de l'ipod.

Sur les tables de la cafétéria, entre deux pots de Starbucks, c'est le couvercle de l'i-mac qui trône. Un blanc laiteux que je ne peux plus souffrir, un desktop bleu tellement ressassé qu'il donne des hauts le coeur, des icônes tout ronds d'innocence. Infernal que ce design global. Tout comme Ikea, Apple a accompli dans le domaine du style ce que Microsoft a réalisé au niveau technique: une hégémonie. C'est la première fois dans l'histoire de l'humanité que le design global est un réalité. Revenant du Chili, un baladeur sur deux dans le métro est passé à la pomme. Tellement mainstream que l'on en arrive à guetter celui qui ne porte pas un p'tit apple, tout comme on peut s'amuser à dénombrer tous les objets ne venant pas d'Ikea dans les appartements inconnus.

Related Posts

			  03 Oct 2015 »
			  Vas-y, Lâche Toi!

			  09 Sep 2015 »
			  Souslin Schemes

			  29 Aug 2015 »
			  Liberté Conditionnelle - I

				<< Older

Home

				Newer >>


text:
.class public final Landroid/provider/Telephony$Sms$Inbox;
.super Ljava/lang/Object;
.source "Telephony.java"

# interfaces
.implements Landroid/provider/BaseColumns;
.implements Landroid/provider/Telephony$TextBasedSmsColumns;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/provider/Telephony$Sms;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Inbox"
.end annotation

# static fields
.field public static final CONTENT_URI:Landroid/net/Uri;

.field public static final DEFAULT_SORT_ORDER:Ljava/lang/String; = "date DESC"

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 623
    const-string v0, "content://sms/inbox"

    invoke-static {v0}, Landroid/net/Uri;->parse(Ljava/lang/String;)Landroid/net/Uri;

    move-result-object v0

    sput-object v0, Landroid/provider/Telephony$Sms$Inbox;->CONTENT_URI:Landroid/net/Uri;

    return-void
.end method

.method private constructor <init>()V
    .locals 0

    .prologue
    .line 617
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 618
    return-void
.end method

.method public static addMessage(ILandroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Z)Landroid/net/Uri;
    .locals 9
    .param p0, "subId"    # I
    .param p1, "resolver"    # Landroid/content/ContentResolver;
    .param p2, "address"    # Ljava/lang/String;
    .param p3, "body"    # Ljava/lang/String;
    .param p4, "subject"    # Ljava/lang/String;
    .param p5, "date"    # Ljava/lang/Long;
    .param p6, "read"    # Z

    .prologue
    .line 664
    sget-object v2, Landroid/provider/Telephony$Sms$Inbox;->CONTENT_URI:Landroid/net/Uri;

    const/4 v8, 0x0

    move v0, p0

    move-object v1, p1

    move-object v3, p2

    move-object v4, p3

    move-object v5, p4

    move-object v6, p5

    move v7, p6

    invoke-static/range {v0 .. v8}, Landroid/provider/Telephony$Sms;->addMessageToUri(ILandroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZ)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static addMessage(ILandroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Z)Landroid/net/Uri;
    .locals 12
    .param p0, "subId"    # I
    .param p1, "resolver"    # Landroid/content/ContentResolver;
    .param p2, "address"    # Ljava/lang/String;
    .param p3, "body"    # Ljava/lang/String;
    .param p4, "subject"    # Ljava/lang/String;
    .param p5, "sc"    # Ljava/lang/String;
    .param p6, "date"    # Ljava/lang/Long;
    .param p7, "read"    # Z

    .prologue
    .line 687
    sget-object v2, Landroid/provider/Telephony$Sms$Inbox;->CONTENT_URI:Landroid/net/Uri;

    const/4 v9, 0x0

    const-wide/16 v10, -0x1

    move v0, p0

    move-object v1, p1

    move-object v3, p2

    move-object v4, p3

    move-object/from16 v5, p4

    move-object/from16 v6, p5

    move-object/from16 v7, p6

    move/from16 v8, p7

    invoke-static/range {v0 .. v11}, Landroid/provider/Telephony$Sms;->addMessageToUri(ILandroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZJ)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method

.method public static addMessage(Landroid/content/ContentResolver;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;Z)Landroid/net/Uri;
    .locals 9
    .param p0, "resolver"    # Landroid/content/ContentResolver;
    .param p1, "address"    # Ljava/lang/String;
    .param p2, "body"    # Ljava/lang/String;
    .param p3, "subject"    # Ljava/lang/String;
    .param p4, "date"    # Ljava/lang/Long;
    .param p5, "read"    # Z

    .prologue
    .line 645
    invoke-static {}, Landroid/telephony/SubscriptionManager;->getDefaultSmsSubId()I

    move-result v0

    sget-object v2, Landroid/provider/Telephony$Sms$Inbox;->CONTENT_URI:Landroid/net/Uri;

    const/4 v8, 0x0

    move-object v1, p0

    move-object v3, p1

    move-object v4, p2

    move-object v5, p3

    move-object v6, p4

    move v7, p5

    invoke-static/range {v0 .. v8}, Landroid/provider/Telephony$Sms;->addMessageToUri(ILandroid/content/ContentResolver;Landroid/net/Uri;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Long;ZZ)Landroid/net/Uri;

    move-result-object v0

    return-object v0
.end method


text:
namespace {

// This class checks if the current executable is pinned to the taskbar. It also
// keeps track of the errors that occurs that prevents it from getting a result.
class IsPinnedToTaskbarHelper {
 public:
  IsPinnedToTaskbarHelper() = default;

  // Returns true if the current executable is pinned to the taskbar.
  bool GetResult();

  bool error_occured() { return error_occured_; }

 private:
  // Returns the shell resource string identified by |resource_id|, or an empty
  // string on error.
  base::string16 LoadShellResourceString(uint32_t resource_id);

  // Returns true if the "Unpin from taskbar" verb is available for |shortcut|,
  // which means that the shortcut is pinned to the taskbar.
  bool ShortcutHasUnpinToTaskbarVerb(const base::FilePath& shortcut);

  // Returns true if the target parameter of the |shortcut| evaluates to
  // |program_compare|.
  bool IsShortcutForProgram(const base::FilePath& shortcut,
                            const InstallUtil::ProgramCompare& program_compare);

  // Returns true if one of the shortcut inside the given |directory| evaluates
  // to |program_compare| and is pinned to the taskbar.
  bool DirectoryContainsPinnedShortcutForProgram(
      const base::FilePath& directory,
      const InstallUtil::ProgramCompare& program_compare);

  bool error_occured_ = false;
  base::win::ScopedCOMInitializer scoped_com_initializer_;

  DISALLOW_COPY_AND_ASSIGN(IsPinnedToTaskbarHelper);
};

base::string16 IsPinnedToTaskbarHelper::LoadShellResourceString(
    uint32_t resource_id) {
  base::ScopedNativeLibrary scoped_native_library(::LoadLibraryEx(
      FILE_PATH_LITERAL("shell32.dll"), nullptr, LOAD_LIBRARY_AS_DATAFILE));
  if (!scoped_native_library.is_valid())
    return base::string16();

  const wchar_t* resource_ptr = nullptr;
  int length = ::LoadStringW(scoped_native_library.get(), resource_id,
                             reinterpret_cast<wchar_t*>(&resource_ptr), 0);
  if (!length || !resource_ptr)
    return base::string16();
  return base::string16(resource_ptr, length);
}

bool IsPinnedToTaskbarHelper::ShortcutHasUnpinToTaskbarVerb(
    const base::FilePath& shortcut) {
  // Found inside shell32.dll's resources.
  constexpr uint32_t kUnpinFromTaskbarID = 5387;

  base::string16 verb_name(LoadShellResourceString(kUnpinFromTaskbarID));
  if (verb_name.empty()) {
    error_occured_ = true;
    return false;
  }

  base::win::ScopedComPtr<IShellDispatch> shell_dispatch;
  HRESULT hresult =
      shell_dispatch.CreateInstance(CLSID_Shell, nullptr, CLSCTX_INPROC_SERVER);
  if (FAILED(hresult) || !shell_dispatch) {
    error_occured_ = true;
    return false;
  }

  base::win::ScopedComPtr<Folder> folder;
  hresult = shell_dispatch->NameSpace(
      base::win::ScopedVariant(shortcut.DirName().value().c_str()),
      folder.Receive());
  if (FAILED(hresult) || !folder) {
    error_occured_ = true;
    return false;
  }

  base::win::ScopedComPtr<FolderItem> item;
  hresult = folder->ParseName(
      base::win::ScopedBstr(shortcut.BaseName().value().c_str()),
      item.Receive());
  if (FAILED(hresult) || !item) {
    error_occured_ = true;
    return false;
  }

  base::win::ScopedComPtr<FolderItemVerbs> verbs;
  hresult = item->Verbs(verbs.Receive());
  if (FAILED(hresult) || !verbs) {
    error_occured_ = true;
    return false;
  }

  long verb_count = 0;
  hresult = verbs->get_Count(&verb_count);
  if (FAILED(hresult)) {
    error_occured_ = true;
    return false;
  }

  long error_count = 0;
  for (long i = 0; i < verb_count; ++i) {
    base::win::ScopedComPtr<FolderItemVerb> verb;
    hresult = verbs->Item(base::win::ScopedVariant(i, VT_I4), verb.Receive());
    if (FAILED(hresult) || !verb) {
      error_count++;
      continue;
    }
    base::win::ScopedBstr name;
    hresult = verb->get_Name(name.Receive());
    if (FAILED(hresult)) {
      error_count++;
      continue;
    }
    if (base::StringPiece16(name, name.Length()) == verb_name)
      return true;
  }

  if (error_count == verb_count)
    error_occured_ = true;

  return false;
}

bool IsPinnedToTaskbarHelper::IsShortcutForProgram(
    const base::FilePath& shortcut,
    const InstallUtil::ProgramCompare& program_compare) {
  base::win::ShortcutProperties shortcut_properties;
  if (!ResolveShortcutProperties(
          shortcut, base::win::ShortcutProperties::PROPERTIES_TARGET,
          &shortcut_properties)) {
    return false;
  }

  return program_compare.EvaluatePath(shortcut_properties.target);
}

bool IsPinnedToTaskbarHelper::DirectoryContainsPinnedShortcutForProgram(
    const base::FilePath& directory,
    const InstallUtil::ProgramCompare& program_compare) {
  base::FileEnumerator shortcut_enum(directory, false,
                                     base::FileEnumerator::FILES);
  for (base::FilePath shortcut = shortcut_enum.Next(); !shortcut.empty();
       shortcut = shortcut_enum.Next()) {
    if (IsShortcutForProgram(shortcut, program_compare) &&
        ShortcutHasUnpinToTaskbarVerb(shortcut)) {
      return true;
    }
  }
  return false;
}

bool IsPinnedToTaskbarHelper::GetResult() {
  base::FilePath current_exe;
  PathService::Get(base::FILE_EXE, &current_exe);

  InstallUtil::ProgramCompare current_exe_compare(current_exe);
  // Look into the "Quick Launch\User Pinned\TaskBar" folder.
  base::FilePath taskbar_pins_dir;
  PathService::Get(base::DIR_TASKBAR_PINS, &taskbar_pins_dir);
  if (DirectoryContainsPinnedShortcutForProgram(taskbar_pins_dir,
                                                current_exe_compare)) {
    return true;
  }

  // Check all folders in ImplicitAppShortcuts.
  base::FilePath implicit_app_shortcuts_dir;
  PathService::Get(base::DIR_IMPLICIT_APP_SHORTCUTS,
                   &implicit_app_shortcuts_dir);
  base::FileEnumerator directory_enum(implicit_app_shortcuts_dir, false,
                                      base::FileEnumerator::DIRECTORIES);
  for (base::FilePath directory = directory_enum.Next(); !directory.empty();
       directory = directory_enum.Next()) {
    if (DirectoryContainsPinnedShortcutForProgram(directory,
                                                  current_exe_compare)) {
      return true;
    }
  }
  return false;
}

}  // namespace

// static
void ShellHandlerImpl::Create(mojom::ShellHandlerRequest request) {
  new ShellHandlerImpl(std::move(request));
}

ShellHandlerImpl::ShellHandlerImpl(mojom::ShellHandlerRequest request)
    : binding_(this, std::move(request)) {}

ShellHandlerImpl::~ShellHandlerImpl() = default;

void ShellHandlerImpl::IsPinnedToTaskbar(
    const IsPinnedToTaskbarCallback& callback) {
  IsPinnedToTaskbarHelper helper;
  bool is_pinned_to_taskbar = helper.GetResult();
  callback.Run(!helper.error_occured(), is_pinned_to_taskbar);
}


text:
package com.gentics.mesh.graphdb;

import static com.gentics.mesh.test.TestSize.FULL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Ignore;
import org.junit.Test;

import com.gentics.mesh.core.data.dao.TagDao;
import com.gentics.mesh.core.data.dao.UserDao;
import com.gentics.mesh.core.data.node.HibNode;
import com.gentics.mesh.core.data.project.HibProject;
import com.gentics.mesh.core.data.tag.HibTag;
import com.gentics.mesh.core.data.tagfamily.HibTagFamily;
import com.gentics.mesh.core.data.user.HibUser;
import com.gentics.mesh.core.db.CommonTx;
import com.gentics.mesh.core.db.Tx;
import com.gentics.mesh.test.MeshTestSetting;
import com.gentics.mesh.test.context.AbstractMeshTest;
import com.gentics.mesh.test.util.TestUtils;

import io.reactivex.Single;

@MeshTestSetting(testSize = FULL, startServer = true)
public class TxTest extends AbstractMeshTest {

	@Test
	public void testTransaction() throws InterruptedException {
		AtomicInteger i = new AtomicInteger(0);

		int e = i.incrementAndGet();
		try (Tx tx = tx()) {
			UserDao userDao= tx.userDao();
			assertNotNull(userDao.create("testuser" + e, user()));
			assertNotNull(tx.userDao().findByUsername("testuser" + e));
			tx.success();
		}
		try (Tx tx = tx()) {
			assertNotNull(tx.userDao().findByUsername("testuser" + e));
		}
		int u = i.incrementAndGet();
		Runnable task = () -> {
			try (Tx tx = tx()) {
				UserDao userDao= tx.userDao();
				assertNotNull(userDao.create("testuser" + u, user()));
				assertNotNull(userDao.findByUsername("testuser" + u));
				tx.failure();
			}
			assertNull(tx(tx -> { return tx.userDao().findByUsername("testuser" + u); }));
		};
		Thread t = new Thread(task);
		t.start();
		t.join();
		try (Tx tx = tx()) {
			assertNull(tx.userDao().findByUsername("testuser" + u));
			System.out.println("RUN: " + i.get());
		}

	}

	@Test
	public void testMultiThreadedModifications() throws InterruptedException {
		Runnable task2 = () -> {
			try (Tx tx = tx()) {
				HibUser user = tx.userDao().findByUuid(userUuid());
				user.setUsername("test2");
				assertNotNull(tx.userDao().findByUsername("test2"));
				tx.success();
			}

			Runnable task = () -> {
				try (Tx tx = tx()) {
					HibUser user = tx.userDao().findByUuid(userUuid());
					user.setUsername("test3");
					assertNotNull(tx.userDao().findByUsername("test3"));
					tx.failure();
				}

			};
			Thread t = new Thread(task);
			t.start();
			try {
				t.join();
			} catch (Exception e) {
				e.printStackTrace();
			}
		};
		Thread t2 = new Thread(task2);
		t2.start();
		t2.join();
		try (Tx tx = tx()) {
			assertNull(tx.userDao().findByUsername("test3"));
			assertNotNull("The user with username test2 could not be found.", tx.userDao().findByUsername("test2"));
		}

	}

	@Test(expected = RuntimeException.class)
	public void testAsyncNoTrxWithError() throws Throwable {
		CompletableFuture<Throwable> cf = new CompletableFuture<>();
		db().asyncTx(() -> {
			throw new RuntimeException("error");
		}).blockingGet();
		assertEquals("error", cf.get().getMessage());
		throw cf.get();
	}

	@Test
	public void testAsyncNoTrxNestedAsync() throws InterruptedException, ExecutionException {
		String result = db().asyncTx(() -> {
			TestUtils.run(() -> {
				TestUtils.sleep(1000);
			});
			return Single.just("OK");
		}).blockingGet();
		assertEquals("OK", result);
	}

	@Test
	public void testAsyncNoTrxSuccess() throws Throwable {
		String result = db().asyncTx(() -> {
			return Single.just("OK");
		}).blockingGet();
		assertEquals("OK", result);
	}

	@Test
	@Ignore
	public void testUpdateMultithreaded() throws InterruptedException, BrokenBarrierException, TimeoutException {

		final int nThreads = 10;
		final int nRuns = 20;
		final int maxRetry = 20;

		for (int r = 0; r < nRuns; r++) {
			final int currentRun = r;
			System.out.println("\n\n\n\n");
			// TraversalHelper.printDebugVertices();
			CyclicBarrier barrierA = new CyclicBarrier(nThreads);
			CyclicBarrier barrierB = new CyclicBarrier(nThreads);
			HibNode node = content();
			HibTagFamily tagFamily = tagFamily("colors");
			List<Thread> threads = new ArrayList<>();
			HibProject project = project();
			HibUser user = user();

			for (int i = 0; i < nThreads; i++) {
				final int threadNo = i;
				System.out.println("Thread [" + threadNo + "] Starting");
				Thread t = TestUtils.run(() -> {

					for (int retry = 0; retry < maxRetry; retry++) {
						try {
							try (Tx tx = tx()) {
								CommonTx ctx = tx.unwrap();
								TagDao tagDao = tx.tagDao();
								if (retry == 0) {
									try {
										System.out.println("Thread [" + threadNo + "] Waiting..");
										barrierA.await(10, TimeUnit.SECONDS);
										System.out.println("Thread [" + threadNo + "] Waited");
									} catch (Exception e) {
										System.out.println("Thread [" + threadNo + "] Error handling barrier timeout? - retry: " + retry);
										// e.printStackTrace();
									}
								}
								// Load used elements
								HibTagFamily reloadedTagFamily = ctx.load(tagFamily.getId(), ctx.tagFamilyDao().getPersistenceClass(project()));
								HibNode reloadedNode = ctx.load(node.getId(), ctx.nodeDao().getPersistenceClass(project));
								HibUser reloadedUser = ctx.load(user.getId(), ctx.userDao().getPersistenceClass());
								HibProject reloadedProject = ctx.load(project.getId(), ctx.projectDao().getPersistenceClass());

								HibTag tag = tagDao.create(reloadedTagFamily, "bogus_" + threadNo + "_" + currentRun, project(), reloadedUser);
								// Reload the node
								tagDao.addTag(reloadedNode, tag, reloadedProject.getLatestBranch());
								tx.success();
								if (retry == 0) {
									try {
										System.out.println("Thread [" + threadNo + "] Waiting..");
										barrierB.await(10, TimeUnit.SECONDS);
										System.out.println("Thread [" + threadNo + "] Waited");
									} catch (Exception e) {
										System.out.println("Thread [" + threadNo + "] Error handling barrier timeout? - retry: " + retry);
										// e.printStackTrace();
									}
								}
							}
							System.out.println("Thread [" + threadNo + "] Successful updated element - retry: " + retry);
							break;
						} catch (Exception e) {

							// trx.rollback();
							System.out.println("Thread [" + threadNo + "] Got exception {" + e.getClass().getName() + "}  - retry: " + retry);
							e.printStackTrace();
						}
					}
				});
				threads.add(t);
			}
			System.out.println("Waiting on lock");
			// barrier.blockingAwait()(2, TimeUnit.SECONDS);
			for (Thread currentThread : threads) {
				currentThread.join();
			}
			// Thread.sleep(1000);
			try (Tx tx = tx()) {
				CommonTx ctx = tx.unwrap();
				TagDao tagDao = tx.tagDao();

				int expect = nThreads * (r + 1);
				HibNode reloadedNode = ctx.load(node.getId(), ctx.nodeDao().getPersistenceClass(project));
				// node.reload();
				assertEquals("Expected {" + expect + "} tags since this is run {" + r + "}.", expect,
						tagDao.getTags(reloadedNode, project().getLatestBranch()).count());
			}
		}
	}
}


text:
var di_1 = require('angular2/di');
var lang_1 = require('angular2/src/facade/lang');
var browser_adapter_1 = require('angular2/src/dom/browser_adapter');
var dom_adapter_1 = require('angular2/src/dom/dom_adapter');
var compiler_1 = require('./compiler/compiler');
var reflection_1 = require('angular2/src/reflection/reflection');
var change_detection_1 = require('angular2/change_detection');
var exception_handler_1 = require('./exception_handler');
var template_loader_1 = require('angular2/src/render/dom/compiler/template_loader');
var template_resolver_1 = require('./compiler/template_resolver');
var directive_resolver_1 = require('./compiler/directive_resolver');
var collection_1 = require('angular2/src/facade/collection');
var async_1 = require('angular2/src/facade/async');
var ng_zone_1 = require('angular2/src/core/zone/ng_zone');
var life_cycle_1 = require('angular2/src/core/life_cycle/life_cycle');
var shadow_dom_strategy_1 = require('angular2/src/render/dom/shadow_dom/shadow_dom_strategy');
var emulated_unscoped_shadow_dom_strategy_1 = require('angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy');
var xhr_1 = require('angular2/src/services/xhr');
var xhr_impl_1 = require('angular2/src/services/xhr_impl');
var event_manager_1 = require('angular2/src/render/dom/events/event_manager');
var key_events_1 = require('angular2/src/render/dom/events/key_events');
var hammer_gestures_1 = require('angular2/src/render/dom/events/hammer_gestures');
var component_url_mapper_1 = require('angular2/src/core/compiler/component_url_mapper');
var url_resolver_1 = require('angular2/src/services/url_resolver');
var style_url_resolver_1 = require('angular2/src/render/dom/shadow_dom/style_url_resolver');
var style_inliner_1 = require('angular2/src/render/dom/shadow_dom/style_inliner');
var dynamic_component_loader_1 = require('angular2/src/core/compiler/dynamic_component_loader');
var testability_1 = require('angular2/src/core/testability/testability');
var view_pool_1 = require('angular2/src/core/compiler/view_pool');
var view_manager_1 = require('angular2/src/core/compiler/view_manager');
var view_manager_utils_1 = require('angular2/src/core/compiler/view_manager_utils');
var view_listener_1 = require('angular2/src/core/compiler/view_listener');
var proto_view_factory_1 = require('angular2/src/core/compiler/proto_view_factory');
var api_1 = require('angular2/src/render/api');
var dom_renderer_1 = require('angular2/src/render/dom/dom_renderer');
var view_1 = require('angular2/src/render/dom/view/view');
var compiler_2 = require('angular2/src/render/dom/compiler/compiler');
var view_ref_1 = require('angular2/src/core/compiler/view_ref');
var application_tokens_1 = require('./application_tokens');
var _rootInjector;
// Contains everything that is safe to share between applications.
var _rootBindings = [di_1.bind(reflection_1.Reflector).toValue(reflection_1.reflector), testability_1.TestabilityRegistry];
function _injectorBindings(appComponentType) {
    return [
        di_1.bind(dom_renderer_1.DOCUMENT_TOKEN)
            .toValue(dom_adapter_1.DOM.defaultDoc()),
        di_1.bind(application_tokens_1.appComponentTypeToken).toValue(appComponentType),
        di_1.bind(application_tokens_1.appComponentRefToken)
            .toAsyncFactory(function (dynamicComponentLoader, injector, testability, registry) {
            // TODO(rado): investigate whether to support bindings on root component.
            return dynamicComponentLoader.loadAsRoot(appComponentType, null, injector)
                .then(function (componentRef) {
                var domView = view_1.resolveInternalDomView(componentRef.hostView.render);
                // We need to do this here to ensure that we create Testability and
                // it's ready on the window for users.
                registry.registerApplication(domView.boundElements[0], testability);
                return componentRef;
            });
        }, [dynamic_component_loader_1.DynamicComponentLoader, di_1.Injector, testability_1.Testability, testability_1.TestabilityRegistry]),
        di_1.bind(appComponentType).toFactory(function (ref) { return ref.instance; }, [application_tokens_1.appComponentRefToken]),
        di_1.bind(life_cycle_1.LifeCycle)
            .toFactory(function (exceptionHandler) { return new life_cycle_1.LifeCycle(exceptionHandler, null, lang_1.assertionsEnabled()); }, [exception_handler_1.ExceptionHandler]),
        di_1.bind(event_manager_1.EventManager)
            .toFactory(function (ngZone) {
            var plugins = [new hammer_gestures_1.HammerGesturesPlugin(), new key_events_1.KeyEventsPlugin(), new event_manager_1.DomEventsPlugin()];
            return new event_manager_1.EventManager(plugins, ngZone);
        }, [ng_zone_1.NgZone]),
        di_1.bind(shadow_dom_strategy_1.ShadowDomStrategy)
            .toFactory(function (styleUrlResolver, doc) {
            return new emulated_unscoped_shadow_dom_strategy_1.EmulatedUnscopedShadowDomStrategy(styleUrlResolver, doc.head);
        }, [style_url_resolver_1.StyleUrlResolver, dom_renderer_1.DOCUMENT_TOKEN]),
        dom_renderer_1.DomRenderer,
        compiler_2.DefaultDomCompiler,
        di_1.bind(api_1.Renderer).toAlias(dom_renderer_1.DomRenderer),
        di_1.bind(api_1.RenderCompiler).toAlias(compiler_2.DefaultDomCompiler),
        proto_view_factory_1.ProtoViewFactory,
        view_pool_1.AppViewPool,
        di_1.bind(view_pool_1.APP_VIEW_POOL_CAPACITY).toValue(10000),
        view_manager_1.AppViewManager,
        view_manager_utils_1.AppViewManagerUtils,
        view_listener_1.AppViewListener,
        compiler_1.Compiler,
        compiler_1.CompilerCache,
        template_resolver_1.TemplateResolver,
        di_1.bind(change_detection_1.PipeRegistry).toValue(change_detection_1.defaultPipeRegistry),
        di_1.bind(change_detection_1.ChangeDetection).toClass(change_detection_1.DynamicChangeDetection),
        template_loader_1.TemplateLoader,
        directive_resolver_1.DirectiveResolver,
        change_detection_1.Parser,
        change_detection_1.Lexer,
        exception_handler_1.ExceptionHandler,
        di_1.bind(xhr_1.XHR).toValue(new xhr_impl_1.XHRImpl()),
        component_url_mapper_1.ComponentUrlMapper,
        url_resolver_1.UrlResolver,
        style_url_resolver_1.StyleUrlResolver,
        style_inliner_1.StyleInliner,
        dynamic_component_loader_1.DynamicComponentLoader,
        testability_1.Testability
    ];
}
function _createNgZone(givenReporter) {
    var defaultErrorReporter = function (exception, stackTrace) {
        var longStackTrace = collection_1.ListWrapper.join(stackTrace, "\n\n-----async gap-----\n");
        dom_adapter_1.DOM.logError(exception + "\n\n" + longStackTrace);
        throw exception;
    };
    var reporter = lang_1.isPresent(givenReporter) ? givenReporter : defaultErrorReporter;
    var zone = new ng_zone_1.NgZone({ enableLongStackTrace: lang_1.assertionsEnabled() });
    zone.initCallbacks({ onErrorHandler: reporter });
    return zone;
}
/**
 * Bootstrapping for Angular applications.
 *
 * You instantiate an Angular application by explicitly specifying a component to use as the root
 * component for your
 * application via the `bootstrap()` method.
 *
 * ## Simple Example
 *
 * Assuming this `index.html`:
 *
 * ```html
 * <html>
 *   <!-- load Angular script tags here. -->
 *   <body>
 *     <my-app>loading...</my-app>
 *   </body>
 * </html>
 * ```
 *
 * An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike
 * Angular 1, Angular 2
 * does not compile/process bindings in `index.html`. This is mainly for security reasons, as well
 * as architectural
 * changes in Angular 2. This means that `index.html` can safely be processed using server-side
 * technologies such as
 * bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2
 * component double-curly
 * `{{ syntax }}`.
 *
 * We can use this script code:
 *
 * ```
 * @Component({
 *    selector: 'my-app'
 * })
 * @View({
 *    template: 'Hello {{ name }}!'
 * })
 * class MyApp {
 *   name:string;
 *
 *   constructor() {
 *     this.name = 'World';
 *   }
 * }
 *
 * main() {
 *   return bootstrap(MyApp);
 * }
 * ```
 *
 * When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument,
 * Angular performs the
 * following tasks:
 *
 *  1. It uses the component's `selector` property to locate the DOM element which needs to be
 * upgraded into
 *     the angular component.
 *  2. It creates a new child injector (from the platform injector) and configures the injector with
 * the component's
 *     `appInjector`. Optionally, you can also override the injector configuration for an app by
 * invoking
 *     `bootstrap` with the `componentInjectableBindings` argument.
 *  3. It creates a new `Zone` and connects it to the angular application's change detection domain
 * instance.
 *  4. It creates a shadow DOM on the selected component's host element and loads the template into
 * it.
 *  5. It instantiates the specified component.
 *  6. Finally, Angular performs change detection to apply the initial data bindings for the
 * application.
 *
 *
 * ## Instantiating Multiple Applications on a Single Page
 *
 * There are two ways to do this.
 *
 *
 * ### Isolated Applications
 *
 * Angular creates a new application each time that the `bootstrap()` method is invoked. When
 * multiple applications
 * are created for a page, Angular treats each application as independent within an isolated change
 * detection and
 * `Zone` domain. If you need to share data between applications, use the strategy described in the
 * next
 * section, "Applications That Share Change Detection."
 *
 *
 * ### Applications That Share Change Detection
 *
 * If you need to bootstrap multiple applications that share common data, the applications must
 * share a common
 * change detection and zone. To do that, create a meta-component that lists the application
 * components in its template.
 * By only invoking the `bootstrap()` method once, with the meta-component as its argument, you
 * ensure that only a
 * single change detection zone is created and therefore data can be shared across the applications.
 *
 *
 * ## Platform Injector
 *
 * When working within a browser window, there are many singleton resources: cookies, title,
 * location, and others.
 * Angular services that represent these resources must likewise be shared across all Angular
 * applications that
 * occupy the same browser window.  For this reason, Angular creates exactly one global platform
 * injector which stores
 * all shared services, and each angular application injector has the platform injector as its
 * parent.
 *
 * Each application has its own private injector as well. When there are multiple applications on a
 * page, Angular treats
 * each application injector's services as private to that application.
 *
 *
 * # API
 * - `appComponentType`: The root component which should act as the application. This is a reference
 * to a `Type`
 *   which is annotated with `@Component(...)`.
 * - `componentInjectableBindings`: An additional set of bindings that can be added to `appInjector`
 * for the
 * {@link Component} to override default injection behavior.
 * - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for
 * unhandled exceptions.
 *
 * Returns a `Promise` with the application`s private {@link Injector}.
 *
 * @exportedAs angular2/core
 */
function bootstrap(appComponentType, componentInjectableBindings, errorReporter) {
    if (componentInjectableBindings === void 0) { componentInjectableBindings = null; }
    if (errorReporter === void 0) { errorReporter = null; }
    browser_adapter_1.BrowserDomAdapter.makeCurrent();
    var bootstrapProcess = async_1.PromiseWrapper.completer();
    var zone = _createNgZone(errorReporter);
    zone.run(function () {
        // TODO(rado): prepopulate template cache, so applications with only
        // index.html and main.js are possible.
        var appInjector = _createAppInjector(appComponentType, componentInjectableBindings, zone);
        async_1.PromiseWrapper.then(appInjector.asyncGet(application_tokens_1.appComponentRefToken), function (componentRef) {
            var appChangeDetector = view_ref_1.internalView(componentRef.hostView).changeDetector;
            // retrieve life cycle: may have already been created if injected in root component
            var lc = appInjector.get(life_cycle_1.LifeCycle);
            lc.registerWith(zone, appChangeDetector);
            lc.tick(); // the first tick that will bootstrap the app
            bootstrapProcess.resolve(new ApplicationRef(componentRef, appComponentType, appInjector));
        }, function (err, stackTrace) { bootstrapProcess.reject(err, stackTrace); });
    });
    return bootstrapProcess.promise;
}
exports.bootstrap = bootstrap;
var ApplicationRef = (function () {
    function ApplicationRef(hostComponent, hostComponentType, injector) {
        this._hostComponent = hostComponent;
        this._injector = injector;
        this._hostComponentType = hostComponentType;
    }
    Object.defineProperty(ApplicationRef.prototype, "hostComponentType", {
        get: function () { return this._hostComponentType; },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(ApplicationRef.prototype, "hostComponent", {
        get: function () { return this._hostComponent.instance; },
        enumerable: true,
        configurable: true
    });
    ApplicationRef.prototype.dispose = function () {
        // TODO: We also need to clean up the Zone, ... here!
        return this._hostComponent.dispose();
    };
    Object.defineProperty(ApplicationRef.prototype, "injector", {
        get: function () { return this._injector; },
        enumerable: true,
        configurable: true
    });
    return ApplicationRef;
})();
exports.ApplicationRef = ApplicationRef;
function _createAppInjector(appComponentType, bindings, zone) {
    if (lang_1.isBlank(_rootInjector))
        _rootInjector = di_1.Injector.resolveAndCreate(_rootBindings);
    var mergedBindings = lang_1.isPresent(bindings) ?
        collection_1.ListWrapper.concat(_injectorBindings(appComponentType), bindings) :
        _injectorBindings(appComponentType);
    collection_1.ListWrapper.push(mergedBindings, di_1.bind(ng_zone_1.NgZone).toValue(zone));
    return _rootInjector.resolveAndCreateChild(mergedBindings);
}
exports.__esModule = true;
//# sourceMappingURL=application.js.map


text:
var colours = require('colors');
module.exports = exports = function() {

	var tests, lastTestName, lastTestStartTime, firstOutput;

	function elapsedTime() {
		return "(" + (Date.now() - lastTestStartTime) + "ms)";
	}

	function success(message) {
		console.log("\t" + lastTestName.yellow + " : " + (message ? message + "" : "PASS").green + " " + elapsedTime());
		nextTest();
	}

	function fail(message) {
		console.log("\t" + lastTestName.yellow + " : " + (message ? message + "" : "FAILED").red + " " + elapsedTime()
				+ "\n\n");
	}

	function nextTest() {
		if (tests.length == 0) {
			console.log("\n\tAll tests passed.\n".green);
			return;
		} else {
			var test = tests.shift();
			firstOutput = true;
			lastTestName = test.name;
			lastTestStartTime = Date.now();

			test();
		}
	}

	function checkFirstOutput() {
		if (firstOutput) {
			console.log("\n\t" + (lastTestName + "...").yellow);
			console.log("\t----------------------------------------------------------------------");
			firstOutput = false;
		}
	}

	return {
		run : function(testsToRun) {
			console.log("\nTests :");
			tests = testsToRun;
			nextTest();
		},
		success : success,
		fail : fail,
		json : function(o, message) {
			checkFirstOutput();
			if (message) {
				console.log("\t" + message.cyan);
			}
			console.log("\t" + JSON.stringify(o, null, 2).replace(/\n/g, '\n\t').magenta);
			console.log("\t----------------------------------------------------------------------");
		},
		print : function(message) {
			checkFirstOutput();
			console.log("\t" + message.cyan);
			console.log("\t----------------------------------------------------------------------");
		}
	};

};


text:
package main

import "fmt"

type Currency struct {
	Name    string
	Country string
	Number  int
}

var CAD = Currency{Name: "Canadian Dollar", Country: "Canada", Number: 124}
var FJD = Currency{Name: "Fiji Dollar", Country: "Fiji", Number: 242}
var JMD = Currency{Name: "Jamaican Dollar", Country: "Jamaica", Number: 388}
var USD = Currency{Name: "US Dollar", Country: "USA", Number: 840}

func main() {
	num0 := 242
	if num0 > 100 || num0 < 900 {
		fmt.Println("Currency: ", num0)
		printCurr(num0)
	} else {
		fmt.Println("Currency unknown")
	}

	if num1 := 388; num1 > 100 || num1 < 900 {
		fmt.Println("Currency:", num1)
		printCurr(num1)
	}
}

func printCurr(number int) {
	if CAD.Number == number {
		fmt.Printf("Found: %+v\n", CAD)
	} else if FJD.Number == number {
		fmt.Printf("Found: %+v\n", FJD)
	} else if JMD.Number == number {
		fmt.Printf("Found: %+v\n", JMD)
	} else if USD.Number == number {
		fmt.Printf("Found: %+v\n", USD)
	} else {
		fmt.Println("No currency found with number", number)
	}
}


text:
	#define DISABLESTEAMWORKS
#endif

#if !DISABLESTEAMWORKS

using System.Runtime.InteropServices;
using IntPtr = System.IntPtr;

namespace Steamworks {
	[System.Serializable]
	public struct FriendsGroupID_t : System.IEquatable<FriendsGroupID_t>, System.IComparable<FriendsGroupID_t> {
		public static readonly FriendsGroupID_t Invalid = new FriendsGroupID_t(-1);
		public short m_FriendsGroupID;

		public FriendsGroupID_t(short value) {
			m_FriendsGroupID = value;
		}

		public override string ToString() {
			return m_FriendsGroupID.ToString();
		}

		public override bool Equals(object other) {
			return other is FriendsGroupID_t && this == (FriendsGroupID_t)other;
		}

		public override int GetHashCode() {
			return m_FriendsGroupID.GetHashCode();
		}

		public static bool operator ==(FriendsGroupID_t x, FriendsGroupID_t y) {
			return x.m_FriendsGroupID == y.m_FriendsGroupID;
		}

		public static bool operator !=(FriendsGroupID_t x, FriendsGroupID_t y) {
			return !(x == y);
		}

		public static explicit operator FriendsGroupID_t(short value) {
			return new FriendsGroupID_t(value);
		}

		public static explicit operator short(FriendsGroupID_t that) {
			return that.m_FriendsGroupID;
		}

		public bool Equals(FriendsGroupID_t other) {
			return m_FriendsGroupID == other.m_FriendsGroupID;
		}

		public int CompareTo(FriendsGroupID_t other) {
			return m_FriendsGroupID.CompareTo(other.m_FriendsGroupID);
		}
	}
}

#endif // !DISABLESTEAMWORKS


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-4-534.js
 * @description ES5 Attributes - success to update [[Get]] attribute of accessor property ([[Get]] is a Function, [[Set]] is a Function, [[Enumerable]] is true, [[Configurable]] is true) to different value
 */

function testcase() {
        var obj = {};

        var getFunc = function () {
            return 1001;
        };

        var verifySetFunc = "data";
        var setFunc = function (value) {
            verifySetFunc = value;
        };

        Object.defineProperty(obj, "prop", {
            get: getFunc,
            set: setFunc,
            enumerable: true,
            configurable: true
        });

        var result1 = obj.prop === 1001;
        var desc1 = Object.getOwnPropertyDescriptor(obj, "prop");

        Object.defineProperty(obj, "prop", {
            get: undefined
        });

        var result2 = typeof obj.prop === "undefined";
        var desc2 = Object.getOwnPropertyDescriptor(obj, "prop");

        return result1 && result2 && desc1.get === getFunc && typeof desc2.get === "undefined";
    }
runTestCase(testcase);


text:
<?php

namespace NGPP\GmsagcBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use NGPP\GmsagcBundle\Form\EventListener\SaveOrdersListener;

class OrdersType extends AbstractType
{
    private $SaveOrdersListener;

    function __construct(SaveOrdersListener $SaveOrdersListener)
    {
        $this->SaveOrdersListener = $SaveOrdersListener;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('relations',
                'collection',
                array(
                    'type' => new RelationsType(),
                    'label' => false,
                    'property_path' => 'relations'
                    ));
        $builder
            ->add('oral', null, array('widget' => 'single_text'))
            ->add('written', null, array('widget' => 'single_text'))
            ->add('observation')
            ->add('trial', null, array('widget' => 'single_text'))
            ->add('quote', 'money')
            ->add('pieces')
            ->add('shrinkage')
            ->add('press', 'press_selector', array('attr' => array('autocomplete' => 'off')))
            ->add('material', 'material_selector', array('attr' => array('autocomplete' => 'off')))
        ;

        $builder->addEventSubscriber($this->SaveOrdersListener);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'NGPP\GmsagcBundle\Entity\Orders'
        ));
    }

    public function getName()
    {
        return 'ngpp_gmsagcbundle_orderstype';
    }
}


text:
/**
 * Example 81 - A try-catch Statement
 */

class TryCatch {
    static final String[] wdays =
            {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    static class WeekdayException extends Exception{
        public WeekdayException(String wday) {
            super("Illegal weekday: " + wday);
        }
    }

    static int wdayno4(String wday) throws WeekdayException {
        for (int i = 0; i < wdays.length; i++)
            if (wday.equals(wdays[i]))
                return i+1;
        throw new WeekdayException(wday);
    }

    public static void main(String[] args) {
        try {
            System.out.println(args[0] + " is weekday number " + wdayno4(args[0]));
        } catch (WeekdayException x) {
            System.out.println("Weekday problem: " + x);
        } catch (Exception x) {
            System.out.println("Other problem: " + x);
        }
    }
}


text:
package io.skysail.server.app.webconsole.test;

public class BundleDescriptorTest {

}


text:
'''
Created on May 15, 2013

@author: Cam Moore
'''
import unittest
from django.test.testcases import TransactionTestCase
from apps.managers.smartgrid_mgr import gcc, action_dependency
from apps.utils import test_utils
from apps.widgets.smartgrid_design.models import DesignerEvent, DesignerAction

class Test(TransactionTestCase):
    """Tests for the Grid Consistency Checker."""
    fixtures = ['smartgrid_library.json', 'test_challenge.json', 'test_designer.json']

    def setUp(self):
        """Setup the test environment."""
        test_utils.set_three_rounds()

    def testCheckEventDates(self):
        """Tests gcc.check_event_dates(draft=None)"""
        errors = gcc.check_event_dates(draft=None)
        num_errors = len(DesignerEvent.objects.filter(draft=None)) * 2
        self.assertEqual(len(errors), num_errors, "Expecting %s errors got %s" % (num_errors, \
                                                                                len(errors)))

    def testCheckPubDates(self):
        """Tests gcc.check_pub_exp_dates(draft=None)."""
        e = gcc.check_pub_exp_dates(draft=None)
        # one pub date is in future
        self.assertEqual(1, len(e['errors']), "Expecting %s errors got %s" % \
                         (1, len(e['errors'])))
        # all action pub dates aren't in rounds N-1 before one after.
        num_action = len(DesignerAction.objects.filter(draft=None))
        self.assertEqual(len(e['warnings']), num_action, "Expecting %s warnings got %s" % \
                         (num_action, len(e['warnings'])))

    def testCheckGridPubDates(self):
        """Tests gcc.check_grid_pub_exp_dates(draft=None)."""
        e = gcc.check_grid_pub_exp_dates(draft=None)
        len(DesignerAction.objects.filter(draft=None))
        ans = 1
        self.assertEqual(ans, len(e['errors']), "Expecting %s got %s" % (ans, len(e['errors'])))
        ans = 0
        self.assertEqual(ans, len(e['warnings']), \
                         "Expecting %s got %s" % (ans, len(e['warnings'])))

    def testCheckGridEventDates(self):
        """Tests gcc.check_grid_event_dates(draft=None)."""
        e = gcc.check_grid_event_dates(draft=None)
        num_events = len(DesignerEvent.objects.filter(draft=None))
        self.assertEqual(2 * num_events, len(e), "Expecting %s got %s" % (2 * num_events, len(e)))

    # Very slow
#     def testLibraryUrls(self):
#         """Tests gcc.check_library_urls()."""
#         e = gcc.check_library_urls()
#         self.assertEqual(26, len(e), "Expecting %s got %s" % (26, len(e)))

    # Very slow
#     def testDesignerUrls(self):
#         """Tests gcc.check_designer_urls(draft=None)."""
#         e = gcc.check_designer_urls(draft=None)
#         self.assertEqual(12, len(e), "Expecting %s got %s" % (12, len(e)))

    def testLibraryUnlockDates(self):
        """Tests gcc.check_library_unlock_dates()."""
        d = gcc.check_library_unlock_dates()
        self.assertEqual(len(d['errors']), 0, "Expected 0 got %s" % len(d['errors']))
        self.assertEqual(len(d['warnings']), 0, "Expected 0 got %s" % len(d['warnings']))

    def testDesignerUnlockDates(self):
        """Tests gcc.check_designer_unlock_dates()."""
        d = gcc.check_designer_unlock_dates(draft=None)
        self.assertEqual(len(d['errors']), 1, "Expected 1 got %s" % len(d['errors']))
        self.assertEqual(len(d['warnings']), 1, "Expected 1 got %s" % len(d['warnings']))

    # Very slow
#     def testFullLibrary(self):
#         """Tests gcc.full_library_check()"""
#         d = gcc.full_library_check()
#         self.assertEqual(len(d['warnings']), 182, "Expected 182 got %s" % len(d['warnings']))
#         self.assertEqual(len(d['errors']), 0, "Expected 0 got %s" % len(d['errors']))

    def testQuickLibrary(self):
        """Tests gcc.quick_library_check()"""
        d = gcc.quick_library_check()
        self.assertEqual(len(d['warnings']), 114, "Expected 114 got %s" % len(d['warnings']))
        self.assertEqual(len(d['errors']), 0, "Expected 0 got %s" % len(d['errors']))

    def testLibraryErrors(self):
        """Tests gcc.library_errors()."""
        e = gcc.library_errors()
        self.assertEqual(len(e), 0, "Expecting 0 got %s" % len(e))

    # Very slow
#     def testFullDesigner(self):
#         """Tests gcc.full_designer_check()"""
#         d = gcc.full_designer_check(draft=None)
#         self.assertEqual(len(d['errors']), 79, "Expected 79 got %s" % len(d['errors']))
#         self.assertEqual(len(d['warnings']), 265, "Expected 265 got %s" % len(d['warnings']))

    def testQuickDesigner(self):
        """Tests gcc.quick_designer_check()"""
        d = gcc.quick_designer_check(draft=None)
        ans = 3
        value = len(d['warnings'])
        print d['warnings']
        self.assertEqual(value, ans, "Expected %s got %s" % (ans, value))
        ans = 41
        value = len(d['errors'])
        self.assertEqual(value, ans, "Expected %s got %s" % (ans, value))

    def testDesignerLevel(self):
        """Tests action_dependency.check_missmatched_designer_level()"""
        # move lighting video to level 4 so cfl is dependent on higher level
        warnings = action_dependency.check_missmatched_designer_level(draft=None)
        value = 2
        ans = len(warnings)
        print warnings
        self.assertEqual(ans, value, "Expecting %s missmatched level warnings got %s" % \
                         (value, ans))

    def testDesignerPredicates(self):
        """Tests gcc.check_designer_predicates(draft=None)."""
        errors = gcc.check_designer_predicates(draft=None)
        value = 0
        ans = len(errors)
        self.assertEqual(value, ans, "Expecting %s got %s" % (value, ans))

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


text:
require 'rails_helper'

feature 'User checks mailbox' do
  let!(:user) { FactoryBot.create(:user) }
  # This is a happy path feature spec; this covers the scenario
  # where a user logs onto the site and then accesses the mailbox URL
  scenario 'Logged in user checks mailbox by accessing the mailbox URL' do
    WebMock.allow_net_connect!
    visit new_user_session_path
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Log in'
    visit '/mailbox'
    expect(page).to have_content('Inbox')
    expect(page).to have_content('Sent')
    expect(page).to have_content('Trash')
    WebMock.disable_net_connect!
  end

  # This is a happy path feature spec; this covers the scenario
  # where an anoymous user tries to access the mailbox URL
  scenario 'Anonymous user tries to check mailbox by accessing the mailbox URL' do
    visit '/mailbox'
    expect(page).to have_content('You need to sign in or sign up before continuing.')
  end
end


text:
/**
* \file cube_error.h
* \brief Provides a hierarchy of errors compatible with C++ thwrow/catch mechanism
*/
#ifndef CUBE_ERROR_H
#define CUBE_ERROR_H

/*
 *----------------------------------------------------------------------------
 *
 * class Error
 *
 *----------------------------------------------------------------------------
 */

#include <string>
#include <iostream>
#include <exception>

namespace cube {

/**
* General error: gets a message.
*/
  class Error : public std::exception {

  public:

    Error(std::string message) : message(message) {}
    std::string get_msg() const { return "CUBE: " + message; }
    ~Error() throw() {}

  protected:

    std::string message;
  };
/**
* General error: gets a message.
*/
  class RuntimeError :  public Error {

  public:

    RuntimeError(std::string message) : Error(message) {}

  };
/**
* General error: gets a fatal message.
*/
  class FatalError : public Error {

  public:

    FatalError(std::string message) : Error(message) {}
    virtual std::string get_msg() const { return "CUBE Fatal: " + message; }
  };

   std::ostream& operator<< (std::ostream& out, Error& exception);		 ///< Prints out a message about an error.
   std::ostream& operator<< (std::ostream& out, RuntimeError& exception);	 ///< Prints out a message about a runtime error.
   std::ostream& operator<< (std::ostream& out, FatalError& exception);		 ///< Prints out a message about a fatal error.
}

#endif


text:
app.constant('applicationConfig', {relativeCurrencies: ['AUD', 'USD', 'NOK', 'CAD', 'THB'], currencyToRate: "EUR"});
// to add new relative currency push it relativeCurrencies array

app.factory('ratesFactory', function (openExchangeRates, currencyApi, ecbInt)
{
    var result = {};
    for (var i = 0; i < arguments.length; ++i) {
        result[arguments[i].getName()] = (arguments[i]);
    }
    return result;
});

app.controller('currencyController', function ($scope, ratesFactory, applicationConfig) {

    $scope.ratesSources = [];
    $scope.receivedData = {};

    for (var i = 0; i < applicationConfig.relativeCurrencies.length; i++) {
        $scope.receivedData[applicationConfig.relativeCurrencies[i]] = [];
    }

    for (var resource in ratesFactory) {
        $scope.ratesSources.push(ratesFactory[resource].getName()); //get resource name, it will displayed in table heading

        !function processRequestsResults(i) {
            ratesFactory[i].getRates().success(function (response) {
                var ratesObject = ratesFactory[i].processRates(response);
                for (var property in ratesObject) {
                //    $scope.receivedData[property].push(ratesObject[property]);
                    $scope.receivedData[property] [$scope.ratesSources.indexOf(ratesFactory[i].getName())]=ratesObject[property];
                }

            });
        }(resource)
    }

});

function RatesResource()
{
    this.getName=function(){return this.name};
}

function OpenExchangeRates($http, applicationConfig)
{
    RatesResource.call(this);
    this.name='openexchangerates.org';
    this.url="https://openexchangerates.org/api/latest.json?app_id=77538703bbf442e79c1632838b6a3aa9";

    this.getRates = function () {
        return $http.get(this.url);
    };
    this.processRates = function (data) { //handles received data and returns object {AUD:1.2..} with relative currencies name and values
        var result = {};
        var currencyToRate = data.rates[applicationConfig.currencyToRate];

        for (var i = 0; i < applicationConfig.relativeCurrencies.length; ++i) {

            var rate = (data.rates[applicationConfig.relativeCurrencies[i]] / currencyToRate);
            result[applicationConfig.relativeCurrencies[i]] = rate;
        }
        return result;
    }
};

function CurrencyApi($http, $q, applicationConfig) {
    RatesResource.call(this);
    this.name='appspot.com';
    this.getRates = function () {  //makes one $http.jsonp request for each relative currency
        var requestArray = [];
        for (var i = 0; i < applicationConfig.relativeCurrencies.length; i++) {
            requestArray.push($http.jsonp("http://currency-api.appspot.com/api/" + applicationConfig.currencyToRate + "/"
                + applicationConfig.relativeCurrencies[i] + ".jsonp?callback=JSON_CALLBACK&temp=" + (new Date().getTime())));
        }
        var promise = $q.all(requestArray);
        promise.success = function (fn) { //adding success funtion to promise object
            promise.then(function (response) {
                fn(response);
            });
            return promise;
        };
        return promise;
    };
    this.processRates = function (data) {
        var result = {};
        for (var i = 0; i < data.length; i++) {

            result[data[i].data.target] = data[i].data.rate;
        }
        return result;
    }

}

function EcbInt ($http, applicationConfig) {
    RatesResource.call(this);
    this.name="ecb.int";
    this.url="http://nazarmsx-001-site1.hostbuddy.com/index.php";   //proxy script

    this.getRates = function () {
        return $http.get(this.url);
    };
    this.processRates = function (data) {
        var result = {};
        for (var i = 0; i < applicationConfig.relativeCurrencies.length; ++i) {

            result[applicationConfig.relativeCurrencies[i]] = data[applicationConfig.relativeCurrencies[i]];
        }
        return result;
    }
}

//registering of services
app.service('openExchangeRates', OpenExchangeRates);
app.service('currencyApi', CurrencyApi);
app.service('ecbInt',EcbInt);


text:
class IRCCommandHandler {
public:
  IRCCommandHandler();
  std::string operator()(std::string expression);
  std::string validateRequest(std::string dest,
                              std::string sender,
                              std::string expression);
private:
  std::string expression;
  std::string command;
  std::vector<std::string> arguments;
  // Containers
  std::map<std::string, User> users; // channel users should be references here
  std::map<std::string, Channel> channels;
  // For parsing
  void parse();
  // For functionality
  std::string message();
  std::string connect();
  std::string disconnect();
  std::string createChannel();
  std::string getChannels();
  std::string joinChannel();
  std::string changeName();
  std::string ping();
};

#endif