text:
This is a the Official Assay Depot Java SDK. You can use it to interact with the Assay Depot (http://www.assaydepot.com) marketplace from within your Java program. More information about the API can be found at http://assaydepot.github.com/api.

## Assay Depot Developer Program

An authentication token is required for the API to function. If you would like access to the API, please email cpetersen@assaydepot.com.

## Configuration

The Java SDK exposes a configuration object which can be used to directly configure the SDK.

```java
import com.assaydepot.conf.Configuration;
import java.net.URL;

conf = new Configuration();
conf.setUrl(new URL("https://www.assaydepot.com/api"));
conf.setApiToken("YOUR TOKEN HERE");
```

Alternatively, you may choose to configure the SDK using a properties file:

```java
import com.assaydepot.conf.Configuration;
import java.net.URL;
import java.io.InputStream;
import java.util.Properties;

ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream stream = loader.getResourceAsStream("assaydepot.properties");
Properties prop = new Properties();
prop.load(stream);

conf = new Configuration();
conf.setUrl(new URL(prop.getProperty("assaydepot.url")));
conf.setApiToken(prop.getProperty("assaydepot.api_token"));
```

The properties file would look like:
```
assaydepot.url=https://www.assaydepot.com/api
assaydepot.api_token=YOUR TOKEN HERE
```

## Accessing Wares

The SDK allows users to search for and get the details of wares in the Assay Depot system. You search using the ```AssayDepot#getWareRefs``` method. For example, to search for wares containing the word "antibody" you would do the following (assuming you've already created the ```conf``` object:
```java
AssayDepot assayDepot = AssayDepotFactory.getAssayDepot( conf );
Results results = assayDepot.getWareRefs( "antibody" );
for( WareRef ref : results.getWareRefs() ) {
  System.out.println( "ware = ["+ref.getName()+"]" );
}
```

Searching for wares returns ```WareRef``` objects which contain a subset of the information contained in a ```Ware``` object. You retrieve the entire ware, use the ```AssayDepot#getWare``` method. For example:
```java
AssayDepot assayDepot = AssayDepotFactory.getAssayDepot( conf );
Ware ware = assayDepot.getWare("SOME WARE ID");
System.out.println( "HTML = ["+ware.htmlDescription()+"]" );
```

## Accessing Providers

The SDK allows users to search for and get the details of providers in the Assay Depot system. You search using the ```AssayDepot#getProviderRefs``` method. For example, to search for providers containing the word "china" you would do the following (assuming you've already created the ```conf``` object:
```java
AssayDepot assayDepot = AssayDepotFactory.getAssayDepot( conf );
Results results = assayDepot.getProviderRefs( "china" );
for( ProviderRef ref : results.getProviderRefs() ) {
  System.out.println( "provider = ["+ref.getName()+"]" );
}
```

Searching for providers returns ```ProviderRef``` objects which contain a subset of the information contained in a ```Provider``` object. You retrieve the entire provider, use the ```AssayDepot#getProvider``` method. For example:
```java
AssayDepot assayDepot = AssayDepotFactory.getAssayDepot( conf );
Provider provider = assayDepot.getProvider("SOME WARE ID");
System.out.println( "HTML = ["+provider.htmlDescription()+"]" );
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

The Assay Depot Ruby SDK is released under the MIT license.


text:
package registofatura.ws.domain;

import pt.ist.fenixframework.pstm.VBox;
import pt.ist.fenixframework.pstm.RelationList;
import pt.ist.fenixframework.pstm.OJBFunctionalSetWrapper;
import pt.ist.fenixframework.ValueTypeSerializationGenerator.*;
public abstract class Cliente_Base extends pt.ist.fenixframework.pstm.OneBoxDomainObject {
    public final static pt.ist.fenixframework.pstm.dml.RoleOne<registofatura.ws.domain.Cliente,registofatura.ws.domain.RegistoFatura> role$$registoFatura = new pt.ist.fenixframework.pstm.dml.RoleOne<registofatura.ws.domain.Cliente,registofatura.ws.domain.RegistoFatura>() {
        public registofatura.ws.domain.RegistoFatura getValue(registofatura.ws.domain.Cliente o1) {
            return ((Cliente_Base.DO_State)o1.get$obj$state(false)).registoFatura;
        }
        public void setValue(registofatura.ws.domain.Cliente o1, registofatura.ws.domain.RegistoFatura o2) {
            ((Cliente_Base.DO_State)o1.get$obj$state(true)).registoFatura = o2;
        }
        public dml.runtime.Role<registofatura.ws.domain.RegistoFatura,registofatura.ws.domain.Cliente> getInverseRole() {
            return registofatura.ws.domain.RegistoFatura.role$$cliente;
        }

    };
    public final static pt.ist.fenixframework.pstm.LoggingRelation<registofatura.ws.domain.Cliente,registofatura.ws.domain.RegistoFatura> RegistoFaturaContainsCliente = new pt.ist.fenixframework.pstm.LoggingRelation<registofatura.ws.domain.Cliente,registofatura.ws.domain.RegistoFatura>(role$$registoFatura);
    static {
        registofatura.ws.domain.RegistoFatura.RegistoFaturaContainsCliente = RegistoFaturaContainsCliente.getInverseRelation();
    }

    static {
        RegistoFaturaContainsCliente.setRelationName("registofatura.ws.domain.Cliente.RegistoFaturaContainsCliente");
    }

    private void initInstance() {
        initInstance(true);
    }

    private void initInstance(boolean allocateOnly) {

    }

    {
        initInstance(false);
    }

    protected  Cliente_Base() {
        super();
    }

    public java.lang.String getNome() {
        pt.ist.fenixframework.pstm.DataAccessPatterns.noteGetAccess(this, "nome");
        return ((DO_State)this.get$obj$state(false)).nome;
    }

    public void setNome(java.lang.String nome) {
        ((DO_State)this.get$obj$state(true)).nome = nome;
    }

    private java.lang.String get$nome() {
        java.lang.String value = ((DO_State)this.get$obj$state(false)).nome;
        return (value == null) ? null : pt.ist.fenixframework.pstm.ToSqlConverter.getValueForString(value);
    }

    private final void set$nome(java.lang.String arg0, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State  obj$state) {
        ((DO_State)obj$state).nome = (java.lang.String)((arg0 == null) ? null : arg0);
    }

    public int getNif() {
        pt.ist.fenixframework.pstm.DataAccessPatterns.noteGetAccess(this, "nif");
        return ((DO_State)this.get$obj$state(false)).nif;
    }

    public void setNif(int nif) {
        ((DO_State)this.get$obj$state(true)).nif = nif;
    }

    private int get$nif() {
        int value = ((DO_State)this.get$obj$state(false)).nif;
        return pt.ist.fenixframework.pstm.ToSqlConverter.getValueForint(value);
    }

    private final void set$nif(int arg0, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State  obj$state) {
        ((DO_State)obj$state).nif = (int)(arg0);
    }

    public registofatura.ws.domain.RegistoFatura getRegistoFatura() {
        pt.ist.fenixframework.pstm.DataAccessPatterns.noteGetAccess(this, "registoFatura");
        return ((DO_State)this.get$obj$state(false)).registoFatura;
    }

    public void setRegistoFatura(registofatura.ws.domain.RegistoFatura registoFatura) {
        RegistoFaturaContainsCliente.add((registofatura.ws.domain.Cliente)this, registoFatura);
    }

    public boolean hasRegistoFatura() {
        return (getRegistoFatura() != null);
    }

    public void removeRegistoFatura() {
        setRegistoFatura(null);
    }

    private java.lang.Long get$oidRegistoFatura() {
        pt.ist.fenixframework.pstm.AbstractDomainObject value = ((DO_State)this.get$obj$state(false)).registoFatura;
        return (value == null) ? null : value.getOid();
    }

    protected void checkDisconnected() {
        if (hasRegistoFatura()) handleAttemptToDeleteConnectedObject();

    }

    protected void readStateFromResultSet(java.sql.ResultSet rs, pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State  state) throws java.sql.SQLException {
        DO_State castedState = (DO_State)state;
        set$nome(pt.ist.fenixframework.pstm.ResultSetReader.readString(rs, "NOME"), state);
        set$nif(pt.ist.fenixframework.pstm.ResultSetReader.readint(rs, "NIF"), state);
        castedState.registoFatura = pt.ist.fenixframework.pstm.ResultSetReader.readDomainObject(rs, "OID_REGISTO_FATURA");
    }
    protected dml.runtime.Relation get$$relationFor(String attrName) {
        return super.get$$relationFor(attrName);

    }
    protected pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State  make$newState() {
        return new DO_State();

    }
    protected void create$allLists() {
        super.create$allLists();

    }
    protected static class DO_State extends pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State {
        private java.lang.String nome;
        private int nif;
        private registofatura.ws.domain.RegistoFatura registoFatura;
        protected void copyTo(pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State  newState) {
            super.copyTo(newState);
            DO_State newCasted = (DO_State)newState;
            newCasted.nome = this.nome;
            newCasted.nif = this.nif;
            newCasted.registoFatura = this.registoFatura;

        }

        // serialization code
        protected Object writeReplace() throws java.io.ObjectStreamException {
            return new SerializedForm(this);
        }

        protected static class SerializedForm extends pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State.SerializedForm {
            private static final long serialVersionUID = 1L;

            private java.lang.String nome;
            private int nif;
            private registofatura.ws.domain.RegistoFatura registoFatura;

            protected  SerializedForm(DO_State obj) {
                super(obj);
                this.nome = obj.nome;
                this.nif = obj.nif;
                this.registoFatura = obj.registoFatura;

            }

             Object readResolve() throws java.io.ObjectStreamException {
                DO_State newState = new DO_State();
                fillInState(newState);
                return newState;
            }

            protected void fillInState(pt.ist.fenixframework.pstm.OneBoxDomainObject.DO_State obj) {
                super.fillInState(obj);
                DO_State state = (DO_State)obj;
                state.nome = this.nome;
                state.nif = this.nif;
                state.registoFatura = this.registoFatura;

            }

        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
ActiveRecord::Schema.define(version: 20150210025458) do

  create_table "acceptances", force: true do |t|
    t.integer  "term_id"
    t.integer  "fi_lab_app_user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "fi_lab_app_organizations", force: true do |t|
    t.string   "name"
    t.integer  "actorId"
    t.integer  "rid"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "fi_lab_app_roles", force: true do |t|
    t.string   "name"
    t.string   "rid"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "fi_lab_app_users", force: true do |t|
    t.string   "email",               default: "", null: false
    t.string   "encrypted_password",  default: "", null: false
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",       default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "provider"
    t.string   "uid"
    t.text     "token"
    t.text     "refresh_token"
    t.string   "name"
    t.string   "nickname"
  end

  create_table "fi_lap_app_roles_organizations", id: false, force: true do |t|
    t.integer "role_id",         null: false
    t.integer "organization_id", null: false
  end

  create_table "fi_lap_app_users_organizations", id: false, force: true do |t|
    t.integer "user_id",         null: false
    t.integer "organization_id", null: false
  end

  create_table "fi_lap_app_users_roles", id: false, force: true do |t|
    t.integer "user_id", null: false
    t.integer "role_id", null: false
  end

  create_table "terms", force: true do |t|
    t.string   "version"
    t.string   "link"
    t.text     "description"
    t.boolean  "enabled"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
[![Build Status](https://travis-ci.org/fp-dom/fd-contains.svg)](https://travis-ci.org/fp-dom/fd-contains) [![npm version](https://badge.fury.io/js/fd-contains.svg)](http://badge.fury.io/js/fd-contains)
> Checks if a node is a descendant of a given node or not in a functional way.

## Installation

`npm install fd-contains --save`

## Usage

```js
var contains = require('fd-contains'),
    append = require('fd-append'),
    elem = require('fd-elem'),
    aseert = require('assert');

let h1 = elem('h1', 'Test');
let h2 = elem('h2', 'Test');

append(document.body, h1);

assert.equal(contains(document.body)(h1), true); // passes
assert.equal(contains(document.body)(h2), false); // passes
```

## API

```
contains :: node -> otherNode
```

* node -> The parent node.

* otherNode -> The node that needs to be checked for.


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('testCon', '0009_auto_20160712_1135'),
    ]

    operations = [
        migrations.AlterField(
            model_name='course_pick',
            name='StuId',
            field=models.CharField(max_length=20),
        ),
        migrations.AlterField(
            model_name='course_pick',
            name='className',
            field=models.CharField(max_length=30),
        ),
        migrations.AlterField(
            model_name='student_info',
            name='username',
            field=models.CharField(max_length=20),
        ),
    ]


text:
package server

import (
	"context"
	"errors"
	"fmt"

	"github.com/jackc/pgx"
	"github.com/pereztr5/cyboard/server/models"
	"github.com/sirupsen/logrus"
)

var (
	rawDB *pgx.ConnPool
	db    models.DBClient
)

func SetGlobalPostgresDBs(pool *pgx.ConnPool) {
	rawDB, db = pool, pool
}

func SetupPostgres(uri string) {
	if db != nil {
		// Database connection is already set up
		return
	}
	if uri == "" {
		Logger.Fatal("No postgres-uri specified.")
	}

	baseCfg, err := pgx.ParseConnectionString(uri)
	if err != nil {
		Logger.Errorf("SetupPostgres: uri parsing failed: uri=`%v`, error=%v", uri, err)
		Logger.Fatal("Did you check the docs? https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING")
	}

	pool, err := pgx.NewConnPool(pgx.ConnPoolConfig{ConnConfig: baseCfg})
	if err != nil {
		cfgStr := PgConfigAsString(&baseCfg)
		Logger.WithFields(logrus.Fields{
			"error":  err,
			"config": cfgStr,
			"uhoh":   "pool's closed, fool",
		}).Fatal("SetupPostgres: failed to create connection pool")
	}
	SetGlobalPostgresDBs(pool)

	if Logger.IsLevelEnabled(logrus.DebugLevel) {
		Logger.Debug("Connected to postgres: ", PgConfigAsString(&baseCfg))
	}
}

func PingDB(ctx context.Context) error {
	if rawDB == nil {
		return errors.New("db is nil (no connection)")
	}
	conn, err := rawDB.Acquire()
	defer rawDB.Release(conn)
	if err != nil {
		return err
	}
	return conn.Ping(ctx)
}

func PgConfigAsString(c *pgx.ConnConfig) string {
	var pw string
	if c.Password != "" {
		pw = "*****"
	}

	port := c.Port
	if port == 0 {
		port = 5432
	}

	return fmt.Sprintf("pgx.ConnConfig{host=%q, port=%v, db=%q, user=%q, password=%q}",
		c.Host, port, c.Database, c.User, pw)
}


text:
<md-toolbar style="position: fixed;">

CP Placas Eletrônicas

 Versão: 0.0.1 - 20160126

</md-toolbar>

<md-content layout="row" layout-align="center center" style="padding-top: 64px;">
  <md-card flex flex-gt-md="50" flex-md="66">
    <md-card-content>

Login

      <form novalidate name="form">
        <md-input-container ng-class="{'invalid-label' : showUsernameError()}" class="md-icon-float" flex>
          Username
          <md-icon md-font-set="material-icons">perm_identity</md-icon>
          <input name="username" ng-model="user.username" ng-class="{'invalid-field' : showUsernameError()}" required>

{{errorMessages.required_field}}

{{errorMessages.users_login_invalid}}

        </md-input-container>
        <md-input-container ng-class="{'invalid-label' : showPasswordError()}" class="md-icon-float" flex>
          Password
          <md-icon md-font-set="material-icons">lock</md-icon>
          <input name="password" type="password" ng-model="user.password" ng-class="{'invalid-field' : showPasswordError()}" required>

{{errorMessages.required_field}}

        </md-input-container>

          <md-button class="md-raised md-primary" ng-click="login(user)" ng-disabled="btnLoginDisabled">Login</md-button>

      </form>
    </md-card-content>
  </md-card>
</md-content>


text:
package de.fu_berlin.inf.ag_se.browser.listener;

import de.fu_berlin.inf.ag_se.browser.html.IElement;

public interface IFocusListener {
	public void focusGained(IElement element);

	public void focusLost(IElement element);
}


text:
using GameEngine;
using GameEngine.GameObjects;
using GameEngine.Interfaces;
using GameEngine.Tiled;
using Microsoft.Xna.Framework;
using Some2DRPG.GameObjects;
using Some2DRPG.GameObjects.Characters;

namespace Some2DRPG.MapScripts
{
    // All functionality that is common between maps should be placed here.
    public class Some2DRPGMasterScript : IMapScript
    {
        public virtual void MapLoaded(TeeEngine engine, TiledMap map, MapEventArgs mapEventArgs)
        {
            if (mapEventArgs.HasProperty("Target"))
            {
                Hero player = new Hero();
                MapEntrance targetEntrance = (MapEntrance)engine.GetEntity(mapEventArgs.GetProperty("Target"));

                player.Pos = targetEntrance.Pos + new Vector2(targetEntrance.Width, targetEntrance.Height) / 2;

                engine.AddEntity("Player", player);
            }
        }

        public virtual void Update(TeeEngine engine, GameTime gameTime)
        {
        }

        public virtual void MapUnloaded(TeeEngine engine, TiledMap map)
        {
        }

        #region EventHandlers

        public void staticObject_UpdateEvent(Entity caller, GameTime gameTime, TeeEngine engine)
        {
            caller.Opacity = 1.0f;

            foreach (RPGEntity entity in engine.Collider.GetIntersectingEntities<RPGEntity>(caller.CurrentBoundingBox))
            {
                if (entity != caller
                    && caller.Pos.Y > entity.Pos.Y
                    && entity.CurrentBoundingBox.Intersects(caller.CurrentBoundingBox))
                {
                    caller.Opacity = 0.5f;
                    return;
                }
            }
        }

        #endregion
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
* @name: S11.8.6_A2.1_T2;
* @section: 11.8.6;
* @assertion: Operator "instanceof" uses GetValue;
* @description: If GetBase(RelationalExpression) is null, throw ReferenceError;
*/

//CHECK#1
try {
  object instanceof Object;
  $ERROR('#1.1: object instanceof Object throw ReferenceError. Actual: ' + (object instanceof Object));
}
catch (e) {
  if ((e instanceof ReferenceError) !== true) {
    $ERROR('#1.2: object instanceof Object throw ReferenceError. Actual: ' + (e));
  }
}


text:
// Core ros functionality like ros::init and spin
#include <ros/ros.h>
// ROS Trajectory Action server definition
#include <control_msgs/FollowJointTrajectoryAction.h>
// Means by which we communicate with above action-server
#include <actionlib/client/simple_action_client.h>

// Includes the descartes robot model we will be using
#include <descartes_moveit/moveit_state_adapter.h>
// Includes the descartes trajectory type we will be using
#include <descartes_trajectory/axial_symmetric_pt.h>
#include <descartes_trajectory/cart_trajectory_pt.h>
// Includes the planner we will be using
#include <descartes_planner/dense_planner.h>

typedef std::vector<descartes_core::TrajectoryPtPtr> TrajectoryVec;
typedef TrajectoryVec::const_iterator TrajectoryIter;

/**
 * Generates an completely defined (zero-tolerance) cartesian point from a pose
 */
descartes_core::TrajectoryPtPtr makeCartesianPoint(const Eigen::Affine3d& pose);
/**
 * Generates a cartesian point with free rotation about the Z axis of the EFF frame
 */
descartes_core::TrajectoryPtPtr makeTolerancedCartesianPoint(const Eigen::Affine3d& pose);

/**
 * Translates a descartes trajectory to a ROS joint trajectory
 */
trajectory_msgs::JointTrajectory
toROSJointTrajectory(const TrajectoryVec& trajectory, const descartes_core::RobotModel& model,
                     const std::vector<std::string>& joint_names, double time_delay);

/**
 * Sends a ROS trajectory to the robot controller
 */
bool executeTrajectory(const trajectory_msgs::JointTrajectory& trajectory);

int main(int argc, char** argv)
{
  // Initialize ROS
  ros::init(argc, argv, "descartes_tutorial");
  ros::NodeHandle nh;

  // Required for communication with moveit components
  ros::AsyncSpinner spinner (1);
  spinner.start();

  // 1. Define sequence of points
  TrajectoryVec points;
  for (unsigned int i = 0; i < 10; ++i)
  {
    Eigen::Affine3d pose;
    pose = Eigen::Translation3d(0.0, 0.0, 1.0 + 0.05 * i);
    descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);
    points.push_back(pt);
  }

  for (unsigned int i = 0; i < 5; ++i)
  {
    Eigen::Affine3d pose;
    pose = Eigen::Translation3d(0.0, 0.04 * i, 1.3);
    descartes_core::TrajectoryPtPtr pt = makeTolerancedCartesianPoint(pose);
    points.push_back(pt);
  }

  // 2. Create a robot model and initialize it
  descartes_core::RobotModelPtr model (new descartes_moveit::MoveitStateAdapter);

  // Name of description on parameter server. Typically just "robot_description".
  const std::string robot_description = "robot_description";

  // name of the kinematic group you defined when running MoveitSetupAssistant
  const std::string group_name = "manipulator";

  // Name of frame in which you are expressing poses. Typically "world_frame" or "base_link".
  const std::string world_frame = "base_link";

  // tool center point frame (name of link associated with tool)
  const std::string tcp_frame = "tool0";

  if (!model->initialize(robot_description, group_name, world_frame, tcp_frame))
  {
    ROS_INFO("Could not initialize robot model");
    return -1;
  }

  // 3. Create a planner and initialize it with our robot model
  descartes_planner::DensePlanner planner;
  planner.initialize(model);

  // 4. Feed the trajectory to the planner
  if (!planner.planPath(points))
  {
    ROS_ERROR("Could not solve for a valid path");
    return -2;
  }

  TrajectoryVec result;
  if (!planner.getPath(result))
  {
    ROS_ERROR("Could not retrieve path");
    return -3;
  }

  // 5. Translate the result into a type that ROS understands
  // Get Joint Names
  std::vector<std::string> names;
  nh.getParam("controller_joint_names", names);
  // Generate a ROS joint trajectory with the result path, robot model, given joint names,
  // a certain time delta between each trajectory point
  trajectory_msgs::JointTrajectory joint_solution = toROSJointTrajectory(result, *model, names, 1.0);

  // 6. Send the ROS trajectory to the robot for execution
  if (!executeTrajectory(joint_solution))
  {
    ROS_ERROR("Could not execute trajectory!");
    return -4;
  }

  // Wait till user kills the process (Control-C)
  ROS_INFO("Done!");
  return 0;
}

descartes_core::TrajectoryPtPtr makeCartesianPoint(const Eigen::Affine3d& pose)
{
  using namespace descartes_core;
  using namespace descartes_trajectory;

  return TrajectoryPtPtr( new CartTrajectoryPt( TolerancedFrame(pose)) );
}

descartes_core::TrajectoryPtPtr makeTolerancedCartesianPoint(const Eigen::Affine3d& pose)
{
  using namespace descartes_core;
  using namespace descartes_trajectory;
  return TrajectoryPtPtr( new AxialSymmetricPt(pose, M_PI/2.0-0.0001, AxialSymmetricPt::Z_AXIS) );
}

trajectory_msgs::JointTrajectory
toROSJointTrajectory(const TrajectoryVec& trajectory,
                     const descartes_core::RobotModel& model,
                     const std::vector<std::string>& joint_names,
                     double time_delay)
{
  // Fill out information about our trajectory
  trajectory_msgs::JointTrajectory result;
  result.header.stamp = ros::Time::now();
  result.header.frame_id = "world_frame";
  result.joint_names = joint_names;

  // For keeping track of time-so-far in the trajectory
  double time_offset = 0.0;
  // Loop through the trajectory
  for (TrajectoryIter it = trajectory.begin(); it != trajectory.end(); ++it)
  {
    // Find nominal joint solution at this point
    std::vector<double> joints;
    it->get()->getNominalJointPose(std::vector<double>(), model, joints);

    // Fill out a ROS trajectory point
    trajectory_msgs::JointTrajectoryPoint pt;
    pt.positions = joints;
    // velocity, acceleration, and effort are given dummy values
    // we'll let the controller figure them out
    pt.velocities.resize(joints.size(), 0.0);
    pt.accelerations.resize(joints.size(), 0.0);
    pt.effort.resize(joints.size(), 0.0);
    // set the time into the trajectory
    pt.time_from_start = ros::Duration(time_offset);
    // increment time
    time_offset += time_delay;

    result.points.push_back(pt);
  }

  return result;
}

bool executeTrajectory(const trajectory_msgs::JointTrajectory& trajectory)
{
  // Create a Follow Joint Trajectory Action Client
  actionlib::SimpleActionClient<control_msgs::FollowJointTrajectoryAction> ac("joint_trajectory_action", true);
  if (!ac.waitForServer(ros::Duration(2.0)))
  {
    ROS_ERROR("Could not connect to action server");
    return false;
  }

  control_msgs::FollowJointTrajectoryGoal goal;
  goal.trajectory = trajectory;
  goal.goal_time_tolerance = ros::Duration(1.0);

  ac.sendGoal(goal);

  if (ac.waitForResult(goal.trajectory.points[goal.trajectory.points.size()-1].time_from_start + ros::Duration(5)))
  {
    ROS_INFO("Action server reported successful execution");
    return true;
  } else {
    ROS_WARN("Action server could not execute trajectory");
    return false;
  }
}


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Fitbit.Api.Portable.OAuth2
{
    public class OAuth2Helper
    {
        private const string FitbitWebAuthBaseUrl = "https://www.fitbit.com";
        private const string FitbitApiBaseUrl = "https://api.fitbit.com";

        private const string OAuthBase = "/oauth2";

        private string ClientId;
        private string ClientSecret;

        private string RedirectUri;

        public OAuth2Helper(FitbitAppCredentials credentials, string redirectUri)
        {
            this.ClientId = credentials.ClientId;
            this.ClientSecret = credentials.ClientSecret;
            this.RedirectUri = redirectUri;
        }
        public string GenerateAuthUrl(string[] scopeTypes, string state = null)
        {
            var sb = new StringBuilder();

            sb.Append(FitbitWebAuthBaseUrl);
            sb.Append(OAuthBase);
            sb.Append("/authorize?");
            sb.Append("response_type=code");
            sb.Append(string.Format("&client_id={0}", this.ClientId));
            sb.Append(string.Format("&redirect_uri={0}", Uri.EscapeDataString(this.RedirectUri)));
            sb.Append(string.Format("&scope={0}", String.Join(" ", scopeTypes)));

            if (!string.IsNullOrWhiteSpace(state))
                sb.Append(string.Format("&state={0}", state));

            return sb.ToString();
        }

        public async Task<OAuth2AccessToken> ExchangeAuthCodeForAccessTokenAsync(string code)
        {
            HttpClient httpClient = new HttpClient();

            string postUrl = OAuth2Helper.FitbitOauthPostUrl;

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("grant_type", "authorization_code"),
                new KeyValuePair<string, string>("client_id", ClientId),
                //new KeyValuePair<string, string>("client_secret", AppSecret),
                new KeyValuePair<string, string>("code", code),
                new KeyValuePair<string, string>("redirect_uri", this.RedirectUri)
            });

            string clientIdConcatSecret = OAuth2Helper.Base64Encode(ClientId + ":" + ClientSecret);

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", clientIdConcatSecret);

            HttpResponseMessage response = await httpClient.PostAsync(postUrl, content);
            string responseString = await response.Content.ReadAsStringAsync();

            OAuth2AccessToken accessToken = OAuth2Helper.ParseAccessTokenResponse(responseString);

            return accessToken;
        }

        public static readonly string FitbitOauthPostUrl = "https://api.fitbit.com/oauth2/token";

        public static OAuth2AccessToken ParseAccessTokenResponse(string responseString)
        {
            // assumption is the errors json will return in usual format eg. errors array
            JObject responseObject = JObject.Parse(responseString);

            var error = responseObject["errors"];
            if (error != null)
            {
                var errors = new JsonDotNetSerializer().ParseErrors(responseString);
                throw new FitbitException($"Unable to parse token response in method -- {nameof(ParseAccessTokenResponse)}.", errors);
            }

            var deserializer = new JsonDotNetSerializer();
            return deserializer.Deserialize<OAuth2AccessToken>(responseString);
        }

        /// <summary>
        /// Convert plain text to a base 64 encoded string - http://stackoverflow.com/a/11743162
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(plainTextBytes);
        }
    }
}


text:
using System;
class MaxNumber
{
    static void Main(string[] args)
    {
        var n = int.Parse(Console.ReadLine());
        var maxNumber = int.MinValue;

        for (int i = 0; i < n; i++)
        {
            var number = int.Parse(Console.ReadLine());

            if (number > maxNumber)
            {
                maxNumber = number;
            }
        }

        Console.WriteLine(maxNumber);
    }
}


text:
+++
template = "personal.html"

sort_by = "weight"

[extra]
id = "personal"
+++

some content


text:
var cookie_name ="", cookie_value="";
chrome.storage.local.get("cookie_name" , function(fetchedData){
    cookie_name = fetchedData["cookie_name"];
	chrome.storage.local.get("cookie_value" , function(fetchedData){
	    cookie_value = fetchedData["cookie_value"];
		var aNames = new Array();
		var aValues = new Array();
		aNames = cookie_name.split("|");
		aValues = cookie_value.split("|");
		for (c in aNames){
			document.cookie = encodeURIComponent( aNames[c] ) + "=" + encodeURIComponent( aValues[c] ) + "" + "; path=/";
		}
		//document.cookie = encodeURIComponent( cookie_name ) + "=" + encodeURIComponent( cookie_value ) + "" + "; path=/";
		window.location.reload();
	});
});


text:
package org.ansj.test;

import java.util.List;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.NlpAnalysis;
import org.ansj.splitWord.analysis.ToAnalysis;

public class NlpTest {
	public static void main(String[] args) {
		// List<Term> paser = NlpAnalysis.paser("所有词性符合标准规范.属于系统识别出的词性有") ;
		// System.out.println(paser);
		List<Term> paser = ToAnalysis.paser("词性符合标准规范.");
		System.out.println(paser);
		System.out.println(NlpAnalysis.paser("吴睿和张三是好朋友."));
		System.out.println(ToAnalysis.paser("吴睿和张三是好朋友."));
	}
}


text:
import sys
import time
import json

import redis

HISTORY_CMD_KEY = "lehome:cmd_history_list"

r = redis.Redis(host='localhost', port=6379)

print "dbsize:", r.dbsize()
print "num of keys:", r.keys()
print "volume:", r.get("lehome:last_volume")

historys = r.lrange(HISTORY_CMD_KEY, 0, -1)
print "history size:", len(historys)

# r.delete(HISTORY_CMD_KEY)

for i in range(1, 10):
    print historys[-i]

look_up_dict = {}
for item in historys:
    item = item.split(":")
    stmp = int(item[0])
    cmd = item[1]
    if cmd not in look_up_dict:
        look_up_dict[cmd] = {'count': 0}
    look_up_dict[cmd]['count'] = look_up_dict[cmd]['count'] + 1

print "dict size:", len(look_up_dict)
with open("../usr/history.json", "w") as f:
    f.write(json.dumps(look_up_dict))


text:
typedef NS_ENUM(NSInteger, PrivateMessageSendStatus) {
  PrivateMessageStatusSendSucess = 0,
  PrivateMessageStatusSending,
  PrivateMessageStatusSendFail
};

@interface PrivateMessage : NSObject
@property (readwrite, nonatomic, strong) NSString *content, *extra;
@property (readwrite, nonatomic, strong) UserInstance *friend, *sender;
@property (readwrite, nonatomic, strong) NSNumber *count, *unreadCount, *id, *read_at, *status;
@property (readwrite, nonatomic, strong) NSDate *created_at;
@property (assign, nonatomic) PrivateMessageSendStatus sendStatus;
@property (strong, nonatomic) UIImage *nextImg;

//- (BOOL)hasMedia;

//+ (instancetype)privateMessageWithObj:(id)obj andFriend:(UserInstance *)curFriend;

//- (NSString *)toSendPath;
//- (NSDictionary *)toSendParams;

//- (NSString *)toDeletePath;
@end


text:
package pl.silver.JGNL;

import pl.silver.JGNL.request.Future;

public interface Transmission
{
	public void sendEvent(Object event);
	public Future sendRequest(Object request);
}


text:
const Validator = require('./validator');

class OptionValidator extends Validator {
  constructor(optionType, additionalFieldToCheck) {
    const fieldsToCheck = ['name', 'entityNames', 'excludedNames', 'getType'];
    if (additionalFieldToCheck) {
      fieldsToCheck.push(additionalFieldToCheck);
    }
    super(`${optionType} option`, fieldsToCheck);
  }

  validate(jdlOption) {
    super.validate(jdlOption);
  }
}

module.exports = OptionValidator;


text:
package console

import (
	"syscall"

	"golang.org/x/crypto/ssh/terminal"
)

// RunningOnTerminal checks whether stdout is terminal
func RunningOnTerminal() bool {
	return terminal.IsTerminal(syscall.Stdout)
}


text:
var abp = abp || {};
(function ($) {

    if (!$) {
        return;
    }

    /* JQUERY ENHANCEMENTS ***************************************************/

    // abp.ajax -> uses $.ajax ------------------------------------------------

    abp.ajax = function (userOptions) {
        userOptions = userOptions || {};

        var options = $.extend({}, abp.ajax.defaultOpts, userOptions);
        options.success = undefined;
        options.error = undefined;

        return $.Deferred(function ($dfd) {
            $.ajax(options)
                .done(function (data) {
                    abp.ajax.handleResponse(data, userOptions, $dfd);
                }).fail(function () {
                    $dfd.reject.apply(this, arguments);
                });
        });
    };

    $.extend(abp.ajax, {
        defaultOpts: {
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json'
        },

        defaultError: {
            message: 'Ajax request is not succeed!',
            details: 'Error detail is not sent by server.'
        },

        logError: function (error) {
            abp.log.error(error);
        },

        showError: function (error) {
            if (error.details) {
                return abp.message.error(error.details, error.message);
            } else {
                return abp.message.error(error.message);
            }
        },

        handleTargetUrl: function (targetUrl) {
            if (!targetUrl) {
                location.reload();
            } else {
                location.href = targetUrl;
            }
        },

        handleUnAuthorizedRequest: function (messagePromise, targetUrl) {
            if (messagePromise) {
                messagePromise.done(function () {
                    abp.ajax.handleTargetUrl(targetUrl);
                });
            } else {
                abp.ajax.handleTargetUrl(targetUrl);
            }
        },

        handleResponse: function (data, userOptions, $dfd) {
            if (data) {
                if (data.success === true) {
                    $dfd && $dfd.resolve(data.result, data);
                    userOptions.success && userOptions.success(data.result, data);

                    if (data.targetUrl) {
                        abp.ajax.handleTargetUrl(data.targetUrl);
                    }
                } else if (data.success === false) {
                    var messagePromise = null;

                    if (data.error) {
                        messagePromise = abp.ajax.showError(data.error);
                    } else {
                        data.error = abp.ajax.defaultError;
                    }

                    abp.ajax.logError(data.error);

                    $dfd && $dfd.reject(data.error);
                    userOptions.error && userOptions.error(data.error);

                    if (data.unAuthorizedRequest) {
                        abp.ajax.handleUnAuthorizedRequest(messagePromise, data.targetUrl);
                    }
                } else { //not abp-related data!
                    $dfd && $dfd.resolve(data);
                    userOptions.success && userOptions.success(data);
                }
            } else { //no data sent to back
                $dfd && $dfd.resolve();
                userOptions.success && userOptions.success();
            }
        },

        blockUI: function (options) {
            if (options.blockUI) {
                if (options.blockUI === true) { //block whole page
                    abp.ui.setBusy();
                } else { //block an element
                    abp.ui.setBusy(options.blockUI);
                }
            }
        },

        unblockUI: function (options) {
            if (options.blockUI) {
                if (options.blockUI === true) { //unblock whole page
                    abp.ui.clearBusy();
                } else { //unblock an element
                    abp.ui.clearBusy(options.blockUI);
                }
            }
        }
    });

    /* JQUERY PLUGIN ENHANCEMENTS ********************************************/

    /* jQuery Form Plugin
     * http://www.malsup.com/jquery/form/
     */

    // abpAjaxForm -> uses ajaxForm ------------------------------------------

    if ($.fn.ajaxForm) {
        $.fn.abpAjaxForm = function (userOptions) {
            userOptions = userOptions || {};

            var options = $.extend({}, $.fn.abpAjaxForm.defaults, userOptions);

            options.beforeSubmit = function () {
                abp.ajax.blockUI(options);
                userOptions.beforeSubmit && userOptions.beforeSubmit.apply(this, arguments);
            };

            options.success = function (data) {
                abp.ajax.handleResponse(data, userOptions);
            };

            //TODO: Error?

            options.complete = function () {
                abp.ajax.unblockUI(options);
                userOptions.complete && userOptions.complete.apply(this, arguments);
            };

            return this.ajaxForm(options);
        };

        $.fn.abpAjaxForm.defaults = {
            method: 'POST'
        };
    }

})(jQuery);


text:
import { Component } from '@angular/core';

@Component({
  // eslint-disable-next-line @angular-eslint/component-selector
  selector: 'demo-tooltip-basic',
  templateUrl: './basic.html'
})
export class DemoTooltipBasicComponent {}


text:
Mycelium state
==============

This file describes the `mycelium.state` object.

Creation
--------

This object is populated in the `js.blade.php` view right after mycelium
has been loaded.

Content
-------

`editing` A boolean value indicating if the page is in editing mode.

`showTaskbar` A boolean value indicating taskbar visibility.


text:
namespace autofill {

// A thin wrapper around an AutofillTable that implements sync's
// MetadataChangeList interface. Changes are passed directly into the table and
// not stored inside this object. Since the table calls can fail, |TakeError()|
// must be called before this object is destroyed to check whether any
// operations failed.
class AutofillMetadataChangeList : public syncer::MetadataChangeList {
 public:
  AutofillMetadataChangeList(AutofillTable* table, syncer::ModelType type);
  ~AutofillMetadataChangeList() override;

  // syncer::MetadataChangeList implementation.
  void UpdateModelTypeState(
      const sync_pb::ModelTypeState& model_type_state) override;
  void ClearModelTypeState() override;
  void UpdateMetadata(const std::string& storage_key,
                      const sync_pb::EntityMetadata& metadata) override;
  void ClearMetadata(const std::string& storage_key) override;

  // Returns the value of |error_| and unsets it.
  base::Optional<syncer::ModelError> TakeError();

 private:
  // The autofill table to store metadata in; always outlives |this|.
  AutofillTable* table_;

  // The sync model type for this metadata.
  syncer::ModelType type_;

  // The first error encountered by this object, if any.
  base::Optional<syncer::ModelError> error_;
};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_WEBDATA_AUTOFILL_METADATA_CHANGE_LIST_H_


text:
<?php
require_once (dirname(__FILE__) . DIRECTORY_SEPARATOR . '../includes/Master2.php');

/**
 * @author fcsistemas - www.fcsistemas.com.ar
 * @version 2.2
 * @created 23-ene-2025
 */
class LaborTareaVO extends Master2 {
    public $idLaborTarea = ["valor" => "",
					        "obligatorio" => FALSE,
					        "tipo" => "integer",
					        "nombre" => "id",
					        "validador" => ["admiteMenorAcero" => FALSE,
					            "admiteCero" => FALSE,
					            "admiteMayorAcero" => TRUE,
					            ],
    ];
	public $idLaborActividad = ["valor" => "",
							"obligatorio" => TRUE,
							"tipo" => "combo",
							"nombre" => " Área de aplicación \\ actividad",
							"referencia" => "",
	];
    public $laborTarea = ["valor" => "",
					        "obligatorio" => TRUE,
					        "tipo" => "string",
					        "nombre" => "denominación de la tarea",
	                        "longitud" => "255"
    ];
    public $orden = ["valor" => "0",
					        "obligatorio" => TRUE,
					        "tipo" => "integer",
					        "nombre" => "orden",
					        "validador" => ["admiteMenorAcero" => FALSE,
					            "admiteCero" => TRUE,
					            "admiteMayorAcero" => TRUE
					        ],
    ];
    public $habilitado = ["valor" => TRUE,
					        "obligatorio" => TRUE,
					        "tipo" => "bool",
					        "nombre" => "habilitado",
    ];

	public function __construct()
	{
		parent::__construct();
		$this->result = new Result();
		$this->setHasNotification(true);
		$this->setTableName('laboresTarea');
		$this->setFieldIdName('idLaborTarea');
		$this->idLaborActividad['referencia'] = new LaborActividadVO();
	}

	/*
     * Funcion que valida cierta logica de negocios
     */
    public function validarLogicasNegocio($operacion){
        return;
    }

	public function getComboList($data = NULL){
		$sql = 'select CONCAT_ws(" \\\ ", a3.laborAreaDeAplicacion, a2.laborActividad, a1.laborTarea) as label, a1.idLaborTarea as data
				from laboresTarea as a1
				inner join laboresActividad as a2 using (idLaborActividad)
				inner join laboresAreaDeAplicacion as a3 using (idLaborAreaDeAplicacion)
				where true ';
		if($data['valorCampoWhere']) {
			$sql .= ' and '.$data['nombreCampoWhere'].' = ' . $data['valorCampoWhere'];
		}
		$sql .= ' order by a3.orden, a2.orden, a1.orden, laborAreaDeAplicacion, laborActividad, laborTarea ';
		//die($sql);
		try{
			$ro = $this->conn->prepare($sql);
			if($ro->execute()){
				$rs = $ro->fetchAll(PDO::FETCH_ASSOC);
				$this->result->setData($rs);
				$this->result->setStatus(STATUS_OK);
			}else{
				$this->result->setData($this);
				$this->result->setStatus(STATUS_ERROR);
				$this->result->setMessage('ERROR: Ocurrió un error al realizar la operación.\nReintente o contactese con el Administrador.');
			}
		}catch(Exception $e){
			$this->result->setData($this);
			$this->result->setStatus(STATUS_ERROR);
			$this->result->setMessage('ERROR: Ocurrió un error al realizar la operación.\nReintente o contactese con el Administrador.');
			myExceptionHandler($e);
		}
		return $this;
	}

	public function getLaboresTareas($data, $format = null){
		$sql = 'select CONCAT_WS(" \\\ ", laborAreaDeAplicacion, laborActividad, laborTarea) as value, idLaborTarea as id
				from laboresTarea as a
				inner join laboresActividad as b using (idLaborActividad)
				inner join laboresAreaDeAplicacion as c using (idLaborAreaDeAplicacion)
				where true ';
		if($data['valorCampoWhere'])
			$sql .= ' and '.$data['nombreCampoWhere'].' = '.$data['valorCampoWhere'];
		if($this->habilitado['valor'])
			$sql .= ' and a.habilitado and b.habilitado and c.habilitado';
		$sql .= ' order by value ';
		//die($sql);
		try {
			$ro = $this->conn->prepare($sql);
			$ro->execute();
			if($format == 'json') {
				echo json_encode(array_map('setHtmlEntityDecode', $ro->fetchAll(PDO::FETCH_ASSOC)));
			} else {
				$rs = $ro->fetchAll(PDO::FETCH_ASSOC);
				$this->result->setData($rs);
			}
		}catch(Exception $e) {
			$this->result->setStatus(STATUS_ERROR);
			$this->result->setMessage('ERROR: Ocurrió un error al realizar la operación. Reintente o contactese con el Administrador.');
			myExceptionHandler($e);
		}
		return $this;
	}
}
if($_GET['action'] == 'json' && $_GET['type'] == 'getLaboresTareas'){
	$aux = new LaborTareaVO();
	$aux->habilitado['valor'] = $_GET['habilitado'];
	$data = array();
	$data['nombreCampoWhere'] = $_GET['nombreCampoWhere'];
	$data['valorCampoWhere'] = $_GET['valorCampoWhere'];
	$aux->{$_GET['type']}($data, 'json');
}

if($_GET['debug'] == 'LaborTareaVO' or false){
	echo "DEBUG<br>";
	$kk = new LaborTareaVO();
	//print_r($kk->getAllRows());
	$kk->idLaborTarea = 226;
	$kk->LaborTarea = 'hhh2';
	//print_r($kk->getRowById());
	//print_r($kk->insertData());
	//print_r($kk->updateData());
	//print_r($kk->deleteData());
	echo $kk->getResultMessage();
}
?>


text:
namespace Sitecore.Ecommerce.Search
{
  /// <summary>
  /// The query Condition.
  /// </summary>
  public class Condition : QueryElement
  {
    /// <summary>
    /// Initializes a new instance of the <see cref="Condition"/> class.
    /// </summary>
    public Condition()
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Condition"/> class.
    /// </summary>
    /// <param name="condition">The condition.</param>
    public Condition(QueryCondition condition)
    {
      this.QueryCondition = condition;
    }

    /// <summary>
    /// Gets or sets the query condition.
    /// </summary>
    /// <value>The query condition.</value>
    public QueryCondition QueryCondition { get; set; }
  }
}


text:
/*
 * File:     Thread.h
 * Project:  LinWarrior 3D
 * Home:     hackcraft.de
 *
 * Created on September 24, 2011, 10:07 PM
 */

#ifndef THREAD_H
#define	THREAD_H

#include "de/hackcraft/lang/Object.h"
#include "de/hackcraft/lang/Runnable.h"

/**
 * Thread class for starting and maintaining runnable threads.
 */
class Thread : public Object, public Runnable {
private:
    Runnable* runnable;
    void* threadhandle;
public:
    Thread();
    Thread(Runnable *runnable);

    void start();
    void stop();
    virtual void run() = 0;
    virtual int hashCode();
public:
    static void sleep(unsigned int ms);
};

#endif	/* THREAD_H */


text:
from rest_framework import serializers

from core import models

class TaskLogSerializer(serializers.ModelSerializer):
    task_status = serializers.SerializerMethodField()

    class Meta:
        model = models.TaskLog
        fields = '__all__'

    def get_task_status(self, obj):
        return obj.task.status


text:
require 'test_helper'

module Jsonforem
  class CategoryTest < ActiveSupport::TestCase
    # test "the truth" do
    #   assert true
    # end
  end
end


text:
import numpy as np
import lasagne as nn
from lasagne.layers import dnn
from functools import partial
import os
import utils
import pickle

conv3 = partial(dnn.Conv2DDNNLayer,
                stride=(1, 1),
                border_mode="same",
                filter_size=(3, 3),
                nonlinearity=nn.nonlinearities.rectify)

dense = partial(nn.layers.DenseLayer,
                nonlinearity=nn.nonlinearities.rectify)

max_pool = partial(dnn.MaxPool2DDNNLayer,
                   pool_size=(2, 2),
                   stride=(2, 2))

def vgg19(batch_shape):
    """
    Create a vgg19, with the parameters from http://www.robots.ox.ac.uk/~vgg/research/very_deep/
    See googlenet.py for the method used to convert these caffe parameters to lasagne parameters.
    :param batch_shape: The shape of the input images. This should be of size (N, 3, X>=224, Y>=224). Note flexible
    image size, as the last dense layers have been implemented here with convolutional layers.
    :return: a struct with the input layer, the logit layer (before the final softmax) and the output layer.
    """
    l_in = nn.layers.InputLayer(shape=batch_shape)
    l = l_in

    l = conv3(l, num_filters=64)
    l = conv3(l, num_filters=64)

    l = max_pool(l)

    l = conv3(l, num_filters=128)
    l = conv3(l, num_filters=128)

    l = max_pool(l)

    l = conv3(l, num_filters=256)
    l = conv3(l, num_filters=256)
    l = conv3(l, num_filters=256)
    l = conv3(l, num_filters=256)

    l = max_pool(l)

    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)

    l = max_pool(l)

    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)
    l = conv3(l, num_filters=512)

    l = max_pool(l)

    l = dnn.Conv2DDNNLayer(l,
                           num_filters=4096,
                           stride=(1, 1),
                           border_mode="valid",
                           filter_size=(7, 7))
    l = dnn.Conv2DDNNLayer(l,
                           num_filters=4096,
                           stride=(1, 1),
                           border_mode="same",
                           filter_size=(1, 1))

    l_logit = dnn.Conv2DDNNLayer(l,
                                 num_filters=1000,
                                 stride=(1, 1),
                                 border_mode="same",
                                 filter_size=(1, 1),
                                 nonlinearity=None)

    l_logit_flat = nn.layers.FlattenLayer(l_logit)
    l_dense = nn.layers.NonlinearityLayer(l_logit_flat, nonlinearity=nn.nonlinearities.softmax)

    filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vgg19.pkl')

    if os.path.exists(filename):
        with open(filename, 'r') as f:
            nn.layers.set_all_param_values(l_dense, pickle.load(f))

    return utils.struct(
        input=l_in,
        out=l_dense,
        logit=l_logit
    )

if __name__ == "__main__":
    model = vgg19((1, 3, 224, 224))
    nn.layers.set_all_param_values(model.out, np.load("data/vgg19.npy"))
    filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vgg19.pkl')
    pickle.dump(nn.layers.get_all_param_values(model.out), open(filename, 'w'))


text:
import * as React from 'react'
import * as Kb from '../../../common-adapters'
import * as Styles from '../../../styles'
import type * as RPCChatTypes from '../../../constants/types/rpc-chat-gen'

export type Info = {
  type: 'image' | 'file'
  title: string
  filename: string
  outboxID: RPCChatTypes.OutboxID | null
}

type PathAndInfo = {
  path: string
  info: Info
}

type Props = {
  pathAndInfos: Array<PathAndInfo>
  onCancel: () => void
  onSubmit: (titles: Array<string>) => void
}

type State = {
  index: number
  titles: Array<string>
}

class GetTitles extends React.Component<Props, State> {
  state: State

  constructor(props: Props) {
    super(props)
    this.state = {
      index: 0,
      titles: props.pathAndInfos.map(() => ''),
    }
  }

  _onNext = (e?: React.BaseSyntheticEvent) => {
    e?.preventDefault()

    const {info} = this.props.pathAndInfos[this.state.index]
    if (!info) return

    const nextIndex = this.state.index + 1

    // done
    if (nextIndex === this.props.pathAndInfos.length) {
      this.props.onSubmit(this.state.titles)
    } else {
      // go to next
      this.setState({index: nextIndex})
    }
  }

  _onSubmit = (e?: React.BaseSyntheticEvent) => {
    e?.preventDefault()
    this.props.onSubmit(this.state.titles)
  }

  _isLast = () => {
    const numPaths = this.props.pathAndInfos.length
    return this.state.index + 1 === numPaths
  }

  // Are we trying to upload multiple?
  _multiUpload = () => {
    return this.props.pathAndInfos.length > 1
  }

  _updateTitle = (title: string) => {
    this.setState(state => ({
      titles: [...state.titles.slice(0, state.index), title, ...state.titles.slice(state.index + 1)],
    }))
  }

  render() {
    const {info, path} = this.props.pathAndInfos[this.state.index] ?? {}
    const titleHint = 'Add a caption...'
    if (!info) return null

    return (
      <Kb.PopupWrapper onCancel={this.props.onCancel}>
        <Kb.Box2 direction="vertical" style={styles.containerOuter} fullWidth={true}>
          <Kb.Box2 alignItems="center" direction="vertical" fullWidth={true} style={styles.container}>
            <Kb.BoxGrow style={styles.boxGrow}>
              {info.type === 'image' ? (
                <Kb.ZoomableImage src={Styles.isAndroid ? `file://${path}` : path} style={styles.image} />
              ) : (
                <Kb.Box2 direction="vertical" fullWidth={true} fullHeight={true} centerChildren={true}>
                  <Kb.Icon type="icon-file-uploading-48" />
                </Kb.Box2>
              )}
            </Kb.BoxGrow>
            {this.props.pathAndInfos.length > 0 && !Styles.isMobile && (
              <Kb.Box2 direction="vertical" style={styles.filename}>
                <Kb.Text type="BodySmallSemibold">Filename</Kb.Text>
                <Kb.Text type="BodySmall" center={true}>
                  {info.filename} ({this.state.index + 1} of {this.props.pathAndInfos.length})
                </Kb.Text>
              </Kb.Box2>
            )}
            <Kb.Box2 direction="vertical" fullWidth={true} style={styles.inputContainer}>
              <Kb.PlainInput
                style={styles.input}
                autoFocus={true}
                autoCorrect={true}
                placeholder={titleHint}
                multiline={true}
                rowsMin={2}
                padding="tiny"
                value={this.state.titles[this.state.index]}
                onEnterKeyDown={this._onNext}
                onChangeText={this._updateTitle}
                selectTextOnFocus={true}
              />
            </Kb.Box2>
          </Kb.Box2>
          <Kb.ButtonBar fullWidth={true} small={true} style={styles.buttonContainer}>
            {!Styles.isMobile && (
              <Kb.Button fullWidth={true} type="Dim" onClick={this.props.onCancel} label="Cancel" />
            )}
            {this._isLast() ? (
              <Kb.WaitingButton
                fullWidth={!this._multiUpload()}
                waitingKey={null}
                onClick={this._onSubmit}
                label="Send"
              />
            ) : (
              <Kb.Button fullWidth={!this._multiUpload()} onClick={this._onNext} label="Next" />
            )}
            {this._multiUpload() ? (
              <Kb.WaitingButton waitingKey={null} onClick={this._onSubmit} label="Send All" />
            ) : null}
          </Kb.ButtonBar>
        </Kb.Box2>
      </Kb.PopupWrapper>
    )
  }
}

