text:
package com.jamonapi.proxy;

import com.jamonapi.MonitorFactory;
import com.jamonapi.utils.AppMap;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/** SQLDeArger takes a sql statement and 1) replaces argument values ('souza', "souza", 'souza''s', 100, 100.5, 0xff, 10e9) with question marks
 *  It makes full sql statements look more like a prepared statement.  2) Returns a sql type which is simply the first word of the command
 *  (typically 'select', 'update' etc. 3) Returns any specified keywords that are in the parsed sql.  This is a good way to return table names.
 *
 *
A normal sql statement with argument values would generate too much data for JAMon and wouldn't be very good for understanding how your query
 *  performed.  Coneceptually the following queries are the same: 1) select * from table where name='steve', 2) select * from table where name='mindy'.
 *  However, if you passed both strings to jamon the 'sameness' wouldn't show up in the stats as each is a different string.  However by putting
 *  question marks in place of the values this problem can be resolved (i.e. select * from table where name=?).  One issue with the way this is done
 *  at this point is numbers or strings in other places can be replaced too. This shouldn't affect monitoring however.  For example
 *  This "select abs(200) from table", would be parsed to "select abs(?) from table".

 *
 *
However, numbers of the format 100.00, really are multiple tokens. And will appear in the returned
 *   strings as ?.?.

 *
 *
The class name SQLDeArger refers to the fact that argument values are removed from SQL statements.

 *
 *
This class is also useful for logging sql statements.

 */

public class SQLDeArger {
    private int parseSize;// size of the sql statement to parse
    private StringBuffer parsedSQL=new StringBuffer();// where the resulting sql statement will reside
    private char[] sqlChars;// characters in sql string
    private String sqlToParse;// original sql
    private int delimCounter=0;//character counter
    private int currentCharNum=0;// current character in sql that is being proceesed
    private boolean isInString=false;// indicates whether or not the parser is currently in a string i.e. 'steve'
    private char delim; // string delimeter which will be either ' or "
    private int totalDelims;// a counter of how many times delimeter appears in a string.
    private boolean firstToken=true;// the first token processed.  usually will be select, update, insert etc.
    private String sqlType;// the first token such as select, update, delete, insert
    private List matchStrings;// a list of strings to match in the sql statement.  table names are a good example
    private String[] matches;// the list of returned matches.
    //@VisibleForTesting
    static final String THRESHOLD_EXCEEDED="sqlSizeExceedsThreshold";
    //@VisibleForTesting
    static final String THRESHOLD_EXCEEDED_LENGTH="MonProxy-SQL-"+THRESHOLD_EXCEEDED+".length";

    private static Map sqlTypes=AppMap.createInstance();// case insensitive map.
    static {
        // These values are just checked for existance so the value can be null.  These indicate the type of sql statement.
        sqlTypes.put("select","select");
        sqlTypes.put("update","update");
        sqlTypes.put("delete","delete");
        sqlTypes.put("insert","insert");
        sqlTypes.put("truncate","truncate");
        sqlTypes.put(THRESHOLD_EXCEEDED,THRESHOLD_EXCEEDED);

        sqlTypes.put("exec","exec");
        sqlTypes.put("create","create");
        sqlTypes.put("drop","drop");
        sqlTypes.put("alter","alter");

        sqlTypes.put("commit","commit");
        sqlTypes.put("rollback","rollback");
        sqlTypes.put("save","save");

        sqlTypes.put("grant","grant");
        sqlTypes.put("revoke","revoke");
    }

    /** Accepts string to parse */
    public SQLDeArger(String sql) {
        this(sql,null);

    }

    /** Accepts strings to parse and a List of strings to check to see if they are in the sql statement.  A good use for this is to
     * pass table names into the constructor.  After the constructor is called the sql will already have been parsed
     *
     * @param sql
     * @param matchStrings
     */
    public SQLDeArger(String sql, List matchStrings) {
        this(sql, matchStrings, 0);
    }

    /** This constructor will truncate any sql statements longer than sqlMaxSize before the JAMon label is created
     *
     * @param sql
     * @param matchStrings
     * @param sqlMaxSize
     */
    public SQLDeArger(String sql, List matchStrings, int sqlMaxSize) {
        if (sqlMaxSize>0 && sql.length()>sqlMaxSize) {
            int len=sql.length();
            sql=THRESHOLD_EXCEEDED+" query time (size="+len+")";
            MonitorFactory.add(THRESHOLD_EXCEEDED_LENGTH, "bytes", len);
        }
        this.sqlToParse=sql.trim()+" ";// ensures that the last character is always a space and not part of the query.
        parseSize=sqlToParse.length()-1; // exclude space which lets me not have to worry about next char.
        sqlChars=sqlToParse.toCharArray();// characters that will be parsed
        setMatchStrings(matchStrings);
        parse();
    }

    /** Parse the passed in where clause and break it along token lines.   */
    private SQLDeArger parse() {
        // tokens are strings broken on word boundaries like spaces
        while (hasTokens()) {
            String token=getNextToken();
            if (firstToken) {
                setSQLType(token);
                firstToken=false;
            }

            // if the token is a number such as 100, 100.5 0xff, 10E9 or a quoted string such as 'steve'
            // the replace it with a '?'.  The final case where token is null and still is in a string can happen more often
            // now that the sql length can arbitrarily be limited. For example: select * from table where name='ste
            // This would return null as the last token and yet be in string.  The following will return '?' in this case.
            token=(isFloatString(token) || isQuotedString(token) || (token==null && isInString())) ? "?" : token;
            parsedSQL.append(token);
        }

        parseMatches();

        return this;
    }

    /** Return sql with original argument values replaced with '?'.  For example:  select * from table where name=? */
    public String getParsedSQL() {
        return parsedSQL.toString();
    }

    /**Get sql that was passed in to parse. */
    public String getSQLToParse() {
        return sqlToParse;
    }

    /** Return the first word from the sql command.  These would include:  select, update, delete, create, insert, commit,...
     * If the word is not recognized then 'other' is returned.
     */
    public String getSQLType() {
        return sqlType;
    }

    /** Returns an array of Strings that matched the Strings specified in
     *  the matches arraylist.   Note that the matches are performed after arg
     *  values have been replaced on the sql with '?'.
     */
    public String[] getMatches() {
        return matches;
    }

    /** Returns true if there were any matches against the match Strings */
    public boolean hasMatches() {
        return (matches==null || matches.length==0) ? false : true;
    }

    /** Returns the number of matches or 0 if there were none */
    public int getNumMatches() {
        return (hasMatches()) ? matches.length : 0;
    }

    /** One for the statement, one for the keyword type of the statment, and the other numbers are for the matches */
    int getNumAll() {
        return 3+getNumMatches();
    }

    /** Return an array that has 1) all sql, 2) the sql type, 3) the parsed sql, 4) any matched strings if they exist.  The array will be at least
     *  2 long.   This is useful to pass all the strings in the array to jamon to track stats associated with the query.
     */
    String[][] getAll() {

        int size=getNumAll(); // 2 represents the sql and sqltype values, so that is always there.
        String[][] allData=new String[size][];

        // start at position 2 assigning any matches to the array.
        for (int i=0, j=0;i<size;i++) {
            allData[i]=new String[3];// ms., and value
            allData[i][1]=getSQLToParse();
            allData[i][2]="ms.";
            // note this loop matches one in SQLDeArgMon constructor and positions are important
            // The constructor must be changed if this method changes - kind of ugly...
            if (i==0)  // All
                allData[i][0]="All";
            else if (i==1) // SQL Type
                allData[i][0]=getSQLType();
            else if (i==2) // parsed SQL
                allData[i][0]=getParsedSQL();
            else // Matches in sql such as table names.
                allData[i][0]=matches[j++];
        }

        return allData;
    }

    /** Add string to see if it matches in the query */
    public void addMatchString(String matchString) {
        matchStrings.add(matchString);
    }

    /** Determine if the matches strings are in the parsed sql */
    private void parseMatches() {
        if (matchStrings!=null) {
            String sql=getParsedSQL();
            List matchesList=new ArrayList();

            Iterator iter=matchStrings.iterator();
            while (iter.hasNext()) {
                Object matchObj = iter.next(); // passed in matches such as table names
                String matchStr = (matchObj==null) ? null : matchObj.toString();
                if (sql.indexOf(matchStr)>0)// i.e. a match found
                    matchesList.add(matchStr);
            }

            matches=(String[]) matchesList.toArray(new String[0]);// convert matches into an array
        }

    }

    /** Note matchStrings should contain Strings.  If it doesn't toString() will be called on the objects */
    void setMatchStrings(List matchStrings) {
        this.matchStrings=matchStrings;
    }

    /** SQL types are the first word that is in a sql statement.  Examples are
     * insert, delete, update, and select.  However, any word that you add by calling this
     * method will be detected as a sql type.  Note the JDBCMonProxy uses this info
     * to add a monitor for whenever a select, insert etc are executed.  This gives the number
     * of times and performances of the sql types.  A list of all the default
     * sql types follows: select, update, delete, insert, truncate, exec, create, drop, alter
     * commit, rollback, grant, revoke, save.  Any value that isn't on the list will return
     * 'other'.	The getSQLType method returns the SQL type value in the sql statement passed to the
     * constructor.
     *
     * @param type
     */
    public static void putSQLType(String type) {
        sqlTypes.put(type,type);
    }

    private void setSQLType(String type) {
        sqlType = (String)sqlTypes.get(type);
        if (sqlType==null)
            sqlType="other";

    }

    // returns true as long as there are characters to process
    private boolean hasTokens() {
        return (currentCharNum<parseSize) ? true : false;
    }

    // Returns String tokens such as: select, from, where, table, etc.
    private String getNextToken() {
        int start=currentCharNum;
        int end=0;

        // loop until word boundary
        while (end==0 && currentCharNum<parseSize) {
            setStringDelim();

            // an example of a word boundary would be next char of space while not in a string, or a puctuation mark
            if (isWordBoundary(getCurrentChar(), getNextChar()) )
                end=currentCharNum+1;

            currentCharNum++;
        }

        // return the word as a token if one was found
        if (end>0)
            return sqlToParse.substring(start,end);
        else
            return null;

    }

    // determine if the character is punctuation or not.
    private boolean isPunctuation(char ch) {
        return (!isInString() && !Character.isLetterOrDigit(ch));
    }

    private boolean isWordBoundary(char currentCh, char nextCh) {
        // word boundaries are special puncutation, when not in a string.
        // select * from table where key=100
        // first part of conditional would be triggered with convert(200. if currentchar was '('
        // 2nd part:  select *, convert(char(20)... from.  if characther is 't' of select or 't'
        // of 'convert'
        return (isPunctuation(currentCh) && Character.isLetterOrDigit(nextCh)) ||
        (!isInString() && (Character.isWhitespace(nextCh) || !Character.isLetterOrDigit(nextCh)));
    }

