text:
/*
 * make.c - bring a target up to date, once rules are in place
 *
 * This modules controls the execution of rules to bring a target and
 * its dependencies up to date.  It is invoked after the targets, rules,
 * et. al. described in rules.h are created by the interpreting of the
 * jam files.
 *
 * This file contains the main make() entry point and the first pass
 * make0().  The second pass, make1(), which actually does the command
 * execution, is in make1.c.
 *
 * External routines:
 *	make() - make a target, given its name
 *
 * Internal routines:
 * 	make0() - bind and scan everything to make a TARGET
 * 	make0sort() - reorder TARGETS chain by their time (newest to oldest)
 *
 * 12/26/93 (seiwald) - allow NOTIME targets to be expanded via $(<), $(>)
 * 01/04/94 (seiwald) - print all targets, bounded, when tracing commands
 * 04/08/94 (seiwald) - progress report now reflects only targets with actions
 * 04/11/94 (seiwald) - Combined deps & headers into deps[2] in TARGET.
 * 12/20/94 (seiwald) - NOTIME renamed NOTFILE.
 * 12/20/94 (seiwald) - make0() headers after determining fate of target, so
 *			that headers aren't seen as dependents on themselves.
 * 01/19/95 (seiwald) - distinguish between CANTFIND/CANTMAKE targets.
 * 02/02/95 (seiwald) - propagate leaf source time for new LEAVES rule.
 * 02/14/95 (seiwald) - NOUPDATE rule means don't update existing target.
 * 08/22/95 (seiwald) - NOUPDATE targets immune to anyhow (-a) flag.
 * 09/06/00 (seiwald) - NOCARE affects targets with sources/actions.
 * 03/02/01 (seiwald) - reverse NOCARE change.
 * 03/14/02 (seiwald) - TEMPORARY targets no longer take on parents age
 * 03/16/02 (seiwald) - support for -g (reorder builds by source time)
 * 07/17/02 (seiwald) - TEMPORARY sources for headers now get built
 * 09/19/02 (seiwald) - new -d displays
 * 09/23/02 (seiwald) - suppress "...using temp..." in default output
 * 09/28/02 (seiwald) - make0() takes parent pointer; new -dc display
 * 11/04/02 (seiwald) - const-ing for string literals
 * 12/03/02 (seiwald) - fix odd includes support by grafting them onto depends
 * 12/17/02 (seiwald) - new copysettings() to protect target-specific vars
 * 01/03/03 (seiwald) - T_FATE_NEWER once again gets set with missing parent
 * 01/14/03 (seiwald) - fix includes fix with new internal includes TARGET
 * 04/04/03 (seiwald) - fix INTERNAL node binding to avoid T_BIND_PARENTS
 */

# include "jam.h"

# include "lists.h"
# include "parse.h"
# include "variable.h"
# include "rules.h"

# include "search.h"
# include "newstr.h"
# include "make.h"
# include "headers.h"
# include "command.h"

# ifndef max
# define max( a,b ) ((a)>(b)?(a):(b))
# endif

typedef struct {
	int	temp;
	int	updating;
	int	cantfind;
	int	cantmake;
	int	targets;
	int	made;
} COUNTS ;

static void make0( TARGET *t, TARGET *p, int depth,
		COUNTS *counts, int anyhow );

static TARGETS *make0sort( TARGETS *c );

static const char *target_fate[] =
{
	"init",		/* T_FATE_INIT */
	"making", 	/* T_FATE_MAKING */
	"stable", 	/* T_FATE_STABLE */
	"newer",	/* T_FATE_NEWER */
	"temp", 	/* T_FATE_ISTMP */
	"touched", 	/* T_FATE_TOUCHED */
	"missing", 	/* T_FATE_MISSING */
	"needtmp", 	/* T_FATE_NEEDTMP */
	"old", 		/* T_FATE_OUTDATED */
	"update", 	/* T_FATE_UPDATE */
	"nofind", 	/* T_FATE_CANTFIND */
	"nomake" 	/* T_FATE_CANTMAKE */
} ;

static const char *target_bind[] =
{
	"unbound",
	"missing",
	"parents",
	"exists",
} ;

# define spaces(x) ( "                " + 16 - ( x > 16 ? 16 : x ) )

/*
 * make() - make a target, given its name
 */

int
make(
	int		n_targets,
	const char	**targets,
	int		anyhow )
{
	int i;
	COUNTS counts[1];
	int status = 0;		/* 1 if anything fails */

	memset( (char *)counts, 0, sizeof( *counts ) );

	for( i = 0; i < n_targets; i++ )
	{
	    TARGET *t = bindtarget( targets[i] );

	    make0( t, 0, 0, counts, anyhow );
	}

	if( DEBUG_MAKE )
	{
	    if( counts->targets )
		printf( "...found %d target(s)...\n", counts->targets );
	    if( counts->temp )
		printf( "...using %d temp target(s)...\n", counts->temp );
	    if( counts->updating )
		printf( "...updating %d target(s)...\n", counts->updating );
	    if( counts->cantfind )
		printf( "...can't find %d target(s)...\n", counts->cantfind );
	    if( counts->cantmake )
		printf( "...can't make %d target(s)...\n", counts->cantmake );
	}

	status = counts->cantfind || counts->cantmake;

	for( i = 0; i < n_targets; i++ )
	    status |= make1( bindtarget( targets[i] ) );

	return status;
}

/*
 * make0() - bind and scan everything to make a TARGET
 *
 * Make0() recursively binds a target, searches for #included headers,
 * calls itself on those headers, and calls itself on any dependents.
 */