const styles = Styles.styleSheetCreate(
  () =>
    ({
      boxGrow: {
        margin: Styles.globalMargins.small,
        overflow: 'hidden',
        width: '100%',
      },
      buttonContainer: Styles.platformStyles({
        isElectron: {
          alignSelf: 'flex-end',
          borderStyle: 'solid',
          borderTopColor: Styles.globalColors.black_10,
          borderTopWidth: 1,
          flexShrink: 0,
          padding: Styles.globalMargins.small,
        },
        isMobile: Styles.padding(Styles.globalMargins.xsmall, Styles.globalMargins.small, 0),
      }),
      cancelButton: {marginRight: Styles.globalMargins.tiny},
      container: {
        flexGrow: 1,
        paddingLeft: Styles.globalMargins.small,
        paddingRight: Styles.globalMargins.small,
      },
      containerOuter: Styles.platformStyles({
        isElectron: {
          height: 560,
          width: 400,
        },
        isMobile: {flexGrow: 1},
      }),
      filename: Styles.platformStyles({
        isElectron: {
          alignItems: 'center',
          marginBottom: Styles.globalMargins.small,
        },
      }),
      image: {
        height: '100%',
        maxHeight: '100%',
        maxWidth: '100%',
        width: '100%',
      },
      imageContainer: Styles.platformStyles({
        common: {justifyContent: 'center'},
        isElectron: {
          flex: 1,
          height: 325,
          paddingBottom: Styles.globalMargins.medium,
          paddingTop: Styles.globalMargins.medium,
          width: 325,
        },
        isMobile: {
          height: '100%',
          width: '100%',
        },
      }),
      input: Styles.platformStyles({
        common: {
          borderColor: Styles.globalColors.blue,
          borderRadius: Styles.borderRadius,
          borderWidth: 1,
          marginBottom: Styles.globalMargins.tiny,
          width: '100%',
        },
        isElectron: {maxHeight: 100},
        isTablet: {
          alignSelf: 'center',
          maxWidth: 460,
        },
      }),
      inputContainer: Styles.platformStyles({
        isElectron: {
          paddingLeft: Styles.globalMargins.small,
          paddingRight: Styles.globalMargins.small,
        },
      }),
      nonImage: {
        alignSelf: 'center',
        justifyContentSelf: 'center',
      },
      scrollView: Styles.platformStyles({
        common: {
          backgroundColor: Styles.globalColors.blueGrey,
          height: '100%',
          width: '100%',
        },
        isElectron: {borderRadius: Styles.borderRadius},
      }),
    } as const)
)