    // Indicates if the character is embedded in a where clause string surrounded by ' or ".
    // i.e. this would return true for any characters in between double quotes "steve's"
    private boolean isInString() {
        return isInString;
    }

    private void setIsInString(boolean isInString) {
        this.isInString=isInString;
    }

    // can either be ' or "
    private void setStringDelim(char delim) {
        this.delim=delim;
    }

    private char getStringDelim() {
        return delim;
    }

    // Get the current character of processing
    private char getCurrentChar() {
        return sqlChars[currentCharNum];
    }

    // get next charater of processing.
    private char getNextChar() {
        return sqlChars[currentCharNum+1];
    }

    // Determine if the delimeter is " or '
    private void setStringDelim() {
        // if first delimiter in a string like 'steve' then prepare for a string to be
        // processed

        // if in the string count delimeters to know when to end.
        boolean isDelim=(isInString() && getCurrentChar()==getStringDelim());
        if (isDelim)
            totalDelims++;

        if (!isInString() && (getCurrentChar()=='\'' || getCurrentChar()=='"')) {
            delimCounter++;
            totalDelims++;
        } // else it is the last ' or " in 'steve' , 'mindy''s'''
        else if (isInString() && getCurrentChar()==getStringDelim() && getNextChar()!=getStringDelim() && totalDelims%2==0) {
            delimCounter--;
        }

        if (!isInString() && delimCounter==1) {
            setStringDelim(getCurrentChar());
            setIsInString(true);
        } else if (isInString() && delimCounter==0)
            setIsInString(false);

    }

    // Any token that starts with a 0 returns true.  i.e. 1000 0xFF, 10E9, would return true.
    private  boolean isFloatString(String str){
        // if null string or the first character is not a digit then this is not a number
        if (str==null || !Character.isDigit(str.charAt(0)))
            return false;
        else // else it is a number
            return true;
    }

    private  boolean isQuotedString(String str) {
        if (str==null || "".equals(str.trim()))
            return false;

        char first=str.charAt(0);
        char last=str.charAt(str.length()-1);

        // either 'souza' or "souza" is a good quoted string.
        if ((first=='\'' || first=='"') && first==last)
            return true;
        else
            return false;
    }

}


text:
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public int startingHealth = 100;
    public int currentHealth;
    public float sinkSpeed = .01f;
    public int scoreValue = 10;
    public AudioClip deathClip;
    public int damagePerShot = 20;

    Animator anim;
    AudioSource enemyAudio;
    ParticleSystem hitParticles;
    CapsuleCollider capsuleCollider;
    public bool isDead;
    bool isSinking;

    void Awake ()
    {
        anim = GetComponent <Animator> ();
        enemyAudio = GetComponent <AudioSource> ();
        hitParticles = GetComponentInChildren <ParticleSystem> ();
        capsuleCollider = GetComponent <CapsuleCollider> ();
        anim.SetBool("Dead", false);

        currentHealth = startingHealth;
    }

    void Update ()
    {
        if(isSinking)
        {
            transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
        }
    }

    public void TakeDamage (int amount)
    {
        if(isDead)
            return;

       // enemyAudio.Play ();

        currentHealth -= amount;

        //hitParticles.transform.position = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
        //hitParticles.Play();

        if(currentHealth <= 0)
        {
            Death ();

        }
    }

    void Death ()
    {
        anim.SetBool("Dead", true);
        isDead = true;

        capsuleCollider.isTrigger = true;

        //anim.SetBool ("Dead", true);

        StartSinking();

        //enemyAudio.clip = deathClip;
        //enemyAudio.Play ();
    }

    public void StartSinking ()
    {

        GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
        GetComponent <Rigidbody> ().isKinematic = true;
        isSinking = true;
        ScoreManager.score += scoreValue;
        Destroy (gameObject, 2f);
    }

 }

redpajama_set_name: RedPajamaGithub


text:
//-----------------------------------------------------------------------
// <copyright file="ObjectBehaviour.cs" company="Benjamin Woodall">
//     Copyright Benjamin Woodall 2014. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using Core.DependencyInjection;
using Core.Programmability;
using Game;
using UnityEngine;

namespace Game.Unity.Behaviours
{
    /// Base behaviour for entity and tile instance game objects
    public abstract class ObjectBehaviour : MonoBehaviour
    {
        /// Backing field for ControllerManager
        private static IControllerManager controllerManager;

        /// Gets or sets the IObject corresponding to the GameObject
        public IObject Object { get; protected set; }

        /// Gets the controller manager
        protected static IControllerManager ControllerManager
        {
            get
            {
                return controllerManager ?? (controllerManager = GlobalContainer.Resolve<IControllerManager>());
            }
        }
    }
}


text:
"""Earth geometry and gravity models."""
import numpy as np
from . import transform
from . util import mv_prod

#: Rotation rate of Earth in rad/s.
RATE = 7.2921157e-5
#: Approximate value of gravity.
G0 = 9.8
#: Semi major axis of Earth ellipsoid (or radius of Earth approximately).
R0 = 6378137.0
#: Squared eccentricity of Earth ellipsoid
E2 = 6.6943799901413e-3
#: Gravity at the equator
GE = 9.7803253359
#: Gravity at the pole.
GP = 9.8321849378

def principal_radii(lat, alt):
    """Compute the principal radii of curvature of Earth ellipsoid.

    See [1]_ (p. 41) for the definition and formulas.

    Parameters
    ----------
    lat : array_like
        Latitude.
    alt : array_like
        Altitude.

    Returns
    -------
    rn : ndarray
        Principle radius in North direction.
    re : ndarray
        Principle radius in East direction.
    rp : ndarray
        Radius of cross-section along the parallel.

    References
    ----------
    .. [1] P. D. Groves, "Principles of GNSS, Inertial, and Multisensor
           Integrated Navigation Systems".
    """
    sin_lat = np.sin(np.deg2rad(lat))
    cos_lat = np.sqrt(1 - sin_lat**2)

    x = 1 - E2 * sin_lat ** 2
    re = R0 / np.sqrt(x)
    rn = re * (1 - E2) / x

    return rn + alt, re + alt, (re + alt) * cos_lat

def gravity(lat, alt):
    """Compute gravity according to a theoretical model.

    Somigliana model used in WGS84 with linear vertical correction is
    implemented. See [1]_ for the discussion.

    Parameters
    ----------
    lat, alt : array_like
        Latitude and altitude.

    Returns
    -------
    g : float or ndarray, shape (n,)
        Magnitude of the gravity.

    References
    ----------
    .. [1] P. D. Groves, "Principles of GNSS, Inertial, and Multisensor
           Integrated Navigation Systems".
    """
    sin_lat = np.sin(np.deg2rad(lat))
    alt = np.asarray(alt)
    F = (1 - E2) ** 0.5 * GP / GE - 1
    return (GE * (1 + F * sin_lat**2) / (1 - E2 * sin_lat**2)**0.5
            * (1 - 2 * alt / R0))

def gravity_n(lat, alt):
    """Compute gravity vector in NED frame.

    Parameters
    ----------
    lat : array_like
        Latitude.
    alt : array_like
        Altitude.

    Returns
    -------
    g_n : ndarray, shape (3,) or (n, 3)
        Vector of the gravity.
    """
    g = gravity(lat, alt)
    if g.ndim == 0:
        return np.array([0, 0, g])
    else:
        result = np.zeros((len(g), 3))
        result[:, 2] = g
        return result

def gravitation_ecef(lla):
    """Compute a vector of the gravitational force in ECEF frame.

    It accounts only for Earth mass attraction. It is computed from
    `gravity` model by eliminating the centrifugal force.

    Parameters
    ----------
    lla : array_like, shape (3,) or (n, 3)
        Latitude, longitude and altitude.

    Returns
    -------
    g0_e: ndarray, shape (3,) or (n, 3)
        Vectors of the gravitational force expressed in ECEF frame.
    """
    lat, lon, alt = np.asarray(lla).T

    sin_lat = np.sin(np.deg2rad(lat))
    cos_lat = np.cos(np.deg2rad(lat))

    _, _, rp = principal_radii(lat, alt)

    g0_g = np.zeros((3,) + sin_lat.shape)
    g0_g[0] = RATE**2 * rp * sin_lat
    g0_g[2] = gravity(lat, alt) + RATE ** 2 * rp * cos_lat
    g0_g = g0_g.T

    Ceg = transform.mat_en_from_ll(lat, lon)

    return mv_prod(Ceg, g0_g)

def curvature_matrix(lat, alt):
    """Compute Earth curvature matrix.

    Curvature matrix `F` links linear displacement and angular rotation of
    NED frame as `rotation_n = F @ translation_n`, where `translation_n` is
    linear translation in NED and `rotation_n` is the corresponding small
    rotation vector of NED.

    For example `transport_rate_n = F @ velocity_n`.

    Parameters
    ----------
    lat, alt : array_like
        Latitude and altitude.

    Returns
    -------
    F: ndarray, shape (3, 3) or (n, 3, 3)
        Curvature matrix.
    """
    rn, re, _ = principal_radii(lat, alt)
    n = 1 if re.ndim == 0 else len(re)

    result = np.zeros((n, 3, 3))
    result[:, 0, 1] = 1 / re
    result[:, 1, 0] = -1 / rn
    result[:, 2, 1] = -result[:, 0, 1] * np.tan(np.deg2rad(lat))

    return result[0] if re.ndim == 0 else result

def rate_n(lat):
    """Compute Earth rate resolved in NED frame.

    Parameters
    ----------
    lat : array_like
        Latitude.

    Returns
    -------
    earth_rate_n : ndarray, shape (3,) or (n, 3)
        NED components of Earth rate.
    """
    lat = np.asarray(lat)
    n = 1 if lat.ndim == 0 else len(lat)
    result = np.zeros((n, 3))
    result[:, 0] = RATE * np.cos(np.deg2rad(lat))
    result[:, 2] = -RATE * np.sin(np.deg2rad(lat))
    return result[0] if lat.ndim == 0 else result