static void
make0(
	TARGET	*t,
	TARGET  *p,		/* parent */
	int	depth,		/* for display purposes */
	COUNTS	*counts,	/* for reporting */
	int	anyhow )	/* forcibly touch all (real) targets */
{
	TARGETS	*c, *d, *incs;
	TARGET 	*ptime = t;
	time_t	last, leaf, hlast;
	int	fate;
	const char *flag = "";
	SETTINGS *s;

	/*
	 * Step 1: initialize
	 */

	if( DEBUG_MAKEPROG )
	    printf( "make\t--\t%s%s\n", spaces( depth ), t->name );

	t->fate = T_FATE_MAKING;

	/*
	 * Step 2: under the influence of "on target" variables,
	 * bind the target and search for headers.
	 */

	/* Step 2a: set "on target" variables. */

	s = copysettings( t->settings );
	pushsettings( s );

	/* Step 2b: find and timestamp the target file (if it's a file). */

	if( t->binding == T_BIND_UNBOUND && !( t->flags & T_FLAG_NOTFILE ) )
	{
	    t->boundname = search( t->name, &t->time );
	    t->binding = t->time ? T_BIND_EXISTS : T_BIND_MISSING;
	}

	/* INTERNAL, NOTFILE header nodes have the time of their parents */

	if( p && t->flags & T_FLAG_INTERNAL )
	    ptime = p;

	/* If temp file doesn't exist but parent does, use parent */

	if( p && t->flags & T_FLAG_TEMP &&
	    t->binding == T_BIND_MISSING &&
	    p->binding != T_BIND_MISSING )
	{
	    t->binding = T_BIND_PARENTS;
	    ptime = p;
	}

	/* Step 2c: If its a file, search for headers. */

	if( t->binding == T_BIND_EXISTS )
	    headers( t );

	/* Step 2d: reset "on target" variables */

	popsettings( s );
	freesettings( s );

	/*
	 * Pause for a little progress reporting
	 */

	if( DEBUG_MAKEPROG )
	{
	    if( strcmp( t->name, t->boundname ) )
	    {
		printf( "bind\t--\t%s%s: %s\n",
			spaces( depth ), t->name, t->boundname );
	    }

	    switch( t->binding )
	    {
	    case T_BIND_UNBOUND:
	    case T_BIND_MISSING:
	    case T_BIND_PARENTS:
		printf( "time\t--\t%s%s: %s\n",
			spaces( depth ), t->name, target_bind[ t->binding ] );
		break;

	    case T_BIND_EXISTS:
		printf( "time\t--\t%s%s: %s",
			spaces( depth ), t->name, ctime( &t->time ) );
		break;
	    }
	}

	/*
	 * Step 3: recursively make0() dependents & headers
	 */

	/* Step 3a: recursively make0() dependents */

	for( c = t->depends; c; c = c->next )
	{
	    int internal = t->flags & T_FLAG_INTERNAL;

	    if( DEBUG_DEPENDS )
		printf( "%s \"%s\" : \"%s\" ;\n",
		    internal ? "Includes" : "Depends",
		    t->name, c->target->name );

	    /* Warn about circular deps, except for includes, */
	    /* which include each other alot. */

	    if( c->target->fate == T_FATE_INIT )
		make0( c->target, ptime, depth + 1, counts, anyhow );
	    else if( c->target->fate == T_FATE_MAKING && !internal )
		printf( "warning: %s depends on itself\n", c->target->name );
	}

	/* Step 3b: recursively make0() internal includes node */

	if( t->includes )
	    make0( t->includes, p, depth + 1, counts, anyhow );

	/* Step 3c: add dependents' includes to our direct dependencies */

	incs = 0;

	for( c = t->depends; c; c = c->next )
	    if( c->target->includes )
		incs = targetentry( incs, c->target->includes );

	t->depends = targetchain( t->depends, incs );

	/*
	 * Step 4: compute time & fate
	 */

	/* Step 4a: pick up dependents' time and fate */

	last = 0;
	leaf = 0;
	fate = T_FATE_STABLE;

	for( c = t->depends; c; c = c->next )
	{
	    /* If LEAVES has been applied, we only heed the timestamps of */
	    /* the leaf source nodes. */

	    leaf = max( leaf, c->target->leaf );

	    if( t->flags & T_FLAG_LEAVES )
	    {
		last = leaf;
		continue;
	    }

	    last = max( last, c->target->time );
	    fate = max( fate, c->target->fate );
	}

	/* Step 4b: pick up included headers time */

	/*
	 * If a header is newer than a temp source that includes it,
	 * the temp source will need building.
	 */

	hlast = t->includes ? t->includes->time : 0;

	/* Step 4c: handle NOUPDATE oddity */

	/*
	 * If a NOUPDATE file exists, make dependents eternally old.
	 * Don't inherit our fate from our dependents.  Decide fate
	 * based only upon other flags and our binding (done later).
	 */

	if( t->flags & T_FLAG_NOUPDATE )
	{
	    last = 0;
	    t->time = 0;
	    fate = T_FATE_STABLE;
	}

	/* Step 4d: determine fate: rebuild target or what? */

	/*
	    In English:
		If can't find or make child, can't make target.
		If children changed, make target.
		If target missing, make it.
		If children newer, make target.
		If temp's children newer than parent, make temp.
		If temp's headers newer than parent, make temp.
		If deliberately touched, make it.
		If up-to-date temp file present, use it.
		If target newer than non-notfile parent, mark target newer.
		Otherwise, stable!

		Note this block runs from least to most stable:
		as we make it further down the list, the target's
		fate is getting stabler.
	*/

	if( fate >= T_FATE_BROKEN )
	{
	    fate = T_FATE_CANTMAKE;
	}
	else if( fate >= T_FATE_SPOIL )
	{
	    fate = T_FATE_UPDATE;
	}
	else if( t->binding == T_BIND_MISSING )
	{
	    fate = T_FATE_MISSING;
	}
	else if( t->binding == T_BIND_EXISTS && last > t->time )
	{
	    fate = T_FATE_OUTDATED;
	}
	else if( t->binding == T_BIND_PARENTS && last > p->time )
	{
	    fate = T_FATE_NEEDTMP;
	}
	else if( t->binding == T_BIND_PARENTS && hlast > p->time )
	{
	    fate = T_FATE_NEEDTMP;
	}
	else if( t->flags & T_FLAG_TOUCHED )
	{
	    fate = T_FATE_TOUCHED;
	}
	else if( anyhow && !( t->flags & T_FLAG_NOUPDATE ) )
	{
	    fate = T_FATE_TOUCHED;
	}
	else if( t->binding == T_BIND_EXISTS && t->flags & T_FLAG_TEMP )
	{
	    fate = T_FATE_ISTMP;
	}
	else if( t->binding == T_BIND_EXISTS && p &&
		 p->binding != T_BIND_UNBOUND && t->time > p->time )
	{
	    fate = T_FATE_NEWER;
	}
	else
	{
	    fate = T_FATE_STABLE;
	}

	/* Step 4e: handle missing files */
	/* If it's missing and there are no actions to create it, boom. */
	/* If we can't make a target we don't care about, 'sokay */
	/* We could insist that there are updating actions for all missing */
	/* files, but if they have dependents we just pretend it's NOTFILE. */

	if( fate == T_FATE_MISSING && !t->actions && !t->depends )
	{
	    if( t->flags & T_FLAG_NOCARE )
	    {
		fate = T_FATE_STABLE;
	    }
	    else
	    {
		printf( "don't know how to make %s\n", t->name );

		fate = T_FATE_CANTFIND;
	    }
	}

	/* Step 4f: propagate dependents' time & fate. */
	/* Set leaf time to be our time only if this is a leaf. */

	t->time = max( t->time, last );
	t->leaf = leaf ? leaf : t->time ;
	t->fate = fate;

	/*
	 * Step 5: sort dependents by their update time.
	 */

	if( globs.newestfirst )
	    t->depends = make0sort( t->depends );

	/*
	 * Step 6: a little harmless tabulating for tracing purposes
	 */

	/* Don't count or report interal includes nodes. */

	if( t->flags & T_FLAG_INTERNAL )
	    return;

	if( !( ++counts->targets % 1000 ) && DEBUG_MAKE )
	    printf( "...patience...\n" );

	if( fate == T_FATE_ISTMP )
	    counts->temp++;
	else if( fate == T_FATE_CANTFIND )
	    counts->cantfind++;
	else if( fate == T_FATE_CANTMAKE && t->actions )
	    counts->cantmake++;
	else if( fate >= T_FATE_BUILD && fate < T_FATE_BROKEN && t->actions )
	    counts->updating++;

	if( !( t->flags & T_FLAG_NOTFILE ) && fate >= T_FATE_SPOIL )
	    flag = "+";
	else if( t->binding == T_BIND_EXISTS && p && t->time > p->time )
	    flag = "*";

	if( DEBUG_MAKEPROG )
	    printf( "made%s\t%s\t%s%s\n",
		flag, target_fate[ t->fate ],
		spaces( depth ), t->name );

	if( DEBUG_CAUSES &&
	    t->fate >= T_FATE_NEWER &&
	    t->fate <= T_FATE_MISSING )
		printf( "%s %s\n", target_fate[ t->fate ], t->name );
}

/*
 * make0sort() - reorder TARGETS chain by their time (newest to oldest)
 */

static TARGETS *
make0sort( TARGETS *chain )
{
	TARGETS *result = 0;

	/* We walk chain, taking each item and inserting it on the */
	/* sorted result, with newest items at the front.  This involves */
	/* updating each TARGETS' c->next and c->tail.  Note that we */
	/* make c->tail a valid prev pointer for every entry.  Normally, */
	/* it is only valid at the head, where prev == tail.  Note also */
	/* that while tail is a loop, next ends at the end of the chain. */

	/* Walk current target list */

	while( chain )
	{
	    TARGETS *c = chain;
	    TARGETS *s = result;

	    chain = chain->next;

	    /* Find point s in result for c */

	    while( s && s->target->time > c->target->time )
		s = s->next;

	    /* Insert c in front of s (might be 0). */
	    /* Don't even think of deciphering this. */

	    c->next = s;			/* good even if s = 0 */
	    if( result == s ) result = c;	/* new head of chain? */
	    if( !s ) s = result;		/* wrap to ensure a next */
	    if( result != c ) s->tail->next = c; /* not head? be prev's next */
	    c->tail = s->tail;			/* take on next's prev */
	    s->tail = c;			/* make next's prev us */
	}

	return result;
}

redpajama_set_name: RedPajamaGithub


text:
package jsonstructure

import (
	"bytes"
	"encoding/json"

	"github.com/shopspring/decimal"
)

type shadowStructure JSONStructureDefinition
type shadowTypeDecl TypeDecl

func (structure *JSONStructureDefinition) UnmarshalJSON(data []byte) error {
	var shell map[string]interface{}
	var shadow shadowStructure

	reader := bytes.NewReader(data)
	decoder := json.NewDecoder(reader)
	decoder.UseNumber()
	err := decoder.Decode(&shell)
	if err != nil {
		return err
	}
	err = Compose(shell)
	if err != nil {
		return err
	}
	data, err = json.Marshal(shell)
	if err != nil {
		return err
	}
	err = json.Unmarshal(data, &shadow)
	if err != nil {
		return err
	}
	*structure = JSONStructureDefinition(shadow)
	return nil
}

func decToJSONNumber(dec *decimal.Decimal) *json.Number {
	val := dec.String()
	num := json.Number(val)
	return &num
}

func (td *TypeDecl) MarshalJSON() ([]byte, error) {
	var shadow *shadowTypeDecl
	if td.Pattern != nil {
		raw := td.Pattern.String()
		td.PatternRaw = &raw
	}
	if td.MultipleOf != nil {
		td.MultipleOfRaw = decToJSONNumber(td.MultipleOf)
	}
	if td.Minimum != nil {
		td.MinimumRaw = decToJSONNumber(td.Minimum)
	}
	if td.Maximum != nil {
		td.MaximumRaw = decToJSONNumber(td.Maximum)
	}
	if td.ExclusiveMinimum != nil {
		td.ExclusiveMinimumRaw = decToJSONNumber(td.ExclusiveMinimum)
	}
	if td.ExclusiveMaximum != nil {
		td.ExclusiveMaximumRaw = decToJSONNumber(td.ExclusiveMaximum)
	}
	shadow = (*shadowTypeDecl)(td)
	return json.Marshal(shadow)
}


text:
<?php

namespace Pingpong\Admin\Seeders;

use Illuminate\Database\Seeder;
use Pingpong\Trusty\Role;

class RolesTableSeeder extends Seeder
{
    public function run()
    {
        Role::create([
            'name' => 'Administrator',
            'slug' => 'admin',
        ]);

        Role::create([
            'name' => 'User',
            'slug' => 'user',
        ]);
    }
}


text:
from sqlalchemy import String, Column, MetaData, Table, select

""" Remove availability_zone column from services model and replace with
    aggregate based zone."""

def upgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    services = Table('services', meta, autoload=True)
    aggregates = Table('aggregates', meta, autoload=True)
    aggregate_metadata = Table('aggregate_metadata', meta, autoload=True)
    # migrate data
    record_list = list(services.select().execute())
    for rec in record_list:
        # Only need to migrate nova-compute availability_zones
        if rec['binary'] != 'nova-compute':
            continue
        # if zone doesn't exist create
        result = aggregate_metadata.select().where(
            aggregate_metadata.c.key == 'availability_zone').where(
            aggregate_metadata.c.value == rec['availability_zone']).execute()
        result = [r for r in result]
        if len(result) > 0:
            agg_id = result[0].aggregate_id
        else:
            agg = aggregates.insert()
            result = agg.execute({'name': rec['availability_zone']})
            agg_id = result.inserted_primary_key[0]
            row = aggregate_metadata.insert()
            row.execute({'created_at': rec['created_at'],
                        'updated_at': rec['updated_at'],
                        'deleted_at': rec['deleted_at'],
                        'deleted': rec['deleted'],
                        'key': 'availability_zone',
                        'value': rec['availability_zone'],
                        'aggregate_id': agg_id,
                        })
        # add host to zone
        agg_hosts = Table('aggregate_hosts', meta, autoload=True)
        num_hosts = agg_hosts.count().where(
            agg_hosts.c.host == rec['host']).where(
            agg_hosts.c.aggregate_id == agg_id).execute().scalar()
        if num_hosts == 0:
            agg_hosts.insert().execute({'host': rec['host'],
                                        'aggregate_id': agg_id})

    services.drop_column('availability_zone')