export default GetTitles


text:
package com.pandazilla.datastrutures.queue;

import com.pandazilla.datastrutures.exceptions.QueueEmptyException;
import com.pandazilla.datastrutures.exceptions.QueueFullException;

/**
 * Queue implementation based on array
 */
public class ArrayQueue implements Queue {

    private int capacity;

    private Object[] elements;

    private int front;
    private int rear;

    public ArrayQueue(int capacity) {
        this.capacity = capacity;
        elements = new Object[capacity];
    }

    @Override
    public int size() {
        return (capacity - front + rear) % capacity;
    }

    @Override
    public boolean isEmpty() {
        return front == rear;
    }

    @Override
    public boolean isFull() {
        return rear == capacity - 1;
    }

    @Override
    public Object front() throws QueueEmptyException {
        if (isEmpty()) {
            throw new QueueEmptyException("The Queue is empty");
        }
        return elements[front];
    }

    @Override
    public void insert(Object element) {
        if (size() == capacity) {
            throw new QueueFullException("The queue is full!");
        }
        elements[rear] = element;
        rear = (rear + 1) % capacity;
    }

    @Override
    public Object remove() throws QueueEmptyException {
        if (isEmpty()) {
            throw new QueueEmptyException("The Queue is empty");
        }
        Object temp = elements[front];
        elements[front] = null;
        front = (front + 1) % capacity;
        return temp;
    }

