text:
import * as React from 'react'
import * as Styles from '../../../styles'
import * as Kb from '../../../common-adapters'
import * as RowTypes from './types'
import type * as Types from '../../../constants/types/fs'
import Placeholder from './placeholder'
import TlfType from './tlf-type-container'
import Tlf from './tlf-container'
import Still from './still-container'
import Editing from './editing'
import {normalRowHeight} from './common'
import {memoize} from '../../../util/memoize'
import {useFsChildren, UploadButton} from '../../common'

export type Props = {
  emptyMode: 'empty' | 'not-empty-but-no-match' | 'not-empty'
  destinationPickerIndex?: number
  items: Array<RowTypes.RowItem>
  path: Types.Path
}

export const WrapRow = ({children}: {children: React.ReactNode}) => (
  <Kb.Box style={styles.rowContainer}>
    {children}
    <Kb.Divider key="divider" style={styles.divider} />
  </Kb.Box>
)

export const EmptyRow = () => <Kb.Box style={styles.rowContainer} />

class Rows extends React.PureComponent<Props> {
  _rowRenderer = (_: number, item: RowTypes.RowItem) => {
    switch (item.rowType) {
      case RowTypes.RowType.Placeholder:
        return (
          <WrapRow>
            <Placeholder type={item.type} />
          </WrapRow>
        )
      case RowTypes.RowType.TlfType:
        return (
          <WrapRow>
            <TlfType name={item.name} destinationPickerIndex={this.props.destinationPickerIndex} />
          </WrapRow>
        )
      case RowTypes.RowType.Tlf:
        return (
          <WrapRow>
            <Tlf
              disabled={item.disabled}
              name={item.name}
              tlfType={item.tlfType}
              destinationPickerIndex={this.props.destinationPickerIndex}
            />
          </WrapRow>
        )
      case RowTypes.RowType.Still:
        return (
          <WrapRow>
            {item.editID ? (
              <Editing editID={item.editID} />
            ) : (
              <Still path={item.path} destinationPickerIndex={this.props.destinationPickerIndex} />
            )}
          </WrapRow>
        )
      case RowTypes.RowType.NewFolder:
        return (
          <WrapRow>
            <Editing editID={item.editID} />
          </WrapRow>
        )
      case RowTypes.RowType.Empty:
        return <EmptyRow />
      case RowTypes.RowType.Header:
        return item.node
      default:
        return (
          <WrapRow>
            <Kb.Text type="BodySmallError">This should not happen.</Kb.Text>
          </WrapRow>
        )
    }
  }
  _getVariableRowLayout = (items: Array<RowTypes.RowItem>, index: number) => ({
    index,
    length: getRowHeight(items[index] || _unknownEmptyRowItem),
    offset: items.slice(0, index).reduce((offset, row) => offset + getRowHeight(row), 0),
  })
  _getTopVariableRowCountAndTotalHeight = memoize((items: Array<RowTypes.RowItem>) => {
    const index = items.findIndex(row => row.rowType !== RowTypes.RowType.Header)
    return index === -1
      ? {count: items.length, totalHeight: -1}
      : {count: index, totalHeight: this._getVariableRowLayout(items, index).offset}
  })
  _getItemLayout = (index: number) => {
    const top = this._getTopVariableRowCountAndTotalHeight(this.props.items)
    if (index < top.count) {
      return this._getVariableRowLayout(this.props.items, index)
    }
    return {
      index,
      length: getRowHeight(this.props.items[index] || _unknownEmptyRowItem),
      offset: (index - top.count) * normalRowHeight + top.totalHeight,
    }
  }
  // List2 caches offsets. So have the key derive from layouts so that we
  // trigger a re-render when layout changes. Also encode items length into
  // this, otherwise we'd get taller-than content rows when going into a
  // smaller folder from a larger one.
  _getListKey = memoize((items: Array<RowTypes.RowItem>) => {
    const index = items.findIndex(row => row.rowType !== RowTypes.RowType.Header)
    return (
      items
        .slice(0, index === -1 ? items.length : index)
        .map(row => getRowHeight(row).toString())
        .join('-') + `:${items.length}`
    )
  })

  render() {
    return this.props.emptyMode !== 'not-empty' ? (
      <Kb.Box2 direction="vertical" fullHeight={true} fullWidth={true}>
        {
          // The folder is empty so these should all be header rows.
          this.props.items.map(item => item.rowType === RowTypes.RowType.Header && item.node)
        }
        <Kb.Box2 direction="vertical" style={styles.emptyContainer} centerChildren={true} gap="small">
          <Kb.Text type="BodySmall">
            {this.props.emptyMode === 'empty'
              ? 'This folder is empty.'
              : 'Sorry, no folder or file was found.'}
          </Kb.Text>
          {this.props.emptyMode === 'empty' && <UploadButton path={this.props.path} />}
        </Kb.Box2>
      </Kb.Box2>
    ) : (
      <Kb.BoxGrow>
        <Kb.List2
          key={this._getListKey(this.props.items)}
          items={this.props.items}
          bounces={true}
          itemHeight={{
            getItemLayout: this._getItemLayout,
            type: 'variable',
          }}
          renderItem={this._rowRenderer}
        />
      </Kb.BoxGrow>
    )
  }
}

const RowsWithAutoLoad = (props: Props) => {
  useFsChildren(props.path, /* recursive */ true) // need recursive for the EMPTY tag
  return <Rows {...props} />
}

const styles = Styles.styleSheetCreate(
  () =>
    ({
      divider: Styles.platformStyles({
        common: {
          backgroundColor: Styles.globalColors.black_05_on_white,
        },
        isElectron: {
          marginLeft: 94,
        },
        isMobile: {
          marginLeft: 102,
        },
      }),
      emptyContainer: {
        ...Styles.globalStyles.flexGrow,
      },
      rowContainer: {
        ...Styles.globalStyles.flexBoxColumn,
        flexShrink: 0,
        height: normalRowHeight,
      },
    } as const)
)

const getRowHeight = (row: RowTypes.RowItem) =>
  row.rowType === RowTypes.RowType.Header ? row.height : normalRowHeight

const _unknownEmptyRowItem: RowTypes.EmptyRowItem = {
  key: 'unknown-empty-row-item',
  rowType: RowTypes.RowType.Empty,
}

export default RowsWithAutoLoad


text:
Created with Pencil -- awesome opensource open-source GUI prototyping tool

http://pencil.evolus.vn/Default.html

redpajama_set_name: RedPajamaGithub


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme1" parent="android:Theme.Holo.Light.DarkActionBar"/>
    <!-- Customize your theme here. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:windowIsTranslucent">true</item>
    </style>
</resources>


text:
var fs = require('fs')
var tape = require('tape')
var fmt = require('..')

function input (name) {
  return fs.readFileSync('test/fixtures/' + name + '.css', 'utf-8')
}

function output (name) {
  return fs.readFileSync('test/fixtures/' + name + '.out.css', 'utf-8')
}

function test (name, description) {
  description = description || name
  return tape(description, function (t) {
    t.equal(fmt.process(input(name)), output(name))
    t.end()
  })
}

test('readme')
test('nested')
test('nested-2')
test('important')
test('values')
test('comment')
test('comment-in-rules')
test('vendor-prefix')
test('nested-atrule')
test('font-face')

test('sass-mixin')
test('sass-extend')
test('sass-variables')
test('sass-include')
test('inline-comment')
test('sass-function')
test('scss')


text:
package com.opengamma.analytics.financial.model.volatility.smile.function;

import java.util.Arrays;

import org.apache.commons.lang.Validate;

/**
 *
 */
public class SVIFormulaData implements SmileModelData {
  private static final int NUM_PARAMETERS = 5;
  private final double[] _parameters;

  public SVIFormulaData(final double[] parameters) {
    Validate.notNull(parameters, "parameters are null");
    Validate.isTrue(parameters.length == NUM_PARAMETERS, "must be " + NUM_PARAMETERS + " parameters");
    Validate.isTrue(parameters[0] >= 0, "Need a >= 0");
    Validate.isTrue(parameters[1] >= 0, "Need b >= 0");
    Validate.isTrue(parameters[2] >= -1 && parameters[2] <= 1, "Need -1 <= rho <= 1");
    Validate.isTrue(parameters[3] >= 0, "Need nu >= 0");

    _parameters = parameters;
  }

  public SVIFormulaData(final double a, final double b, final double rho, final double nu, final double m) {
    this(new double[] {a, b, rho, nu, m });
  }

  @Override
  public boolean isAllowed(int index, double value) {
    switch (index) {
      case 0:
        return value >= 0;
      case 1:
        return value >= 0;
      case 2:
        return value >= -1 && value <= 1;
      case 3:
        return value >= 0.0;
      case 4:
        return true;
      default:
        throw new IllegalArgumentException("index " + index + " outside range");
    }
  }