def downgrade(migrate_engine):
    meta = MetaData()
    meta.bind = migrate_engine

    services = Table('services', meta, autoload=True)
    aggregate_metadata = Table('aggregate_metadata', meta, autoload=True)
    agg_hosts = Table('aggregate_hosts', meta, autoload=True)
    availability_zone = Column('availability_zone', String(255),
            default='nova')
    services.create_column(availability_zone)

    # Migrate data back
    # NOTE(jhesketh): This needs to be done with individual inserts as multiple
    # results in an update sub-query do not work with MySQL. See bug/1207309.
    record_list = list(services.select().execute())
    for rec in record_list:
        # Only need to update nova-compute availability_zones
        if rec['binary'] != 'nova-compute':
            continue
        result = select([aggregate_metadata.c.value],
            from_obj=aggregate_metadata.join(
                agg_hosts,
                agg_hosts.c.aggregate_id == aggregate_metadata.c.aggregate_id
            )
        ).where(
            aggregate_metadata.c.key == 'availability_zone'
        ).where(
            agg_hosts.c.aggregate_id == aggregate_metadata.c.aggregate_id
        ).where(
            agg_hosts.c.host == rec['host']
        )

        services.update().values(
            availability_zone=list(result.execute())[0][0]
        ).where(
            services.c.id == rec['id']
        )


text:
package de.brockhaus.m2m.integration.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE })
public @interface XMLSerializer {

}


text:
import React from 'react'
import PropTypes from 'prop-types'
import { Menu, Icon, Popover, Input, Dropdown } from 'antd'
import styles from './Header.less'
import Menus from './Menu'

const SubMenu = Menu.SubMenu

function Header ({ user, logout, switchSider, siderFold, isNavbar, menuPopoverVisible, location, switchMenuPopover, navOpenKeys, changeOpenKeys, menu }) {
  let handleClickMenu = e => e.key === 'logout' && logout()
  const menusProps = {
    menu,
    siderFold: false,
    darkTheme: false,
    isNavbar,
    handleClickNavMenu: switchMenuPopover,
    location,
    navOpenKeys,
    changeOpenKeys,
  }

  const rightMenu = (<Menu mode="horizontal" onClick={handleClickMenu} style={{width: '200px'}}>
      <Menu.Item key="accountSetting" className="menuItem">帐号设置</Menu.Item>
      <Menu.Item key="preferenceSetting" className="menuItem">偏好设置</Menu.Item>
      <Menu.Divider></Menu.Divider>
      <Menu.Item key="update" className="menuItem" style={{clolr: '#3d8f5'}}>升级</Menu.Item>
      <Menu.Divider></Menu.Divider>
      <Menu.Item key="shortcut" className="menuItem">快捷键</Menu.Item>
      <Menu.Item key="donwload" className="menuItem">应用下载</Menu.Item>
      <Menu.Divider></Menu.Divider>
      <Menu.Item key="international" className="menuItem">切换至国际服务器</Menu.Item>
      <Menu.Divider></Menu.Divider>
      <Menu.Item key="logout" className="menuItem">退出</Menu.Item>
    </Menu>);
  return (

          <Icon type={siderFold ? 'menu-unfold' : 'menu-fold'} style={{color: '#CCC'}}/>

        个人项目
        <Input prefix={<Icon type="search" style={{fontSize: 14}}/>} placeholder="在个人项目中搜索" className={styles.searchInput}/>
        <Icon type="plus-circle" className={styles.plusIcon}/>

          <Icon type="question-circle-o" className={styles.question} />

          我的

          日历

          <Icon type="bell" className={styles.message} />

          <Icon type="solution" className={styles.message} />

        <Dropdown overlay={rightMenu} trigger={['click']}>

        </Dropdown>

  )
}

Header.propTypes = {
  menu: PropTypes.array,
  user: PropTypes.object,
  logout: PropTypes.func,
  switchSider: PropTypes.func,
  siderFold: PropTypes.bool,
  isNavbar: PropTypes.bool,
  menuPopoverVisible: PropTypes.bool,
  location: PropTypes.object,
  switchMenuPopover: PropTypes.func,
  navOpenKeys: PropTypes.array,
  changeOpenKeys: PropTypes.func,
}

export default Header


text:
<?php

use Zend\ServiceManager\Config as ServiceConfig;
use Zend\ServiceManager\ServiceManager;

use QBonaventure\InnerCryptography\Service as CryptographyService;
use Zend\Config\Config;
use Application\Model\Database\ServiceInterface as DatabaseInterface;
use Application\Model\Database\AdapterFactory;

// Load configuration
$config = require __DIR__.'/config.php';

// Build container
$container = new ServiceManager();
(new ServiceConfig($config['dependencies']))->configureServiceManager($container);

// Inject config
$container->setService('config', $config);

$cryptoConfig = new Config($container->get('config')->cryptography);
$cryptoService = new CryptographyService($cryptoConfig);
$container->setService(CryptographyService::class, $cryptoService);

$dbAdapterConfig = new \Application\Model\Database\Config($container->get('config')->db);
$dbAdapter = AdapterFactory::createAdapter($dbAdapterConfig);
$container->setService(DatabaseInterface::class, $dbAdapter);

$jwtManager = new Application\JWT\Manager($container->get('config')->jwtConfigs);
$container->setService(Application\JWT\Manager::class, $jwtManager);

$jwtConfig   = new Lcobucci\JWT\Configuration($container->get('config')->jwt);
$validationJwtConfig   = new Lcobucci\JWT\Configuration($container->get('config')->validation_jwt);
$container->setService(Lcobucci\JWT\Configuration::class, $jwtConfig);

$jwtKey    = new Lcobucci\JWT\Signer\Key($container->get('config')->jwt['key']);
$container->setService(Lcobucci\JWT\Signer\Key::class, $jwtKey);

return $container;


text:
package de.czyrux.store.util;

import io.reactivex.CompletableObserver;
import io.reactivex.CompletableTransformer;
import io.reactivex.ObservableTransformer;
import io.reactivex.SingleObserver;
import io.reactivex.SingleTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.functions.Functions;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * Utility methods for RxJava 2
 */
public class RxUtil {

    private RxUtil() {
    }

    @SuppressWarnings("unchecked")
    public static <T> DisposableObserver<T> emptyObserver() {
        return new DisposableObserver() {

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(Object o) {
            }
        };
    }