    public void clearQueue() {
        while(isEmpty()) {
            remove();
        }
    }

    public void printQueue() {
        for (Object obj : elements) {
            System.out.print(obj + " ");
        }
    }

}


text:
require 'rubygems'
require 'bundler/setup'
Bundler.setup(:default)

require 'active_support'
require 'active_support/time'
require 'active_support/core_ext'

RSpec.configure do |config|
  # disable SimpleCov when running through Guard
  if ENV['COVERAGE']
    # NOTE: this must happen before application code is required
    require 'simplecov'
    require 'launchy'
    SimpleCov.start do
      add_filter '/spec/'
      add_filter '/lib/tasks/'
      add_group 'Application', '../lib/'
      add_group 'Configuration', '../config/'
    end

    config.after(:suite) do
      # Open the newly generated coverage report
      Launchy.open('file://' + File.join(__dir__, '..', 'coverage', 'index.html'))
    end
  end

  config.add_setting :selenium_webdriver, default: :firefox

  config.mock_with :rspec do |mocks|
    mocks.syntax = :expect
  end

  config.before(:each, selenium: false) do
    allow(Selenium::WebDriver).to receive(:for).and_return(Selenium::FakeDriver.new)
    allow_any_instance_of(Selenium::FakeDriver).to receive(:find_element).and_return(nil)
    allow_any_instance_of(Selenium::FakeDriver).to receive(:find_elements).and_return([])
    allow_any_instance_of(Selenium::FakeDriver).to receive(:get).and_return(true)
  end

  # find all of these paths
  Dir[
    # attempts cross platform support
    File.join('.', 'lib', '*.rb'),
    File.join('.', 'lib', 'forae', '*.rb'),
    File.join('.', 'lib', 'fora_mora', '*.rb'),
    File.join('.', 'spec', 'support', '**', '*.rb')
  ].sort.each do |file|
    # build the require statement
    dirname = File.dirname(file)
    basename = File.basename(file, '.rb')
    require_statement = File.join(dirname, basename)
    # puts "requiring #{require_statement.inspect}"
    require require_statement
  end