text:
[![Build
Status](https://travis-ci.org/m-lab/ndt-e2e-testmaster.svg?branch=master)](https://travis-ci.org/m-lab/ndt-e2e-testmaster)
[![Coverage
Status](https://coveralls.io/repos/m-lab/ndt-e2e-testmaster/badge.svg?branch=master&service=github)](https://coveralls.io/github/m-lab/ndt-e2e-testmaster?branch=master)

## Utilities

### JSON to CSV converter

The JSON to CSV converter takes a collection of raw NDT result JSON files
(created by the
[client\_wrapper](https://github.com/m-lab/ndt-e2e-clientworker)) and/or a
collection of NDT result file packages (created by the [Ansible
playbook](https://github.com/m-lab/ndt-e2e-ansible)) and gathers the results
together in a CSV file.

To run the converter:

```bash
python testmaster/json_to_csv.py --pattern "ndt-results/*" > results.csv
```

Where `ndt-results` is a folder containing raw JSON results, zips of results, or
both.

### Result Aggregate Statistics Calculator

The aggregate statistics calculator calculates the aggregate statistics of each
metric in the NDT results.

##### Print metric statistics in simple text format

```bash
python testmaster/calculate_statistics.py \
  --pattern "ndt-results/*" \
  --format=simple
```

##### Write metric statistics in CSV format

```bash
python testmaster/calculate_statistics.py \
  --pattern "ndt-results/*" \
  --format=csv > results.csv
```


text:
package org.kohsuke.args4j.apt;

import java.io.PrintWriter;
import java.io.Writer;

/**
 * Writes the option list as HTML to a {@link Writer}.
 *
 * @author Kohsuke Kawaguchi
 */
class HtmlWriter implements AnnotationVisitor {
    private final PrintWriter out;

    public HtmlWriter(Writer out) {
        this.out = new PrintWriter(out);
        this.out.println("
");
    }

    public void onOption(String name, String usage) {
        out.println("
");
        writeTag("td","args4j-option",name);
        writeTag("td","args4j-usage",usage);
        out.println("
");
    }

    public void onOption( OptionWithUsage optionWithUsage ) {
        out.println("
");
        writeTag("td","args4j-option",optionWithUsage.option.name());
        writeTag("td","args4j-usage",optionWithUsage.usage);
        out.println("
");
    }

    private void writeTag(String tag, String cssClass, String value) {
        out.println("    <"+tag+" class='"+cssClass+"'><![CDATA["+value+"]]></"+tag+">");
    }

    public void done() {
        out.println("
");
        out.close();
    }
}


text:
Module("Cactus.Web", function (m) {
  var $f = Cactus.Web.selectFirst;
  var tag = Cactus.Web.tag;
  /**
   * Converts a string into a DOM structure. Expects completely valid html
   * without any initial white space.
   *
   * @param string s
   * @return HTMLElement
   */
  m.stringToDom = function (s) {
    var el = tag("div");
    var selector;
    if (/^<tr/.test(s)) {
      el.innerHTML = "

%s

".format(s);
      selector = "tr";
    } else if (/^<option/.test(s)) {
      el.innerHTML = "<select>%s</select>".format(s);
      selector = "option";
    } else {
      el.innerHTML = s;
      selector = "*";
    }
    return $f(selector, el);
  };
});


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateConnectorTypeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('connector_type', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('connector_id')->unsigned()->index();
            $table->integer('type_id')->unsigned()->index();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('connector_type');
    }
}


text:
NSString *JSValueToNSString( JSContextRef ctx, JSValueRef v ) {
	JSStringRef jsString = JSValueToStringCopy( ctx, v, NULL );
	if( !jsString ) return nil;

	NSString *string = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, jsString );
	[string autorelease];
	JSStringRelease( jsString );

	return string;
}

JSValueRef NSStringToJSValue( JSContextRef ctx, NSString *string ) {
	JSStringRef jstr = JSStringCreateWithCFString((CFStringRef)string);
	JSValueRef ret = JSValueMakeString(ctx, jstr);
	JSStringRelease(jstr);
	return ret;
}

// JSValueToNumberFast blindly assumes that the given JSValueRef is a
// a number. Everything else will be silently converted to 0.
// This functions comes in a 64bit and 32bit flavor, since the NaN-Boxing
// in JSC works a bit differently on each platforms. For an explanation
// of the taggging refer to JSC/runtime/JSCJSValue.h

#if __LP64__ // arm64 version
double JSValueToNumberFast(JSContextRef ctx, JSValueRef v) {
    union {
        int64_t asInt64;
        double asDouble;
        struct { int32_t asInt; int32_t tag; } asBits;
    } taggedValue = { .asInt64 = (int64_t)v };

#define DoubleEncodeOffset 0x1000000000000ll
#define TagTypeNumber 0xffff0000
#define ValueTrue 0x7

    if( (taggedValue.asBits.tag & TagTypeNumber) == TagTypeNumber ) {
        return taggedValue.asBits.asInt;
    }
    else if( taggedValue.asBits.tag & TagTypeNumber ) {
        taggedValue.asInt64 -= DoubleEncodeOffset;
        return taggedValue.asDouble;
    }
    else if( taggedValue.asBits.asInt == ValueTrue ) {
        return 1.0;
    }
    else {
        return 0; // false, undefined, null, object
    }
}
#else // armv7 version
double JSValueToNumberFast( JSContextRef ctx, JSValueRef v ) {
    struct {
        unsigned char cppClassData[4];
        union {
            double asDouble;
            struct { int32_t asInt; int32_t tag; } asBits;
        } payload;
    } *decoded = (void *)v;

    return decoded->payload.asBits.tag < 0xfffffff9
    ? decoded->payload.asDouble
    : decoded->payload.asBits.asInt;
}
#endif

void JSValueUnprotectSafe( JSContextRef ctx, JSValueRef v ) {
	if( ctx && v ) {
		JSValueUnprotect(ctx, v);
	}
}

JSValueRef NSObjectToJSValue( JSContextRef ctx, NSObject *obj ) {
	JSValueRef ret = NULL;

	// String
	if( [obj isKindOfClass:NSString.class] ) {
		ret = NSStringToJSValue(ctx, (NSString *)obj);
	}

	// Number or Bool
	else if( [obj isKindOfClass:NSNumber.class] ) {
		NSNumber *number = (NSNumber *)obj;
		if( strcmp(number.objCType, @encode(BOOL)) == 0 ) {
			ret = JSValueMakeBoolean(ctx, number.boolValue);
		}
		else {
			ret = JSValueMakeNumber(ctx, number.doubleValue);
		}
	}

	// Date
	else if( [obj isKindOfClass:NSDate.class] ) {
		NSDate *date = (NSDate *)obj;
		JSValueRef timestamp = JSValueMakeNumber(ctx, date.timeIntervalSince1970 * 1000.0);
		ret = JSObjectMakeDate(ctx, 1, &timestamp, NULL);
	}

	// Array
	else if( [obj isKindOfClass:NSArray.class] ) {
		NSArray *array = (NSArray *)obj;
		JSValueRef *args = malloc(array.count * sizeof(JSValueRef));
		for( int i = 0; i < array.count; i++ ) {
			args[i] = NSObjectToJSValue(ctx, array[i] );
		}
		ret = JSObjectMakeArray(ctx, array.count, args, NULL);
		free(args);
	}

	// Dictionary
	else if( [obj isKindOfClass:NSDictionary.class] ) {
		NSDictionary *dict = (NSDictionary *)obj;
		ret = JSObjectMake(ctx, NULL, NULL);
		for( NSString *key in dict ) {
			JSStringRef jsKey = JSStringCreateWithUTF8CString(key.UTF8String);
			JSValueRef value = NSObjectToJSValue(ctx, dict[key]);
			JSObjectSetProperty(ctx, (JSObjectRef)ret, jsKey, value, NULL, NULL);
			JSStringRelease(jsKey);
		}
	}

	return ret ? ret : JSValueMakeNull(ctx);
}

NSObject *JSValueToNSObject( JSContextRef ctx, JSValueRef value ) {
	JSType type = JSValueGetType(ctx, value);

	switch( type ) {
		case kJSTypeString: return JSValueToNSString(ctx, value);
		case kJSTypeBoolean: return [NSNumber numberWithBool:JSValueToBoolean(ctx, value)];
		case kJSTypeNumber: return [NSNumber numberWithDouble:JSValueToNumberFast(ctx, value)];
		case kJSTypeNull: return nil;
		case kJSTypeUndefined: return nil;
		case kJSTypeObject: break;
	}

	if( type == kJSTypeObject ) {
		JSObjectRef jsObj = (JSObjectRef)value;

		// Get the Array constructor to check if this Object is an Array
		JSStringRef arrayName = JSStringCreateWithUTF8CString("Array");
		JSObjectRef arrayConstructor = (JSObjectRef)JSObjectGetProperty(ctx, JSContextGetGlobalObject(ctx), arrayName, NULL);
		JSStringRelease(arrayName);

		if( JSValueIsInstanceOfConstructor(ctx, jsObj, arrayConstructor, NULL) ) {
			// Array
			JSStringRef lengthName = JSStringCreateWithUTF8CString("length");
			int count = JSValueToNumberFast(ctx, JSObjectGetProperty(ctx, jsObj, lengthName, NULL));
			JSStringRelease(lengthName);

			NSMutableArray *array = [NSMutableArray arrayWithCapacity:count];
			for( int i = 0; i < count; i++ ) {
				NSObject *obj = JSValueToNSObject(ctx, JSObjectGetPropertyAtIndex(ctx, jsObj, i, NULL));
				[array addObject:(obj ? obj : NSNull.null)];
			}
			return array;
		}
		else {
			// Plain Object
			JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames(ctx, jsObj);
			size_t count = JSPropertyNameArrayGetCount(properties);

			NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:count];
			for( size_t i = 0; i < count; i++ ) {
				JSStringRef jsName = JSPropertyNameArrayGetNameAtIndex(properties, i);
				NSObject *obj = JSValueToNSObject(ctx, JSObjectGetProperty(ctx, jsObj, jsName, NULL));

				NSString *name = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, jsName );
				dict[name] = obj ? obj : NSNull.null;
				[name release];
			}

			JSPropertyNameArrayRelease(properties);
			return dict;
		}
	}

	return nil;
}


text:
package org.apache.camel.component.reactive.streams.util;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.camel.Exchange;
import org.apache.camel.TypeConversionException;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A publisher that converts Camel {@code Exchange}s into the given type.
 */
public class ConvertingPublisher<R> implements Publisher<R> {

    private static final Logger LOG = LoggerFactory.getLogger(ConvertingPublisher.class);

    private Publisher<Exchange> delegate;

    private Class<R> type;

    public ConvertingPublisher(Publisher<Exchange> delegate, Class<R> type) {
        Objects.requireNonNull(delegate, "delegate publisher cannot be null");
        this.delegate = delegate;
        this.type = type;
    }

    @Override
    public void subscribe(Subscriber<? super R> subscriber) {
        delegate.subscribe(new Subscriber<Exchange>() {

            private AtomicBoolean active = new AtomicBoolean(true);

            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription newSubscription) {
                if (newSubscription == null) {
                    throw new NullPointerException("subscription is null");
                } else if (newSubscription == this.subscription) {
                    throw new IllegalArgumentException("already subscribed to the subscription: " + newSubscription);
                }

                if (this.subscription != null) {
                    newSubscription.cancel();
                } else {
                    this.subscription = newSubscription;
                    subscriber.onSubscribe(newSubscription);
                }
            }

            @Override
            public void onNext(Exchange ex) {
                if (!active.get()) {
                    return;
                }

                R r;
                try {
                    r = ex.getIn().getBody(type);
                } catch (TypeConversionException e) {
                    LOG.warn("Unable to convert body to the specified type: " + type.getName(), e);
                    r = null;
                }

                if (r == null && ex.getIn().getBody() != null) {
                    this.onError(new ClassCastException("Unable to convert body to the specified type: " + type.getName()));

                    active.set(false);
                    subscription.cancel();
                } else {
                    subscriber.onNext(r);
                }

            }

            @Override
            public void onError(Throwable throwable) {
                if (!active.get()) {
                    return;
                }

                subscriber.onError(throwable);
            }

            @Override
            public void onComplete() {
                if (!active.get()) {
                    return;
                }

                subscriber.onComplete();
            }
        });
    }
}


text:
<?php

namespace app\master\controllers;

use Yii;
use app\master\models\StockHelper;
use app\master\models\StockHelperSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\master\models\SoStockHelperHistory;
/**
 * StockHelperController implements the CRUD actions for StockHelper model.
 */
class StockHelperController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all StockHelper models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new StockHelperSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionIndexHelp()
    {
        $searchModel = new StockHelperSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single StockHelper model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new StockHelper model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($id)
    {
        $model = new StockHelper();
        $search = new StockHelperSearch();

        if ($model->load(Yii::$app->request->post())) {
            $helpid = Yii::$app->request->post('helpid');
            $model->StockHelpId = $search->GenerateId();
            $model->HelperId = $helpid;
            $model->DateAdd = date('Y-m-d');
            $model->DateCrt = date('Y-m-d h:i:s');
            $model->save();
            return $this->redirect(['index', 'id' => $id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing StockHelper model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->StockHelpId]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing StockHelper model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionDetail($id)
    {
        $searchModel = new StockHelperSearch();
        $dataProvider = $searchModel->search($id);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionAddSo($id)
    {
        $model = $this->findModel($id);
        $stockoldisi = $model->Isi;
        $stockoldkosong = $model->Kosong;
        $helper = $model->HelperId;
        $jenis = $model->JenisId;
        if($model->load(Yii::$app->request->post()))
        {
          $modelHis = new SoStockHelperHistory();
          $newisi = Yii::$app->request->post('jmlso','xxx');
          $dateadd = Yii::$app->request->post('dateadd','xxx');

          if($helper != 'A001' && $jenis == 'G001')
          {
            $modelStockHelper = StockHelper::find()->where(['HelperId' => 'A001','JenisId' => 'G001'])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi - $newisi);
            $modelStockHelper->Kosong = ($kosong + $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');

          }
          else if ($helper != 'A002' && $jenis == 'AQ001')
          {
            $modelStockHelper = StockHelper::find()->where(['HelperId' => 'A002','JenisId' => 'AQ001'])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi - $newisi);
            $modelStockHelper->Kosong = ($kosong + $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');

          } else {

            $modelStockHelper = StockHelper::find()->where(['HelperId' => $helper,'JenisId' => $jenis])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi - $newisi);
            $modelStockHelper->Kosong = ($kosong + $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');
          }

          $model->Isi = $stockoldisi + $newisi;
          $model->Kosong = $stockoldkosong - $newisi;
          $model->DateAdd = date('Y-m-d',strtotime($dateadd));
          $model->DateUpdate = date('Y-m-d',strtotime($dateadd));

          $modelHis->StockHelpId = $id;
          $modelHis->JenisId = $jenis;
          $modelHis->HelperId = $helper;
          $modelHis->Isi = $newisi;
          $modelHis->DateAdd = date('Y-m-d',strtotime($dateadd));
          $modelHis->DateCrt = date('Y-m-d h:i:s');

          $modelStockHelper->save();
          $modelHis->save();
          $model->save();

          return $this->redirect(['/master/stock-helper/detail','id' => $helper]);
        } else {

          return $this->render('_addso', [
              'model' => $model
          ]);
        }

    }

    public function actionCancelSo($id)
    {
        $model = $this->findModel($id);
        $stockoldisi = $model->Isi;
        $stockoldkosong = $model->Kosong;
        $helper = $model->HelperId;
        $jenis = $model->JenisId;
        if($model->load(Yii::$app->request->post()))
        {
          $modelHis = SoStockHelperHistory::find()->where(['StockHelpId' => $id])->orderBy('DateCrt DESC')->one();
          $newisi = Yii::$app->request->post('jmlso','xxx');

          if($helper != 'A001' && $jenis == 'G001')
          {
            $modelStockHelper = StockHelper::find()->where(['HelperId' => 'A001','JenisId' => 'G001'])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi + $newisi);
            $modelStockHelper->Kosong = ($kosong - $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');

          }
          else if ($helper != 'A002' && $jenis == 'AQ001')
          {
            $modelStockHelper = StockHelper::find()->where(['HelperId' => 'A002','JenisId' => 'AQ001'])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi + $newisi);
            $modelStockHelper->Kosong = ($kosong - $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');

          } else {

            $modelStockHelper = StockHelper::find()->where(['HelperId' => $helper,'JenisId' => $jenis])->one();
            $isi = $modelStockHelper->Isi;
            $kosong = $modelStockHelper->Kosong;

            $modelStockHelper->Isi = ($isi + $newisi);
            $modelStockHelper->Kosong = ($kosong - $newisi);
            $modelStockHelper->DateUpdate = date('Y-m-d h:i:s');
          }

          $model->Isi = $stockoldisi - $newisi;
          $model->Kosong = $stockoldkosong + $newisi;
          $model->DateUpdate = date('Y-m-d h:i:s');

          $modelHis->delete();

          $modelStockHelper->save();
          $model->save();

          return $this->redirect(['/master/stock-helper/detail','id' => $helper]);
        } else {

          return $this->render('_cancelso', [
              'model' => $model
          ]);
        }

    }
    /**
     * Finds the StockHelper model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return StockHelper the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = StockHelper::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
module Cryptoexchange::Exchanges
  module Coinpark
    module Services
      class Market < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            true
          end
        end

        def fetch(market_pair)
          output = super(ticker_url(market_pair))
          adapt(output['result'], market_pair)
        end

        def ticker_url(market_pair)
          base   = market_pair.base
          target = market_pair.target
          "#{Cryptoexchange::Exchanges::Coinpark::Market::API_URL}/mdata?cmd=ticker&pair=#{base}_#{target}"
        end

        def adapt(output, market_pair)
          ticker           = Cryptoexchange::Models::Ticker.new
          ticker.base      = market_pair.base
          ticker.target    = market_pair.target
          ticker.market    = Coinpark::Market::NAME
          ticker.ask       = NumericHelper.to_d(output['sell'])
          ticker.bid       = NumericHelper.to_d(output['buy'])
          ticker.last      = NumericHelper.to_d(output['last'])
          ticker.high      = NumericHelper.to_d(output['high'])
          ticker.low       = NumericHelper.to_d(output['low'])
          ticker.volume    = NumericHelper.to_d(output['vol'])
          ticker.change    = NumericHelper.to_d(output['percent'].to_f)
          ticker.timestamp = nil
          ticker.payload   = output
          ticker
        end

      end
    end
  end
end


text:
import re
import csv
import ipaddress

__version__ = 1.0

routes_key = {"C"     : "Connected",
              "S"     : "Static",
              "R"     : "RIP",
              "B"     : "BGP",
              "B*"    : "BGP*",
              "D"     : "EIGRP",
              "D*"    : "EIGRP*",
              "D EX"  : "EIGRP External",
              "O"     : "OSPF",
              "O*"    : "OSPF*",
              "O*E1"  : "OSPF* Candidate Default",
              "O*E2"  : "OSPF* Candidate Default",
              "O E1"  : "OSPF External 1",
              "O E2"  : "OSPF External 2",
              "O IA"  : "OSPF Inter-Area",
              "O N1"  : "OSPF NSSA External Type 1",
              "O N2"  : "OSPF NSSA External Type 2",
              "L"  : "Local",
              "i"  : "IS-IS",
              "i su"  : "IS-IS Summary",
              "i L1"  : "IS-IS Level-1",
              "i L2"  : "IS-IS Level-2",
              "i ia"  : "IS-IS Inter-Area",
              "*"  : "Candidate Default"}

# Each route will have the following values
class Route(object):
    def __init__(self):
        self.route = {}
        self.protocol = []
        self.metric = []
        self.next_hop = []
        self.age = []
        self.interface = []
    def __repr__(self):
        return str(self.route)

# The main code structure
class Code(object):
    def __init__(self):
        self.route_table = {}
        self.read_file()
        self.generate_output_to_file()

    # Retrieve a route object if it exists
    def get_route(self,route):
        return self.route_table.get(route)

    # If the regular expression picked up a valid route, extract the values into a temporary dictionary
    def get_match_values(self,match):
        values = {}
        for keyword, value in vars(Route()).items():
            if keyword in match.groupdict():
                val =  str(match.group(keyword).strip())
                values[keyword] = val
            else:
                values[keyword] = ""
        return values

    # Create a new route object using the values from the temporary dictionary
    def create_route(self,match):
        match_values = self.get_match_values(match)
        route_prefix = match_values["route"]
        existing_route = self.get_route(route_prefix)

        if not existing_route:
            new_route = Route()
            new_route.route = match_values["route"]
            new_route.protocol.append(match_values["protocol"])
            new_route.metric.append(match_values["metric"])
            new_route.next_hop.append(match_values["next_hop"])
            new_route.interface.append(match_values["interface"])
            new_route.age.append(match_values["age"])
            self.route_table[route_prefix] = new_route

    # Search the route for an ECMP pattern and then update the route object if it is found
    def add_ecmp_route(self,route,string_to_search):
        parent_route = self.get_route(route)
        ecmp_patterns = [
            r'(?P<metric>\[.*\/.*\]) via (?P<next_hop>.*), (?P<age>.*), (?P<interface>.*)', \
            r'(?P<metric>\[.*\/.*\]) via (?P<next_hop>.*), (?P<age>.*)'
        ]
        for pattern in ecmp_patterns:
            match = re.search(pattern,string_to_search)
            if match:
                parent_route.protocol.append(parent_route.protocol[0])
                parent_route.metric.append(match.group('metric').strip())
                parent_route.next_hop.append(match.group('next_hop').strip())
                parent_route.age.append(match.group('age').strip())
                try:
                    parent_route.interface.append(match.group('interface').strip())
                except IndexError:
                    parent_route.interface.append("N/A")
                break

    def get_host_range(self,subnet):
        try:
            range = ipaddress.ip_network(subnet)
            return range[1],range[-2]
        except ValueError:
            return "error", "error"
        except IndexError: # Handles /32
            return range[0], ""

    def generate_output_to_file(self):
        try:
            with open('routes.csv', 'w', newline='') as csv_file:
                spamwriter = csv.writer(
                    csv_file,
                    delimiter=',',
                    quotechar='|',
                    quoting=csv.QUOTE_MINIMAL
                )
                spamwriter.writerow([
                    'Route',
                    'Protocol',
                    'Metric',
                    'Next Hop',
                    'Age',
                    'Interface',
                    'From Range',
                    'To Range']
                )
                for entry in sorted(self.route_table):
                    route = self.get_route(entry)
                    first_ip, last_ip = self.get_host_range(route)
                    for no in range(len(route.protocol)):
                        spamwriter.writerow([
                            route.route,
                            route.protocol[no],
                            route.metric[no],
                            route.next_hop[no],
                            route.age[no],
                            route.interface[no],
                            first_ip,
                            last_ip
                        ])
            print ("  -- Output saved to 'routes.csv'")
        except:
            print ("  -- Unable to write to routes.csv, if the file is already open close it.")

    def read_file(self):
        start_processing = False
        invalid_phrases = ["variably","subnetted"]

        with open("routes.txt","r") as route_file:
            for line in route_file:
                #-----------------------
                # Ignore certain input
                #-----------------------
                if line.count(' ') < 2:
                    continue
                if any(x in line for x in invalid_phrases):
                    continue
                if "Gateway" in line:
                    start_processing = True
                    continue
                if not start_processing:
                    continue

                line = line.strip().replace("\n","")
                #---------------------------------------
                # Define all the possible regex patterns
                #---------------------------------------
                # Line 1. BGP
                # Line 2. IGP (OSPF,EIGRP etc)
                # Line 3. Static routes
                # Line 4. Connected/local routes
                #---------------------------------------
                if start_processing:
                    patterns = [
                        r'(?P<protocol>[a-zA-Z] ..) (?P<route>.*) (?P<metric>.*) via (?P<next_hop>.*), ?(?P<age>.*), ?(?P<interface>.*)', \
                        r'(?P<protocol>[a-zA-Z]..) (?P<route>.*) (?P<metric>.*) via (?P<next_hop>.*), ?(?P<age>.*), ?(?P<interface>.*)', \
                        r'(?P<protocol>[a-zA-Z]) (?P<route>.*) is a summary, (?P<age>.*), (?P<interface>.*)', \
                        r'(?P<protocol>[a-zA-Z]..) (?P<route>.*) is a summary, (?P<age>.*), (?P<interface>.*)', \
                        r'(?P<protocol>B.*|B\*.*) (?P<route>.*) (?P<metric>.*) via (?P<next_hop>.*), (?P<age>.*)', \
                        r'(?P<protocol>S.*|S\*.*) (?P<route>.*) (?P<metric>.*) via (?P<next_hop>.*)', \
                        r'(?P<protocol>C.*|L.*) (?P<route>.*) is directly connected, (?P<interface>.*)'
                    ]
                    #-----------------------------------------------------
                    # Cycle through all the patterns and grab the matches
                    #-----------------------------------------------------
                    ecmp_route_found = False
                    for regex in patterns:
                        match = re.search(regex,line)
                        if match:
                            self.create_route(match)
                            prefix_being_processed = match.group('route').strip()
                            ecmp_route_found = True
                            break
                    if not ecmp_route_found:
                        self.add_ecmp_route(prefix_being_processed, line)

print ("Cisco IOS Route Parser version: '{}'".format(__version__))
c = Code()


text:
const fs = require('fs');
const path = require('path');
const settings = require("./settings");
const net = require('net');
const api = require('./client-api.js');
const cities = {};
const coords = {};
const file = fs.readFileSync(path.join(__dirname,'data/city.list.json'), 'utf8');

const arr = file.split('\n');

arr.forEach(function (line) {
	line = line.trim().replace(/\n/g, '');
    var c = JSON.parse(line);
    cities[c.name] = c;
    coords[c.coord.lon.toString() + "_" + c.coord.lat.toString()] = c;
});

var server = net.createServer(function(socket) {
  socket.on('data', (data) => {
    const evt = JSON.parse(data.toString('utf8'))
    switch (evt.action) {
      case 'getForecast':
        console.log('getting forecast for city ', evt.city);
        if (evt.city) {
          api.forCity(evt.city, (err, result) => {
              if (err) {
                return console.error(err);
              }
              socket.end(JSON.stringify(result));
            });
        } else {
          socket.write('City not provided');
        }
      }
    })
});

// grab a random port.
server.listen({
  port: settings.PORT
}, function() {
  address = server.address();
  console.log("opened server on %j", address);
});


text:
import unittest
import constants
import robocup

class TestConstants(unittest.TestCase):
    def test_our_goal_zone(self):
        # right in the center of the goal zone
        in_zone = robocup.Point(0, constants.Field.PenaltyShortDist / 2.0)

        out_zone = robocup.Point(0, constants.Field.Length / 2.0)

        self.assertTrue(constants.Field.OurGoalZoneShape.contains_point(
            in_zone))
        # self.assertFalse(constants.Field.OurGoalZoneShape.contains_point(out_zone))


text:
housingData = {}

-- We shouldn't sync the whole table, maybe just the new additions? I dunno.
function syncHousingTable(sync)
	housingData = sync
end
addEvent("UCDhousing.syncHousingTable", true)
addEventHandler("UCDhousing.syncHousingTable", root, syncHousingTable)

function syncHouse(houseID, houseTable)
	if (not houseID) or (not houseTable) then
		return
	end
	housingData[houseID] = houseTable
	outputDebugString("Synced housing data for houseID = "..houseID)
end
addEvent("UCDhousing.syncHouse", true)
addEventHandler("UCDhousing.syncHouse", root, syncHouse)

-- I didn't want to request the data on resource start, but we'll need a login event of some sort (client-side)
-- This is only for if the resource is restarted
function requestHousingTableSync()
	if (exports.UCDaccounts:isPlayerLoggedIn(localPlayer)) then
		setTimer(
			function ()
				triggerServerEvent("UCDhousing.requestHousingTableSync", localPlayer)
			end, 500, 1, localPlayer
		)
	end
end
addEventHandler("onClientResourceStart", resourceRoot, requestHousingTableSync)

function getHouseData(houseID, column)
	if (not houseID) or (not column) then
		return nil
	end
	if (type(column) ~= "string") or (type(houseID) ~= "number") then
		return false
	end

	if (column == "*") then
		return housingData[houseID]
	else
		if (housingData[houseID] == nil) or (housingData[houseID][column] == nil) then
			return nil
		end
	end
	outputDebugString("Client call for getHouseData. Column: "..column.." houseID: "..houseID)
	return housingData[houseID][column]
end
--]]


text:
package com.elmakers.mine.bukkit.api.magic;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;

public class DeathLocation {
    private final Location location;
    private final ItemStack[] items;
    private final int experiencePoints;

    public DeathLocation(Location location, ItemStack[] items, int experiencePoints) {
        this.location = location;
        this.items = items;
        this.experiencePoints = experiencePoints;
    }

    @Nonnull
    public Location getLocation() {
        return location;
    }

    @Nullable
    public ItemStack[] getItems() {
        return items;
    }

    public int getExperiencePoints() {
        return experiencePoints;
    }
}


text:
// CDBG - A console extension for the Microsoft MDBG debugger
// Copyright (c) 2013 Craig Oberg
// Licensed under the MIT License (MIT) http://opensource.org/licenses/MIT

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cjomd.Mdbg.Extensions.Cdbg
{
    class SourceViewer : OutputBuffer
    {
        private List<int> _Breakpoints = new List<int>();
        private bool _ForceHighlight = false;
        private int _Highlight;

        public int HighLight
        {
            set
            {
                _Highlight = value;
                _ForceHighlight = true;
            }
        }

        public SourceViewer(string name)
            : base(name)
        {
        }

        public override void Draw(int position, int height)
        {
            int top = Console.WindowTop;

            // adjust position based on ip if we just stopped
            if (_ForceHighlight)
            {
                if (_Highlight < _LineOffset ||
                    _Highlight > _LineOffset + height)
                {
                    _LineOffset = _Highlight - 5;
                }
                _ForceHighlight = false;
            }

            ConsoleColor currentBGC = Console.BackgroundColor;
            Console.ForegroundColor = ConsoleColor.DarkGreen;

            int lineidx = _LineOffset;
            int count = _Lines.Count;

            for (int i = position; i <= height; i++)
            {
                Console.SetCursorPosition(0, i);
                Console.Write(string.Empty.PadRight(Console.WindowWidth, ' '));
                Console.SetCursorPosition(0, i);
                string linenum = (lineidx + 1).ToString().PadLeft(4);

                if (lineidx < _Lines.Count)
                {
                    if (_Breakpoints.Contains(lineidx + 1))
                    {
                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.ForegroundColor = ConsoleColor.Black;
                    }

                    Console.Write(String.Format("{0}", linenum));
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.BackgroundColor = currentBGC;

                    if (lineidx == _Highlight - 1)
                    {
                        Console.BackgroundColor = ConsoleColor.Yellow;
                        Console.ForegroundColor = ConsoleColor.Black;
                    }

                    Console.Write(String.Format(" {0}", _Lines[lineidx]));
                    Console.ForegroundColor = ConsoleColor.DarkGreen;
                    Console.BackgroundColor = currentBGC;

                    lineidx++;
                }
            }

            Console.ResetColor();
        }

        public void AddBreakpoint(int breakpoint)
        {
            _Breakpoints.Add(breakpoint);
        }
    }
}


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

using Grasshopper.Kernel;
using Rhino.Geometry;
using System.Windows.Forms;
using System.IO;
using Rhino.Collections;
using Grasshopper.Kernel.Types;
using System.Linq;

namespace UserDataUtils
{
    public class CsvUserData : GH_Component
    {

        string csv;
        /// <summary>
        /// Initializes a new instance of the CsvUserData class.
        /// </summary>
        public CsvUserData()
          : base("User Data to CSV", "CSVUD",
              "Spits out csvs for the provied dictionaries.",
              "Speckle", "User Data Utils")
        {
        }

        public override void AppendAdditionalMenuItems(ToolStripDropDown menu)
        {
            base.AppendAdditionalMenuItems(menu);
            GH_DocumentObject.Menu_AppendSeparator(menu);
            GH_DocumentObject.Menu_AppendItem(menu, @"Save results to file.", (e, sender) =>
            {
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.FileName = "userDictionaries.csv";
                savefile.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";

                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter sw = new StreamWriter(savefile.FileName))
                        sw.WriteLine(csv);
                }
            });
            GH_DocumentObject.Menu_AppendSeparator(menu);
        }

        /// <summary>
        /// Registers all the input parameters for this component.
        /// </summary>
        protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager)
        {
            pManager.AddGenericParameter("User Data", "D", "User Dictionaries to export as CSV.", GH_ParamAccess.list);
        }

        /// <summary>
        /// Registers all the output parameters for this component.
        /// </summary>
        protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager)
        {
            pManager.AddTextParameter("CSV", "C", "CSV output", GH_ParamAccess.item);
        }

        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List<object> objs = new List<object>();
            DA.GetDataList(0, objs);
            if (objs.Count == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No dictionaries found.");
                return;
            }

            List<ArchivableDictionary> dictList = new List<ArchivableDictionary>();

            foreach (var obj in objs)
            {
                GH_ObjectWrapper goo = obj as GH_ObjectWrapper;
                if (goo == null)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Provided object not a dictionary.");
                    return;
                }
                ArchivableDictionary dict = goo.Value as ArchivableDictionary;
                if (dict == null)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Provided object not a dictionary.");
                    return;
                }

                dictList.Add(dict);
            }

            if (dictList.Count == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "No dictionaries found.");
                return;
            }

            HashSet<string> allProps = new HashSet<string>();
            List<string> rows = new List<string>();

            // construct headers
            foreach (var dict in dictList)
                allProps.UnionWith(getDictProps("", dict));

            rows.Add(String.Join(",", allProps.ToArray()));

            foreach (var dict in dictList)
            {
                List<string> row = new List<string>();
                foreach (string prop in allProps)
                    row.Add(tryGetProperty(prop, dict).ToString());
                rows.Add(String.Join(",", row));
            }

            csv = String.Join("\n", rows);
            DA.SetData(0, csv);
        }

        public List<string> getDictProps(string rootProp, ArchivableDictionary d)
        {
            List<string> props = new List<string>();

            foreach (var key in d.Keys)
            {
                if (d[key] is ArchivableDictionary)
                {
                    props.AddRange(getDictProps(rootProp + (rootProp == "" ? "" : ".") + key, d[key] as ArchivableDictionary));
                }
                else
                {
                    props.Add(rootProp + (rootProp == "" ? "" : ".") + key);
                }
            }

            return props;
        }

        public object tryGetProperty(string prop, ArchivableDictionary d)
        {
            List<string> props = prop.Split('.').ToList();

            if (props.Count == 0)
                return "error";

            if (!d.Keys.Contains(props.ElementAt(0)))
                return "null";

            if (props.Count > 1)
            {
                var key = props.ElementAt(0);
                props.RemoveAt(0);
                return tryGetProperty(String.Join(".", props), d[key] as ArchivableDictionary);
            }

            return d[props.ElementAt(0)];
        }

        /// <summary>
        /// Provides an Icon for the component.
        /// </summary>
        protected override System.Drawing.Bitmap Icon
        {
            get
            {
                return Properties.Resources.csv;
            }
        }

        /// <summary>
        /// Gets the unique ID for this component. Do not change this ID after release.
        /// </summary>
        public override Guid ComponentGuid
        {
            get { return new Guid("{6ec27144-e337-47b4-af22-d9934feaa365}"); }
        }
    }
}


text:
$(document).ready(function(){
  //window.localStorage.setItem('arduino', null);
});

/**
 * List of tab names.
 * @private
 */
var TABS_ = ['blocks', 'arduino', 'xml'];

var selected = 'blocks';

/**
 * Switch the visible pane when a tab is clicked.
 * @param {string} id ID of tab clicked.
 */
function tabClick(id) {
  // If the XML tab was open, save and render the content.
  // if (document.getElementById('tab_xml').className == 'tabon') {
  //   var xmlTextarea = document.getElementById('textarea_xml');
  //   var xmlText = xmlTextarea.value;
  //   var xmlDom = null;
  //   try {
  //     xmlDom = Blockly.Xml.textToDom(xmlText);
  //   } catch (e) {
  //     var q =
  //         window.confirm('Error parsing XML:\n' + e + '\n\nAbandon changes?');
  //     if (!q) {
  //       // Leave the user on the XML tab.
  //       return;
  //     }
  //   }
  //   if (xmlDom) {
  //     Blockly.mainWorkspace.clear();
  //     Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, xmlDom);
  //   }
  // }

  // // Deselect all tabs and hide all panes.
  // for (var x in TABS_) {
  //   document.getElementById('tab_' + TABS_[x]).className = 'taboff';
  //   document.getElementById('content_' + TABS_[x]).style.display = 'none';
  // }

  // // Select the active tab.
  // selected = id.replace('tab_', '');
  // document.getElementById(id).className = 'tabon';
  // // Show the selected pane.
  // var content = document.getElementById('content_' + selected);
  // content.style.display = 'block';
  renderContent();
}

/**
 * Populate the currently selected pane with content generated from the blocks.
 */
function renderContent() {
  var content = document.getElementById('content_' + selected);
  // Initialize the pane.
  if (content.id == 'content_blocks') {
    // If the workspace was changed by the XML tab, Firefox will have performed
    // an incomplete rendering due to Blockly being invisible.  Rerender.
    Blockly.mainWorkspace.render();
  } else if (content.id == 'content_xml') {
    var xmlTextarea = document.getElementById('textarea_xml');
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    xmlTextarea.value = xmlText;
    xmlTextarea.focus();
  /*} else if (content.id == 'content_javascript') {
    content.innerHTML = Blockly.Generator.workspaceToCode('JavaScript');
  } else if (content.id == 'content_dart') {
    content.innerHTML = Blockly.Generator.workspaceToCode('Dart');
  } else if (content.id == 'content_python') {
    content.innerHTML = Blockly.Generator.workspaceToCode('Python');*/
  } else if (content.id == 'content_arduino') {
    //content.innerHTML = Blockly.Generator.workspaceToCode('Arduino');

  }

  var arduinoTextarea = document.getElementById('textarea_arduino');
  arduinoTextarea.value = Blockly.Generator.workspaceToCode('Arduino');
  var xmlTextarea = document.getElementById('textarea_xml');
  var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
  var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
  xmlTextarea.value = xmlText;
    //arduinoTextarea.focus();
}

/**
 * Initialize Blockly.  Called on page load.
 * @param {!Blockly} blockly Instance of Blockly from iframe.
 */
function init(blockly) {
  window.onbeforeunload = function() {
   //return 'Leaving this page will result in the loss of your work.';
   //return 'Als je deze pagina verlaat, ben je al je werk kwijt en moet je weer opnieuw beginnen.';
  };

  window.Blockly = blockly;

  // var blockly_frame = document.getElementById("content_blocks");
  // Blockly.inject(blockly_frame, {path: '../../'});

  // Make the 'Blocks' tab line up with the toolbox.
  // if (Blockly.Toolbox) {
  //   window.setTimeout(function() {
  //       document.getElementById('tab_blocks').style.minWidth =
  //           (Blockly.Toolbox.width - 38) + 'px';
  //           // Account for the 19 pixel margin and on each side.
  //     }, 1);
  // }

  auto_save_and_restore_blocks();

  //load from url parameter (single param)
  //http://stackoverflow.com/questions/2090551/parse-query-string-in-javascript
  var dest = unescape(location.search.replace(/^.*\=/, '')).replace(/\+/g, " ");
  if(dest){
    load_by_url(dest);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CursoDesignPatterns
{
  class NotaFicalBuilder
  {
    public String RazaoSocial { get; private set; }
    public String Cnpj { get; private set; }
    public String Observacoes { get; private set; }
    public DateTime Data { get; private set; }

    private double valorTotal;
    private double Impostos;
    private IList<ItemDaNota> todosItens = new List<ItemDaNota>();

    private IList<AcaoAposGerarNota> todasAcoesASeremExecutadas = new List<AcaoAposGerarNota>;

    public NotaFical Constroi()
    {
      NotaFiscal nf = new NotaFiscal(RazaoSocial, Cnpj, Data, valorTotal, Impostos, todosItens, Observacoes);

      foreach(AcaoAposGerarNota acao in todasAcoesASeremExecutadas)
      {
        acao.Executa(nf);
      }

      return nf;
    }

    public void AdicionaAcao(AcaoAposGerarNota novaAcao)
    {
      this.todasAcoesASeremExecutadas.Add(novaAcao);
    }

    public NotaFiscalBuilder ParaEmpresa(String razaoSocial)
    {
      this.RazaoSocial = razaoSocial;
      return this;
    }

    public NotaFiscalBuilder ComCnpj(String cnpj)
    {
      this.Cnpj = cnpj;
      return this;
    }

    public NotaFiscalBuilder NaDataAtual()
    {
      this.Data = DateTime.now;
      return this;
    }

    public NotaFiscalBuilder ComObservacoes(String observacoes)
    {
      this.Observacoes = observacoes;
      return this;
    }

    public NotaFiscalBuilder ComItem(ItemDaNota item)
    {
      todosItens.Add(item);
      valorTotal += item.Valor;
      impostos += item.Valor * 0.05;
      return this;
    }
  }
}


text:
@import Foundation;
#import "PUObject.h"

typedef NS_ENUM(short, BookingNotificationType) {
    Region = 0,
    Time,
    RegionTime
};

@interface PUBookingNotification : NSObject <PUObject>

@property (nonatomic, readonly) BookingNotificationType type;

@end


text:
module ActiveSupport
  module Dependencies
    alias_method(:load_missing_constant_classmeta_renamed, :load_missing_constant)
    undef_method(:load_missing_constant)
    def load_missing_constant(from_mod, const_name)
      #puts "Classmeta's load_missing_constant from_mod=#{from_mod} const_name=#{const_name}"
      klazz = Classmeta::ClassRegistry.get(const_name) || load_missing_constant_classmeta_renamed(from_mod, const_name)
      klazz.class_eval('extend Classmeta::ClassMethods')
    end
  end
end


text:
package nuclei.persistence.intent;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import nuclei.persistence.apt.AptProcessor;

public class IntentBinding {

    final Element element;
    final String name;
    final String fullName;
    final String packageName;
    final List<IntentProperty> properties;
    final Map<String, String> attributes;

    public IntentBinding(Element element, ProcessingEnvironment environment) {
        if (!(element instanceof TypeElement))
            throw new IllegalArgumentException("TypeElement required");
        attributes = new HashMap<>();

        for (AnnotationMirror m : environment.getElementUtils().getAllAnnotationMirrors(element)) {
            Element a = m.getAnnotationType().asElement();
            if (a instanceof TypeElement) {
                if (((TypeElement) a).getQualifiedName().contentEquals(AptProcessor.BINDING)) {
                    for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> e : m.getElementValues().entrySet()) {
                        if (e.getValue() != null && e.getValue().getValue() != null)
                            attributes.put(e.getKey().getSimpleName().toString(), e.getValue().getValue().toString());
                    }
                    break;
                }
            }
        }

        String fullName = environment.getElementUtils().getBinaryName((TypeElement) element).toString();
        this.fullName = fullName.replace('$', '.');

        int ix = fullName.lastIndexOf('.');
        if (ix == -1) {
            this.name = fullName.replace('$', '_');
            this.packageName = null;
        } else {
            this.name = fullName.substring(ix + 1, fullName.length()).replace('$', '_');
            this.packageName = fullName.substring(0, ix);
        }
        this.element = element;
        this.properties = new ArrayList<>();
        for (Element child : element.getEnclosedElements()) {
            for (AnnotationMirror mirror : child.getAnnotationMirrors()) {
                Element a = mirror.getAnnotationType().asElement();
                if (a instanceof TypeElement) {
                    if (((TypeElement) a).getQualifiedName().contentEquals(AptProcessor.BINDINGPROPERTY)) {
                        properties.add(new IntentProperty(child, environment));
                    }
                }
            }
        }
    }

    public Map<String, String> getAttributes() {
        return attributes;
    }

    public Element getElement() {
        return element;
    }

    public String getName() {
        return name;
    }

    public String getFullName() {
        return fullName;
    }

    public String getPackageName() {
        return packageName;
    }

    public List<IntentProperty> getProperties() {
        return properties;
    }
}


text:
<?php

namespace CommerceGuys\AuthNet;

use GuzzleHttp\Client;

/**
 * @method CreateTransactionRequest createTransactionRequest()
 */
class RequestFactory
{
    /**
     * @var \CommerceGuys\AuthNet\Configuration
     */
    protected $configuration;

    /**
     * @var \GuzzleHttp\Client
     */
    protected $client;

    /**
     * BaseRequest constructor.
     *
     * @param \CommerceGuys\AuthNet\Configuration $configuration
     * @param \GuzzleHttp\Client $client
     */
    public function __construct(Configuration $configuration, Client $client)
    {
        $this->configuration = $configuration;
        $this->client = $client;
    }

    public function __call($name, $args = null)
    {

        $class = '\\' . (new \ReflectionClass($this))->getNamespaceName() . '\\' . ucfirst($name);
        if (!class_exists($class)) {
            throw new \InvalidArgumentException("Request $name does not exist");
        }

        if (!(new \ReflectionClass($class))->implementsInterface(ApiRequestInterface::class)) {
            throw new \InvalidArgumentException("Request $name is not a valid request");
        }

        $instance = new $class($this->configuration, $this->client);

        return $instance;
    }
}


text:
//
//  MPFeatureDetector.m
//  MoPub
//
//  Copyright (c) 2013 MoPub. All rights reserved.
//

#import "MPStoreKitProvider.h"
#import "MPGlobal.h"

#import <StoreKit/StoreKit.h>

/*
 * On iOS 7 and above, SKStoreProductViewController can cause a crash if the application does not list Portrait as a supported
 * interface orientation. Specifically, SKStoreProductViewController's shouldAutorotate returns YES, even though
 * the SKStoreProductViewController's supported interface orientations does not intersect with the application's list.
 *
 * To fix, we disallow autorotation so the SKStoreProductViewController will use its supported orientation on iOS 7 devices.
 */
@interface MPiOS7SafeStoreProductViewController : SKStoreProductViewController

@end

@implementation MPiOS7SafeStoreProductViewController

- (BOOL)shouldAutorotate
{
    return NO;
}

@end

@implementation MPStoreKitProvider

+ (BOOL)deviceHasStoreKit
{
    return !!NSClassFromString(@"SKStoreProductViewController");
}

+ (SKStoreProductViewController *)buildController
{
    // use our safe subclass on iOS 7 and above
    if ([[UIDevice currentDevice].systemVersion compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending) {
        return [[MPiOS7SafeStoreProductViewController alloc] init];
    } else {
        return [[SKStoreProductViewController alloc] init];
    }
}

@end


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe StatesController do

  it "index action should render index template" do
    request.env["HTTP_ACCEPT"] = "application/json"
    get :index, :country_id => 2
    assert_response :success
  end
end


text:
// @flow
/* global SETTINGS: false */
import React from "react"
import { connect } from "react-redux"
import { bindActionCreators } from "redux"

import ImageUploader, { makeDialogKey } from "./ImageUploader"

import { BannerContainer, BannerImage, Gradient } from "ol-util"

import { showDialog } from "../actions/ui"

import type { Dispatch } from "redux"
import type { Channel } from "../flow/discussionTypes"

type Props = {
  channel: Channel,
  editable?: boolean,
  formImageUrl?: ?string,
  showDialog?: () => any,
  name?: string,
  onUpdate?: (event: Object) => Promise<*>
}

const ChannelBanner = (props: Props) => {
  const { channel, editable, formImageUrl, showDialog, onUpdate, name } = props

  const imageUrl = formImageUrl || channel.banner

  return (
    <BannerContainer className="channel-banner">
      <BannerImage src={imageUrl} alt={`Channel banner for ${channel.name}`} />
      <Gradient />
      {editable ? (
        <React.Fragment>
          <ImageUploader
            name={name}
            showButton={false}
            onUpdate={onUpdate}
            isAdd={!imageUrl}
            description="Channel Banner"
            width={1150}
            height={200}
          />
          <a onClick={showDialog} className="upload-banner grey-surround">
            Upload cover image
          </a>
        </React.Fragment>
      ) : null}
    </BannerContainer>
  )
}

const mapDispatchToProps = (dispatch: Dispatch<*>, ownProps: Props) =>
  // $FlowFixMe
  bindActionCreators(
    {
      // $FlowFixMe
      showDialog: () => showDialog(makeDialogKey(ownProps.name))
    },
    dispatch
  )

export default connect<Props, Props, _, _, _, _>(
  null,
  mapDispatchToProps
)(ChannelBanner)


text:
<?php

namespace Symfony\Component\Finder\Tests\Comparator;

use Symfony\Component\Finder\Comparator\Comparator;

class ComparatorTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSetOperator()
    {
        $comparator = new Comparator();
        try {
            $comparator->setOperator( 'foo' );
            $this->fail( '->setOperator() throws an \InvalidArgumentException if the operator is not valid.' );
        } catch( \Exception $e ) {
            $this->assertInstanceOf( 'InvalidArgumentException', $e,
                '->setOperator() throws an \InvalidArgumentException if the operator is not valid.' );
        }

        $comparator = new Comparator();
        $comparator->setOperator( '>' );
        $this->assertEquals( '>', $comparator->getOperator(), '->getOperator() returns the current operator' );
    }

    public function testGetSetTarget()
    {
        $comparator = new Comparator();
        $comparator->setTarget( 8 );
        $this->assertEquals( 8, $comparator->getTarget(), '->getTarget() returns the target' );
    }

    /**
     * @dataProvider getTestData
     */
    public function testTest( $operator, $target, $match, $noMatch )
    {
        $c = new Comparator();
        $c->setOperator( $operator );
        $c->setTarget( $target );

        foreach ($match as $m) {
            $this->assertTrue( $c->test( $m ), '->test() tests a string against the expression' );
        }

        foreach ($noMatch as $m) {
            $this->assertFalse( $c->test( $m ), '->test() tests a string against the expression' );
        }
    }

    public function getTestData()
    {
        return array(
            array( '<', '1000', array( '500', '999' ), array( '1000', '1500' ) ),
        );
    }
}


text:
package org.elasticsearch.search.fetch.fielddata;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.index.fielddata.AtomicFieldData;
import org.elasticsearch.index.fielddata.ScriptDocValues;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.InternalSearchHit;
import org.elasticsearch.search.internal.InternalSearchHitField;
import org.elasticsearch.search.internal.SearchContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static java.util.Collections.unmodifiableMap;

/**
 * Query sub phase which pulls data from field data (using the cache if
 * available, building it if not).
 *
 * Specifying {@code "fielddata_fields": ["field1", "field2"]}
 */
public class FieldDataFieldsFetchSubPhase implements FetchSubPhase {

    public static final String[] NAMES = {"fielddata_fields", "fielddataFields"};
    public static final ContextFactory<FieldDataFieldsContext> CONTEXT_FACTORY = new ContextFactory<FieldDataFieldsContext>() {

        @Override
        public String getName() {
            return NAMES[0];
        }

        @Override
        public FieldDataFieldsContext newContextInstance() {
            return new FieldDataFieldsContext();
        }
    };

    @Inject
    public FieldDataFieldsFetchSubPhase() {
    }

    @Override
    public Map<String, ? extends SearchParseElement> parseElements() {
        Map<String, SearchParseElement> parseElements = new HashMap<>();
        parseElements.put("fielddata_fields", new FieldDataFieldsParseElement());
        parseElements.put("fielddataFields", new FieldDataFieldsParseElement());
        return unmodifiableMap(parseElements);
    }

    @Override
    public boolean hitsExecutionNeeded(SearchContext context) {
        return false;
    }

    @Override
    public void hitsExecute(SearchContext context, InternalSearchHit[] hits) {
    }

    @Override
    public boolean hitExecutionNeeded(SearchContext context) {
        return context.getFetchSubPhaseContext(CONTEXT_FACTORY).hitExecutionNeeded();
    }

    @Override
    public void hitExecute(SearchContext context, HitContext hitContext) {
        for (FieldDataFieldsContext.FieldDataField field : context.getFetchSubPhaseContext(CONTEXT_FACTORY).fields()) {
            if (hitContext.hit().fieldsOrNull() == null) {
                hitContext.hit().fields(new HashMap<String, SearchHitField>(2));
            }
            SearchHitField hitField = hitContext.hit().fields().get(field.name());
            if (hitField == null) {
                hitField = new InternalSearchHitField(field.name(), new ArrayList<>(2));
                hitContext.hit().fields().put(field.name(), hitField);
            }
            MappedFieldType fieldType = context.mapperService().fullName(field.name());
            if (fieldType != null) {
                AtomicFieldData data = context.fieldData().getForField(fieldType).load(hitContext.readerContext());
                ScriptDocValues values = data.getScriptValues();
                values.setNextDocId(hitContext.docId());
                hitField.values().addAll(values.getValues());
            }
        }
    }
}


text:
require 'network_drawer'
require 'thor'

module NetworkDrawer
  # Cli for NetworkDrawer
  class Cli < Thor
    desc 'draw SOURCE', 'draw network diagram with SOURCE file'
    option(:style, aliases: :s,
                   banner: 'STYLE_FILE_IN_JSON')
    option(:layout, aliases: :l,
                    banner: 'GRAPHVIZ LAYOUT such as dot fdp ..')
    option(:format, aliases: :f,
                    banner: 'OUTPUT_FILE_FORMAT such as svg, png',
                    default: :svg)
    def draw(source_file)
      src = Source.read(source_file)
      op = {}
      op = { style: Source.read(options[:style]) } if options[:style]
      op.merge!(layout: options[:layout])
      op.merge!(format: options[:format])
      dest_file = source_file.gsub(File.extname(source_file), '')
      Diagram.draw(src, dest_file, op)
    end
  end
end


text:
"""
Instana WSGI Middleware
"""
import opentracing as ot
import opentracing.ext.tags as tags

from ..singletons import agent, tracer
from ..util.secrets import strip_secrets_from_query

class InstanaWSGIMiddleware(object):
    """ Instana WSGI middleware """

    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        env = environ

        def new_start_response(status, headers, exc_info=None):
            """Modified start response with additional headers."""
            tracer.inject(self.scope.span.context, ot.Format.HTTP_HEADERS, headers)
            headers.append(('Server-Timing', "intid;desc=%s" % self.scope.span.context.trace_id))

            res = start_response(status, headers, exc_info)

            sc = status.split(' ')[0]
            if 500 <= int(sc) <= 511:
                self.scope.span.mark_as_errored()

            self.scope.span.set_tag(tags.HTTP_STATUS_CODE, sc)
            self.scope.close()
            return res

        ctx = tracer.extract(ot.Format.HTTP_HEADERS, env)
        self.scope = tracer.start_active_span("wsgi", child_of=ctx)

        if agent.options.extra_http_headers is not None:
            for custom_header in agent.options.extra_http_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                wsgi_header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if wsgi_header in env:
                    self.scope.span.set_tag("http.header.%s" % custom_header, env[wsgi_header])

        if 'PATH_INFO' in env:
            self.scope.span.set_tag('http.path', env['PATH_INFO'])
        if 'QUERY_STRING' in env and len(env['QUERY_STRING']):
            scrubbed_params = strip_secrets_from_query(env['QUERY_STRING'], agent.options.secrets_matcher,
                                                       agent.options.secrets_list)
            self.scope.span.set_tag("http.params", scrubbed_params)
        if 'REQUEST_METHOD' in env:
            self.scope.span.set_tag(tags.HTTP_METHOD, env['REQUEST_METHOD'])
        if 'HTTP_HOST' in env:
            self.scope.span.set_tag("http.host", env['HTTP_HOST'])

        return self.app(environ, new_start_response)


text:
using System.IO;

namespace WGSharpAPITests
{
    public static class TestHelper
    {
        public static string LoadJson(string filename)
        {
            var jsonResponse = string.Empty;
            using (var fileStream = File.OpenRead(filename))
            {
                jsonResponse = File.ReadAllText(filename);
            }
            return jsonResponse;
        }
    }
}


text:
function J = vl_imarraysc(A, varargin)
% VL_IMARRAYSC  Scale and flattens image array
%   J=VL_IMARRAYSC(A) constructs an image mosaic similar to
%   J=VL_IMARRAY(A), but it rescales the range of each image in the
%   array. If A is an array of grayscale images, J will index all the
%   colors in the current colormap; if A is a true color image, J will
%   span the range [0,1].
%
%   If A is of an integer class, J will be of class single SINGLE class.
%
%   VL_IMARRAYSC(...) displays the image J rather than returning it.
%
%   VL_IMARRAYSC() accepts the options of VL_IMARRAY() and:
%
%   CLim:: []
%     Rescale the specified range of values rather than the actual
%     range of each image.
%
%   Uniform:: [false]
%     Rescale the range of all the images together, rather than on
%     an image-by-image basis.
%
%   CMap:: []
%     Use the specified color map as a reference rather than the
%     current or default one.
%
%   Algorithm::
%     CLim is seet to the image range [m, M], where m is the minimum
%     value of an image and M is the maximum. The image range CLim is
%     then affinely mapped to the integers from 1 to C, where C is the
%     number of colors in the colormap, or to the range [0,1] for true
%     color images. The mapping is done so that the first color is
%     assigned the first subinterval of length C of the range [m,M]
%     and so on.
%
%   See also: VL_IMARRAY(), VL_HELP(), IMAGE().

% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).

opts.clim = [] ;
opts.cmap = colormap ;
opts.uniform = false ;
[opts, varargin] = vl_argparse(opts, varargin) ;

numDimensions = ndims(A)  ;
if numDimensions <= 3
  numChannels = 1 ;
  numImages = size(A,3) ;
  numLevels = size(opts.cmap,1) ;
elseif numDimensions == 4
  numChannels = size(A,3) ;
  numImages = size(A,4) ;
  numLevels = 1 ;
  if numChannels ~= 3
    error('A has more than three dimensions and the third one is not equal to three.') ;
  end
else
  error('A has neither 2, 3 or 4 dimensions.') ;
end

if opts.uniform & ~isempty(opts.clim)
  error('UNIFORM cannot be used in combination with CLIM.') ;
end

if isinteger(A)
  A = single(A) ;
end

if opts.uniform && numDimensions < 4
  opts.clim = [min(A(:)) max(A(:))] ;
end

for k = 1:numImages
  if isempty(opts.clim)
    if numChannels == 1
      tmp = A(:,:,k) ;
    else
      tmp = A(:,:,:,k) ;
    end
    dataMin = min(tmp(:)) ;
    dataMax = max(tmp(:)) ;
  else
    dataMin = opts.clim(1) ;
    dataMax = opts.clim(2) ;
  end
  a = numLevels  / (dataMax - dataMin + eps) ;
  b = - dataMin * a ;
  if numChannels == 1
    A(:,:,k) = max(min(floor(a * A(:,:,k) + b + 1),numLevels),1) ;
  else
    A(:,:,:,k) = max(min(a * A(:,:,:,k) + b,numLevels),0) ;
  end
end

if nargout == 0
  vl_imarray(A,varargin{:}, 'cmap', opts.cmap) ;
else
  J = vl_imarray(A,varargin{:}, 'cmap', opts.cmap) ;
end


text:
describe 'list of contributors in README', chdir: false do
  let(:contributors_in_readme) do
    File.readlines('README.md').last.chomp("\n").split(', ')
  end

  let(:contributors_in_release_notes) do
    File.read('NEWS.md').scan(/\[[^\]]+\]$/).map { |s| s[1..-2].split(', ') }.flatten
  end

  it 'should include everyone mentioned in NEWS.md' do
    diff = (contributors_in_release_notes - contributors_in_readme).uniq.sort
    expect(diff).to be_empty, "some contributors are missing from the README: #{diff.join(', ')}"
  end

  it 'should be sorted' do
    expect(contributors_in_readme).to be_humanly_sorted
  end
end


text:
// Compiled by ClojureScript 1.9.542 {}
goog.provide('uikit_hl.offcanvas');
goog.require('cljs.core');
goog.require('cljsjs.uikit');
goog.require('hoplon.core');
goog.require('uikit_hl.core');
uikit_hl.offcanvas._STAR_uk_offcanvas_STAR_ = "";
cljs.core._add_method.call(null,hoplon.core.do_BANG_,new cljs.core.Keyword(null,"uk-offcanvas","uk-offcanvas",97881009),(function (elem,_,v){
return UIkit.offcanvas(elem,cljs.core.clj__GT_js.call(null,v));
}));
/**
 * @param {...*} var_args
 */
uikit_hl.offcanvas.content = (function() {
var uikit_hl$offcanvas$content__delegate = function (args__9094__auto__){
var vec__10087 = hoplon.core.parse_args.call(null,args__9094__auto__);
var attr = cljs.core.nth.call(null,vec__10087,(0),null);
var kids = cljs.core.nth.call(null,vec__10087,(1),null);
return hoplon.core.div.call(null,uikit_hl.core.assoc_class.call(null,attr,new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"uk-offcanvas-content","uk-offcanvas-content",-796821258),true], null)),kids);
};
var uikit_hl$offcanvas$content = function (var_args){
var args__9094__auto__ = null;
if (arguments.length > 0) {
var G__10090__i = 0, G__10090__a = new Array(arguments.length -  0);
while (G__10090__i < G__10090__a.length) {G__10090__a[G__10090__i] = arguments[G__10090__i + 0]; ++G__10090__i;}
  args__9094__auto__ = new cljs.core.IndexedSeq(G__10090__a,0,null);
}
return uikit_hl$offcanvas$content__delegate.call(this,args__9094__auto__);};
uikit_hl$offcanvas$content.cljs$lang$maxFixedArity = 0;
uikit_hl$offcanvas$content.cljs$lang$applyTo = (function (arglist__10091){
var args__9094__auto__ = cljs.core.seq(arglist__10091);
return uikit_hl$offcanvas$content__delegate(args__9094__auto__);
});
uikit_hl$offcanvas$content.cljs$core$IFn$_invoke$arity$variadic = uikit_hl$offcanvas$content__delegate;
return uikit_hl$offcanvas$content;
})()
;
/**
 * @param {...*} var_args
 */
uikit_hl.offcanvas.offcanvas = (function() {
var uikit_hl$offcanvas$offcanvas__delegate = function (args__9094__auto__){
var vec__10095 = hoplon.core.parse_args.call(null,args__9094__auto__);
var attr = cljs.core.nth.call(null,vec__10095,(0),null);
var kids = cljs.core.nth.call(null,vec__10095,(1),null);
var offcanvas = new cljs.core.Keyword(null,"uk-offcanvas","uk-offcanvas",97881009).cljs$core$IFn$_invoke$arity$2(attr,uikit_hl.offcanvas._STAR_uk_offcanvas_STAR_);
var attr__$1 = cljs.core.assoc.call(null,attr,new cljs.core.Keyword(null,"uk-offcanvas","uk-offcanvas",97881009),offcanvas);
return hoplon.core.div.call(null,attr__$1,kids);
};
var uikit_hl$offcanvas$offcanvas = function (var_args){
var args__9094__auto__ = null;
if (arguments.length > 0) {
var G__10098__i = 0, G__10098__a = new Array(arguments.length -  0);
while (G__10098__i < G__10098__a.length) {G__10098__a[G__10098__i] = arguments[G__10098__i + 0]; ++G__10098__i;}
  args__9094__auto__ = new cljs.core.IndexedSeq(G__10098__a,0,null);
}
return uikit_hl$offcanvas$offcanvas__delegate.call(this,args__9094__auto__);};
uikit_hl$offcanvas$offcanvas.cljs$lang$maxFixedArity = 0;
uikit_hl$offcanvas$offcanvas.cljs$lang$applyTo = (function (arglist__10099){
var args__9094__auto__ = cljs.core.seq(arglist__10099);
return uikit_hl$offcanvas$offcanvas__delegate(args__9094__auto__);
});
uikit_hl$offcanvas$offcanvas.cljs$core$IFn$_invoke$arity$variadic = uikit_hl$offcanvas$offcanvas__delegate;
return uikit_hl$offcanvas$offcanvas;
})()
;

//# sourceMappingURL=offcanvas.js.map


text:
namespace MetaMorpheusGUI
{
    internal class GuiGlobalParams
    {
        public bool AskAboutUpdating { get; internal set; }
    }
}


text:
var loopback = require('loopback');
var boot = require('loopback-boot');
var path = require('path');

var app = module.exports = loopback();

app.use(loopback.static(path.resolve(__dirname, '../client/')));
app.use(loopback.context());
app.use(loopback.token({model: app.models.accessToken}));

app.use(function setCurrentUser(req, res, next) {
    if (!req.accessToken) {
        return next();
    }
    app.models.User.findById(req.accessToken.userId, function (err, user) {
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(new Error('No user with this access token was found.'));
        }

        var loopbackContext = loopback.getCurrentContext();
        if (loopbackContext) {
            loopbackContext.set('currentUser', user);
        }
        next();
    });
});

app.start = function () {
    // start the web server
    return app.listen(function () {
        app.emit('started');
        console.log('Web server listening at: %s', app.get('url'));
    });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function (err) {
    if (err)
        throw err;

    // start the server if `$ node server.js`
    if (require.main === module)
        app.start();
});