    public static <T> SingleObserver<T> emptySingleObserver() {
        return new SingleObserver<T>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onSuccess(T value) {
            }

            @Override
            public void onError(Throwable e) {
            }
        };
    }

    public static CompletableObserver emptyCompletableObserver() {
        return new CompletableObserver() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
            }
        };
    }

    public static Consumer<? super Throwable> emptyConsumer() {
        return Functions.emptyConsumer();
    }

    public static <T> ObservableTransformer<T, T> applyObservableSchedulers() {
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static CompletableTransformer applyCompletableSchedulers() {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> SingleTransformer<T, T> applySingleSchedulers() {
        return upstream -> upstream.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }
}


text:
/**
 * @file
 * Defines global host-dependent types:
 * Counter, Tick, and (indirectly) {int,uint}{8,16,32,64}_t.
 */

#ifndef __BASE_TYPES_HH__
#define __BASE_TYPES_HH__

#include <inttypes.h>

#include <cassert>
#include <memory>
#include <ostream>

#include "base/refcnt.hh"

/** uint64_t constant */
#define ULL(N)          ((uint64_t)N##ULL)
/** int64_t constant */
#define LL(N)           ((int64_t)N##LL)

/** Statistics counter type.  Not much excuse for not using a 64-bit
 * integer here, but if you're desperate and only run short
 * simulations you could make this 32 bits.
 */
typedef int64_t Counter;

/**
 * Tick count type.
 */
typedef uint64_t Tick;

const Tick MaxTick = ULL(0xffffffffffffffff);

/**
 * Cycles is a wrapper class for representing cycle counts, i.e. a
 * relative difference between two points in time, expressed in a
 * number of clock cycles.
 *
 * The Cycles wrapper class is a type-safe alternative to a
 * typedef, aiming to avoid unintentional mixing of cycles and ticks
 * in the code base.
 *
 * Operators are defined inside an ifndef block to avoid swig touching
 * them. Note that there is no overloading of the bool operator as the
 * compiler is allowed to turn booleans into integers and this causes
 * a whole range of issues in a handful locations. The solution to
 * this problem would be to use the safe bool idiom, but for now we
 * make do without the test and use the more elaborate comparison >
 * Cycles(0).
 */
class Cycles
{

  private:

    /** Member holding the actual value. */
    uint64_t c;

  public:

    /** Explicit constructor assigning a value. */
    explicit Cycles(uint64_t _c) : c(_c) { }

    /** Default constructor for parameter classes. */
    Cycles() : c(0) { }

#ifndef SWIG // keep the operators away from SWIG

    /** Converting back to the value type. */
    operator uint64_t() const { return c; }

    /** Prefix increment operator. */
    Cycles& operator++()
    { ++c; return *this; }

    /** Prefix decrement operator. Is only temporarily used in the O3 CPU. */
    Cycles& operator--()
    { assert(c != 0); --c; return *this; }

    /** In-place addition of cycles. */
    const Cycles& operator+=(const Cycles& cc)
    { c += cc.c; return *this; }

    /** Greater than comparison used for > Cycles(0). */
    bool operator>(const Cycles& cc) const
    { return c > cc.c; }

    const Cycles operator +(const Cycles& b) const
    { return Cycles(c + b.c); }

    const Cycles operator -(const Cycles& b) const
    { assert(c >= b.c); return Cycles(c - b.c); }

    const Cycles operator <<(const int32_t shift)
    { return Cycles(c << shift); }

    const Cycles operator >>(const int32_t shift)
    { return Cycles(c >> shift); }

    friend std::ostream& operator<<(std::ostream &out, const Cycles & cycles);

#endif // SWIG not touching operators

};

/**
 * Address type
 * This will probably be moved somewhere else in the near future.
 * This should be at least as big as the biggest address width in use
 * in the system, which will probably be 64 bits.
 */
typedef uint64_t Addr;

typedef uint16_t MicroPC;

static const MicroPC MicroPCRomBit = 1 << (sizeof(MicroPC) * 8 - 1);

static inline MicroPC
romMicroPC(MicroPC upc)
{
    return upc | MicroPCRomBit;
}

static inline MicroPC
normalMicroPC(MicroPC upc)
{
    return upc & ~MicroPCRomBit;
}

static inline bool
isRomMicroPC(MicroPC upc)
{
    return MicroPCRomBit & upc;
}

const Addr MaxAddr = (Addr)-1;

/**
 * Thread index/ID type
 */
typedef int16_t ThreadID;
const ThreadID InvalidThreadID = (ThreadID)-1;

/**
 * Port index/ID type, and a symbolic name for an invalid port id.
 */
typedef int16_t PortID;
const PortID InvalidPortID = (PortID)-1;

class FaultBase;
typedef std::shared_ptr<FaultBase> Fault;

#ifndef SWIG // Swig gets really confused by decltype
// Rather than creating a shared_ptr instance and assigning it nullptr,
// we just create an alias.
constexpr decltype(nullptr) NoFault = nullptr;
#endif

enum ByteOrder {
    BigEndianByteOrder,
    LittleEndianByteOrder
};

#endif // __BASE_TYPES_HH__


text:
Titanium.include('include_start.js');

var MONTHS = [ 'Jan', 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] ;
var data = [];
for( var t=0; t < MONTHS.length; t++ ){
	data.push({ title: MONTHS[t] + ' ' + Titanium.App.DIARY.SELECTEDYEAR , hasChild:true });
}
var tableview = Titanium.UI.createTableView({ data: data });

tableview.addEventListener('click', function(e){

	var win = Titanium.UI.createWindow({
		url: 'month.js',
		title: 'Entries for ' + MONTHS[e.index] ,
		backgroundColor:'#FFEB8F',
		barColor:'#111' ,
		selectedMonth: e.index
	});

	//win.open();
	Titanium.UI.currentTab.open( win , {animated: true });
});

Titanium.UI.currentWindow.add( tableview );


text:
package barsan.opengl.rendering;

import java.util.List;

import javax.media.opengl.GL2;

import barsan.opengl.Yeti;

public abstract class Model {

	/** Whether GL_TRIANGLES or GL_QUADS is being used. */
	private int faceMode;

	/** Actual number of vertices per triangle. */
	protected int pointsPerFace;

	/** List of objects containing VBO sub-array coordinates and the material
	 *  required to render each of them */
	protected List<MaterialGroup> defaultMaterialGroups;

	/**
	 * This shouldn't be invoked directly in new code, and should be phased out
	 * of the forward renderer as well.
	 *
	 * @param arrayLength 	How many things are to be drawn. Used so both static
	 * 						and dynamic meshes can polymorphically return their
	 * 						correct element count.
	 */
	@Deprecated
	public void render(int arrayLength) {
		GL2 gl = Yeti.get().gl;
		gl.glDrawArrays(faceMode, 0, arrayLength);
		gl.glBindBuffer(GL2.GL_ARRAY_BUFFER, 0);
	}

	public List<MaterialGroup> getDefaultMaterialGroups() {
		return defaultMaterialGroups;
	}

	public void setDefaultMaterialGroups(List<MaterialGroup> mGroups) {
		this.defaultMaterialGroups = mGroups;
	}

	/**
	 * The number of data entities this model has (groups of vertex/normal etc.
	 * data.
	 */
	public abstract int getArrayLength();

	/** Resets the OpenGL state set by the model's usage. */
	public void cleanUp(int... indices) {
		GL2 gl = Yeti.get().gl;
		for(int el : indices) {
			if(el >= 0) {
				gl.glDisableVertexAttribArray(el);
			}
		}
	}

	/**
	 * Cleans up all the native resourses (such as VBOs) used by this model.
	 */
	public abstract void dispose();

	/**
	 * Updates faceMode based on pointsPerFace, crashing with an error message
	 * if not using triangles or quads.
	 */
	private void updateFaceMode() {
		if(pointsPerFace == 3) {
			faceMode = GL2.GL_TRIANGLES;
		} else if(pointsPerFace == 4) {
			faceMode = GL2.GL_QUADS;
		} else {
			Yeti.screwed("Disallowed number of points per face (can only be 3 or 4).");
		}
	}

	/** Provides a VBO of the model's texture coordinates; FIXME: more generalised approach */
	public abstract VBO getTexCoords();

	public int getFaceMode() {
		return faceMode;
	}

	public void setFaceMode(int faceMode) {
		this.faceMode = faceMode;
	}

	/** @note Also updates faceMode */
	public void setPointsPerFace(int pointsPerFace) {
		this.pointsPerFace = pointsPerFace;
		updateFaceMode();
	}

	public int getPointsPerFace() {
		return pointsPerFace;
	}
}


text:
var express = require('express');

var app = express();

var router = express.Router();

app.use(express.static(process.cwd() + '/public'));
// app.use(express.static('public'));

// app.get('/', function(req,res){
//   res.redirect("/index.html")
// })
app.get('/', function(req,res){
  res.sendFile(__dirname + '/index.html');
});
// app.get('/index', function(req,res){
//   res.redirect('/index.html')
// })

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log('App listening on PORT: ' + port);
});


text:
'''
To seperate Gaussian log file with with multistep calculation
Userage : seperate_log.py logfile1 logfile2 ...
Created by Chang Liu @ Apr.29.2015
'''
import sys

def seperate_file(filename):
	try:
		logfile=open(filename, 'r')
		inputTemp=logfile.read().splitlines()
		logfile.close()
	except:
		print "No such file: %s" % filename
		return

	outNUM=0
	outName="%d_%s" % (outNUM, filename)
	outfile=open(outName, "w")

	for line in inputTemp:
		outfile.write("%s\n"%line)
		if "Normal term" in line:
			outfile.close
			outNUM += 1
			outName="%d_%s" % (outNUM, filename)
			outfile=open(outName, "w")

if __name__=="__main__":
	for filename in sys.argv[1:]:
		seperate_file(filename)
	exit(0)


text:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ModalController, NavController, NavParams } from 'ionic-angular';
import { Logger } from '../../../providers/logger/logger';

// providers
import { ExternalLinkProvider } from '../../../providers/external-link/external-link';
import { GlideraProvider } from '../../../providers/glidera/glidera';
import { OnGoingProcessProvider } from '../../../providers/on-going-process/on-going-process';
import { PopupProvider } from '../../../providers/popup/popup';
// pages
import { AmountPage } from '../../send/amount/amount';
import { GlideraTxDetailsPage } from './glidera-tx-details/glidera-tx-details';

@Component({
  selector: 'page-glidera',
  templateUrl: 'glidera.html',
})
export class GlideraPage {

  public account: any;
  public tx: any;
  public showOauthForm: boolean;
  public network: string;
  public currency: string;
  public oauthCodeForm: FormGroup;

  constructor(
    private externalLinkProvider: ExternalLinkProvider,
    private onGoingProcessProvider: OnGoingProcessProvider,
    private glideraProvider: GlideraProvider,
    private popupProvider: PopupProvider,
    private logger: Logger,
    private navParams: NavParams,
    private navCtrl: NavController,
    private formBuilder: FormBuilder,
    private modalCtrl: ModalController
  ) {
    this.oauthCodeForm = this.formBuilder.group({
      code: ['', Validators.compose([Validators.minLength(1), Validators.required])]
    });
    this.network = this.glideraProvider.getNetwork();
    this.currency = this.glideraProvider.getCurrency();
    this.showOauthForm = false;
    this.account = {};
  }

  ionViewDidEnter() {
    if (this.navParams.data && this.navParams.data.code) this.submitOauthCode(this.navParams.data.code);
    else this.init();
  }

  public openExternalLink(url: string): void {
    this.externalLinkProvider.open(url);
  }

  private init(): void {
    this.onGoingProcessProvider.set('connectingGlidera');
    this.glideraProvider.init((err, data) => {
      this.onGoingProcessProvider.clear();
      if (err) {
        this.popupProvider.ionicAlert('Error connecting Glidera', err + '. Please re-connect to Glidera');
        return;
      }
      if (!data || (data && !data.token)) return;

      this.account.token = data.token;
      this.account.status = data.status;
      this.account.txs = data.txs;
      this.update();
    });
  }

  public update(opts?: any): void {
    this.logger.debug('Updating Glidera...');
    this.glideraProvider.updateStatus(this.account);
  }

  public getAuthenticateUrl(): string {
    return this.glideraProvider.getOauthCodeUrl();
  }

  public submitOauthCode(code?: string): void {
    this.onGoingProcessProvider.set('connectingGlidera');
    this.glideraProvider.authorize(code, (err, data) => {
      this.onGoingProcessProvider.clear();
      if (err) {
        this.popupProvider.ionicAlert('Authorization error', err);
        return;
      }
      this.account.token = data.token;
      this.account.status = data.status;
      this.init();
    });
  };