end


text:
- Make cli options extensible
- Update scopt to 3.5.0


text:
// -----------------------------------------------------------------------------------------
// <copyright file="CommonUtil.cs" company="Microsoft">
//    Copyright 2013 Microsoft Corporation
//
//    Licensed 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.
// </copyright>
// -----------------------------------------------------------------------------------------

namespace Sandboxable.Microsoft.WindowsAzure.Storage.Table.Queryable
{
    using System;
    using System.Diagnostics;
    using System.Linq;

    internal static class CommonUtil
    {
        private static readonly Type[] UnsupportedTypes = new Type[]
        {
#if !ASTORIA_LIGHT
                typeof(System.Dynamic.IDynamicMetaObjectProvider),
                typeof(System.Tuple<>),
                typeof(System.Tuple<,>),
                typeof(System.Tuple<,,>),
                typeof(System.Tuple<,,,>),
                typeof(System.Tuple<,,,,>),
                typeof(System.Tuple<,,,,,>),
                typeof(System.Tuple<,,,,,,>),
                typeof(System.Tuple<,,,,,,,>)
#endif
        };

        internal static bool IsUnsupportedType(Type type)
        {
            if (type.IsGenericType)
            {
                type = type.GetGenericTypeDefinition();
            }

            if (UnsupportedTypes.Any(t => t.IsAssignableFrom(type)))
            {
                return true;
            }

            Debug.Assert(!type.FullName.StartsWith("System.Tuple", StringComparison.Ordinal), "System.Tuple is not blocked by unsupported type check");
            return false;
        }