  public double getA() {
    return _parameters[0];
  }

  public double getB() {
    return _parameters[1];
  }

  public double getRho() {
    return _parameters[2];
  }

  public double getNu() {
    return _parameters[3];
  }

  public double getM() {
    return _parameters[4];
  }

  @Override
  public int getNumberOfparameters() {
    return NUM_PARAMETERS;
  }

  @Override
  public double getParameter(int index) {
    return _parameters[index];
  }

  @Override
  public SmileModelData with(int index, double value) {
    double[] temp = new double[NUM_PARAMETERS];
    System.arraycopy(_parameters, 0, temp, 0, NUM_PARAMETERS);
    temp[index] = value;
    return new SVIFormulaData(temp);
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + Arrays.hashCode(_parameters);
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    SVIFormulaData other = (SVIFormulaData) obj;
    if (!Arrays.equals(_parameters, other._parameters)) {
      return false;
    }
    return true;
  }

  @Override
  public String toString() {
    return "SVIFormulaData [a=" + getA() + ", b=" + getB() + ", rho=" + getRho() + ", nu=" + getNu() + ", m=" + getM() + "]";
  }

}


text:
package com.amazonaws.services.glue.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.glue.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * WorkflowRun JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class WorkflowRunJsonUnmarshaller implements Unmarshaller<WorkflowRun, JsonUnmarshallerContext> {

    public WorkflowRun unmarshall(JsonUnmarshallerContext context) throws Exception {
        WorkflowRun workflowRun = new WorkflowRun();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Name", targetDepth)) {
                    context.nextToken();
                    workflowRun.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("WorkflowRunId", targetDepth)) {
                    context.nextToken();
                    workflowRun.setWorkflowRunId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("PreviousRunId", targetDepth)) {
                    context.nextToken();
                    workflowRun.setPreviousRunId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("WorkflowRunProperties", targetDepth)) {
                    context.nextToken();
                    workflowRun.setWorkflowRunProperties(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
                if (context.testExpression("StartedOn", targetDepth)) {
                    context.nextToken();
                    workflowRun.setStartedOn(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("CompletedOn", targetDepth)) {
                    context.nextToken();
                    workflowRun.setCompletedOn(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("Status", targetDepth)) {
                    context.nextToken();
                    workflowRun.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ErrorMessage", targetDepth)) {
                    context.nextToken();
                    workflowRun.setErrorMessage(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Statistics", targetDepth)) {
                    context.nextToken();
                    workflowRun.setStatistics(WorkflowRunStatisticsJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("Graph", targetDepth)) {
                    context.nextToken();
                    workflowRun.setGraph(WorkflowGraphJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("StartingEventBatchCondition", targetDepth)) {
                    context.nextToken();
                    workflowRun.setStartingEventBatchCondition(StartingEventBatchConditionJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return workflowRun;
    }

    private static WorkflowRunJsonUnmarshaller instance;

    public static WorkflowRunJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new WorkflowRunJsonUnmarshaller();
        return instance;
    }
}


text:
yusukezzz\Routing - Simple and fast request routing for PHP
=======================================
[![Build Status](https://travis-ci.org/yusukezzz/routing.svg?branch=master)](https://travis-ci.org/yusukezzz/routing)

This library forked from [nikic/FastRoute](https://github.com/nikic/FastRoute).

Very thanks to nikic and other contributors of FastRoute.

Install
-------

Require this package in your composer.json

```
"yusukezzz/routing": "dev-master"
```

Usage
-----

```php
<?php
require_once __DIR__ . '/path/to/vendor/autoload.php';

$router = new \yusukezzz\Routing\Router();

$router->get('/', function()
{
    return 'Hello world.';
});

$router->get('/user/:name', function($name)
{
    return "Hello {$name}";
});

echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
```

run in PHP builtin server

```
php -S localhost:8080 router.php
```

Reverse routing

```php
// set third parameter to define named route
$router->get('/hoge/:piyo', function($piyo){}, 'a_named_route');
echo $router->urlFor('a_named_route', ['piyo' => 'abc']);
// output is '/hoge/abc'
```

If you want to use Controller like routing, you should implement RouteHandlerInterface.

```php
<?php
require_once __DIR__ . '/../vendor/autoload.php';

class PhotoController
{
    public function index()
    {
        return 'photo list';
    }

    public function show($id)
    {
        return "show photo id {$id}";
    }
}

class Handler implements \yusukezzz\Routing\RouteHandlerInterface
{
    /**
     * @param \yusukezzz\Routing\Route $route
     * @return mixed
     */
    public function handleRoute(\yusukezzz\Routing\Route $route)
    {
        list($controller, $method) = explode('@', $route->getHandler());
        $handler = [new $controller, $method];

        return call_user_func_array($handler, $route->getVariables());
    }
}

$handler = new \Handler();
$router = new \yusukezzz\Routing\Router($handler);

$router->get('/photo', 'PhotoController@index');
$router->get('/photo/:id', 'PhotoController@show');

echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
```


text:
<?php

namespace Magento\Framework\Filesystem\File;

interface ReadInterface
{
    /**
     * Reads the specified number of bytes from the current position.
     *
     * @param int $length The number of bytes to read
     * @return string
     */
    public function read($length);

    /**
     * Reads the line with specified number of bytes from the current position.
     *
     * @param int $length The number of bytes to read
     * @param string $ending [optional]
     * @return string
     */
    public function readLine($length, $ending = null);

    /**
     * Reads one CSV row from the file
     *
     * @param int $length [optional] <p>
     * @param string $delimiter [optional]
     * @param string $enclosure [optional]
     * @param string $escape [optional]
     * @return array|bool false on end of file
     */
    public function readCsv($length = 0, $delimiter = ',', $enclosure = '"', $escape = '\\');

    /**
     * Returns the current position
     *
     * @return int
     */
    public function tell();

    /**
     * Seeks to the specified offset
     *
     * @param int $length
     * @param int $whence
     * @return int
     */
    public function seek($length, $whence = SEEK_SET);

    /**
     * Checks if the current position is the end-of-file
     *
     * @return bool
     */
    public function eof();

    /**
     * Closes the file.
     *
     * @return bool
     */
    public function close();

    /**
     * Get file properties.
     *
     * @return array
     */
    public function stat();
}


text:
<?php

/**
 * Norwegian Bokmål PHPMailer language file: refer to English translation for definitive list
 * @package PHPMailer
 */

$PHPMAILER_LANG['authenticate']         = 'SMTP Feil: Kunne ikke autentisere.';
$PHPMAILER_LANG['connect_host']         = 'SMTP Feil: Kunne ikke koble til SMTP tjener.';
$PHPMAILER_LANG['data_not_accepted']    = 'SMTP Feil: Datainnhold ikke akseptert.';
$PHPMAILER_LANG['empty_message']        = 'Meldingsinnhold mangler';
$PHPMAILER_LANG['encoding']             = 'Ukjent koding: ';
$PHPMAILER_LANG['execute']              = 'Kunne ikke utføre: ';
$PHPMAILER_LANG['file_access']          = 'Får ikke tilgang til filen: ';
$PHPMAILER_LANG['file_open']            = 'Fil Feil: Kunne ikke åpne filen: ';
$PHPMAILER_LANG['from_failed']          = 'Følgende Frå adresse feilet: ';
$PHPMAILER_LANG['instantiate']          = 'Kunne ikke initialisere post funksjon.';
$PHPMAILER_LANG['invalid_address']      = 'Ugyldig adresse: ';
$PHPMAILER_LANG['mailer_not_supported'] = ' sender er ikke støttet.';
$PHPMAILER_LANG['provide_address']      = 'Du må opppgi minst en mottakeradresse.';
$PHPMAILER_LANG['recipients_failed']    = 'SMTP Feil: Følgende mottakeradresse feilet: ';
$PHPMAILER_LANG['signing']              = 'Signering Feil: ';
$PHPMAILER_LANG['smtp_connect_failed']  = 'SMTP connect() feilet.';
$PHPMAILER_LANG['smtp_error']           = 'SMTP server feil: ';
$PHPMAILER_LANG['variable_set']         = 'Kan ikke skrive eller omskrive variabel: ';
$PHPMAILER_LANG['extension_missing']    = 'Utvidelse mangler: ';


text:
RxGo
====

Reactive Extensions implementation for the Go Programming Language


text:
package net.imagej.ops.features.tamura2d;

import net.imagej.ops.Ops;
import net.imagej.ops.special.chain.RTs;
import net.imagej.ops.special.function.UnaryFunctionOp;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.RealType;

import org.scijava.plugin.Plugin;

/**
 * Default implementation of tamura feature contrast.
 *
 * @author Andreas Graumann (University of Konstanz)
 */
@Plugin(type = Ops.Tamura.Contrast.class, label = "Tamura 2D: Contrast")
public class DefaultContrastFeature<I extends RealType<I>, O extends RealType<O>>
		extends AbstractTamuraFeature<I, O> implements Ops.Tamura.Contrast {

	private UnaryFunctionOp<RandomAccessibleInterval<I>, O> m4Op;
	private UnaryFunctionOp<RandomAccessibleInterval<I>, O> varOp;
	private UnaryFunctionOp<RandomAccessibleInterval<I>, O> stdOp;

	@Override
	public void initialize() {
		m4Op = RTs.function(ops(), Ops.Stats.Moment4AboutMean.class, in());
		varOp = RTs.function(ops(), Ops.Stats.Variance.class, in());
		stdOp = RTs.function(ops(), Ops.Stats.StdDev.class, in());
	}

	@Override
	public void compute(final RandomAccessibleInterval<I> input, final O output) {

		// Get fourth moment about mean
		double m4 = m4Op.calculate(input).getRealDouble();
		double var = varOp.calculate(input).getRealDouble();
		double std = stdOp.calculate(input).getRealDouble();

		double l4 = m4 / (var * var);

		// contrast
		double fCon = std / Math.pow(l4, 0.25);
		output.setReal(fCon);
	}

}


text:
function usage() {
    echo "Usage: $0 [start|stop|restart|startclean] [-r runner_count] [-s scheduler_count] [-w workflow_engine_count] [-g] [-x] [-c] [-6] [-m]" >&2
}

subcommand=$1; shift
runner_count=1
scheduler_count=1
workflow_engine_count=1
use_gunicorn=true
copy_test_packs=false
load_content=true
use_ipv6=false

while getopts ":r:s:w:gxcu6" o; do
    case "${o}" in
        r)
            runner_count=${OPTARG}
            ;;
        s)
            scheduler_count=${OPTARG}
            ;;
        w)
            workflow_engine_count=${OPTARG}
            ;;
        g)
            use_gunicorn=false
            ;;
        x)
            copy_test_packs=true
            ;;
        c)
            load_content=false
            ;;
        6)
            use_ipv6=true
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            usage
            exit 2
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            usage
            exit 2
            ;;
    esac
done

function init(){
    ST2_BASE_DIR="/opt/stackstorm"
    COMMAND_PATH=${0%/*}
    CURRENT_DIR=`pwd`
    CURRENT_USER=`whoami`
    CURRENT_USER_GROUP=`id -gn`
    echo "Current user:group = ${CURRENT_USER}:${CURRENT_USER_GROUP}"

    if [[ (${COMMAND_PATH} == /*) ]] ;
    then
        ST2_REPO=${COMMAND_PATH}/..
    else
        ST2_REPO=${CURRENT_DIR}/${COMMAND_PATH}/..
    fi

    VIRTUALENV=${VIRTUALENV_DIR:-${ST2_REPO}/virtualenv}
    VIRTUALENV=$(readlink -f ${VIRTUALENV})
    PY=${VIRTUALENV}/bin/python
    PYTHON_VERSION=$(${PY} --version 2>&1)

    echo "Using virtualenv: ${VIRTUALENV}"
    echo "Using python: ${PY} (${PYTHON_VERSION})"

    if [ -z "$ST2_CONF" ]; then
        ST2_CONF=${ST2_REPO}/conf/st2.dev.conf
    fi

    ST2_CONF=$(readlink -f ${ST2_CONF})
    echo "Using st2 config file: $ST2_CONF"

    if [ ! -f "$ST2_CONF" ]; then
        echo "Config file $ST2_CONF does not exist."
        exit 1
    fi

}

function exportsdir(){
    local EXPORTS_DIR=$(grep 'dump_dir' ${ST2_CONF} | sed -e "s~^dump_dir[ ]*=[ ]*\(.*\)~\1~g")
    if [ -z $EXPORTS_DIR ]; then
        EXPORTS_DIR="/opt/stackstorm/exports"
    fi
    echo "$EXPORTS_DIR"
}

function st2start(){
    echo "Starting all st2 servers..."

    # Determine where the st2 repo is located. Some assumption is made here
    # that this script is located under st2/tools.

    # Change working directory to the root of the repo.
    echo "Changing working directory to ${ST2_REPO}"
    cd ${ST2_REPO}

    BASE_DIR=$(grep 'base_path' ${ST2_CONF} \
        | awk 'BEGIN {FS=" = "}; {print $2}')
    if [ -z BASE_DIR ]; then
        BASE_DIR="/opt/stackstorm"
    fi
    CONFIG_BASE_DIR="${BASE_DIR}/configs"
    echo "Using config base dir: $CONFIG_BASE_DIR"

    if [ ! -d "$CONFIG_BASE_DIR" ]; then
        echo "$CONFIG_BASE_DIR doesn't exist. Creating..."
        sudo mkdir -p $CONFIG_BASE_DIR
    fi

    PACKS_BASE_DIR=$(grep 'packs_base_path' ${ST2_CONF} \
        | awk 'BEGIN {FS=" = "}; {print $2}')
    if [ -z $PACKS_BASE_DIR ]; then
        PACKS_BASE_DIR="/opt/stackstorm/packs"
    fi
    echo "Using content packs base dir: $PACKS_BASE_DIR"

    # Copy and overwrite the action contents
    if [ ! -d "$ST2_BASE_DIR" ]; then
        echo "$ST2_BASE_DIR doesn't exist. Creating..."
        sudo mkdir -p $PACKS_BASE_DIR
    fi

    if [ "${use_ipv6}" = true ]; then
        echo '  using IPv6 bindings...'
        BINDING_ADDRESS="[::]"
    else
        BINDING_ADDRESS="0.0.0.0"
    fi

    VIRTUALENVS_DIR=$ST2_BASE_DIR/virtualenvs

    sudo mkdir -p $PACKS_BASE_DIR/default/sensors/
    sudo mkdir -p $PACKS_BASE_DIR/default/actions/
    sudo mkdir -p $PACKS_BASE_DIR/default/rules/
    sudo mkdir -p $VIRTUALENVS_DIR
    sudo chown -R ${CURRENT_USER}:${CURRENT_USER_GROUP} $PACKS_BASE_DIR
    sudo chown -R ${CURRENT_USER}:${CURRENT_USER_GROUP} $VIRTUALENVS_DIR
    sudo chown -R ${CURRENT_USER}:${CURRENT_USER_GROUP} $CONFIG_BASE_DIR
    cp -Rp ./contrib/core/ $PACKS_BASE_DIR
    cp -Rp ./contrib/packs/ $PACKS_BASE_DIR

    if [ "$copy_test_packs" = true ]; then
        echo "Copying test packs examples and fixtures to $PACKS_BASE_DIR"
        cp -Rp ./contrib/examples $PACKS_BASE_DIR
        # Clone st2tests in /tmp directory.
        pushd /tmp
        echo Cloning https://github.com/StackStorm/st2tests.git
        # -q = no progress reporting (better for CI). Errors will still print.
        git clone -q https://github.com/StackStorm/st2tests.git
        ret=$?
        if [ ${ret} -eq 0 ]; then
            cp -Rp ./st2tests/packs/fixtures $PACKS_BASE_DIR
            rm -R st2tests/
        else
            echo "Failed to clone st2tests repo"
        fi
        popd
    fi

    # activate virtualenv to set PYTHONPATH
    source ${VIRTUALENV}/bin/activate

    # Kill existing st2 screens
    screen -wipe
    screen -ls | grep st2 &> /dev/null
    if [ $? == 0 ]; then
        echo 'Killing existing st2 screen sessions...'
        screen -ls | grep st2 | cut -d. -f1 | awk '{print $1}' | xargs kill
    fi

    # NOTE: We can't rely on latest version of screen with "-Logfile path"
    # option so we need to use screen config file per screen window

    # Run the st2 API server
    echo 'Starting screen session st2-api...'
    if [ "${use_gunicorn}" = true ]; then
        echo '  using gunicorn to run st2-api...'
        export ST2_CONFIG_PATH=${ST2_CONF}
        screen -L -c tools/screen-configs/st2api.conf -d -m -S st2-api ${VIRTUALENV}/bin/gunicorn \
            st2api.wsgi:application -k eventlet -b "$BINDING_ADDRESS:9101" --workers 1
    else
        screen -L -c tools/screen-configs/st2api.conf -d -m -S st2-api ${VIRTUALENV}/bin/python \
            ./st2api/bin/st2api \
            --config-file $ST2_CONF
    fi

    # Run st2stream API server
    if [ "${use_gunicorn}" = true ]; then
        echo '  using gunicorn to run st2-stream'
        export ST2_CONFIG_PATH=${ST2_CONF}
        screen -L -c tools/screen-configs/st2stream.conf -d -m -S st2-stream ${VIRTUALENV}/bin/gunicorn \
            st2stream.wsgi:application -k eventlet -b "$BINDING_ADDRESS:9102" --workers 1
    else
        screen -L -c tools/screen-configs/st2stream.conf -d -m -S st2-stream ${VIRTUALENV}/bin/python \
            ./st2stream/bin/st2stream \
            --config-file $ST2_CONF
    fi

    # Run the workflow engine server
    echo 'Starting screen session st2-workflow(s)'
    WORKFLOW_ENGINE_SCREENS=()
    for i in $(seq 1 $workflow_engine_count)
    do
        WORKFLOW_ENGINE_NAME=st2-workflow-$i
        WORKFLOW_ENGINE_SCREENS+=($WORKFLOW_ENGINE_NAME)
        echo '  starting '$WORKFLOW_ENGINE_NAME'...'
        screen -L -c tools/screen-configs/st2workflowengine.conf -d -m -S $WORKFLOW_ENGINE_NAME ${VIRTUALENV}/bin/python \
            ./st2actions/bin/st2workflowengine \
            --config-file $ST2_CONF
    done

    # Start a screen for every runner
    echo 'Starting screen sessions for st2-actionrunner(s)'
    RUNNER_SCREENS=()
    for i in $(seq 1 $runner_count)
    do
        RUNNER_NAME=st2-actionrunner-$i
        RUNNER_SCREENS+=($RUNNER_NAME)
        echo '  starting '$RUNNER_NAME'...'
        screen -L -c tools/screen-configs/st2actionrunner.conf -d -m -S $RUNNER_NAME ${VIRTUALENV}/bin/python \
            ./st2actions/bin/st2actionrunner \
            --config-file $ST2_CONF
    done

    # Run the garbage collector service
    echo 'Starting screen session st2-garbagecollector'
    screen -L -c tools/screen-configs/st2garbagecollector.conf -d -m -S st2-garbagecollector ${VIRTUALENV}/bin/python \
        ./st2reactor/bin/st2garbagecollector \
        --config-file $ST2_CONF

    # Run the scheduler server
    echo 'Starting screen session st2-scheduler(s)'
    SCHEDULER_SCREENS=()
    for i in $(seq 1 $scheduler_count)
    do
        SCHEDULER_NAME=st2-scheduler-$i
        SCHEDULER_SCREENS+=($SCHEDULER_NAME)
        echo '  starting '$SCHEDULER_NAME'...'
        screen -L -c tools/screen-configs/st2scheduler.conf -d -m -S $SCHEDULER_NAME ${VIRTUALENV}/bin/python \
            ./st2actions/bin/st2scheduler \
            --config-file $ST2_CONF
    done

    # Run the sensor container server
    echo 'Starting screen session st2-sensorcontainer'
    screen -L -c tools/screen-configs/st2sensorcontainer.conf -d -m -S st2-sensorcontainer ${VIRTUALENV}/bin/python \
        ./st2reactor/bin/st2sensorcontainer \
        --config-file $ST2_CONF

    # Run the rules engine server
    echo 'Starting screen session st2-rulesengine...'
    screen -L -c tools/screen-configs/st2rulesengine.conf -d -m -S st2-rulesengine ${VIRTUALENV}/bin/python \
        ./st2reactor/bin/st2rulesengine \
        --config-file $ST2_CONF

    # Run the timer engine server
    echo 'Starting screen session st2-timersengine...'
    screen -L -c tools/screen-configs/st2timersengine.conf -d -m -S st2-timersengine ${VIRTUALENV}/bin/python \
        ./st2reactor/bin/st2timersengine \
        --config-file $ST2_CONF

    # Run the actions notifier
    echo 'Starting screen session st2-notifier...'
    screen -L -c tools/screen-configs/st2notifier.conf -d -m -S st2-notifier ${VIRTUALENV}/bin/python \
        ./st2actions/bin/st2notifier \
        --config-file $ST2_CONF

    # Run the auth API server
    echo 'Starting screen session st2-auth...'
    if [ "${use_gunicorn}" = true ]; then
        echo '  using gunicorn to run st2-auth...'
        export ST2_CONFIG_PATH=${ST2_CONF}
        screen -L -c tools/screen-configs/st2auth.conf -d -m -S st2-auth ${VIRTUALENV}/bin/gunicorn \
            st2auth.wsgi:application -k eventlet -b "$BINDING_ADDRESS:9100" --workers 1
    else
        screen -L -c tools/screen-configs/st2auth.conf -d -m -S st2-auth ${VIRTUALENV}/bin/python \
            ./st2auth/bin/st2auth \
            --config-file $ST2_CONF
    fi

    # Check whether screen sessions are started
    SCREENS=(
        "st2-api"
        "${WORKFLOW_ENGINE_SCREENS[@]}"
        "${SCHEDULER_SCREENS[@]}"
        "${RUNNER_SCREENS[@]}"
        "st2-sensorcontainer"
        "st2-rulesengine"
        "st2-notifier"
        "st2-auth"
        "st2-timersengine"
        "st2-garbagecollector"
    )

    echo
    for s in "${SCREENS[@]}"
    do
        screen -ls | grep "${s}[[:space:]]" &> /dev/null
        if [ $? != 0 ]; then
            echo "ERROR: Unable to start screen session for $s."
        fi
    done

    if [ "$load_content" = true ]; then
        # Register contents
        echo 'Registering sensors, runners, actions, rules, aliases, and policies...'
        ${VIRTUALENV}/bin/python \
            ./st2common/bin/st2-register-content \
            --config-file $ST2_CONF --register-all
    fi

    if [ "$copy_test_packs" = true ]; then
        st2 run packs.setup_virtualenv packs=fixtures
        if [ $? != 0 ]; then
            echo "Warning: Unable to setup virtualenv for the \"tests\" pack. Please setup virtualenv for the \"tests\" pack before running integration tests"
        fi
    fi

    # Print default creds to the screen
    echo "The default creds are testu:testp"

    # List screen sessions
    screen -ls || exit 0
}

function st2stop(){
    screen -ls | grep st2 &> /dev/null
    if [ $? == 0 ]; then
        echo 'Killing existing st2 screen sessions...'
        screen -ls | grep st2 | cut -d. -f1 | awk '{print $1}' | xargs -L 1 pkill -P
    fi

    if [ "${use_gunicorn}" = true ]; then
        pids=`ps -ef | grep "wsgi:application" | grep -v "grep" | awk '{print $2}'`
        if [ -n "$pids" ]; then
            echo "Killing gunicorn processes"
            # true ensures that any failure to kill a process which does not exist will not lead
            # to failure. for loop to ensure all processes are killed even if some are missing
            # assuming kill will fail-fast.
            for pid in ${pids}; do
                echo ${pid} | xargs -L 1 kill -9 || true
            done
        fi
    fi
}

function st2clean(){
    # clean mongo
    . ${VIRTUALENV}/bin/activate
    python ${ST2_REPO}/st2common/bin/st2-cleanup-db --config-file $ST2_CONF
    deactivate

    # start with clean logs
    LOGDIR=$(dirname $0)/../logs
    if [ -d ${LOGDIR} ]; then
        rm ${LOGDIR}/*
    fi
    if [ -n "$ST2_EXPORTER" ]; then
        EXPORTS_DIR=$(exportsdir)
        echo "Removing $EXPORTS_DIR..."
        rm -rf ${EXPORTS_DIR}
    fi

}

case ${subcommand} in
start)
    init
    st2start
    ;;
startclean)
    init
    st2clean
    st2start
    ;;
stop)
    st2stop
    ;;
restart)
    st2stop
    sleep 1
    init
    st2start
    ;;
*)
    usage
    ;;
esac


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Sponsor',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(blank=True, max_length=32, null=True, unique=True)),
                ('year', models.IntegerField(default=2016)),
                ('url', models.CharField(blank=True, max_length=256, null=True)),
                ('level', models.CharField(choices=[('a', 'Level A Sponsor'), ('b', 'Level B Sponsor'), ('c', 'Level C Sponsor'), ('c', 'Level D Sponsor')], default='c', max_length=2)),
                ('active', models.BooleanField(default=False)),
                ('created', models.DateTimeField(auto_now_add=True)),
            ],
            options={
                'db_table': 'sponsors',
            },
        ),
    ]


text:
package org.apache.accumulo.core.clientImpl;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;

/**
 * provides scanner functionality
 *
 * "Clients can iterate over multiple column families, and there are several mechanisms for limiting
 * the rows, columns, and timestamps traversed by a scan. For example, we could restrict [a] scan
 * ... to only produce anchors whose columns match [a] regular expression ..., or to only produce
 * anchors whose timestamps fall within ten days of the current time."
 *
 */
public class ScannerImpl extends ScannerOptions implements Scanner {

  // keep a list of columns over which to scan
  // keep track of the last thing read
  // hopefully, we can track all the state in the scanner on the client
  // and just query for the next highest row from the tablet server

  private final ClientContext context;
  private Authorizations authorizations;
  private TableId tableId;

  private int size;

  private Range range;
  private boolean isolated = false;
  private long readaheadThreshold = Constants.SCANNER_DEFAULT_READAHEAD_THRESHOLD;

  boolean closed = false;

  private static final int MAX_ENTRIES = 16;

  private long iterCount = 0;

  // Create an LRU map of iterators that tracks the MAX_ENTRIES most recently used iterators. An LRU
  // map is used to support the use case of a long lived scanner that constantly creates iterators
  // and does not read all of the data. For this case do not want iterator tracking to consume too
  // much memory. Also it would be best to avoid an RPC storm of close methods for thousands
  // sessions that may have timed out.
  private Map<ScannerIterator,Long> iters =
      new LinkedHashMap<ScannerIterator,Long>(MAX_ENTRIES + 1, .75F, true) {
        private static final long serialVersionUID = 1L;

        // This method is called just after a new entry has been added
        @Override
        public boolean removeEldestEntry(Map.Entry<ScannerIterator,Long> eldest) {
          return size() > MAX_ENTRIES;
        }
      };

  /**
   * This is used for ScannerIterators to report their activity back to the scanner that created
   * them.
   */
  class Reporter {

    void readBatch(ScannerIterator iter) {
      synchronized (ScannerImpl.this) {
        // This iter just had some activity, so access it in map so it becomes the most recently
        // used.
        iters.get(iter);
      }
    }

    void finished(ScannerIterator iter) {
      synchronized (ScannerImpl.this) {
        iters.remove(iter);
      }
    }
  }

  private synchronized void ensureOpen() {
    if (closed)
      throw new IllegalArgumentException("Scanner is closed");
  }

  public ScannerImpl(ClientContext context, TableId tableId, Authorizations authorizations) {
    checkArgument(context != null, "context is null");
    checkArgument(tableId != null, "tableId is null");
    checkArgument(authorizations != null, "authorizations is null");
    this.context = context;
    this.tableId = tableId;
    this.range = new Range((Key) null, (Key) null);
    this.authorizations = authorizations;

    this.size = Constants.SCAN_BATCH_SIZE;
  }

  @Override
  public synchronized void setRange(Range range) {
    ensureOpen();
    checkArgument(range != null, "range is null");
    this.range = range;
  }

  @Override
  public synchronized Range getRange() {
    ensureOpen();
    return range;
  }

  @Override
  public synchronized void setBatchSize(int size) {
    ensureOpen();
    if (size > 0)
      this.size = size;
    else
      throw new IllegalArgumentException("size must be greater than zero");
  }

  @Override
  public synchronized int getBatchSize() {
    ensureOpen();
    return size;
  }

  @Override
  public synchronized Iterator<Entry<Key,Value>> iterator() {
    ensureOpen();
    ScannerIterator iter = new ScannerIterator(context, tableId, authorizations, range, size,
        getTimeout(TimeUnit.SECONDS), this, isolated, readaheadThreshold, new Reporter());

    iters.put(iter, iterCount++);

    return iter;
  }

  @Override
  public Authorizations getAuthorizations() {
    ensureOpen();
    return authorizations;
  }

  @Override
  public synchronized void enableIsolation() {
    ensureOpen();
    this.isolated = true;
  }

  @Override
  public synchronized void disableIsolation() {
    ensureOpen();
    this.isolated = false;
  }

  @Override
  public synchronized void setReadaheadThreshold(long batches) {
    ensureOpen();
    if (batches < 0) {
      throw new IllegalArgumentException(
          "Number of batches before read-ahead must be non-negative");
    }

    readaheadThreshold = batches;
  }

  @Override
  public synchronized long getReadaheadThreshold() {
    ensureOpen();
    return readaheadThreshold;
  }

  @Override
  public synchronized void close() {
    if (!closed) {
      iters.forEach((iter, v) -> iter.close());
      iters.clear();
    }

    closed = true;
  }
}


text:
#ifndef SERIAL_LCD_H
#define SERIAL_LCD_H

#include <inttypes.h>
#include <Arduino.h>
#include <SoftwareSerial.h>

//Initialization Commands or Responses

#define SLCD_INIT	0xA3
#define SLCD_INIT_ACK	0xA5
#define SLCD_INIT_DONE	0xAA

//WorkingMode Commands or Responses
#define SLCD_CONTROL_HEADER	0x9F
#define SLCD_CHAR_HEADER	0xFE
#define SLCD_CURSOR_HEADER	0xFF
#define SLCD_CURSOR_ACK		0x5A

#define SLCD_RETURN_HOME	0x61
#define SLCD_DISPLAY_OFF	0x63
#define SLCD_DISPLAY_ON		0x64
#define SLCD_CLEAR_DISPLAY	0x65
#define SLCD_CURSOR_OFF		0x66
#define SLCD_CURSOR_ON		0x67
#define SLCD_BLINK_OFF		0x68
#define SLCD_BLINK_ON		0x69
#define SLCD_SCROLL_LEFT	0x6C
#define SLCD_SCROLL_RIGHT	0x72
#define SLCD_NO_AUTO_SCROLL	0x6A
#define SLCD_AUTO_SCROLL	0x6D
#define SLCD_LEFT_TO_RIGHT	0x70
#define SLCD_RIGHT_TO_LEFT	0x71
#define SLCD_POWER_ON    	0x83
#define SLCD_POWER_OFF  	0x82
#define SLCD_INVALIDCOMMAND	0x46
#define SLCD_BACKLIGHT_ON	0x81
#define SLCD_BACKLIGHT_OFF	0x80

class SerialLCD : public SoftwareSerial{
public:

    SerialLCD(uint8_t, uint8_t);
    void begin();
    void clear();
    void home();

    void noDisplay();
    void display();
    void noBlink();
    void blink();
    void noCursor();
    void cursor();
    void scrollDisplayLeft();
    void scrollDisplayRight();
    void leftToRight();
    void rightToLeft();
    void autoscroll();
    void noAutoscroll();

    void setCursor(uint8_t, uint8_t);
    void noPower(void);
    void Power(void);
    void noBacklight(void);
    void backlight(void);
    void print(uint8_t b);
    void print(const char[]);
    void print(unsigned long n, uint8_t base);
	void print(float data,uint8_t num);
};

#endif


text:
/** 374. Guess Number Higher or Lower
We are playing the Guess Game. The game is as follows:

I pick a number from 1 to n. You have to guess which number I picked.

Every time you guess wrong, I'll tell you whether the number is higher or lower.

You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):

-1 : My number is lower
 1 : My number is higher
 0 : Congrats! You got it!

Example:

n = 10, I pick 6.

Return 6.

**/

#include <iostream>
#include "../utils.h"
using namespace std;

// Forward declaration of guess API.
// @param num, your guess
// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
int guess(int num);

class Solution {
public:
    int guessNumber(int n) {

    }
};

int main() {
    Solution s;
    return 0;
}


text:
<?php

namespace PDepend\Metrics\Analyzer;

use PDepend\Metrics\AbstractAnalyzer;
use PDepend\Source\AST\AbstractASTArtifact;
use PDepend\Source\AST\AbstractASTClassOrInterface;
use PDepend\Source\AST\ASTArtifactList;
use PDepend\Source\AST\ASTClass;
use PDepend\Source\AST\ASTInterface;
use PDepend\Source\AST\ASTMethod;
use PDepend\Source\AST\ASTNamespace;

/**
 * This visitor generates the metrics for the analyzed namespaces.
 *
 * @copyright 2008-2017 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 */
class ClassDependencyAnalyzer extends AbstractAnalyzer
{
    /**
     * Metrics provided by the analyzer implementation.
     */
    const M_AFFERENT_COUPLING          = 'ca',
          M_EFFERENT_COUPLING          = 'ce';

    /**
     * Hash with all calculated node metrics.
     *
     *
     * array(
     *     '0375e305-885a-4e91-8b5c-e25bda005438'  =>  array(
     *         'loc'    =>  42,
     *         'ncloc'  =>  17,
     *         'cc'     =>  12
     *     ),
     *     'e60c22f0-1a63-4c40-893e-ed3b35b84d0b'  =>  array(
     *         'loc'    =>  42,
     *         'ncloc'  =>  17,
     *         'cc'     =>  12
     *     )
     * )
     *
     *
     * @var array(string=>array)
     */
    private $nodeMetrics = null;

    protected $nodeSet = array();

    private $efferentNodes = array();

    private $afferentNodes = array();

    /**
     * All collected cycles for the input code.
     *
     *
     * array(
     *     <type-id> => array(
     *         \PDepend\Source\AST\AbstractASTClassOrInterface {},
     *         \PDepend\Source\AST\AbstractASTClassOrInterface {},
     *     ),
     *     <type-id> => array(
     *         \PDepend\Source\AST\AbstractASTClassOrInterface {},
     *         \PDepend\Source\AST\AbstractASTClassOrInterface {},
     *     ),
     * )
     *
     *
     * @var array(string=>array)
     */
    private $collectedCycles = array();

    /**
     * Processes all {@link \PDepend\Source\AST\ASTNamespace} code nodes.
     *
     * @param  \PDepend\Source\AST\ASTNamespace[] $namespaces
     * @return void
     */
    public function analyze($namespaces)
    {
        if ($this->nodeMetrics === null) {
            $this->fireStartAnalyzer();

            $this->nodeMetrics = array();

            foreach ($namespaces as $namespace) {
                $namespace->accept($this);
            }

            $this->postProcess();

            $this->fireEndAnalyzer();
        }
    }

    /**
     * Returns an array of all afferent nodes.
     *
     * @param  \PDepend\Source\AST\AbstractASTArtifact $node
     * @return \PDepend\Source\AST\AbstractASTArtifact[]
     */
    public function getAfferents(AbstractASTArtifact $node)
    {
        $afferents = array();
        if (isset($this->afferentNodes[$node->getId()])) {
            $afferents = $this->afferentNodes[$node->getId()];
        }
        return $afferents;
    }

    /**
     * Returns an array of all efferent nodes.
     *
     * @param  \PDepend\Source\AST\AbstractASTArtifact $node
     * @return \PDepend\Source\AST\AbstractASTArtifact[]
     */
    public function getEfferents(AbstractASTArtifact $node)
    {
        $efferents = array();
        if (isset($this->efferentNodes[$node->getId()])) {
            $efferents = $this->efferentNodes[$node->getId()];
        }
        return $efferents;
    }

    /**
     * Visits a method node.
     *
     * @param  \PDepend\Source\AST\ASTMethod $method
     * @return void
     */
    public function visitMethod(ASTMethod $method)
    {
        $this->fireStartMethod($method);

        $type = $method->getParent();
        foreach ($method->getDependencies() as $dependency) {
            $this->collectDependencies($type, $dependency);
        }

        $this->fireEndMethod($method);
    }

    /**
     * Visits a namespace node.
     *
     * @param  \PDepend\Source\AST\ASTNamespace $namespace
     * @return void
     */
    public function visitNamespace(ASTNamespace $namespace)
    {
        $this->fireStartNamespace($namespace);

        $this->nodeSet[$namespace->getId()] = $namespace;

        foreach ($namespace->getTypes() as $type) {
            $type->accept($this);
        }

        $this->fireEndNamespace($namespace);
    }

    /**
     * Visits a class node.
     *
     * @param  \PDepend\Source\AST\ASTClass $class
     * @return void
     */
    public function visitClass(ASTClass $class)
    {
        $this->fireStartClass($class);
        $this->visitType($class);
        $this->fireEndClass($class);
    }

    /**
     * Visits an interface node.
     *
     * @param  \PDepend\Source\AST\ASTInterface $interface
     * @return void
     */
    public function visitInterface(ASTInterface $interface)
    {
        $this->fireStartInterface($interface);
        $this->visitType($interface);
        $this->fireEndInterface($interface);
    }

    /**
     * Generic visit method for classes and interfaces. Both visit methods
     * delegate calls to this method.
     *
     * @param  \PDepend\Source\AST\AbstractASTClassOrInterface $type
     * @return void
     */
    protected function visitType(AbstractASTClassOrInterface $type)
    {
        $id = $type->getId();

        foreach ($type->getDependencies() as $dependency) {
            $this->collectDependencies($type, $dependency);
        }

        foreach ($type->getMethods() as $method) {
            $method->accept($this);
        }
    }

    /**
     * Collects the dependencies between the two given classes.
     *
     * @param \PDepend\Source\AST\AbstractASTClassOrInterface $typeB
     * @param \PDepend\Source\AST\AbstractASTClassOrInterface $typeB
     *
     * @return void
     */
    private function collectDependencies(AbstractASTClassOrInterface $typeA, AbstractASTClassOrInterface $typeB)
    {
        $idA = $typeA->getId();
        $idB = $typeB->getId();

        if ($idB === $idA) {
            return;
        }

        // Create a container for this dependency
        $this->initTypeMetric($typeA);
        $this->initTypeMetric($typeB);

        if (!in_array($idB, $this->nodeMetrics[$idA][self::M_EFFERENT_COUPLING])) {
            $this->nodeMetrics[$idA][self::M_EFFERENT_COUPLING][] = $idB;
            $this->nodeMetrics[$idB][self::M_AFFERENT_COUPLING][] = $idA;
        }
    }

    /**
     * Initializes the node metric record for the given $type.
     *
     * @param \PDepend\Source\AST\AbstractASTClassOrInterface $type
     * @return void
     */
    protected function initTypeMetric(AbstractASTClassOrInterface $type)
    {
        $id = $type->getId();

        if (!isset($this->nodeMetrics[$id])) {
            $this->nodeSet[$id] = $type;

            $this->nodeMetrics[$id] = array(
                self::M_AFFERENT_COUPLING =>  array(),
                self::M_EFFERENT_COUPLING =>  array(),
            );
        }
    }

    /**
     * Post processes all analyzed nodes.
     *
     * @return void
     */
    protected function postProcess()
    {
        foreach ($this->nodeMetrics as $id => $metrics) {
            $this->afferentNodes[$id] = array();
            foreach ($metrics[self::M_AFFERENT_COUPLING] as $caId) {
                $this->afferentNodes[$id][] = $this->nodeSet[$caId];
            }

            $this->efferentNodes[$id] = array();
            foreach ($metrics[self::M_EFFERENT_COUPLING] as $ceId) {
                $this->efferentNodes[$id][] = $this->nodeSet[$ceId];
            }

            $afferent = count($metrics[self::M_AFFERENT_COUPLING]);
            $efferent = count($metrics[self::M_EFFERENT_COUPLING]);

            $this->nodeMetrics[$id][self::M_AFFERENT_COUPLING] = $afferent;
            $this->nodeMetrics[$id][self::M_EFFERENT_COUPLING] = $efferent;
        }
    }

    /**
     * Collects a single cycle that is reachable by this namespace. All namespaces
     * that are part of the cylce are stored in the given $list array.
     *
     * @param  \PDepend\Source\AST\AbstractASTArtifact[] &$list
     * @param  \PDepend\Source\AST\AbstractASTArtifact   $namespace
     * @return boolean If this method detects a cycle the return value is true
     *                 otherwise this method will return false.
     */
    protected function collectCycle(array &$list, AbstractASTArtifact $node)
    {
        if (in_array($node, $list, true)) {
            $list[] = $node;
            return true;
        }

        $list[] = $node;

        foreach ($this->getEfferents($node) as $efferent) {
            if ($this->collectCycle($list, $efferent)) {
                return true;
            }
        }

        if (is_int($idx = array_search($node, $list, true))) {
            unset($list[$idx]);
        }
        return false;
    }
}


text:
class AliAnalysisTaskCmeEse : public AliAnalysisTaskSE {
    public:
        AliAnalysisTaskCmeEse();
        AliAnalysisTaskCmeEse(const char *name);

        virtual ~AliAnalysisTaskCmeEse();

        virtual void   UserCreateOutputObjects();
        virtual void   UserExec(Option_t *option);
        virtual void   Terminate(Option_t *);

        virtual void  SetVtxCut(Double_t vtxCut){fVtxCut = vtxCut;}
        virtual void  SetFilterbit(UInt_t filterbit){fFilterbit = filterbit;}
        virtual void  SetNoClus(Int_t noclus){fNoClus = noclus;}
        virtual void  SetEtaCut(Double_t etaCut){fEtaCut = etaCut;}
        virtual void  SetMinPt(Double_t minPt){fMinPt = minPt;}
        virtual void  SetMaxPt(Double_t maxPt){fMaxPt = maxPt;}
        virtual void  SetFlagLHC10h(Bool_t IsLHC10h){fLHC10h = IsLHC10h;}
        virtual void  SetFlagPileUp(Bool_t IsPileUP){fPileUp = IsPileUP;}
        virtual void  SetCentFlag(Short_t nCent){fCent = nCent;}
        virtual void  SetFlagRecEff(Bool_t IsRec){fRecEff = IsRec;}
        virtual void  SetFlagQAV0(Bool_t isQAV0){fQAV0 = isQAV0;}
        virtual void  SetFlagQATrk(Bool_t isTrkQA){fTrkQA = isTrkQA;}

    private:
        virtual Float_t GetVertex(AliAODEvent* aod) const;
        virtual void Analyze(AliAODEvent* aod, Float_t vtxZ);
        void OpenInfoCalbration(Int_t run);
        Short_t GetPercCode(Double_t perc) const;
        virtual Int_t GetTPCMult(AliVEvent* ev) const;
        virtual Int_t GetGlobalMult(AliVEvent* ev) const;
        Double_t GetWDist(const AliVVertex* v0, const AliVVertex* v1);
        Bool_t plpMV(const AliVEvent *event);

        AliAODEvent* fAOD;                //! AOD object

        Int_t        fRun;                // run number - for calibration
        TH1D*        fMultV0;             // profile from V0 multiplicity

        TH1D*        fQx2mV0A;            // <Qx2> V0A
        TH1D*        fQy2mV0A;            // <Qy2> V0A
        TH1D*        fQx2sV0A;            // sigma Qx2 V0A
        TH1D*        fQy2sV0A;            // sigma Qy2 V0A
        TH1D*        fQx2mV0C;            // <Qx2> V0C
        TH1D*        fQy2mV0C;            // <Qy2> V0C
        TH1D*        fQx2sV0C;            // sigma Qx2 V0C
        TH1D*        fQy2sV0C;            // sigma Qy2 V0C

        // Cuts and options
        TF1*         fFitRecLow;          // rec eff fit 1
        TF1*         fFitRecHigh;         // rec eff fit 2
        Bool_t       fRecEff;             // rec eff flag
        Double_t     fVtxCut;             // Vtx cut on z position in cm
        UInt_t       fFilterbit;          // filter bit
        Double_t     fEtaCut;             // Eta cut used to select particles
        Int_t        fNoClus;	          // No of TPC clusters
        Double_t     fMinPt;              // Min pt - for histogram limits
        Double_t     fMaxPt;              // Max pt - for histogram limits
        Bool_t       fLHC10h;             // flag to LHC10h data
        Bool_t       fPileUp;             // flag for pileup
        Short_t      fCent;               // centrality flag
        Bool_t       fQAV0;               // qa V0 flag
        Bool_t       fTrkQA;              // qa for tracks
        TSpline3*    fSplQ2c[90];         // splines for q2 V0C

        // Output objects
        TList*        fListOfObjects;     //! Output list of objects
        TH1I*         fVtx;               //! Event vertex info
        TH1F*         fVtxBeforeCuts;     //! Vertex z dist before cuts
        TH1F*         fVtxAfterCuts;      //! Vertex z dist after cuts
        TH2F*         fMultCorBeforeCuts; //! correlation between TPC and global track multiplicity before cuts
        TH2F*         fMultCorAfterCuts;  //! correlation between TPC and global track multiplicity after cuts

        TH2D*         fPercqc2;          //! percentile distribution

        THnSparseF*    fAllQA;               //! qa histo for tracks

        TH2D*         fQxavsV0Bef;          //! corrected Qx V0A cent
        TH2D*         fQyavsV0Bef;          //! corrected Qy V0A cent
        TH2D*         fQxcvsV0Bef;          //! corrected Qx V0C cent
        TH2D*         fQycvsV0Bef;          //! corrected Qx V0C cent

        TH2D*         fQxavsVtxZBef;          //! corrected Qx V0A vtx
        TH2D*         fQyavsVtxZBef;          //! corrected Qy V0A vtx
        TH2D*         fQxcvsVtxZBef;          //! corrected Qx V0C vtx
        TH2D*         fQycvsVtxZBef;          //! corrected Qx V0C vtx

        TH2D*         fQxavsV0Aft;          //! corrected Qx V0A cent
        TH2D*         fQyavsV0Aft;          //! corrected Qy V0A cent
        TH2D*         fQxcvsV0Aft;          //! corrected Qx V0C cent
        TH2D*         fQycvsV0Aft;          //! corrected Qx V0C cent

        TH2D*         fQxavsVtxZAft;          //! corrected Qx V0A vtx
        TH2D*         fQyavsVtxZAft;          //! corrected Qy V0A vtx
        TH2D*         fQxcvsVtxZAft;          //! corrected Qx V0C vtx
        TH2D*         fQycvsVtxZAft;          //! corrected Qx V0C vtx

        TProfile*     fV2A;              //! v2 V0A
        TProfile*     fV0AV0Cv2;         //! correlation V0A-V0C for resolution
        TProfile*     fV0ATPCv2;         //! correlation V0A-TPC for resolution
        TProfile*     fV0CTPCv2;         //! correlation V0C-TPC for resolution

        TProfile*     fCMESameQPos;  //! cme same charge pos
        TProfile*     fCMESameQNeg;  //! cme same charge neg
        TProfile*     fCMEOppQ;      //! cme opp charge

        TProfile*     fCMESameQPosCos;  //! cme same charge pos <cos*cos>
        TProfile*     fCMESameQPosSin;  //! cme same charge pos <sin*sin>
        TProfile*     fCMESameQPosv1;   //! cme same charge pos v1

        TProfile*     fCMESameQNegCos;  //! cme same charge neg <cos*cos>
        TProfile*     fCMESameQNegSin;  //! cme same charge neg <sin*sin>
        TProfile*     fCMESameQNegv1;   //! cme same charge neg v1

        TProfile*     fCMEOppQCos;  //! cme opp charge <cos*cos>
        TProfile*     fCMEOppQSin;  //! cme opp charge <sin*sin>
        TProfile*     fCMEOppQv1;   //! cme opp charge v1

        TProfile*     fV2Aqc2[10];        //! v2 V0A ESE
        TProfile*     fV0AV0Cv2qc2[10];   //! correlation V0A-V0C for resolution ESE
        TProfile*     fV0ATPCv2qc2[10];   //! correlation V0A-TPC for resolution ESE
        TProfile*     fV0CTPCv2qc2[10];   //! correlation V0C-TPC for resolution ESE

        TProfile*     fCMESameQPosqc2[10];  //! cme same charge pos ESE
        TProfile*     fCMESameQNegqc2[10];  //! cme same charge neg ESE
        TProfile*     fCMEOppQqc2[10];      //! cme opp charge ESE

        TProfile*     fCMESameQPosCosqc2[10];  //! cme same charge pos <cos*cos>
        TProfile*     fCMESameQPosSinqc2[10];  //! cme same charge pos <sin*sin>
        TProfile*     fCMESameQPosv1qc2[10];   //! cme same charge pos v1

        TProfile*     fCMESameQNegCosqc2[10];  //! cme same charge neg <cos*cos>
        TProfile*     fCMESameQNegSinqc2[10];  //! cme same charge neg <sin*sin>
        TProfile*     fCMESameQNegv1qc2[10];   //! cme same charge neg v1

        TProfile*     fCMEOppQCosqc2[10];  //! cme opp charge <cos*cos>
        TProfile*     fCMEOppQSinqc2[10];  //! cme opp charge <sin*sin>
        TProfile*     fCMEOppQv1qc2[10];   //! cme opp charge v1

        TProfile*     fV2Pt[9];              //! v2 pt unbiased

        TProfile*     fCMESameQPosEta[9];    //! cme same charge pos eta
        TProfile*     fCMESameQPosPtDif[9];  //! cme same charge pos pt dif
        TProfile*     fCMESameQPosPtSum[9];  //! cme same charge pos pt sum

        TProfile*     fCMESameQNegEta[9];    //! cme same charge neg eta
        TProfile*     fCMESameQNegPtDif[9];  //! cme same charge neg pt dif
        TProfile*     fCMESameQNegPtSum[9];  //! cme same charge neg pt sum

        TProfile*     fCMEOppQEta[9];        //! cme opp charge eta
        TProfile*     fCMEOppQPtDif[9];      //! cme opp charge pt dif
        TProfile*     fCMEOppQPtSum[9];      //! cme opp charge pt sum

        TH1D*         fPsiA[10];               //! Psi V0A
        TH1D*         fPsiC[10];               //! Psi V0C
        TH2D*         fPsiAvsPsiC[10];         //! correlation PsiA-PsiC

        TProfile*     fV2Ptqc2[9][10];            //! v2 pt ESE

        TProfile*     fCMESameQPosEtaqc2[9][10];  //! cme same charge pos ESE
        TProfile*     fCMESameQPosPtDifqc2[9][10];  //! cme same charge pos ESE
        TProfile*     fCMESameQPosPtSumqc2[9][10];  //! cme same charge pos ESE

        TProfile*     fCMESameQNegEtaqc2[9][10];  //! cme same charge neg ESE
        TProfile*     fCMESameQNegPtDifqc2[9][10];  //! cme same charge neg ESE
        TProfile*     fCMESameQNegPtSumqc2[9][10];  //! cme same charge neg ESE

        TProfile*     fCMEOppQEtaqc2[9][10];      //! cme opp charge ESE
        TProfile*     fCMEOppQPtDifqc2[9][10];      //! cme opp charge ESE
        TProfile*     fCMEOppQPtSumqc2[9][10];      //! cme opp charge ESE

        AliAnalysisTaskCmeEse(const AliAnalysisTaskCmeEse&);
        AliAnalysisTaskCmeEse& operator=(const AliAnalysisTaskCmeEse&);

        ClassDef(AliAnalysisTaskCmeEse, 1);
};

#endif


text:
package me.ci.sarica.games;

import me.ci.sarica.games.tier0.ColoredButtons.ColoredButtons;
import me.ci.sarica.terminal.Terminal;

/**
 * Created by thedudefromci on 10/9/17.
 *
 * This class handles loading and passing out games to various agents.
 */
public class GameManager
{
    private final GameEnvironment[][] games = {
        // Tier 0
        {
            new ColoredButtons()
        }
    };
    private int gamesPerTier = 10;
    private float scoreToPass = 0.8f;

    public GameManager(AgentSensorySettings settings)
    {
        Terminal.logVerbose("Game Manager", "Initialized game agent sensory settings.\n" + settings);
        for (int i = 0; i < games.length; i++)
            for (int j = 0; j < games[i].length; j++)
                games[i][j].initGameData(settings);
    }

    public GameEnvironment loadRandomGame(int tier)
    {
        return games[tier][(int)(Math.random() * games[tier].length)];
    }

    public int getTierCount()
    {
        return games.length;
    }

    public int getGameCountInTier(int tier)
    {
        return games[tier].length;
    }

    public float runLoop(GameEnvironment game, GamePlayingAgent agent)
    {
        game.loadGameData();

        while(!game.isGameComplete())
        {
            game.updateGameState();

            game.updatePixelData(agent.getPixelInputData());
            game.updateSoundData(agent.getSoundInputData());
            game.updateFeeling(agent.getFeelingInputData());
            game.updateTexture(agent.getTextureInputData());
            game.updateCommunicationReceived(agent.getCommunicationReceievedData());
            game.updateCommunicationSent(agent.getCommunicationSentData());

            agent.updateAgentState();
        }

        float score = game.getFinalScore();
        game.disposeGameData();

        return score;
    }

    public int getGamesPerTier()
    {
        return gamesPerTier;
    }

    public void setGamesPerTier(int gamesPerTier)
    {
        Terminal.logNormal("Game Manager", String.format("Adjusted games per tier to %d.", gamesPerTier));
        this.gamesPerTier = gamesPerTier;
    }

    public float getScoreToPass()
    {
        return scoreToPass;
    }

    public void setScoreToPass(float scoreToPass)
    {
        Terminal.logNormal("Game Manager", String.format("Adjusted score to pass to %f.", scoreToPass));
        this.scoreToPass = scoreToPass;
    }

    public float fullTestAgent(GamePlayingAgent agent)
    {
        Terminal.logNormal("Game Manager", String.format("Began full game tier test for agent %s.", agent.getUUID()));
        float fullScore = 0f;
        for (int i = 0; i < games.length; i++)
        {
            Terminal.logNormal("Game Manager", String.format("Starting tier %d.", i));
            float totalScore = 0f;
            for (int j = 0; j < gamesPerTier; j++)
            {
                GameEnvironment game = loadRandomGame(i);
                Terminal.logNormalf("Game Manager", "Starting game %d/$d, %s.", j+1, gamesPerTier, game.getName());
                float s = runLoop(loadRandomGame(i), agent);

                Terminal.logNormalf("Game Manager", "Completed game with a final score of %.02f.", s);
                totalScore += s;
                fullScore += s;

                Terminal.logVerbosef("Game Manager", "Current passing score: %.02f. (Required: %.02f)",
                    totalScore / (j + 1), scoreToPass);
                Terminal.logVerbosef("Game Manager", "Current full score: %.02f.", fullScore);
            }
            totalScore /= gamesPerTier;

            if (totalScore < scoreToPass)
            {
                Terminal.logVerbose("Game Manager", "Agent has failed to meet minimum tier requirements.");
                break;
            }
            Terminal.logNormal("Game Manager", "Agent has passed mimimum tire requirements. Advancing to next tier" +
                                                    ".");
        }

        Terminal.logNormal("Game Manager", "All tiers completed.");
        return fullScore;
    }
}


text:
//{{{header files
#include "nmi.h"
//}}}

//{{{void show_help_short()
void show_help_short(char **argv)
{
	cout<<"Calculate normalized mutual information between two configurations"<<endl;
	cout<<"Usage: "<<argv[0]<<" file1 file2"<<endl;
	exit(0);
}
//}}}

//{{{ int main(int argc, char** argv)
int main(int argc, char** argv)
{
	//read the first argument to set the function.
	if(argc < 3) show_help_short(argv);
	long t_begin=get_cpu_time();
	int randseed=int(time(NULL));
	ZRANDOMv3 rg(randseed);
	int nsample=10;
	if(argc>=4) nsample=atoi(argv[3]);
//	cout<<"nsample="<<nsample<<endl;

	ifstream fa(argv[1]);
	ifstream fb(argv[2]);
	assert(fa.good()&&fb.good()&&"I can not open the file that contains the partition.");

	vector <string> pas;//partition a in string
	vector <string> pbs;//partition b in string
	string tmpstr;
	while(fa >> tmpstr) pas.push_back(tmpstr);
	while(fb >> tmpstr) pbs.push_back(tmpstr);
	assert(pas.size() == pbs.size() && "Two partitions have different number of nodes !");

	vector <int> pa;//partition a in number
	vector <int> pb;//partition b in number
	int qa=ps2p(pas,pa);
	int qb=ps2p(pbs,pb);

	double the_nmi=0;
	bool agtb=true; //qa is greater than qb
	if(qa<qb) agtb=false;
	if(agtb) the_nmi=compute_nmi(pa,pb);
	else the_nmi=compute_nmi(pb,pa);
//	cout<<"NMI="<<the_nmi<<endl;
	double tot_nmi=0;
	for(int sample=0;sample<nsample;sample++){
		double nmi=0;
		if(agtb){
			shuffle_seq(pb,rg);
			nmi=compute_nmi(pa,pb);
		}else{
			shuffle_seq(pa,rg);
			nmi=compute_nmi(pb,pa);
		}
//		cout<<nmi<<" "<<flush;
		tot_nmi += nmi;
	}
//	cout<<endl;
	tot_nmi /= nsample;
	cout<<the_nmi-tot_nmi<<endl;
//	cout<<"RNMI="<<the_nmi-tot_nmi<<endl;
//	cout<<"time used: "<<(get_cpu_time()-t_begin)/1000.0<<" seconds."<<endl;
}
//}}}


text:
<?php

class Admin_Controller extends MY_Controller{
  function __construct(){
    parent::__construct();
    // echo 'This is from admin controller';
    $this->load->add_package_path(APPPATH.'libraries/third_party/ion_auth/');
		$this->load->library('ion_auth');

    // $this->load->add_package_path(APPPATH.'libraries/third_party/');
		// $this->load->library('eventviva/imageResize');
    if (!$this->ion_auth->logged_in()){
			redirect('auth/login');
		}
  }

  var $template  = array();
  var $data      = array();
  public function layout(){
    // making template and send data to view.
    // $this->template['header'] = $this->load->view('admin/layout/header', $this->data, true);
    $this->template['left']   = $this->load->view('admin/layout/left', $this->data, true);
    $this->template['middle'] = $this->load->view($this->middle, $this->data, true);
    // $this->template['footer'] = $this->load->view('admin/layout/footer', $this->data, true);
    $this->load->view('admin/layout/index', $this->template);
  }
}


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

class NewRelic::DelayedJobInstrumentationTest < Test::Unit::TestCase
  def test_skip_logging_if_no_logger_found
    Object.const_set('Delayed', Module.new) unless defined?(Delayed)
    ::Delayed.const_set('Worker', Class.new)

    NewRelic::Agent.stubs(:logger).raises(NoMethodError,
                                            'tempoarily not allowed')
    NewRelic::Agent.stubs(:respond_to?).with(:logger).returns(false)

    assert DependencyDetection.detect!

    Object.class_eval { remove_const('Delayed') }
  end
end


text:
package com.heroku.demo.config;

import com.heroku.demo.web.LocalDateTimeConverter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;

import javax.sql.DataSource;

@Configuration
public class DatabaseConfig {
    @Bean
    @Profile("postgres")
    @Primary
    @ConfigurationProperties(prefix = "custom.spring.datasource")
    public DataSource dataSource() {
        return new org.apache.tomcat.jdbc.pool.DataSource();
    }
}