  public openTxModal(tx) {
    this.tx = tx;

    let modal = this.modalCtrl.create(GlideraTxDetailsPage, { tx: this.tx });
    modal.present();

    this.glideraProvider.getTransaction(this.account.token, tx.transactionUuid, (err, tx) => {
      if (err) {
        this.popupProvider.ionicAlert('Error getting transaction', 'Could not get transactions');
        return;
      }
      this.tx = tx;
    });
  }

  public openAuthenticateWindow(): void {
    this.openExternalLink(this.getAuthenticateUrl());
    this.navCtrl.popToRoot();
  }

  public openLoginWindow() {
    let glideraUrl = (this.network === 'testnet') ? 'https://sandbox.glidera.io/login' : 'https://glidera.io/login';
    this.openExternalLink(glideraUrl);
  }

  public openSupportWindow(): void {
    var url = this.glideraProvider.getSupportUrl();
    var optIn = true;
    var title = 'Glidera Support';
    var message = 'You can email glidera at support@glidera.io for direct support, or you can contact Glidera on Twitter.';
    var okText = 'Tweet @GlideraInc';
    var cancelText = 'Go Back';
    this.externalLinkProvider.open(url, optIn, title, message, okText, cancelText);
  }

  public toggleOauthForm(): void {
    this.showOauthForm = !this.showOauthForm;
  }

  public goToBuyGlideraPage(): void {
    this.navCtrl.push(AmountPage, { nextPage: 'BuyGlideraPage', currency: this.currency, coin: 'btc', fixedUnit: true });
  }

  public goToSellGlideraPage(): void {
    this.navCtrl.push(AmountPage, { nextPage: 'SellGlideraPage', currency: this.currency, coin: 'btc', fixedUnit: true })
  }
}