        internal static bool IsClientType(Type t)
        {
            return t.GetInterface(typeof(ITableEntity).FullName, false) != null;
        }
    }
}


text:
<!DOCTYPE html>

    <title>TokenStream Class Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          OysterKit Docs

         (93% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

      OysterKit Reference

      TokenStream Class Reference

            Classes

                AbstractSyntaxTreeConstructor

                – IntermediateRepresentationNode

                ChoiceRule

                ClosureRule

                Lexer

                NodeStack

                NodeStackEntry

                RecursiveRule

                ReferenceRule

                SequenceRule

                StateCache

                StringScanner

                TerminalRule

                TokenStream

                TokenStreamIterator

            Enumerations

                Log

                MatchResult

                ProcessingError

                RuleAnnotation

                RuleAnnotationValue

            Extensions

                Array

                CharacterSet

                Collection

                Decodable

                Dictionary

                Int

                NSRegularExpression

                String

                _ParsingDecoder

            Functions

                !(_:)

                -(_:)

                ==(_:_:)

                >>(_:)

                areEqual(lhs:rhs:)

                ~(_:)

            Protocols

                AbstractSyntaxTree

                CausalErrorType

                DecodeableAbstractSyntaxTree

                Grammar

                IntermediateRepresentation

                LexicalAnalyzer

                LexicalContext

                Node

                Rule

                Terminal

                TokenType

            Structures

                Behaviour

                – Kind

                Cardinality

                EndOfFile

                HomogenousTree

                ParsingDecoder

                ProcessingErrorType

                StringToken

            Type Aliases

                Language

                Parser

                RuleAnnotations

                StreamedToken

                Test

TokenStream

public class TokenStream : Sequence

A TokenStream provides lazy iterators that minimize memory consumption and overhead allowing you to iterate through the tokens created by the
root rules (those at the lowest level in the language) in the supplied Grammar

                    Iterator

The iterator implementation to use

Declaration

Swift

public typealias Iterator = TokenStreamIterator

                    init(_:using:)

Undocumented

Declaration

Swift

public init(_ source: String, using grammar: Grammar)

                    init(_:using:with:)

Undocumented

Declaration

Swift

public init<Lex>(_ source: String, using grammar: Grammar, with lexer: Lex.Type) where Lex : LexicalAnalyzer

                    makeIterator()

Declaration

Swift

public func makeIterator() -> Iterator

© 2018 . All rights reserved. (Last updated: 2018-09-03)

Generated by jazzy ♪♫ v0.9.3, a Realm project.


text:
package org.jnosql.artemis;

import org.jnosql.artemis.model.Person;

public interface PersonIgnoreRepository extends IgnoreRepository<Person, Long>{
}


text:
class OtherClass:
    pass


text:
<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Dangky;

/**
 * DangkySearch represents the model behind the search form about `common\models\Dangky`.
 */
class DangkySearch extends Dangky
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'student_id', 'detai_id', 'teacher_id', 'created_at', 'status'], 'integer'],
            [['description'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Dangky::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'student_id' => $this->student_id,
            'detai_id' => $this->detai_id,
            'teacher_id' => $this->teacher_id,
            'created_at' => $this->created_at,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}


text:
<?hh //strict

namespace HHPack\Performance\Test\Generator;

use HHPack\Performance\Generator\DefaultGenerator;
use type Facebook\HackTest\HackTest;
use function Facebook\FBExpect\expect;

final class DefaultGeneratorTest extends HackTest {
  public function testGenerateWatchers(): void {
    $generator = new DefaultGenerator();

    $orderNumber = Set {};
    $watchers = $generator->generate(5);

    foreach ($watchers as $number => $watcher) {
      $orderNumber->add($number);
    }

    expect($orderNumber->count())->toBeSame(5);
    expect($orderNumber->contains(1))->toBeTrue();
    expect($orderNumber->contains(2))->toBeTrue();
  }
}


text:
<?php

App::uses('DebugPanel', 'DebugKit.Lib');

/**
 * Class LogPanel
 *
 */
class LogPanel extends DebugPanel {

/**
 * Constructor - sets up the log listener.
 *
 * @return \LogPanel
 */
	public function __construct() {
		parent::__construct();
		$existing = CakeLog::configured();
		if (empty($existing)) {
			CakeLog::config('default', array(
				'engine' => 'FileLog'
			));
		}
		CakeLog::config('debug_kit_log_panel', array(
			'engine' => 'DebugKit.DebugKitLog',
			'panel' => $this
		));
	}

/**
 * beforeRender Callback
 *
 * @param Controller $controller
 * @return array
 */
	public function beforeRender(Controller $controller) {
		$logger = $this->logger;
		return $logger;
	}
}


text:
'use strict';
// StrongLoop/LoopBack Modules
var app = require('app-core').loopback;
var boot = require('loopback-boot');
var debug = require('debug')('app-api');
var colors = require('colors');
var config = require('app-core').config;

module.exports = {
    loopback: app,
    config: config
}

boot(app, __dirname);

/**
 * Start the API Server
 */

app.start = function () {

    // start the web server
    return app.listen(function () {
        app.emit('started');
        debug('listening in ' + app.settings.env.green.bold + ' mode.');
        debug('Ctrl+C'.green.bold + ' to shut down. ;)');
        console.log('listening on port ' + app.get('port'));

        // Exit cleanly on Ctrl+C
        process.on('SIGINT', function () {
            // app.io.close();  // close socket.io
            console.log('\n');
            debug('has ' + 'shutdown'.green.bold);
            debug('was running for ' + Math.round(process.uptime()).toString().green.bold + ' seconds.');
            process.exit(0);
        });

    });

};

if (require.main === module || (
    require.main.filename.indexOf('interceptor.js') !== -1 &&
    (require.main.children || []).indexOf(module) !== -1)
) {
    app.start();
}


text:
//
//  BusViewController.m
//  MU Bus Tracking
//
//  Created by Jake Gregg on 5/6/14.
//  Copyright (c) 2014 Jake Gregg. All rights reserved.
//

#import "BusViewController.h"

@interface BusViewController ()

@end

@implementation BusViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithBus:(Bus *)bus {
    self = [super init];
    _bus = bus;
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = [NSString stringWithFormat:@"Bus %@", _bus.busID];

    CGRect bounds = [[UIScreen mainScreen]bounds];
    self.view = [[BusView alloc]initWithFrame:CGRectMake(0, 0, bounds.size.width, bounds.size.height) andBus:_bus];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package pl.kodujdlapolski.na4lapy.ui.payment;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import pl.kodujdlapolski.na4lapy.R;

public class BankListDecoration extends RecyclerView.ItemDecoration {

    private int mSpace;
    private int mSpanCount;

    public BankListDecoration(Context context, int spanCount) {
        mSpace = context.getResources().getDimensionPixelSize(R.dimen.element_spacing);
        mSpanCount = spanCount;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int position = parent.getChildAdapterPosition(view);
        int column = position % mSpanCount;

        outRect.top = (position < mSpanCount) ? mSpace : 0;
        outRect.right = (column == mSpanCount - 1) ? mSpace : 0;

        outRect.left = mSpace;
        outRect.bottom = mSpace;
    }
}


text:
<?php
// Make sure we are not already loaded
if (defined('IN_SIMPLAFORM')) {
    return;
}

/**
 * SimplaForm Autoloader
 * @package SimplaForm
 * @author Jeremy Simkins <jpsimkins@gmail.com>
 */
class SimplaFormAutoloader {

    /**
     * Object Instance
     * @var object
     */
    protected static $instance;

    /**
     * Register methods for the autoloader
     */
    private function __construct() {
        // Allow file access
        if (!defined('IN_SIMPLAFORM')) {
            define('IN_SIMPLAFORM', true);
        }
        spl_autoload_register(array($this, 'loadLibrary'));
    }

    /**
     * Initiate the autoloader
     */
    public static function init() {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Includes the file
     * @param string $filePath
     * @return bool
     */
    private static function _include($filePath) {
        if (file_exists($filePath)) {
            include($filePath);
            return true;
        }
        return false;
    }

    /**
     * Library Files
     * @param string $className
     * @return bool
     */
    private function loadLibrary($className) {
        if (!is_string($className)) {
            return false;
        }
        return self::_include(SIMPLAFORM_LIBRARY_PATH . $className . '.php');
    }

}
SimplaFormAutoloader::init();


text:
module TestNet (testTree) where

import qualified Data.List as DL
import qualified Data.ByteString as DB
import qualified Jade.TopLevel as TopLevel
import qualified Jade.Decode as Decode
import qualified Jade.Module as Modul
import qualified Jade.Net as Net
import qualified Jade.Wire as Wire
import Text.Format
import TestUtil
import Control.Monad
import Jade.Rawr.Types
import Jade.Common

testTreeGetInternalSigNames = TestTree "getinternalsigname" $
  let t name exp = TestCase name (testGetInternalSigNames name exp)
  in [ t "Rep1FA2" ["CO"]
     ]

testGetInternalSigNames modname expected = do
  testExpGot modname expected $ do
    TopLevel.getInternalSigNames (qualifiedModName modname)

testGetNumNetsInternalSigNames = TestTree "getinternalsigname" $
  let t name exp = TestCase name (testGetInternalSigNames name exp)
  in [ t "Rep1FA2" ["CO"]
     ]

testTree = TestTree "Net" [ testTreeGetInternalSigNames
                          ]


text:
import { EffectNodeBase } from './base';

export const NAME = 'Tremolo';
export const TYPE = 'tremolo';

function tremoloEffectParameterObject() {
  return {
    type: TYPE,
    bypass: false,
    parameters: {
      intensity: 0.3,
      rate: 4,
      stereoPhase: 0,
    },
  };
}

class TremoloEffectNode extends EffectNodeBase {
  constructor(tuna, po) {
    super(tuna, po);

    this.fx = new tuna.Tremolo({
      intensity: po.parameters.intensity,
      rate: po.parameters.rate,
      stereoPhase: po.parameters.stereoPhase,
      bypass: po.bypass,
    });
  }

  updateFromParameterObject(po) {
    this.fx.bypass = po.bypass;
    this.fx.intensity = po.parameters.intensity;
    this.fx.rate = po.parameters.rate;
    this.fx.stereoPhase = po.parameters.stereoPhase;
  }
}

export { TremoloEffectNode as Node, tremoloEffectParameterObject as parameterObject };


text:
'use-strict';

import {
  Widget
} from 'phosphor-widget';

import {
  OutputAreaModel, OutputAreaWidget, IOutputAreaModel,
  OutputType, StreamName
} from '../../lib/index';

import '../index.css';

function main(): void {
  let model = new OutputAreaModel();

  // import the data json file
  let data = require('../data/data.json');
  data.forEach((msg: any) => {
    consumeMessage(msg, model);
  });
  let out = new OutputAreaWidget(model);
  out.attach(document.body);
}

window.onload = main;

/**
  * A function to update an output area Model to reflect a stream of messages
  */
export
function consumeMessage(msg: any, outputArea: IOutputAreaModel): void {
    let output: any = {};
    let content = msg.content;
    switch (msg.header.msg_type) {
    case 'clear_output':
      outputArea.clear(content.wait)
      break;
    case 'stream':
      output.outputType = OutputType.Stream;
      output.text = content.text;
      switch(content.name) {
      case "stderr":
        output.name = StreamName.StdErr;
        break;
      case "stdout":
        output.name = StreamName.StdOut;
        break;
      default:
        throw new Error(`Unrecognized stream type ${content.name}`);
      }
      outputArea.add(output);
      break;
    case 'display_data':
      output.outputType = OutputType.DisplayData;
      output.data = content.data;
      output.metadata = content.metadata;
      outputArea.add(output);
      break;
    case 'execute_result':
      output.outputType = OutputType.ExecuteResult;
      output.data = content.data;
      output.metadata = content.metadata;
      output.execution_count = content.execution_count;
      outputArea.add(output);
      break;
    case 'error':
      output.outputType = OutputType.Error;
      output.ename = content.ename;
      output.evalue = content.evalue;
      output.traceback = content.traceback.join('\n');
      outputArea.add(output);
      break;
    default:
      console.error('Unhandled message', msg);
    }
}


text:
class GL_ImplicitLineGraph : public GL_LineGraph
{
public:
	GL_ImplicitLineGraph(Graph &graph) : GL_LineGraph(graph){ }

	virtual bool has_unit_normals() const{ return true; } // has no normals

	virtual void update(int n_threads, double quality);
};


text:
require 'helper'

describe Surveygizmo::Error do
  subject { Surveygizmo::Client.new(:username => "maarten@moretea.nl", :password => "keyboardcat") }
  let(:survey_id) { 42 }
  let(:response_url) { "/v2/survey/#{survey_id}/surveyresponse" }
  let(:query) {
    {
      "user:md5" => "maarten@moretea.nl:39f8d5313141b1f2bade311ba571537e",
      "filter[field][0]"    => "datesubmitted",
      "filter[operator][0]" => ">=",
      "filter[value][0]"    => "2012-01-01",
    }
  }

  before do
    stub_get(response_url).with(query: query).
      to_return(:body => fixture("error.json"), :headers => {:content_type => "application/json; charset=utf-8"})
  end

  let(:request) { subject.survey_responses(survey_id, filter: { field: "datesubmitted", operator: ">=", value: "2012-01-01" }) }

  it "throws an Surveygizmo::Error" do
    expect { request }.to raise_error Surveygizmo::Error
  end

  it "has the correct code" do
    expect { request }.to raise_error(Surveygizmo::Error) { |e| e.code.should == 103 }
  end

  it "has the correct message" do
    expect { request }.to raise_error(Surveygizmo::Error) { |e| e.message.should == "Surveygizmo error! (103) Service currently unavailable" }
  end
end


text:
package javaselast.lessons.lesson03.payer;

public class Run {

    public static void main(String[] args) {

        PrivatePayer[] payers = new PrivatePayer[5];

        for (int i = 0; i < payers.length; i++) {
            payers[i] = new PrivatePayer(1,"name"+i,"last"+i);
        }

        System.out.println(payers[1].pay(100));
        System.out.println(payers[3].pay(1000));
        System.out.println(payers[3].pay(10));
    }
}


text:
import $ from 'jquery';
import Marionette from 'backbone.marionette';
import _ from 'underscore';

import {CollectionView} from 'pageflow/ui';

import {app} from 'pageflow/editor';
import {events} from 'pageflow/frontend';
import {delayedStart, Slideshow, widgetTypes} from 'pageflow-paged/frontend';

import {BlankEntryView} from './BlankEntryView';
import {PagePreviewView} from './PagePreviewView';

import template from '../templates/entryPreview.jst';

export const EntryPreviewView = Marionette.ItemView.extend({
  template,
  className: 'entry_preview',

  ui: {
    container: '> .container',
    header: '> .container > .header',
    entry: '> .container > .entry',
    overview: '> .container > .overview',
    navigationDisabledHint: '.navigation_disabled_hint'
  },

  initialize: function() {
    this.pages = this.model.pages.persisted();

    this.widgets = $();
    this.debouncedFetchWidgets = _.debounce(this.fetchWidgets, 200);
  },

  onRender: function() {
    this.pageViews = this.subview(new CollectionView({
      el: this.ui.entry,
      collection: this.pages,
      itemViewConstructor: PagePreviewView,
      blankSlateViewConstructor: BlankEntryView
    }));

    this.ui.entry.append($('#indicators_seed > *'));

    this.update();

    this.listenTo(this.model, 'sync:order sync:widgets', this.update);
    this.listenTo(this.model, 'change:metadata', function() {
      this.model.once('sync', this.update, this);
    });
    this.listenTo(this.model, 'change:emulation_mode', this.updateEmulationMode);

    this.listenTo(this.model.storylines, 'sync', this.update);
    this.listenTo(this.model.chapters, 'sync', this.update);
    this.listenTo(this.model.pages, 'sync', this.update);

    this.listenTo(this.model.audioFiles, 'sync', this.update);
    this.listenTo(this.model.imageFiles, 'sync', this.update);
    this.listenTo(this.model.videoFiles, 'sync', this.update);

    this.listenTo(events, 'page:changing', function(event) {
      if (this.model.get('emulation_mode')) {
        this.ui.navigationDisabledHint.css('opacity', 1);

        clearTimeout(this.navigationDisabledHintTimeout);
        this.navigationDisabledHintTimeout = setTimeout(_.bind(function() {
          this.ui.navigationDisabledHint.css('opacity', 0);
        }, this), 2000);

        event.cancel();
      }
    });

    this.listenTo(events, 'page:change', function(page) {
      this.updateEmulationModeSupport(page.getPermaId());
    });
  },

  onShow: function() {
    var slideshow = this.slideshow = Slideshow.setup({
      element: this.ui.entry,
      enabledFeatureNames: this.model.get('enabled_feature_names'),
      simulateHistory: true
    });

    delayedStart.perform();

    this.listenTo(this.pages, 'add', function() {
      slideshow.update();
    });

    this.listenTo(this.pages, 'remove', function() {
      slideshow.update();
    });

    this.listenTo(this.pages, 'edit', function(model) {
      if (this.lastEditedPage != model) {
        this.model.unset('emulation_mode');
      }

      this.lastEditedPage = model;

      slideshow.goTo(this.pageViews.itemViews.findByModel(model).$el);
    });

    this.listenTo(app, 'resize', function() {
      slideshow.triggerResizeHooks();
      this.updateSimulatedMediaQueryClasses();
    });

    this.listenTo(this.model.pages, 'change:template', function() {
      this.updateEmulationModeSupport(slideshow.currentPagePermaId());
    });

    this.updateSimulatedMediaQueryClasses();
  },

  updateEmulationModeSupport: function(permaId) {
    var model = this.model.pages.getByPermaId(permaId);

    this.model.set('emulation_mode_disabled',
                       !model || !model.pageType().supportsPhoneEmulation());
  },

  updateSimulatedMediaQueryClasses: function() {
    var width = this.ui.container.width();
    var height = this.ui.container.height();
    var portrait = width < height;

    $('html')
      .toggleClass('simulate_mobile', width <= 900)
      .toggleClass('simulate_phone', (portrait && width <= 500) || (!portrait && height <= 500))
      .toggleClass('simulate_desktop', (portrait && width > 500) || (!portrait && height > 500))
      .toggleClass('simulate_narrow_desktop', width <= 1200)
      .toggleClass('simulate_wide_desktop', width > 1600)
      .toggleClass('simulate_pad_portrait', width <= 768 && portrait)
      .toggleClass('simulate_phone_portrait', width <= 500 && portrait);
  },

  update: function() {
    this.debouncedFetchWidgets();

    this.$el.toggleClass('emphasize_chapter_beginning', !!this.model.metadata.get('emphasize_chapter_beginning'));
  },

  fetchWidgets: function() {
    var view = this;

    $.ajax(this.model.url() + '/paged/partials').success(function(response) {
      var partials = $('<div />').html(response);

      view.ui.header.replaceWith(partials.find('> .header'));
      view.ui.overview.replaceWith(partials.find('> .overview'));
      view.bindUIElements();

      view.updateWidgets(partials);

      view.ui.header.header({
        slideshow: view.slideshow
      });
      view.ui.overview.overview();
    });
  },

  updateWidgets: function(partials) {
    var widgets = partials.find('[data-widget]');
    this.updatePresentWidgetsCssClasses(widgets);

    this.widgets.remove();
    this.widgets = widgets;
    this.ui.entry.before(this.widgets);

    widgetTypes.enhance(this.$el);
  },

  updatePresentWidgetsCssClasses: function(newWidgets) {
    var previousClasses = this.widgetNames(this.widgets);
    var newClasses = this.widgetNames(newWidgets);
    var removedClasses = _.difference(previousClasses, newClasses);
    var addedClasses = _.difference(newClasses, previousClasses);

    this.$el.addClass('widgets_present');
    this.$el.removeClass(removedClasses.join(' '));
    this.$el.addClass(addedClasses.join(' '));

    if (removedClasses.length || addedClasses.length) {
      events.trigger('widgets:update');
    }
  },

  widgetNames: function(widgets) {
    return widgets.map(function() {
      return 'widget_' + $(this).data('widget') + '_present';
    }).get();
  },

  updateEmulationMode: function() {
    if (this.model.previous('emulation_mode')) {
      this.$el.removeClass(this.emulationModeClassName(this.model.previous('emulation_mode')));
    }

    if (this.model.get('emulation_mode')) {
      this.$el.addClass(this.emulationModeClassName(this.model.get('emulation_mode')));
    }

    app.trigger('resize');
  },

  emulationModeClassName: function(mode) {
    return 'emulation_mode_' + mode;
  }
});


text:
function filter_plot(in_data, myFilter, time, handles)

L=length(in_data);

Tx=linspace(0, time, L);
axes(handles.axes1);
plot(Tx, in_data);
set(gca,'YDir','normal')
xlabel('Normalized Time Vector (s)')
ylabel('Normalzed Magnitude')
title('Recorded Signal')

fft_data = fft(in_data, L);
out_data = fft_data.*myFilter;
spect = ifft(out_data, L);

axes(handles.axes2);
plot(Tx, spect);
set(gca,'YDir','normal')
xlabel('Normalized Time Vector (s)')
ylabel('Normalzed Magnitude')
title('After Filtering')

axes(handles.axes3);
spectrogram(spect, 8000);
title('spectrogram')


text:
package com.altova.text.edi;

import com.altova.text.ITextNode;
import com.altova.text.edi.Scanner.State;

import java.io.IOException;

public class DataElement extends StructureItem {
	DataTypeValidator mValidator;

	public DataElement (String name, DataTypeValidator validator) {
		super(name, ITextNode.DataElement);
		mValidator = validator;
	}

	public boolean read (Parser.Context context) {
		State beforeState = context.getScanner().getCurrentState();
		if ( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIFixed )
		{
			Scanner scanner = context.getScanner();
			StringBuffer sBuffer = new StringBuffer();
			while( sBuffer.length() < mValidator.getMaxLength() && !scanner.isAtEnd() &&
				scanner.getCurrentChar() != scanner.mServiceChars.getSegmentTerminator() )
			{
				char c = scanner.rawConsumeChar();
				if( scanner.getCurrentChar() == '\n' )
				{
					if( c != '\r' )
						sBuffer.append( c );
				}
				else
					sBuffer.append( c );
			}

			mValidator.makeValidOnRead( sBuffer, context, beforeState);
			if ( sBuffer.length() == 0)
				return false; //data element is absent

			context.getGenerator().insertElement (context.getParticle().getName(), sBuffer.toString(), mNodeClass);
			return true;
		}

        //MSH-2 in HL7 MODE also needs special treatment
		if( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIHL7
			&& isHL7SpecialField(context.getParticle().getName(), "-2"))
		{
			Scanner scanner = context.getScanner();
			String s = new String();
			char c = scanner.rawConsumeChar();
			scanner.mServiceChars.setComponentSeparator( c);
			s += c;
			s += c = scanner.rawConsumeChar();
			scanner.mServiceChars.setRepetitionSeparator( c);
			if( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
			{
				s += c = scanner.rawConsumeChar();
				scanner.mServiceChars.setReleaseCharacter( c);
			}
			if( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
			{
				s += c = scanner.rawConsumeChar();
				scanner.mServiceChars.setSubComponentSeparator( c);
			}
			while( scanner.getCurrentChar() != scanner.mServiceChars.getDataElementSeparator())
			{
				s += c = scanner.rawConsumeChar();
			}
			context.getGenerator().insertElement (context.getParticle().getName(), s, mNodeClass);
			return true;
		}

		StringBuffer s = context.getScanner().consumeString(ServiceChars.ComponentSeparator, true);
		if ( s.length() == 0 )
			return false;  // data element is absent

		mValidator.makeValidOnRead(s, context, beforeState);

		if( context.getParser().getEDIKind() == EDISettings.EDIStandard.EDIX12 )
		{
			if( context.getParticle().getName().equals( "F447") && context.getCurrentSegmentName().equals("LS") )
				context.getParser().setF447( new String( s) );
		}

		// codelist validate
		if (!mValidator.hasValue(s.toString()))
		{
			if (!mValidator.isIncomplete())
				context.handleError(
					Parser.ErrorType.CodeListValueWrong,
					ErrorMessages.GetInvalidCodeListValueMessage(s.toString(), mValidator.getCodeListValues()),
					new ErrorPosition( beforeState ),
					s.toString()
				);
			else
				context.handleWarning(
					ErrorMessages.GetIncompleteCodeListValueMessage(s.toString(), mValidator.getCodeListValues()),
					new ErrorPosition( beforeState ),
					s.toString()
				);
		}

		// embedded codelist validate
		if (!embeddedCodeListValidate(s.toString(), context.getParticle()))
			context.handleError(
				Parser.ErrorType.CodeListValueWrong,
				ErrorMessages.GetInvalidCodeListValueMessage(s.toString(), embeddedCodeListValueList(context.getParticle())),
				new ErrorPosition( beforeState ),
				s.toString()
			);

		// edi validate
		String sError = context.getValidator().validate( context.getParticle().getName(), s.toString());
		if( sError.length() > 0)
			context.handleError(
				Parser.ErrorType.SemanticWrong,
				sError,
				new ErrorPosition( beforeState ),
				s.toString()
			);

		context.getGenerator().insertElement (context.getParticle().getName(), s.toString(), mNodeClass);

		return true;
	}

	public void write (Writer writer, ITextNode node, Particle particle) throws IOException {

		StringBuffer sbvalue = new StringBuffer();
		String nodeName = new String();

		if (node != null)
		{
			sbvalue.append(node.getValue());
			nodeName = node.getName();
		}

		if (writer.getEDIKind() == EDISettings.EDIStandard.EDIFixed)
		{
			mValidator.makeValidOnWrite( sbvalue, node, writer, false);
			writer.write( sbvalue.toString() );
			return;
		}

		boolean escapeString = true;
        if (writer.getEDIKind() == EDISettings.EDIStandard.EDIHL7
        	&& isHL7SpecialField(nodeName, "-2"))
        {
            sbvalue = new StringBuffer();
            sbvalue.append( writer.getServiceChars().getComponentSeparator());
            sbvalue.append( writer.getServiceChars().getRepetitionSeparator());
            if( writer.getServiceChars().getReleaseCharacter() != 0 )
            {
            	sbvalue.append( writer.getServiceChars().getReleaseCharacter());
            	if( writer.getServiceChars().getSubComponentSeparator() != 0 )
            		sbvalue.append( writer.getServiceChars().getSubComponentSeparator());
            }
            //don't escape separators
			escapeString = false;
        }

		if (!mValidator.makeValidOnWrite (sbvalue, node, writer, escapeString))
        	return;

		//codelist validate
		String sValue = sbvalue.toString();
		if (!mValidator.hasValue( sValue))
		{
			if (!mValidator.isIncomplete())
				writer.handleError( node, Parser.ErrorType.CodeListValueWrong, ErrorMessages.GetInvalidCodeListValueMessage(sValue, mValidator.getCodeListValues()) );
			else
				writer.handleWarning( node, ErrorMessages.GetIncompleteCodeListValueMessage(sValue, mValidator.getCodeListValues()) );
		}

		// embedded codelist validate
		if (!embeddedCodeListValidate(sValue, particle))
			writer.handleError(
				node,
				Parser.ErrorType.CodeListValueWrong,
				ErrorMessages.GetInvalidCodeListValueMessage(sValue, embeddedCodeListValueList(particle))
			);

		//edi validate
		String sError = writer.getValidator().validate( nodeName, sValue);
		if( sError.length() > 0)
			writer.handleError( node, Parser.ErrorType.SemanticWrong, sError);

		writer.write (sValue);
	}

	private boolean embeddedCodeListValidate(String value, Particle particle)
	{
		if (particle.getCodeValues().length == 0)
			return true;

		for(String s : particle.getCodeValues())
			if (s.equals( value ))
				return true;

		return false;
	}

	private String embeddedCodeListValueList(Particle particle)
	{
		StringBuffer validList = new StringBuffer();
		for(String s : particle.getCodeValues())
			validList.append(", '" + s + "'");

		return validList.toString().substring(2);
	}
}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { DragSource, DropTarget } from 'react-dnd';

import { ITEM } from './ItemTypes';

const style = {
  cursor: 'move',
};

let hoveredTarget;

const cardSource = {
  beginDrag(props) {
    return {
      id: props.id,
      originalIndex: props.findItem(props.id).index,
    };
  },

  endDrag(props, monitor) {
    const { id: droppedId, originalIndex } = monitor.getItem();
    const didDrop = monitor.didDrop();

    let finalTarget = [droppedId, originalIndex];

    if (!didDrop) {
      console.log('did not drop');
      // do nothing
    } else if (hoveredTarget) {
      finalTarget = hoveredTarget;
    }

    const { onSortEnded } = props;
    const { data } = props.moveItem(...finalTarget);

    onSortEnded(data);

    hoveredTarget = undefined;
  },
};

const cardTarget = {
  canDrop() {
    return false;
  },

  hover(props, monitor) {
    const { id: draggedId } = monitor.getItem();
    const { id: overId } = props;

    if (draggedId !== overId) {
      const { index: overIndex } = props.findItem(overId);
      // const { onSortEnded } = props;
      // const { data } = props.moveItem(draggedId, overIndex);

      // onSortEnded(data);

      // eslint-disable-next-line no-param-reassign
      hoveredTarget = [draggedId, overIndex];
    }
  },
};

/* eslint-disable react/no-unused-prop-types */

@DropTarget(ITEM, cardTarget, connect => ({
  connectDropTarget: connect.dropTarget(),
}))
@DragSource(ITEM, cardSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging(),
}))
export default class SortableItem extends Component {
  static propTypes = {
    connectDragSource: PropTypes.func.isRequired,
    connectDropTarget: PropTypes.func.isRequired,
    isDragging: PropTypes.bool.isRequired,
    children: PropTypes.any.isRequired,
    id: PropTypes.any.isRequired,
    moveItem: PropTypes.func.isRequired,
    findItem: PropTypes.func.isRequired,
    onSortEnded: PropTypes.func.isRequired,
  };

  render() {
    const {
      isDragging,
      connectDragSource,
      connectDropTarget,
      children,
    } = this.props;

    const opacity = isDragging ? 0.5 : 1;

    return connectDragSource(connectDropTarget(
      <div style={{ ...style, opacity }}>
        {children}
      </div>,
    ));
  }
}