text:
define(function(require, exports, module) {
  "use strict";

  var Class = require("./class");
  var Sync = require("./sync");
  var wrapError = require("./util/wrap_error");
  var urlError = require("./util/url_error");

  var _ = require("lodash");

  // FIXME
  var array = [];
  var push = array.push;
  var slice = array.slice;
  var splice = array.splice;

  // Backbone.Model
  // --------------

  // Backbone **Models** are the basic data object in the framework --
  // frequently representing a row in a table in a database on your server.
  // A discrete chunk of data and a bunch of useful, related methods for
  // performing computations and transformations on that data.

  // A list of options to be attached directly to the model, if provided.
  var modelOptions = ['url', 'urlRoot', 'collection'];

  // Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Class.extend({
    constructor: function(attributes, options) {
      var attrs = attributes || {};
      options = options || {};

      this.cid = _.uniqueId('c');
      this.attributes = {};
      if (options && options.collection) this.collection = options.collection;
      if (options && options.parse) attrs = this.parse(attrs, options) || {};
      attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
      this.set(attrs, options);
      this.changed = {};
      this.initialize.apply(this, arguments);

      // Set up custom Model handler logic for the channel.
      if (this.channel) {
        // Whenever new data comes in, update the internal data store unless it's
        // already changed.
        this.channel.subscribe(function(value, path) {
          if (this.get(path) !== value) {
            this.set(path, value);
          }
        }, this);

        // Whenever this internal data changes, update.
        this.on("change", function() {
          this.channel.publish(this.changed);
        }, this);
      }
    },

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `Backbone.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      // Backbone compatibility.
      var _sync = typeof Backbone !== "undefined" ? Backbone.sync : Sync;
      return _sync.apply(this, arguments);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      var attr, attrs, unset, changes, silent, changing, prev, current;
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      unset           = options.unset;
      silent          = options.silent;
      changes         = [];
      changing        = this._changing;
      this._changing  = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }
      current = this.attributes, prev = this._previousAttributes;

      // Check for changes of `id`.
      if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];

      // For each `set` attribute, update or delete the current value.
      for (attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          this.changed[attr] = val;
        } else {
          delete this.changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0, l = changes.length; i < l; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {unset: true}));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var val, changed = false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      for (var attr in diff) {
        if (_.isEqual(old[attr], (val = diff[attr]))) continue;
        (changed || (changed = {}))[attr] = val;
      }
      return changed;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server. If the server's representation of the
    // model differs from its current attributes, they will be overridden,
    // triggering a `"change"` event.
    fetch: function(options) {
      options = options ? _.clone(options) : {};
      if (options.parse === void 0) options.parse = true;
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        if (!model.set(model.parse(resp, options), options)) return false;
        if (success) success(model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      var attrs, method, xhr, attributes = this.attributes;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({validate: true}, options);

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !options.wait) {
        if (!this.set(attrs, options)) return false;
      } else {
        if (!this._validate(attrs, options)) return false;
      }

      // Set temporary attributes if `{wait: true}`.
      if (attrs && options.wait) {
        this.attributes = _.extend({}, attributes, attrs);
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      if (options.parse === void 0) options.parse = true;
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = model.parse(resp, options);
        if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
        if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) {
          return false;
        }
        if (success) success(model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      xhr = this.sync(method, this, options);

      // Restore attributes.
      if (attrs && options.wait) this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;

      var destroy = function() {
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (options.wait || model.isNew()) destroy();
        if (success) success(model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      if (this.isNew()) {
        options.success();
        return false;
      }
      wrapError(this, options);

      var xhr = this.sync('delete', this, options);
      if (!options.wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      var model = new Model(this.attributes);
      model.cid = this.cid;
      model.id = this.id;
      return model;
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return this.id == null;
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.extend(options || {}, { validate: true }));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

  });

  // Underscore methods that we want to implement on the Model.
  var modelMethods = {
    "keys": _.keys,
    "values": _.values,
    "pairs": _.pairs,
    "invert": _.invert,
    "pick": _.pick,
    "omit": _.omit,
    "chain": _.chain
  };

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  _.each(modelMethods, function(func, method) {
    Model.prototype[method] = function() {
      var args = slice.call(arguments);
      args.unshift(this.attributes);
      return func.apply(_, args);
    };
  });

  module.exports = Model;
});


text:
module Neo4j
  module Embedded
    class EmbeddedRelationship
      class << self
        Java::OrgNeo4jKernelImplCore::RelationshipProxy.class_eval do
          include Neo4j::Embedded::Property
          include Neo4j::EntityEquality
          include Neo4j::Relationship::Wrapper
          include Neo4j::Core::ActiveEntity
          extend Neo4j::Core::TxMethods

          alias_method :_other_node, :getOtherNode

          def exist?
            !!graph_database.get_relationship_by_id(neo_id)
          rescue Java::OrgNeo4jGraphdb.NotFoundException
            false
          end
          tx_methods :exist?

          def inspect
            "EmbeddedRelationship neo_id: #{neo_id}"
          end

          def start_node
            _start_node.wrapper
          end
          tx_methods :start_node
          alias_method :_start_node_id, :start_node
          tx_methods :_start_node_id

          def _start_node
            getStartNode
          end

          def rel_type
            @_rel_type ||= _rel_type
          end

          def _rel_type
            getType.name.to_sym
          end
          tx_methods :rel_type

          def del
            delete
          end
          tx_methods :del
          tx_methods :delete

          alias_method :destroy, :del
          tx_methods :destroy

          def other_node(n)
            _other_node(n.neo4j_obj).wrapper
          end
          tx_methods :other_node

          def end_node
            _end_node.wrapper
          end
          tx_methods :end_node
          alias_method :_end_node_id, :end_node
          tx_methods :_end_node_id

          def _end_node
            getEndNode
          end
        end
      end
    end
  end
end


text:
<?php

namespace Claudiucreanga\Import\Model;

use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Data\Collection\Db;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filter\FilterManager;
use Magento\Framework\Model\AbstractModel;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Claudiucreanga\Import\Model\ResourceModel\Products as ModelProducts;
use Claudiucreanga\Import\Model\Source\AbstractSource;

class Products extends AbstractModel
{

	/**
	 * @var int
	 */
	const STATUS_ENABLED = 1;
	/**
	 * @var int
	 */
	const STATUS_DISABLED = 0;

	/**
	 * cache tag
	 *
	 * @var string
	 */
	const CACHE_TAG = 'claudiucreanga_import_integration_products';

	/**
	 * filter model
	 *
	 * @var \Magento\Framework\Filter\FilterManager
	 */
	public $filter;

	/**
	 * @var AbstractSource[]
	 */
	public $optionProviders;
	/**
	 * @param Context $context
	 * @param Registry $registry
	 * @param FilterManager $filter
	 * @param array $optionProviders
	 * @param array $data
	 * @param AbstractResource|null $resource
	 * @param AbstractDb|null $resourceCollection
	 */
	public function __construct(
		Context $context,
		Registry $registry,
		FilterManager $filter,
		array $optionProviders = [],
		array $data = [],
		AbstractResource $resource = null,
		AbstractDb $resourceCollection = null
	) {
		$this->filter          = $filter;
		$this->optionProviders = $optionProviders;
		parent::__construct($context, $registry, $resource, $resourceCollection, $data);
	}
	/**
	 * Initialize resource model
	 *
	 * @return void
	 */
	public function _construct()
	{
		$this->_init(ModelProducts::class);
	}

	/**
	 * Get identities
	 *
	 * @return array
	 */
	public function getIdentities()
	{
		return [self::CACHE_TAG . '_' . $this->getId()];
	}

	/**
	 * set name
	 *
	 * @param $name
	 * @return string
	 */
	public function setName($name)
	{
		return $this->setData("name", $name);
	}

	/**
	 * Set status
	 *
	 * @param $status
	 * @return string
	 */
	public function setStatus($status)
	{
		return $this->setData("status", $status);
	}

	/**
	 * set created at
	 *
	 * @param $createdAt
	 * @return string
	 */
	public function setCreatedAt($createdAt)
	{
		return $this->setData("created_at", $createdAt);
	}
	/**
	 * set updated at
	 *
	 * @param $updatedAt
	 * @return string
	 */
	public function setUpdatedAt($updatedAt)
	{
		return $this->setData("updated_at", $updatedAt);
	}
	/**
	 * Get name
	 *
	 * @return string
	 */
	public function getName()
	{
		return $this->getData("name");
	}

	/**
	 * Get status
	 *
	 * @return bool|int
	 */
	public function getStatus()
	{
		return $this->getData("status");
	}
	/**
	 * Get created at
	 *
	 * @return string
	 */
	public function getCreatedAt()
	{
		return $this->getData("created_at");
	}
	/**
	 * Get updated at
	 *
	 * @return string
	 */
	public function getUpdatedAt()
	{
		return $this->getData("updated_at");
	}

	/**
	 * @return array
	 */
	public function getStoreId()
	{
		return $this->getData("store_id");
	}

	/**
	 * @return bool
	 */
	public function status()
	{
		return (bool)$this->getStatus();
	}
	/**
	 * @param $attribute
	 * @return string
	 */
	public function getAttributeText($attribute)
	{
		if (!isset($this->optionProviders[$attribute])) {
			return '';
		}
		if (!($this->optionProviders[$attribute] instanceof AbstractSource)) {
			return '';
		}
		return $this->optionProviders[$attribute]->getOptionText($this->getData($attribute));
	}

    public function addFieldToFilter($field, $condition = null)
    {

        return parent::addFieldToFilter($field, $condition);
    }

}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use std::rc::Rc;
use std::sync::Arc;

use arrow::array::*;
use arrow::compute;
use arrow::datatypes::{DataType, Schema};
use arrow::record_batch::RecordBatch;

use super::super::logicalplan::{Expr, Operator, ScalarValue};
use super::context::ExecutionContext;
use super::error::{ExecutionError, Result};

/// Compiled Expression (basically just a closure to evaluate the expression at runtime)
pub type CompiledExpr = Rc<Fn(&RecordBatch) -> Result<ArrayRef>>;

pub type CompiledCastFunction = Rc<Fn(&ArrayRef) -> Result<ArrayRef>>;

pub enum AggregateType {
    Min,
    Max,
    Sum,
    Count,
    CountDistinct,
    Avg,
}

/// Runtime expression
pub enum RuntimeExpr {
    Compiled {
        name: String,
        f: CompiledExpr,
        t: DataType,
    },
    AggregateFunction {
        name: String,
        f: AggregateType,
        args: Vec<CompiledExpr>,
        t: DataType,
    },
}

impl RuntimeExpr {
    pub fn get_func(&self) -> CompiledExpr {
        match self {
            &RuntimeExpr::Compiled { ref f, .. } => f.clone(),
            _ => panic!(),
        }
    }

    pub fn get_name(&self) -> &String {
        match self {
            &RuntimeExpr::Compiled { ref name, .. } => name,
            &RuntimeExpr::AggregateFunction { ref name, .. } => name,
        }
    }

    pub fn get_type(&self) -> DataType {
        match self {
            &RuntimeExpr::Compiled { ref t, .. } => t.clone(),
            &RuntimeExpr::AggregateFunction { ref t, .. } => t.clone(),
        }
    }
}

/// Compiles a scalar expression into a closure
pub fn compile_expr(
    ctx: &ExecutionContext,
    expr: &Expr,
    input_schema: &Schema,
) -> Result<RuntimeExpr> {
    match *expr {
        Expr::AggregateFunction {
            ref name,
            ref args,
            ref return_type,
        } => {
            assert_eq!(1, args.len());

            let compiled_args: Result<Vec<RuntimeExpr>> = args
                .iter()
                .map(|e| compile_scalar_expr(&ctx, e, input_schema))
                .collect();

            let func = match name.to_lowercase().as_ref() {
                "min" => Ok(AggregateType::Min),
                "max" => Ok(AggregateType::Max),
                "count" => Ok(AggregateType::Count),
                "sum" => Ok(AggregateType::Sum),
                _ => Err(ExecutionError::General(format!(
                    "Unsupported aggregate function '{}'",
                    name
                ))),
            };

            Ok(RuntimeExpr::AggregateFunction {
                name: name.to_string(),
                f: func?,
                args: compiled_args?
                    .iter()
                    .map(|e| e.get_func().clone())
                    .collect(),
                t: return_type.clone(),
            })
        }
        _ => Ok(compile_scalar_expr(&ctx, expr, input_schema)?),
    }
}

macro_rules! binary_op {
    ($LEFT:expr, $RIGHT:expr, $OP:ident, $DT:ident) => {{
        let ll = $LEFT.as_any().downcast_ref::<$DT>().unwrap();
        let rr = $RIGHT.as_any().downcast_ref::<$DT>().unwrap();
        Ok(Arc::new(compute::$OP(&ll, &rr)?))
    }};
}

macro_rules! math_ops {
    ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{
        let left_values = $LEFT.get_func()($BATCH)?;
        let right_values = $RIGHT.get_func()($BATCH)?;
        match (left_values.data_type(), right_values.data_type()) {
            (DataType::Int8, DataType::Int8) => {
                binary_op!(left_values, right_values, $OP, Int8Array)
            }
            (DataType::Int16, DataType::Int16) => {
                binary_op!(left_values, right_values, $OP, Int16Array)
            }
            (DataType::Int32, DataType::Int32) => {
                binary_op!(left_values, right_values, $OP, Int32Array)
            }
            (DataType::Int64, DataType::Int64) => {
                binary_op!(left_values, right_values, $OP, Int64Array)
            }
            (DataType::UInt8, DataType::UInt8) => {
                binary_op!(left_values, right_values, $OP, UInt8Array)
            }
            (DataType::UInt16, DataType::UInt16) => {
                binary_op!(left_values, right_values, $OP, UInt16Array)
            }
            (DataType::UInt32, DataType::UInt32) => {
                binary_op!(left_values, right_values, $OP, UInt32Array)
            }
            (DataType::UInt64, DataType::UInt64) => {
                binary_op!(left_values, right_values, $OP, UInt64Array)
            }
            (DataType::Float32, DataType::Float32) => {
                binary_op!(left_values, right_values, $OP, Float32Array)
            }
            (DataType::Float64, DataType::Float64) => {
                binary_op!(left_values, right_values, $OP, Float64Array)
            }
            _ => Err(ExecutionError::ExecutionError(format!("math_ops"))),
        }
    }};
}

macro_rules! comparison_ops {
    ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{
        let left_values = $LEFT.get_func()($BATCH)?;
        let right_values = $RIGHT.get_func()($BATCH)?;
        match (left_values.data_type(), right_values.data_type()) {
            (DataType::Int8, DataType::Int8) => {
                binary_op!(left_values, right_values, $OP, Int8Array)
            }
            (DataType::Int16, DataType::Int16) => {
                binary_op!(left_values, right_values, $OP, Int16Array)
            }
            (DataType::Int32, DataType::Int32) => {
                binary_op!(left_values, right_values, $OP, Int32Array)
            }
            (DataType::Int64, DataType::Int64) => {
                binary_op!(left_values, right_values, $OP, Int64Array)
            }
            (DataType::UInt8, DataType::UInt8) => {
                binary_op!(left_values, right_values, $OP, UInt8Array)
            }
            (DataType::UInt16, DataType::UInt16) => {
                binary_op!(left_values, right_values, $OP, UInt16Array)
            }
            (DataType::UInt32, DataType::UInt32) => {
                binary_op!(left_values, right_values, $OP, UInt32Array)
            }
            (DataType::UInt64, DataType::UInt64) => {
                binary_op!(left_values, right_values, $OP, UInt64Array)
            }
            (DataType::Float32, DataType::Float32) => {
                binary_op!(left_values, right_values, $OP, Float32Array)
            }
            (DataType::Float64, DataType::Float64) => {
                binary_op!(left_values, right_values, $OP, Float64Array)
            }
            //TODO other types
            _ => Err(ExecutionError::ExecutionError(format!("comparison_ops"))),
        }
    }};
}

macro_rules! boolean_ops {
    ($LEFT:expr, $RIGHT:expr, $BATCH:expr, $OP:ident) => {{
        let left_values = $LEFT.get_func()($BATCH)?;
        let right_values = $RIGHT.get_func()($BATCH)?;
        Ok(Arc::new(compute::$OP(
            left_values.as_any().downcast_ref::<BooleanArray>().unwrap(),
            right_values
                .as_any()
                .downcast_ref::<BooleanArray>()
                .unwrap(),
        )?))
    }};
}

macro_rules! literal_array {
    ($VALUE:expr, $ARRAY_TYPE:ident, $TY:ident) => {{
        let nn = *$VALUE;
        Ok(RuntimeExpr::Compiled {
            name: format!("{}", nn),
            f: Rc::new(move |batch: &RecordBatch| {
                let capacity = batch.num_rows();
                let mut builder = $ARRAY_TYPE::builder(capacity);
                for _ in 0..capacity {
                    builder.append_value(nn)?;
                }
                let array = builder.finish();
                Ok(Arc::new(array) as ArrayRef)
            }),
            t: DataType::$TY,
        })
    }};
}

/// Casts a column to an array with a different data type
macro_rules! cast_column {
    ($INDEX:expr, $FROM_TYPE:ty, $TO_TYPE:ident, $DT:ty) => {{
        Rc::new(move |batch: &RecordBatch| {
            // get data and cast to known type
            match batch.column($INDEX).as_any().downcast_ref::<$FROM_TYPE>() {
                Some(array) => {
                    // create builder for desired type
                    let mut builder = $TO_TYPE::builder(batch.num_rows());
                    for i in 0..batch.num_rows() {
                        if array.is_null(i) {
                            builder.append_null()?;
                        } else {
                            builder.append_value(array.value(i) as $DT)?;
                        }
                    }
                    Ok(Arc::new(builder.finish()) as ArrayRef)
                }
                None => Err(ExecutionError::InternalError(format!(
                    "Column at index {} is not of expected type",
                    $INDEX
                ))),
            }
        })
    }};
}

macro_rules! cast_column_outer {
    ($INDEX:expr, $FROM_TYPE:ty, $TO_TYPE:expr) => {{
        match $TO_TYPE {
            DataType::UInt8 => cast_column!($INDEX, $FROM_TYPE, UInt8Array, u8),
            DataType::UInt16 => cast_column!($INDEX, $FROM_TYPE, UInt16Array, u16),
            DataType::UInt32 => cast_column!($INDEX, $FROM_TYPE, UInt32Array, u32),
            DataType::UInt64 => cast_column!($INDEX, $FROM_TYPE, UInt64Array, u64),
            DataType::Int8 => cast_column!($INDEX, $FROM_TYPE, Int8Array, i8),
            DataType::Int16 => cast_column!($INDEX, $FROM_TYPE, Int16Array, i16),
            DataType::Int32 => cast_column!($INDEX, $FROM_TYPE, Int32Array, i32),
            DataType::Int64 => cast_column!($INDEX, $FROM_TYPE, Int64Array, i64),
            DataType::Float32 => cast_column!($INDEX, $FROM_TYPE, Float32Array, f32),
            DataType::Float64 => cast_column!($INDEX, $FROM_TYPE, Float64Array, f64),
            _ => unimplemented!(),
        }
    }};
}

/// Compiles a scalar expression into a closure
pub fn compile_scalar_expr(
    ctx: &ExecutionContext,
    expr: &Expr,
    input_schema: &Schema,
) -> Result<RuntimeExpr> {
    match expr {
        &Expr::Literal(ref value) => match value {
            //NOTE: this is a temporary hack .. due to the way expressions like 'a > 1'
            // are evaluated, currently the left and right are evaluated
            // separately and must result in arrays and then the '>' operator
            // is evaluated against the two arrays. This works but is dumb ...
            // I intend to optimize this soon to add special handling for
            // binary expressions that involve literal values to avoid creating arrays of
            // literals filed as https://github.com/andygrove/datafusion/issues/191
            ScalarValue::Int8(n) => literal_array!(n, Int8Array, Int8),
            ScalarValue::Int16(n) => literal_array!(n, Int16Array, Int16),
            ScalarValue::Int32(n) => literal_array!(n, Int32Array, Int32),
            ScalarValue::Int64(n) => literal_array!(n, Int64Array, Int64),
            ScalarValue::UInt8(n) => literal_array!(n, UInt8Array, UInt8),
            ScalarValue::UInt16(n) => literal_array!(n, UInt16Array, UInt16),
            ScalarValue::UInt32(n) => literal_array!(n, UInt32Array, UInt32),
            ScalarValue::UInt64(n) => literal_array!(n, UInt64Array, UInt64),
            ScalarValue::Float32(n) => literal_array!(n, Float32Array, Float32),
            ScalarValue::Float64(n) => literal_array!(n, Float64Array, Float64),
            other => Err(ExecutionError::ExecutionError(format!(
                "No support for literal type {:?}",
                other
            ))),
        },
        &Expr::Column(index) => Ok(RuntimeExpr::Compiled {
            name: input_schema.field(index).name().clone(),
            f: Rc::new(move |batch: &RecordBatch| Ok((*batch.column(index)).clone())),
            t: input_schema.field(index).data_type().clone(),
        }),
        &Expr::Cast {
            ref expr,
            ref data_type,
        } => match expr.as_ref() {
            &Expr::Column(index) => {
                let col = input_schema.field(index);
                Ok(RuntimeExpr::Compiled {
                    name: col.name().clone(),
                    t: col.data_type().clone(),
                    f: match col.data_type() {
                        DataType::Int8 => {
                            cast_column_outer!(index, Int8Array, &data_type)
                        }
                        DataType::Int16 => {
                            cast_column_outer!(index, Int16Array, &data_type)
                        }
                        DataType::Int32 => {
                            cast_column_outer!(index, Int32Array, &data_type)
                        }
                        DataType::Int64 => {
                            cast_column_outer!(index, Int64Array, &data_type)
                        }
                        DataType::UInt8 => {
                            cast_column_outer!(index, UInt8Array, &data_type)
                        }
                        DataType::UInt16 => {
                            cast_column_outer!(index, UInt16Array, &data_type)
                        }
                        DataType::UInt32 => {
                            cast_column_outer!(index, UInt32Array, &data_type)
                        }
                        DataType::UInt64 => {
                            cast_column_outer!(index, UInt64Array, &data_type)
                        }
                        DataType::Float32 => {
                            cast_column_outer!(index, Float32Array, &data_type)
                        }
                        DataType::Float64 => {
                            cast_column_outer!(index, Float64Array, &data_type)
                        }
                        _ => panic!("unsupported CAST operation"), /*TODO */
                                                                   /*Err(ExecutionError::NotImplemented(format!(
                                                                       "CAST column from {:?} to {:?}",
                                                                       col.data_type(),
                                                                       data_type
                                                                   )))*/
                    },
                })
            }
            &Expr::Literal(ref value) => {
                //NOTE this is all very inefficient and needs to be optimized - tracking
                // issue is https://github.com/andygrove/datafusion/issues/191
                match value {
                    ScalarValue::Int64(n) => {
                        let nn = *n;
                        match data_type {
                            DataType::Float64 => Ok(RuntimeExpr::Compiled {
                                name: "lit".to_string(),
                                f: Rc::new(move |batch: &RecordBatch| {
                                    let mut b = Float64Array::builder(batch.num_rows());
                                    for _ in 0..batch.num_rows() {
                                        b.append_value(nn as f64)?;
                                    }
                                    Ok(Arc::new(b.finish()) as ArrayRef)
                                }),
                                t: data_type.clone(),
                            }),
                            other => Err(ExecutionError::NotImplemented(format!(
                                "CAST from Int64 to {:?}",
                                other
                            ))),
                        }
                    }
                    other => Err(ExecutionError::NotImplemented(format!(
                        "CAST from {:?} to {:?}",
                        other, data_type
                    ))),
                }
            }
            other => Err(ExecutionError::General(format!(
                "CAST not implemented for expression {:?}",
                other
            ))),
        },
        &Expr::BinaryExpr {
            ref left,
            ref op,
            ref right,
        } => {
            let left_expr = compile_scalar_expr(ctx, left, input_schema)?;
            let right_expr = compile_scalar_expr(ctx, right, input_schema)?;
            let name = format!("{:?} {:?} {:?}", left, op, right);
            let op_type = left_expr.get_type().clone();
            match op {
                &Operator::Eq => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, eq)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::NotEq => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, neq)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::Lt => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, lt)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::LtEq => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, lt_eq)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::Gt => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, gt)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::GtEq => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        comparison_ops!(left_expr, right_expr, batch, gt_eq)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::And => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        boolean_ops!(left_expr, right_expr, batch, and)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::Or => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        boolean_ops!(left_expr, right_expr, batch, or)
                    }),
                    t: DataType::Boolean,
                }),
                &Operator::Plus => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        math_ops!(left_expr, right_expr, batch, add)
                    }),
                    t: op_type,
                }),
                &Operator::Minus => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        math_ops!(left_expr, right_expr, batch, subtract)
                    }),
                    t: op_type,
                }),
                &Operator::Multiply => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        math_ops!(left_expr, right_expr, batch, multiply)
                    }),
                    t: op_type,
                }),
                &Operator::Divide => Ok(RuntimeExpr::Compiled {
                    name,
                    f: Rc::new(move |batch: &RecordBatch| {
                        math_ops!(left_expr, right_expr, batch, divide)
                    }),
                    t: op_type,
                }),
                other => Err(ExecutionError::ExecutionError(format!(
                    "operator: {:?}",
                    other
                ))),
            }
        }
        other => Err(ExecutionError::ExecutionError(format!(
            "expression {:?}",
            other
        ))),
    }
}


text:
<?php

namespace Estey\Rubix\Models;

class Category extends Model
{
    /**
     * Fields.
     * @var array
     */
    protected static $fields = [
        'id',
        'title',
        'created_at',
        'updated_at'
    ];

    /**
     * Fields.
     * @var array
     */
    protected static $dates = [
        'created_at',
        'updated_at'
    ];

    /**
     * Create a new instance of this model.
     *
     * @param array|null $data
     * @return Estey\Rubix\Models\Model
     */
    public static function getInstance($data = null)
    {
        return new self($data);
    }
}


text:
"""
Latex Plugin For Pelican
========================

This plugin allows you to write mathematical equations in your articles using Latex.
It uses the MathJax Latex JavaScript library to render latex that is embedded in
between `$..$` for inline math and `$$..$$` for displayed math. It also allows for
writing equations in by using `\begin{equation}`...`\end{equation}`.
"""

from pelican import signals

# Reference about dynamic loading of MathJax can be found at http://docs.mathjax.org/en/latest/dynamic.html
# The https cdn address can be found at http://www.mathjax.org/resources/faqs/#problem-https
latexScript = """
    <script type= "text/javascript">
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = 'https:' == document.location.protocol ? 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js' : 'http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
        s[(window.opera ? "innerHTML" : "text")] =
            "MathJax.Hub.Config({" +
            "    config: ['MMLorHTML.js']," +
            "    jax: ['input/TeX','input/MathML','output/HTML-CSS','output/NativeMML']," +
            "    TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
            "    extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
            "    tex2jax: { " +
            "        inlineMath: [ [\'$\',\'$\'] ], " +
            "        displayMath: [ [\'$$\',\'$$\'] ]," +
            "        processEscapes: true }, " +
            "    'HTML-CSS': { " +
            "        styles: { '.MathJax .mo, .MathJax .mi': {color: 'black ! important'}} " +
            "    } " +
            "}); ";
        (document.body || document.getElementsByTagName('head')[0]).appendChild(s);
    </script>
"""

def addLatex(gen, metadata):
    """
        The registered handler for the latex plugin. It will add
        the latex script to the article metadata
    """
    if 'LATEX' in gen.settings.keys() and gen.settings['LATEX'] == 'article':
        if 'latex' in metadata.keys():
            metadata['latex'] = latexScript
    else:
        metadata['latex'] = latexScript

def register():
    """
        Plugin registration
    """
    signals.article_generator_context.connect(addLatex)
    signals.page_generator_context.connect(addLatex)


text:
/**
 * Sort the array based on a property in the items.
 * pass desc if you want to reverse the sort.
 * @param p
 */

define('sortOn', ['sort'], function (sort) {

    var sortOn = function (array, property, desc) {
        if (desc) {
            desc = 1;
        } else {
            desc = 0;
        }
        var sortfunc = function (a, b) {// handle both numbers and strings.
            return desc ? (b[property] > a[property] ? 1 : (a[property] > b[property] ? -1 : 0)) : (b[property] < a[property] ? 1 : (a[property] < b[property] ? -1 : 0));
        };
        return sort(array, sortfunc);
    };

    return sortOn;

});


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('smsbillables', '0010_gateway_fee_amount_null'),
    ]

    operations = [
        migrations.AlterField(
            model_name='smsbillable',
            name='date_created',
            field=models.DateTimeField(auto_now_add=True),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='smsbillable',
            name='date_sent',
            field=models.DateTimeField(),
            preserve_default=True,
        ),
    ]


text:
package com.restfulbooker.api.payloads.request;

import com.fasterxml.jackson.annotation.JsonProperty;

public class AuthPayload {

    @JsonProperty
    private String username;
    @JsonProperty
    private String password;

    private AuthPayload(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public static class AuthPayloadBuilder{

        private String username;
        private String password;

        public AuthPayloadBuilder setUsername(String username) {
            this.username = username;
            return this;
        }

        public AuthPayloadBuilder setPassword(String password) {
            this.password = password;
            return this;
        }

        public AuthPayload build(){
            return new AuthPayload(username, password);
        }
    }
}


text:
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}
caption{
    text-align: center;
    color: white;
    font-size: 16px;
    font-weight: 600;
    background: #2c3b41;
}
td, th {
    border: 1px solid #999;
    text-align: left;
    text-transform: capitalize;
    padding: 7px !important;
}

tr:nth-child(even) {
    background-color: white;
    outline: none;
}
.table-hover>tbody>tr:hover:nth-of-type(even){
    background-color: rgba(250, 250, 250, 0.2) !important;
	outline: none;
}
.tableui{
    margin: 0 auto;
    padding: 0px;
}
.tableui thead{
    padding: 5px;
}
.tableimg{
    border: 1px double rgba(128, 128, 128, 0.63);
    padding: 5px;
    width: 170px;
    margin-left: 30px;
}
.h1, h1 {
    font-size: 28px !important;
    text-decoration: none !important;
    text-transform: uppercase;
	color: #2c3b41;
    font-style: italic;
}
.form-group {
    margin: 0 auto;
    float: none;
    width: 50%;
}
label {
    margin-top: 10px;
    text-transform: uppercase;
    font-size: 14px;
    font-family: sans-serif;
}
.form-control {
    height: 40px;
}
.btn-success{
    margin-left: 25%;
    margin-top: 20px;
    border-radius: 0px !important;
    height: 45px;
    text-transform: uppercase;
    font-size: 16px;
    background: #222d32 !important;
    border: 1px solid #222d32 !important;
    padding: 10px 20px;
}
.form-group select{
    margin: 0px;
}
.form-group .form-inline{
    margin-left: 10px;
}
.datetime {
    margin-top: 10px;
}
select {
    height: 40px;
    width: 13%;
    margin: 8px;
}
.tablemarg{
	margin: 10px !important;
	}
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 1023px) {
    .tableimg{
        margin: 20px auto;
    }
    .form-group {
        width: 100% ;
    }
    .btn{
        margin-left:0%;
    }
    select {
        width:auto;
        margin: 10px 3px 0px;
    }

}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 579px) {
	#clientName
	{
    margin-left: 90px !important;
	}

}
@media only screen and (min-device-width : 580px) and (max-device-width : 727px) {
	#clientName
	{
    margin-left: 200px !important;
	}

}
@media only screen and (min-device-width : 728px) and (max-device-width : 1023px) {
	#clientName
	{
    margin-left: 175px !important;
	}

}
#clientName
{
    margin-top: 2px;
    margin-left: 38px;
    text-decoration: black;
    font-weight: bold;
    font-size: 22px;
}
.btn-left{
	margin-left: 0%;
}
.dt-buttons.btn-group {
    margin-top: 15px;
}
.btn-group>.btn:last-child:not(:first-child), .btn-group>.dropdown-toggle:not(:first-child) {
    border-radius: 0;
}
.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle) {
    border-radius: 0 !important;
}

table.dataTable thead .sorting_asc:after {
    content: " \e155";
}

.pagination>li:first-child>a, .pagination>li:first-child>span ,.pagination > li:last-child > a, .pagination > li:last-child > span{
    border-radius: 0px !important;
}

div#clientDetailsTable_info ,.dataTables_info{
    color: grey;
    font-style: italic;
}
a:focus, a:hover {
    text-decoration: none !important;
}
div#clientDetailsTable_filter label {
    font-weight: 600;
}
div.dataTables_wrapper div.dataTables_filter input {
    border-radius: 0px;
    outline: none;
}

.sign-hr {
    width: 100%;
    height: 20px;
    border-bottom: 1px solid #a1a1a1;
    text-align: center;
	margin-bottom: 20px;
}
.sign-title {
    font-size: 25px;
    background-color:#fbfafa;
    padding: 0 10px;
	text-align: center;
}
.tablefd{
	    float: none;
}
/* color css - theme change */
.skin-blue .main-header .navbar,.skin-blue .main-header .navbar .sidebar-toggle:hover {
    background-color: #2c3b41 !important;
}
.skin-blue .main-header .logo {
    background-color: #222d32 !important;
}
table.dataTable tbody>tr.selected, table.dataTable tbody>tr>.selected {
    background-color: #e8e7e7 !important;
}
table.dataTable tbody tr.selected, table.dataTable tbody th.selected, table.dataTable tbody td.selected {
    color: black !important;
}
.content-wrapper, .right-side {
    background-color: rgb(251, 250, 250) !important;
}
.pagination>.active>a, .pagination>.active>a:focus, .pagination>.active>a:hover, .pagination>.active>span, .pagination>.active>span:focus, .pagination>.active>span:hover {
    background-color: #2c3b41 !important;
    border-color: #2c3b41 !important;
}
.table-bordered>tbody>tr>td, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>td, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>thead>tr>th {
    border:1px solid rgba(44, 59, 65, 0.17) !important;
}
.table-bordered {
    border: 1px solid rgba(44, 59, 65, 0.39) !important;
}
table.dataTable thead .sorting:after {
    opacity: 0.7 !important;
}
th.sorting,th.sorting_asc ,th.sorting_desc{
    background-color: #2c3b41;
    color: white;
    border: 1px #2c3b41;
}
/*end color css - theme change */


text:
describe('Auth module test', function() {
    var user = {username: 'tsq', password: 'kkk'};
    beforeEach(module('btcchina'));
    var Auth_LoginService;
    var $scope, MainCtrl;
    beforeEach(inject(function(_Auth_LoginService_, _$controller_, _$rootScope_, _$httpBackend_) {
        $scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        $httpBackend.when('POST', 'http://dev.btcchina.com/api.php/account/authenticate')
          .respond({JsonWebToken: 'token'});
        MainCtrl = _$controller_('MainCtrl', {$scope: $scope});
        $httpBackend.flush();
        Auth_LoginService = _Auth_LoginService_;
    }));
    it('MainCtrl', function() {
        expect($scope.data).toEqual({JsonWebToken: 'token'});
    });
    it('Auth_LoginService', function() {
        var obj = Auth_LoginService.login(user);
        expect(obj.success).not.toBe(null);
        expect(obj.success).not.toBe(null);
    });
});

describe('PasswordController', function () {
    beforeEach(module('btcchina'));
    var $controller;
    // we can use `inject` to access $controller, the service that is responsible for instantiating controllers
    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
    }));
    describe('$scope.grade', function() {
        var $scope, controller;
        beforeEach(function () {
            $scope = {};
            controller = $controller('PasswordController', {$scope: $scope});
        });
        it('sets the strength to strong if the password len is >8 chars', function() {
            $scope.password = 'longerthaneightchars';
            $scope.grade();
            expect($scope.strength).toEqual('strong');
        });
        it('set the strength to weak if the password length <3 chars', function() {
            $scope.password = 'a';
            $scope.grade();
            expect($scope.strength).toEqual('weak');
        });
    });

});
describe('length filter', function() {
    beforeEach(module('btcchina'));
    var $filter;
    beforeEach(inject(function (_$filter_) {
        $filter = _$filter_;
    }));
    it('returns 0 when given null', function() {
        var length = $filter('length');
        expect(length(null)).toEqual(0);
    });
    it('returns the correct value when given a string of chars', function() {
        var length = $filter('length');
        expect(length('abc')).toEqual(3);
    });
});

describe('Unit testing great quotes', function() {
    var $compile, $rootScope;
    beforeEach(module('btcchina'));
    // store reference to $rootScope and $compile so they are available to all
    // tests in this describe block
    beforeEach(inject(function (_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
    }));
    it('Replaces the ele with the appropritate content', function() {
        // Compile a piece of HTMl containing the directive
        var element = $compile('<a-great-eye></a-great-eye>')($rootScope);
        // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
        $rootScope.$digest();
        // Check that the compiled element contains the templated content
        expect(element.html()).toContain('lidless, wreathed in flame, 2 times');
    });
});