text:
package edu.umn.paull011.evolveworkoutlogger.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import edu.umn.paull011.evolveworkoutlogger.R;
import edu.umn.paull011.evolveworkoutlogger.data_structures.DatabaseHelper;
import edu.umn.paull011.evolveworkoutlogger.data_structures.Exercise;
import edu.umn.paull011.evolveworkoutlogger.data_structures.Routine;
import edu.umn.paull011.evolveworkoutlogger.fragments.RoutineExercisesFragment;

public class CreateRoutine extends AppCompatActivity
        implements RoutineExercisesFragment.OnFragmentInteractionListener {

    private Routine mRoutine;
    private String mTitle;
    private String mDescription;
    private EditText mEditTitle;
    private EditText mEditDescription;
    private RoutineExercisesFragment mFragment;
    private FloatingActionButton fab;

    private boolean mEditingMode;
    private static final String TITLE_STRING = "Title";
    private static final String DESCRIPTION_STRING = "Description";
    private static final String TAG = CreateRoutine.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_routine);

        mEditingMode = getIntent().getBooleanExtra("Edit", false);

        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                persistRoutineAndFinish();
            }
        });

        mEditTitle = (EditText) findViewById(R.id.edit_title);
        mEditDescription = (EditText) findViewById(R.id.edit_description);
        DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this);

        // Load the routine that is currently being created

        if (savedInstanceState != null) {
            char[] temp = savedInstanceState.getCharArray(DatabaseHelper.KEY_ROUTINE_NAME);
            if (temp != null) {
                String routineName = String.valueOf(temp);
                mRoutine = databaseHelper.getRoutine(routineName);
                mTitle = savedInstanceState.getString(TITLE_STRING);
                mDescription = savedInstanceState.getString(DESCRIPTION_STRING);
            }
        }
        else {
            if (mEditingMode) {
                String routineName = getIntent().getStringExtra(DatabaseHelper.KEY_ROUTINE_NAME);
                mRoutine = databaseHelper.getRoutine(routineName);
                mTitle = mRoutine.getName();
                mDescription = mRoutine.getDescription();
            }
            else {
                mRoutine = new Routine();
            }
        }
        mEditTitle.setText(mTitle);
        mEditDescription.setText(mDescription);

        FragmentManager fm = getSupportFragmentManager();
        mFragment = (RoutineExercisesFragment) fm.findFragmentById(R.id.fragment_create_routine);
        mFragment.setRoutine(mRoutine);

        if (mRoutine.getNumExercises() == 0) {
            fab.hide();
        }

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mEditingMode) {
            toolbar.setTitle("Edit Routine");
        }
        else {
            toolbar.setTitle("Create Routine");
        }
        setSupportActionBar(toolbar);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.d(TAG, "onSaveInstanceState()");
        extractRoutineDataFromActivity();
        DatabaseHelper db = DatabaseHelper.getInstance(this);
        db.updateRoutine(mRoutine);
        db.close();
        outState.putString(DatabaseHelper.KEY_ROUTINE_NAME, mRoutine.getName());
        outState.putString(TITLE_STRING, mEditTitle.getText().toString());
        outState.putString(DESCRIPTION_STRING, mEditDescription.getText().toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    public void exerciseSelected(String exerciseName) {
        Log.d(TAG, "exerciseSelected()");
        //TODO: do something when exercise selected
    }

    public void handleButtonClick(View view) {
        Log.d(TAG, "handleButtonClick()");
        Button button = (Button) view;
        switch (button.getId()) {
            case R.id.button_add_exercise_to_routine:
                addNewExercise();
        }
    }

    public void addNewExercise() {
        Log.d(TAG, "addNewExercise()");
        Intent addExercise = new Intent(this, AddExercise.class);
        startActivityForResult(addExercise, ResponseCodes.NEW_EXERCISE.getValue());
    }

    private void persistRoutineAndFinish() {
        Log.d(TAG, "persistRoutineAndFinish()");
        Intent returnIntent = new Intent();
        boolean routineSaved = persistRoutine();
        if (routineSaved){
            returnIntent.putExtra(DatabaseHelper.KEY_ROUTINE_NAME, mRoutine.getName());
            setResult(Activity.RESULT_OK, returnIntent);
        }
        finish();
    }

    private void extractRoutineDataFromActivity() {
        EditText titleEdit = (EditText) findViewById(R.id.edit_title);
        EditText descriptionEdit = (EditText) findViewById(R.id.edit_description);
        assert titleEdit != null;
        assert descriptionEdit != null;

        String title = titleEdit.getText().toString();
        String description = descriptionEdit.getText().toString();
        mRoutine.setName(title);
        mRoutine.setDescription(description);
    }

    private boolean persistRoutine() {
        Log.d(TAG, "persistRoutine");

        extractRoutineDataFromActivity();

        String routineName;
        DatabaseHelper db = DatabaseHelper.getInstance(this);
        if (mEditingMode && !mTitle.equals(mRoutine.getName())) {
            routineName = db.replaceRoutine(mTitle, mRoutine);
        }
        else {
            routineName = db.insertRoutine(mRoutine, true);
        }
        db.close();
        return routineName.equals(mRoutine.getName());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult()");
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ResponseCodes.NEW_EXERCISE.getValue()) {
            if (resultCode == Activity.RESULT_OK) {
                // Add selected exercise to routine
                String exerciseName = data.getStringExtra(DatabaseHelper.KEY_EXERCISE_NAME);
                DatabaseHelper db = DatabaseHelper.getInstance(this);
                Exercise exercise = db.getExercise(exerciseName);
                mRoutine.addExercise(exercise);
                db.insertRoutineExercise(
                        mRoutine.getName(),
                        exercise.getName(),
                        mRoutine.getNumExercises() - 1
                );
                mFragment.refresh();
                fab.show();
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (v instanceof EditText) {
                Rect outRect = new Rect();
                v.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
                    v.clearFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean exercisesDeletable() {
        return true;
    }
}


text:
package entities

import (
	"errors"
	"time"
)

// Time is a type alias so we could override methods and add our own
type Time struct {
	time.Time
}

// MarshalJSON implements the json.Marshaler interface.
// Time is formatted as RFC3339 instead of RFC3339Nano (original time.Time)
func (t Time) MarshalJSON() ([]byte, error) {
	loc, err := time.LoadLocation("UTC")
	if err != nil {
		return nil, err
	}
	if y := t.Year(); y < 0 || y >= 10000 {
		return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]")
	}
	return []byte(t.In(loc).Format(`"` + time.RFC3339 + `"`)), nil
}

// ParseTime parses date string of RFC3339 format
func ParseTime(s string) (Time, error) {
	var res Time

	t, err := time.Parse(time.RFC3339, s)
	if err == nil {
		res = Time{t}
	}

	return res, err
}

redpajama_set_name: RedPajamaGithub


text:
package de.geeksfactory.opacclient.apis;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class BaseApiTest {
    @Test
    public void cleanUrlShouldHandleMultipleEqualsSigns() throws Exception {
        String url = "http://www.example.com/file?param1=value=1&param=value2";
        assertEquals("http://www.example.com/file?param1=value%3D1&param=value2",
                BaseApi.cleanUrl(url));
    }
}


text:
/*
 * LinksBaseSetTest.java
 * JUnit based test
 */

package wikipedia.kleinberg;

import wikipedia.language.Encodings;
import wikipedia.sql.*;
import wikipedia.util.*;

import junit.framework.*;
import java.util.*;

public class LinksBaseSetTest extends TestCase {

    public Connect  connect, connect_ru;
    Links           links;
    LinksBaseSet    links_baseset;
    DumpToGraphViz  dump;
    SessionHolder   session;

    public LinksBaseSetTest(String testName) {
        super(testName);
    }

    protected void setUp() throws java.lang.Exception {
        connect = new Connect();
        connect.Open(Connect.WP_HOST, Connect.WP_DB, Connect.WP_USER, Connect.WP_PASS);

        connect_ru = new Connect();
        connect_ru.Open(Connect.WP_RU_HOST,Connect.WP_RU_DB,Connect.WP_RU_USER,Connect.WP_RU_PASS);

        links_baseset   = new LinksBaseSet();

        dump            = new DumpToGraphViz();
        dump.file_dot.setFileInHomeDir("graphviz", "empty.txt", "Cp1251",true);
        dump.file_bat.setFileInHomeDir("graphviz", "bat_ruwiki.bat", "Cp866",true);
        dump.file_sh.setFileInHomeDir("graphviz", "bat_ruwiki.sh", "Cp1251",true);

        session = new SessionHolder();
        session.initObjects();
        session.dump = dump;
    }

    protected void tearDown() throws java.lang.Exception {
        connect.Close();
        connect_ru.Close();
    }

    public static junit.framework.Test suite() {
        junit.framework.TestSuite suite = new junit.framework.TestSuite(LinksBaseSetTest.class);

        return suite;
    }

    /**
     * Test of CreateBaseSet method, of class wikipedia.LinksBaseSet.
     */
    public void testCreateBaseSet() {
        /*String  article;

        article = "Робот";      //          vertices:9      edges:11
        //article = "Самолёт";  // too big: vertices:1383   edges:34192
        //article = "Фуникулёр";  // medium size

        dump.file.SetFilename(article + "_all.dot");
        dump.file.Open(false, "UTF8");

        dump.connect = connect_ru;
        Map<Integer, Article> base_nodes = links_baseset.CreateBaseSet(connect_ru, article, dump);
        if (article.equals("Робот")) {
            assertEquals(base_nodes.size(), 9);
            assertTrue("Robot should refer to Dance", base_nodes.containsKey(10578));
            assertTrue("Robot should be referred to Transformers", base_nodes.containsKey(18991));
        }*/

        /*
         String[] all_words = {"Робот", "Рычаг", "Фуникулёр",
                "Глаз", "Окуляр", "Орбитальная станция", "Плазма", "Фут",
                "Свёртка", "Ноты", "Предложение", "Преферанс", "Взрыв",
                "Самосознание", "Свобода", "Оптимизм"};

        // no refer: "Окуляр", "Свёртка",
        String[] big_words   = {"Фуникулёр", "Фут", "Глаз", "Ноты", "Предложение",
                                "Взрыв", "Самосознание", "Свобода"};
        String[] small_words = {"Робот", "Рычаг", "Плазма",
                                "Преферанс", "Оптимизм"};

        String[] new_words2 = {"Кварк", "Похмелье", "Кегль",
                                "Киноварь", "Компилятор"};
        String[] new_words = {"Контрабас", "Конунг", "Константа",
                                "Спин", "Спорт", "Дзюдо"};

        for(int i=0; i<new_words.length; i++) {
            links_baseset.CreateBaseSet(connect_ru, new_words[i]);
        }*/
    }
/*
    public void testCreateBaseSetEnglish() {
        //links_baseset.CreateBaseSet(connect, "Innuendo");
        //links_baseset.CreateBaseSet(connect, "Parallelogram");

        String[] words_Blondel = {"disappear", "parallelogram", "sugar", "science"};
        String[] rare_words = {"Parallelogram", "Sycamore", "Innuendo"};

        for(int i=0; i<rare_words.length; i++) {
            links_baseset.CreateBaseSet(connect, rare_words[i]);
        }
    }
*/

    // test parametrized CreateBaseSet(,..., int root_set_size, int increment)
    public void testCreateBaseSetParametrized_ru() {
        System.out.println("testCreateBaseSetParametrized_ru");
        int     root_set_size, increment;
        String  article, article_fn;

        // Kleinberg default values
        root_set_size = 19; //200;  18, 19 - failed
        increment = 50; //50;

        // Simple test values
        //root_set_size = 1;
        //increment = 1;

        int categories_max_steps = 5;
        session.Init(connect_ru, null, categories_max_steps);
        session.randomPages(false);
        session.skipTitlesWithSpaces(true);

        Encodings e = connect_ru.enc;

        article = e.EncodeFromJava("Робот");
        article_fn = StringUtilRegular.encodeRussianToLatinitsa(article, Encodings.enc_java_default, Encodings.enc_int_default);

        /*article = "Parallelogram";      // 77,953 sec   Hot MySQL: 48,344 sec
        //article = "Science";            // 76,094 sec   Hot MySQL: 50,094 sec
        dump.connect = connect_ru;*/

        dump.file_dot.setFileInHomeDir("graphviz", article_fn + ".dot", "UTF8",true);

        List<String> synonyms = new ArrayList<String>();
        Map<Integer, Article>  base_nodes = LinksBaseSet.CreateBaseSet(article, synonyms, session, root_set_size, increment);

        assertTrue(base_nodes.containsKey(session.source_article_id));
        Article s = base_nodes.get(session.source_article_id);
        assertTrue(null != s);

        String android = e.EncodeFromJava("Андроид");
        int android_id = PageTable.getIDByTitleNamespace(connect_ru, android, PageNamespace.MAIN);

        String search_engine = e.EncodeFromJava("Поисковая_система");
        int search_engine_id = PageTable.getIDByTitleNamespace(connect_ru, search_engine, PageNamespace.MAIN);

        // 1) "Андроид" is presented and "Поисковая_система" is absent in base_nodes;
        assertTrue (base_nodes.containsKey(      android_id));
        assertFalse(base_nodes.containsKey(search_engine_id));

        // 2) assert that "Андроид" and "Киборг" (submitted as synonyms) are in base_nodes;
        synonyms.add(android);
        synonyms.add(search_engine);
        base_nodes = LinksBaseSet.CreateBaseSet(article, synonyms, session, root_set_size, increment);
        assertTrue(base_nodes.containsKey(      android_id));
        assertTrue(base_nodes.containsKey(search_engine_id));

        Article a_android       = base_nodes.get(      android_id);
        Article a_search_engine = base_nodes.get(search_engine_id);
        assertEquals(NodeType.RATED_SYNONYMS, a_android.      type);
        assertEquals(NodeType.RATED_SYNONYMS, a_search_engine.type);

        //dump.connect = connect_ru;
        //links_baseset.CreateBaseSet(dump.connect, "Parallelogram", dump, 2, 2);
        /*
        String[] all_words = {"Робот", "Рычаг", "Фуникулёр",
                "Глаз", "Окуляр", "Орбитальная станция", "Плазма", "Фут",
                "Свёртка", "Ноты", "Предложение", "Преферанс", "Взрыв",
                "Самосознание", "Свобода", "Оптимизм"};

        // no refer: "Окуляр", "Свёртка",
        String[] big_words   = {"Фуникулёр", "Фут", "Глаз", "Ноты", "Предложение",
                                "Взрыв", "Самосознание", "Свобода"};
        String[] small_words = {"Робот", "Рычаг", "Плазма",
                                "Преферанс", "Оптимизм"};

        String[] new_words2 = {"Кварк", "Похмелье", "Кегль",
                                "Киноварь", "Компилятор"};
        String[] new_words = {"Контрабас", "Конунг", "Константа",
                                "Спин", "Спорт", "Дзюдо"};

        for(int i=0; i<new_words.length; i++) {
            links_baseset.CreateBaseSet(dump.connect, new_words[i]);
        }*/
    }

    public void testCreateBaseSet_ForAbsentWord() {
        System.out.println("testCreateBaseSet_ForAbsentWord");
        int     root_set_size, increment;
        String  article;

        // Kleinberg default values
        /*root_set_size = 200;
        increment = 50;
        */

        // Simple test values
        root_set_size = 1;
        increment = 1;

        List<String> synonyms = new ArrayList<String>();
        //synonyms.add("syn1");
        //synonyms.add("syn2");

        article = "AbsentWord";
        int categories_max_steps = 99;
        session.Init(connect_ru, null, categories_max_steps);
        //session.skipTitlesWithSpaces(true);
        session.randomPages(false);

        /*article = "Parallelogram";      // 77,953 sec   Hot MySQL: 48,344 sec
        //article = "Science";            // 76,094 sec   Hot MySQL: 50,094 sec
        dump.connect = connect;*/

        dump.file_dot.SetFilename(article + ".dot");
        dump.file_dot.Open(false, "UTF8");

        Map<Integer, Article>  base_nodes = LinksBaseSet.CreateBaseSet(article, synonyms, session, root_set_size, increment);
        assertTrue(null == base_nodes);
    }

}

    /*
    public HashMap<Integer, Article> CreateBaseSet(Connect connect, String page_title, SessionHolder session) {
        Article         node = new Article();
        Links           link = new Links();
        DCEL            dcel = new DCEL();

        int             increment, root_set_size;
        root_set_size   = 200;
        //increment       = 50;

        // 1.
        String latin1_article = Encodings.UTF8ToLatin1(page_title);
        int p = connect.page_table.GetIDByTitle(connect, latin1_article);
        session.source_article_id = p;
        Article[] root_nodes = links.GetLFromByLTo(session, p, root_set_size);
        if(null == root_nodes) {
            if (null != session.dump) {
                String bat_text = "\n:: " + session.dump.file_dot.GetFilename() +".dot \t Warning: no page refers to this page.\n";
                session.dump.file_bat.Print(bat_text);
                session.dump.file_bat.Flush();
            }
            return null;    // nobody refers to the p page
        }
        node.SetType(root_nodes, 1);
        //file_dot.WriteNew(path + "1_0_ruwiki.dot", session.dump.Dump(root_nodes), "UTF8");

        // 2.1
        Article[] base_nodes1 = links.GetLFromByLTo(session, root_nodes, -1);
        //file_dot.WriteNew(path + "2_1_ruwiki.dot", session.dump.Dump(base_nodes1), "UTF8");

        // 2.2
        Article[] base_nodes2 = links.GetLToByLFrom(session, root_nodes);
        //file_dot.WriteNew(path + "2_2_ruwiki.dot", session.dump.Dump(base_nodes2), "UTF8");

        Article[] base_nodes           = node.JoinUnique(base_nodes1, base_nodes2);
        Article[] base_and_root_nodes  = node.JoinUnique(base_nodes, root_nodes);
        //file_dot.WriteNew(path + "2_2_unique.dot", session.dump.Dump(base_and_root_nodes), "UTF8");
        node.SetType(base_and_root_nodes, 2);

        // 2.3
        HashMap<Integer, Article> hash_node = node.CreateHashMap(base_and_root_nodes);
        hash_node.get(p).type = -1;  // set type for the very source article
        link.GetAllLinks(connect, hash_node);
        if (null != session.dump) {
            session.dump.Dump(hash_node);

            // append 1) statistics and 2) dot command to bat file
            String bat_text = "\n:: "+session.dump.file_dot.GetFilename()+"\t vertices:" + hash_node.values().size() +
                                               "\t edges:"    + dcel.CountLinksIn(hash_node) +
                              "\ndot.exe -Tjpeg " + session.dump.file_dot.GetFilename() + " -v -o " + session.dump.file_dot.GetFilenameWoExt() + ".jpeg\n";
            session.dump.file_bat.Print(bat_text);
            session.dump.file_bat.Flush();
        }

        return hash_node;
    }*/


text:
var test = require('tape'),
    SeaLion = require('../');

function fakeRequest(url, method){
    return {
        url: url,
        method: method || 'GET'
    };
}

test('SeaLion is a function', function (t) {
    t.plan(1);
    t.equal(typeof SeaLion, 'function',  'SeaLion is a function');
});

test('new seaLion takes routes', function (t) {
    t.plan(2);

    var expectedRoutes = {
            '/foo': function(){}
        };

    var seaLion = new SeaLion({
        '/foo': expectedRoutes['/foo']
    });

    t.deepEqual(Object.keys(seaLion._routes), Object.keys(expectedRoutes), 'got expected routes');
    t.deepEqual(seaLion._routes['/foo'], {any: expectedRoutes['/foo']}, '/foo route is correct');
});

test('can only add valid routes', function (t) {
    t.plan(1);

    var seaLion = new SeaLion();

    t.throws(function(){
        seaLion.add({
            '/foo': null
        });
    });
});

test('add routes using seaLion.add', function (t) {
    t.plan(2);
    var testRoutes = {
            foo: 'bar',
            stuff: 'meh'
        },
        expectedRoutes = {
            foo: 'bar',
            stuff: 'meh'
        },
        seaLion = new SeaLion();

    t.deepEqual(Object.keys(seaLion._routes), [],  'routes has no keys to start');

    seaLion.add(testRoutes);

    t.deepEqual(Object.keys(seaLion._routes), Object.keys(expectedRoutes),  'routes has correct keys after add');
});

test('add routes handels multiple calls correctly', function (t) {
    t.plan(2);
    var testRoutes = {
            foo: {
                GET: 'foo'
            }
        },
        testRoutes2 = {
            stuff: {
                GET: 'meh'
            }
        },
        testRoutes3 = {
            stuff: {
                POST: 'things'
            }
        },
        expectedRoutes = {
            foo: {
                GET: 'foo'
            },
            stuff: {
                GET: 'meh',
                POST: 'things'
            }
        },
        seaLion = new SeaLion();

    t.deepEqual(Object.keys(seaLion._routes), [],  'routes has no keys to start');

    seaLion.add(testRoutes);
    seaLion.add(testRoutes2);
    seaLion.add(testRoutes3);

    t.deepEqual(seaLion._routes, expectedRoutes,  'routes has correct keys after multiple adds and overrides');
});

test('matched route gets handled', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo': function(request, response){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo'));

});

test('matched route gets handled', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/new': function(request, response){
            t.pass();
        },
        '/foo/`id`': function(request, response){
            t.fail();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/new'));
});

test('matched route gets handled', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/`id`': function(request, response, tokens){
            t.equal(tokens.id, 'new');
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/new'));
});

test('matched route gets tokens wrong order', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/`id`': function(request, response){
            t.fail();
        },
        '/foo/new': function(request, response){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/new'));
});

test('matched route gets tokens wrong order with tokens', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/`id`/`bar`': function(request, response){
            t.fail();
        },
        '/foo/`id`/potato': function(request, response){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/new/potato'));
});

test('matched route gets correct method when identical routes in wrong order', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/`things`': {
            PUT: function(request, response){
                t.fail();
            }
        },
        '/foo/`stuff`': {
            GET: function(request, response){
                t.pass();
            }
        },
        '/foo/`pototoes`': {
            POST: function(request, response){
                t.fail();
            }
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/majigger'));
});

test('matched route same token length precedence order', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/`things...`.foo': {
            GET: function(request, response){
                t.pass();
            }
        },
        '/`things...`': {
            GET: function(request, response){
                t.fail();
            }
        }
    });

    seaLion.createHandler()(fakeRequest('/majigger.foo'));
});

test('matched route gets handled', function (t) {
    t.plan(3);

    var seaLion = new SeaLion({
        '/foo/`1`/`2`/`3`': function(request, response, tokens){
            t.equal(tokens[1], 'a');
            t.equal(tokens[2], 'b');
            t.equal(tokens[3], 'c');
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/a/b/c'));
});

test('multi-rule route is matched', function (t) {
    t.plan(3);

    var seaLion = new SeaLion({
        '/foo /bar': function(request, response){
            t.pass();
        }
    });
    seaLion.notFound = function(request){
        t.equal(request.url, '/baz');
    };

    seaLion.createHandler()(fakeRequest('/foo'));
    seaLion.createHandler()(fakeRequest('/bar'));
    seaLion.createHandler()(fakeRequest('/baz'));
});

test('multi-rule route with tokens is matched', function (t) {
    t.plan(3);

    var seaLion = new SeaLion({
        '/foo/`bar` /bar': function(request, response, tokens){
            if(Object.keys(tokens).length){
                t.equal(request.url, '/foo/bar');
                t.equal(tokens.bar, 'bar');
            }else{
                t.equal(request.url, '/bar');
            }
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/bar'));
    seaLion.createHandler()(fakeRequest('/bar'));
});

test('matching stops on slashes', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo/`id`': function(request, response, tokens){
            t.fail();
        },
        '/foo/`id`/bar': function(request, response, tokens){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo/bar/bar'));
});

test('get rest of path', function (t) {
    t.plan(2);

    var seaLion = new SeaLion({
        '/foo/`thing...`': function(request, response, tokens){
            t.pass();
        }
    });
    seaLion.notFound = function(request){
        t.fail();
    };

    seaLion.createHandler()(fakeRequest('/foo/thing/bar.svg'));
    seaLion.createHandler()(fakeRequest('/foo/thing/bar.png'));
});

test('get lots of path', function (t) {
    t.plan(2);

    var seaLion = new SeaLion({
        '/foo/`thing...`.svg': function(request, response, tokens){
            t.equal(tokens.thing, 'thing/bar', 'Matches .svg');
        }
    });
    seaLion.notFound = function(request){
        t.pass('route didn\'t match .png');
    };

    seaLion.createHandler()(fakeRequest('/foo/thing/bar.svg'));
    seaLion.createHandler()(fakeRequest('/foo/thing/bar.png'));
});

test('get multiple tokens from path', function (t) {
    t.plan(2);

    var seaLion = new SeaLion({
        '/`foo`/`thing`': function(request, response, tokens){
            t.equal(tokens.foo, 'baz', 'Matches baz');
            t.equal(tokens.thing, 'thing', 'Matches thing');
        }
    });

    seaLion.createHandler()(fakeRequest('/baz/thing'));
});

test('get multiple types of token from path', function (t) {
    t.plan(2);

    var seaLion = new SeaLion({
        '/`foo`/`thing...`': function(request, response, tokens){
            t.equal(tokens.foo, 'baz', 'Matches baz');
            t.equal(tokens.thing, 'thing/bar.svg', 'Matches rest of path');
        }
    });

    seaLion.createHandler()(fakeRequest('/baz/thing/bar.svg'));
});

test('method routing', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo': {
            get: function(request, response, tokens){
                t.fail();
            },
            post: function(request, response, tokens){
                t.pass();
            }
        }
    });

    seaLion.createHandler()(fakeRequest('/foo', 'POST'));
});

test('any method routing', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo': {
            post: function(request, response, tokens){
                t.fail();
            },
            any: function(request, response, tokens){
                t.pass();
            }
        }
    });

    seaLion.createHandler()(fakeRequest('/foo'));
});

test('any method routing to fn', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo': function(request, response, tokens){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo', 'POST'));
});

test('query strings', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/foo': function(request, response, tokens){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/foo?bar=baz'));
});

test('query strings with rest token', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/`foo...`': function(request, response, tokens){
            t.pass();
        }
    });

    seaLion.createHandler()(fakeRequest('/bar?bar=baz'));
});

test('match order with greedy', function (t) {
    t.plan(1);

    var seaLion = new SeaLion({
        '/`foo`/`bar`': function(request, response, tokens){
            t.pass();
        },
        '/`foo...`': function(request, response, tokens){
            t.fail();
        }
    });

    seaLion.createHandler()(fakeRequest('/bar/baz'));
});

require('./matchRule');
require('./matchRuleKeys');


text:
jest
  .dontMock('../store')
  .dontMock('../flightTimeStore')
  .dontMock('keymirror');

describe('FlightTimeStore', () => {
  let ActionConstants = require('../../constants/constants').ActionConstants;
  let flightTimeStore;
  let dispatcher;
  let callback;
  let flightTime = 1;
  let utc = 2;

  let actionFlightTimeUpdate = {
    type: ActionConstants.FLIGHT_TIME_UPDATE,
    flightTime
  };
  let actionUTCRegister = {
    type: ActionConstants.UTC_REGISTER,
    utc
  };

  beforeEach(() => {
    flightTimeStore = require('../flightTimeStore');
    dispatcher = flightTimeStore.dispatcher;
    callback = dispatcher.register.mock.calls[0][0];
  });

  it(`updates flight time`, () => {
    callback(actionFlightTimeUpdate);

    expect(flightTimeStore.data.time).toBe(flightTime);
  });

  it(`changes utc offset`, () => {
    flightTimeStore.data.time = { utcOffset: jest.genMockFunction() };
    callback(actionUTCRegister);

    expect(flightTimeStore.data.time.utcOffset).toBeCalledWith(utc);
  });
});


text:
#ifndef MAINFRAME_HPP
#define MAINFRAME_HPP

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif
#include <wx/preferences.h>
#include "mapsettingsdialog.hpp"
#include "miniframes/displayframe.hpp"
#include "miniframes/paletteframe.hpp"
#include "miniframes/toolbarframe.hpp"
#include "miniframes/sceneryframe.hpp"
#include "notebook.hpp"
#include "settings.hpp"

/**
 * \brief Main wxFrame that is going to be shown during the entire execution of the program.
 * It also handles communication between widgets.
 */
class MainFrame: public wxFrame
{
    public:
        MainFrame(Settings *settings);
        ~MainFrame();
        const DisplayFrame& GetDisplayFrame() const { return *m_displayFrame; }
        PaletteFrame& GetPaletteFrame() const { return *m_paletteFrame; }
        const ToolbarFrame& GetToolbarFrame() const { return *m_toolbarFrame; }
        SceneryFrame& GetSceneryFrame() const { return *m_sceneryFrame; }
        const Settings& GetSettings() const { return *m_settings; }

    private:
        MapSettingsDialog *m_mapSettingsDialog;

        DisplayFrame *m_displayFrame;
        PaletteFrame *m_paletteFrame;
        ToolbarFrame *m_toolbarFrame;
        SceneryFrame *m_sceneryFrame;

        Notebook *m_notebook;
        wxPreferencesEditor *m_preferencesEditor;
        Settings *m_settings;

        void AddWorkspace(wxString mapPath);

        void OnBackgroundColorChanged(wxColourPickerEvent &event);
        void OnDisplayFrameCheckBoxClicked(wxCommandEvent &event);
        void OnMenuBarItemClicked(wxCommandEvent &event);
        void OnNotebookPageChanged(wxBookCtrlEvent &event);
        void OnPolygonsTextureChanged(wxCommandEvent &event);

        void ShowAllMiniFrames(bool show);
};

#endif


text:
import RPi.GPIO as GPIO
import time, datetime, json, os
from picamera import PiCameraError
from threading import Timer
from argparse import ArgumentParser

class PIR:

    def __init__(self,camera,conf):
        """Initialise module for recording with configuration file_conf or
        conf.json if unspecified.
        """
        self.camera = camera
        self.conf = conf

        self.run_complete = False
        self.motion = False
        self.recording = False
        self.record_video = self.conf["record video"]
        self.run_timer = None
        self.motion_timer =  None
        self.duration = None

        # set configuration of camera
        self.camera.resolution = tuple(self.conf["resolution"])
        self.camera.led = self.conf["camera LED"]

    def motion_detected(self,file_name):
        """Callback if motion is detected. A video or still image will be created
        with name file_name.
        """

        print("[INFO] Motion detected")

        self.motion = True

        # if video file requested and not already recording, start recording
        if (not self.recording) and self.record_video:
            self.camera.start_recording(file_name)
            self.recording = True

            print("[INFO] Start recording" + file_name)

        # capture still image
        elif not self.record_video:
            self.camera.capture(file_name)

            print("[INFO] Capture frame " + file_name)

    def no_motion(self):
        """Callback if motion ended."""

        print("[INFO] Motion ended")

        self.motion = False

        if self.record_video:
            # cancel already running timer if needed
            if self.motion_timer is not None:
                self.motion_timer.cancel()

            self.motion_timer = Timer(self.conf["motion delay"], self.stop_recording).start()

    def stop_recording(self):
        """Stops camera recording (if in progress)."""

        if (not self.motion) and self.recording:
            self.camera.stop_recording()
            self.recording = False

            print("[INFO] Recording stopped.")

    def pir_event(self,pin):
        """PIR GPIO event callback."""

        if GPIO.input(pin): # rising
            if self.record_video:
                self.motion_detected(os.path.join(self.conf["directory"], "motion-" + datetime.datetime.now().strftime("%d-%m-%Y-%H-%M-%S") + ".h264"))
            else:
                self.motion_detected(self.conf["directory"] + "motion-" + datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + "-%dx%d.jpg" % (self.conf["resolution"][0], self.conf["resolution"][1]))
        else: # falling
            self.no_motion()

    def run_timer_callback(self):
        """Callback to end motion detection after conf["duration"] seconds"""

        # stop recording
        self.run_complete = True

        print("[INFO] Run timer callback: stop recording")

    def run(self,stop_function,stop_button,duration=None):
        """Perform motion detecton."""

        GPIO.setup(self.conf["PIR GPIO pin"], GPIO.IN) # register GPIO pin

        self.run_complete = False # run flag

        # load duration from config file if needed
        if duration is None:
            self.duration = self.conf["duration"]
        else:
            self.duration = duration

        # stop recording after specified time if needed
        if self.duration > 0:
            self.run_timer = Timer(self.duration, self.run_timer_callback)
            self.run_timer.start()

        # start recording, if KeyboardInterrupt stop execution (for debugging)
        try:
            print("[INFO] Press CTRL-C to exit run function prematurely")
            time.sleep(1)

            GPIO.add_event_detect(self.conf["PIR GPIO pin"], GPIO.BOTH, callback=self.pir_event)

            # configure exit button if configured
            if self.conf["stop detection GPIO pin"] >= 0:
                print("[INFO] Detection GPIO pin active")
                GPIO.setup(self.conf["stop detection GPIO pin"], GPIO.IN)
                GPIO.add_event_detect(self.conf["stop detection GPIO pin"], GPIO.BOTH, callback=self.run_timer_callback)

            # keep function alive and check every 3 seconds if the script needs to stop
            while (not self.run_complete) and (not stop_function(stop_button)):
                time.sleep(3)
                print(stop_function(stop_button))

        except KeyboardInterrupt:
            print("[INFO] Motion detection ended.")
        except PiCameraError:
            print("[ERROR] Camera error... Stopped detection.")

    def delete(self):
        """Release all nessesary veriables and stop timers."""

        # if camera is still recording, stop it before deallocation
        if self.camera.recording:
            self.camera.stop_recording()
            print('[INFO] Stopped recording.')

        if self.run_timer is not None:
            self.run_timer.cancel()
            self.run_timer.join()
            print('[INFO] Cancelled run timer.')

        if self.motion_timer is not None:
            self.motion_timer.cancel()
            self.motion_timer.join()
            print('[INFO] Cancelled motion timer.')

        # clean GPIO pins
        GPIO.cleanup(self.conf["PIR GPIO pin"])
        if self.conf["stop detection GPIO pin"] >= 0:
            GPIO.cleanup(self.conf["stop detection GPIO pin"])

        print("[INFO] Released objects")


text:
package com.t3coode.togg.services.views;

public interface ProjectUserUpdateView {

    boolean isAmdin();

    float getRate();

}


text:
package server

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/googleinterns/recomator/pkg/automation"
	"google.golang.org/api/recommender/v1"
)

const defaultNumConcurrentCalls = 200

// ListRecommendationsResponse is response to list/recommendations method
type ListRecommendationsResponse struct {
	Recommendations []*recommender.GoogleCloudRecommenderV1Recommendation `json:"recommendations"`
	FailedProjects  []*automation.ProjectRequirements                     `json:"failedProjects"`
}

type listRequestHandler struct {
	result             *automation.ListResult
	service            automation.GoogleService
	task               automation.Task
	projects           []string
	numConcurrentCalls int
	err                error
}

// NewListRequestHandler creates new listRequestHandler
func NewListRequestHandler(service automation.GoogleService, projects []string) RequestHandler {
	return &listRequestHandler{service: service, projects: projects, numConcurrentCalls: defaultNumConcurrentCalls}
}

func (h *listRequestHandler) Start() {
	h.task.SetNumberOfSubtasks(1) // 1 call to ListProjectsRecommendations
	h.result, h.err = automation.ListProjectsRecommendations(h.service, h.projects, h.numConcurrentCalls, h.task.GetNextSubtask())
	h.task.SetAllDone()
}

func (h *listRequestHandler) GetResponse() (Response, bool) {
	done, all := h.task.GetProgress()
	if done < all {
		return Response{Content: Progress{int(done), int(all)}}, false
	}
	if h.err != nil {
		return Response{Error: h.err}, true
	}
	return Response{Content: ListRecommendationsResponse{
		Recommendations: h.result.Recommendations,
		FailedProjects:  h.result.FailedProjects}}, true
}

// ListRequest contains the body of POST /recommendations request
type ListRequest struct {
	Projects []string `json:"projects"`
}

func getStartListingHandler(service *SharedService) func(c *gin.Context) {
	return func(c *gin.Context) {
		var listRequest ListRequest

		body, err := ioutil.ReadAll(c.Request.Body)
		if err != nil {
			sendError(c, fmt.Errorf("Error reading body: %s", err.Error()), http.StatusBadRequest)
			return
		}

		err = json.Unmarshal(body, &listRequest)

		if err != nil {
			sendError(c, fmt.Errorf("Error parsing body: %s", err.Error()), http.StatusBadRequest)
			return
		}

		user, err := authorizeRequest(service.auth, c.Request)

		if err != nil {
			sendError(c, err)
			return
		}

		handler := NewListRequestHandler(user.service, listRequest.Projects)
		requestID := StartProcessingWithNewRequestID(&service.requests, user.email, handler)
		c.String(http.StatusCreated, requestID)
	}
}

func getListHandler(service *SharedService) func(c *gin.Context) {
	return func(c *gin.Context) {
		id := c.Query("request_id")
		user, err := authorizeRequest(service.auth, c.Request)

		if err != nil {
			sendError(c, err)
			return
		}

		response, ok := service.requests.GetResponse(RequestInfo{user.email, id})

		if !ok {
			sendError(c, fmt.Errorf("No request for %s with id %s", user.email, id), http.StatusNotFound)
			return
		}

		if response.Error != nil {
			sendError(c, response.Error)
			return
		}

		c.JSON(http.StatusOK, response.Content)
	}
}


text:
"""Command for deleting network peerings."""

from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import networks_utils
from googlecloudsdk.calliope import base

@base.ReleaseTracks(base.ReleaseTrack.ALPHA)
class DeleteAlpha(base_classes.BaseAsyncMutator):
  """Delete a Google Compute Engine network peering."""

  @property
  def service(self):
    return self.compute.networks

  @property
  def method(self):
    return 'RemovePeering'

  @property
  def resource_type(self):
    return 'peerings'

  def ComputeDynamicProperties(self, args, items):
    self._network_name = args.name
    return networks_utils.AddMode(items)

  @staticmethod
  def Args(parser):

    parser.add_argument(
        'name',
        help='The name of the peering to delete.')

    parser.add_argument(
        '--network',
        required=True,
        help='The name of the network in the current project containing the '
             'peering.')

  def CreateRequests(self, args):
    """Returns the request necessary for deleting the peering."""

    request = self.messages.ComputeNetworksRemovePeeringRequest(
        network=args.network,
        networksRemovePeeringRequest=self.messages.NetworksRemovePeeringRequest(
            name=args.name),
        project=self.project)

    return [request]


text:
<?php

declare(strict_types=1);

namespace Nekudo\ShinyGeoip;

use Nekudo\ShinyGeoip\Responder\HttpResponder;

class ShowLocationResponder extends HttpResponder
{
    /**
     * Defines if we respond with json or javascript header.
     *
     * @var string $responseType
     */
    protected $responseType = 'json';

    /**
     * Holds the callback function name for JSONP responses.
     *
     * @var string $callback
     */
    protected $callback = '';

    /**
     * Sets callback function name for JSONP responses.
     *
     * @param string $callback
     */
    public function setCallback(string $callback)
    {
        $this->callback = $callback;
        $this->responseType = 'javascript';
    }

    /**
     * Sends json encoded record data to client.
     *
     * @param array $record
     */
    public function recordFound(array $record)
    {
        $payload = json_encode($record);
        $this->respondLocation($payload);
    }

    /**
     * Responds with error message if no record was found for requested IP.
     */
    public function recordNotFound()
    {
        $response = json_encode([
            'type' => 'error',
            'msg' => 'No record found.'
        ]);
        $this->respondLocation($response);
    }

    /**
     * Sets headers and sends response data to client.
     *
     * @param string $payload
     */
    protected function respondLocation(string $payload)
    {
        if ($this->responseType === 'javascript') {
            header('Content-Type: application/javascript', true);
        } else {
            header('Content-Type: application/json', true);
        }
        header('Access-Control-Allow-Origin: *', true);
        if (!empty($this->callback)) {
            $payload = $this->callback . '(' . $payload . ');';
        }
        $this->found($payload);
    }
}


text:
'use strict';

describe('"Dashboard" module', function() {

  let module;
  before(function() {
    module = angular.module('dashboard');
  });

  it('should be registered', function() {
    expect(module).not.to.be.empty;
  });

});


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

namespace Utilities.DataTypes.AOP.Interfaces
{
    /// <summary>
    /// Aspect interface
    /// </summary>
    public interface IAspect
    {
        /// <summary>
        /// Set of assemblies that the aspect requires
        /// </summary>
        ICollection<Assembly> AssembliesUsing { get; }

        /// <summary>
        /// List of interfaces that need to be injected by this aspect
        /// </summary>
        ICollection<Type> InterfacesUsing { get; }

        /// <summary>
        /// Using statements that the aspect requires
        /// </summary>
        ICollection<string> Usings { get; }

        /// <summary>
        /// Used to hook into the object once it has been created
        /// </summary>
        /// <param name="Object">Object created by the system</param>
        void Setup(object Object);

        /// <summary>
        /// Used to insert code into the default constructor
        /// </summary>
        /// <param name="BaseType">Base type</param>
        /// <returns>The code to insert</returns>
        string SetupDefaultConstructor(Type BaseType);

        /// <summary>
        /// Used to insert code at the end of the method
        /// </summary>
        /// <param name="Method">Overridding Method</param>
        /// <param name="BaseType">Base type</param>
        /// <param name="ReturnValueName">Local holder for the value returned by the function</param>
        /// <returns>The code to insert</returns>
        string SetupEndMethod(MethodInfo Method, Type BaseType, string ReturnValueName);

        /// <summary>
        /// Used to insert code within the catch portion of the try/catch portion of the method
        /// </summary>
        /// <param name="Method">Overridding Method</param>
        /// <param name="BaseType">Base type</param>
        /// <returns>The code to insert</returns>
        string SetupExceptionMethod(MethodInfo Method, Type BaseType);

        /// <summary>
        /// Used to set up any interfaces, extra fields, methods, etc. prior to overridding any methods.
        /// </summary>
        /// <param name="Type">Type of the object</param>
        /// <returns>The code to insert</returns>
        string SetupInterfaces(Type Type);

        /// <summary>
        /// Used to insert code at the beginning of the method
        /// </summary>
        /// <param name="Method">Overridding Method</param>
        /// <param name="BaseType">Base type</param>
        /// <returns>The code to insert</returns>
        string SetupStartMethod(MethodInfo Method, Type BaseType);
    }
}


text:
namespace pmr = std::experimental::pmr;

template <class T>
struct MyHash : std::hash<T> {};

template <class T>
struct MyPred : std::equal_to<T> {};

int main()
{
    using K = int;
    using V = char;
    using DH = std::hash<K>;
    using MH = MyHash<K>;
    using DP = std::equal_to<K>;
    using MP = MyPred<K>;
    using P = std::pair<const K, V>;
    {
        using StdMap = std::unordered_map<K, V, DH, DP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_map<K, V>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        using StdMap = std::unordered_map<K, V, MH, DP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_map<K, V, MH>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        using StdMap = std::unordered_map<K, V, MH, MP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_map<K, V, MH, MP>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        pmr::unordered_map<int, int> m;
        assert(m.get_allocator().resource() == pmr::get_default_resource());
    }
    {
        using StdMap = std::unordered_multimap<K, V, DH, DP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_multimap<K, V>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        using StdMap = std::unordered_multimap<K, V, MH, DP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_multimap<K, V, MH>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        using StdMap = std::unordered_multimap<K, V, MH, MP, pmr::polymorphic_allocator<P>>;
        using PmrMap = pmr::unordered_multimap<K, V, MH, MP>;
        static_assert(std::is_same<StdMap, PmrMap>::value, "");
    }
    {
        pmr::unordered_multimap<int, int> m;
        assert(m.get_allocator().resource() == pmr::get_default_resource());
    }
}


text:
from rpython.jit.codewriter.policy import JitPolicy

from cycy.cli import parse_args

def main(argv):
    command_line = parse_args(argv[1:])
    exit_status = command_line.action(command_line)
    return exit_status

def target(driver, args):
    return main, None

def jitpolicy(driver):
    return JitPolicy()

def untranslated_main():
    """
    Runs main, exiting with the appropriate exit status afterwards.

    """

    import sys
    sys.exit(main(sys.argv))


text:
<?php

class OffState implements IState
{
  private $context;

  public function __construct(Context $contextNow)
  {
    $this->context = $contextNow;
  }
  public function turnLightOff()
  {
    echo 'Light is already off
';
  }
  public function turnLightOn()
  {
    echo "Lights on!
";
    $this->context->setState($this->context->getOnState());
  }
}


text:
package sagex.phoenix.metadata.search;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import sagex.phoenix.common.SystemConfigurationFileManager;
import sagex.phoenix.metadata.MediaType;
import sagex.phoenix.util.BaseBuilder;
import sagex.phoenix.util.FileUtils;
import sagex.phoenix.util.XmlUtil;

public class FileMatcherManager extends SystemConfigurationFileManager implements
        SystemConfigurationFileManager.ConfigurationFileVisitor {
    public static class FileMatcherXmlBuilder extends BaseBuilder {
        private File sourceFile;

        public FileMatcherXmlBuilder(File sourceFile) {
            super(sourceFile.getAbsolutePath());
            this.sourceFile = sourceFile;
        }

        private List<FileMatcher> matchers = new ArrayList<FileMatcher>();
        private FileMatcher curMatcher = null;

        public List<FileMatcher> getMatchers() {
            return matchers;
        }

        /*
         * (non-Javadoc)
         *
         * @see
         * org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         * java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
            if ("match".equals(name)) {
                curMatcher = new FileMatcher();
                curMatcher.setSourceFile(sourceFile);
            } else if ("regex".equals(name)) {
            } else if ("file".equals(name)) {
            } else if ("title".equals(name)) {
            } else if ("year".equals(name)) {
            } else if ("metadata".equals(name)) {
                curMatcher.setMetadata(new ID(XmlUtil.attr(attributes, "name", null), null));
                curMatcher.setMediaType(MediaType.toMediaType(XmlUtil.attr(attributes, "type", "movie")));
            } else if ("fanart".equals(name)) {
                curMatcher.setFanart(new ID(XmlUtil.attr(attributes, "name", null), null));
            } else if ("titles".equals(name)) {
            } else {
                warning("Unhandled element: " + name + " in file matcher xml");
            }
        }

        /*
         * (non-Javadoc)
         *
         * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
         * java.lang.String, java.lang.String)
         */
        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            if ("match".equals(name)) {
                matchers.add(curMatcher);
                curMatcher = null;
            } else if ("regex".equals(name)) {
                curMatcher.setFileRegex(getData());
            } else if ("file".equals(name)) {
                curMatcher.setFile(new File(getData()));
            } else if ("title".equals(name)) {
                curMatcher.setTitle(getData());
            } else if ("year".equals(name)) {
                curMatcher.setYear(getData());
            } else if ("metadata".equals(name)) {
                curMatcher.getMetadata().setValue(getData());
            } else if ("fanart".equals(name)) {
                curMatcher.getFanart().setValue(getData());
            }
        }
    }

    private List<FileMatcher> buildMatchers(File xmlFile) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        SAXParser parser = saxFactory.newSAXParser();

        FileMatcherXmlBuilder handler = new FileMatcherXmlBuilder(xmlFile);
        parser.parse(xmlFile, handler);

        return handler.getMatchers();
    }

    /**
     * Returns a new builder that can be used to build {@link FileMatcher}
     * objects from Xml.
     *
     * @param sourceFile
     * @return
     */
    public FileMatcherXmlBuilder createBuilder(File sourceFile) {
        return new FileMatcherXmlBuilder(sourceFile);
    }

    private Logger log = Logger.getLogger(FileMatcherManager.class);

    private List<FileMatcher> matchers = new ArrayList<FileMatcher>();

    public FileMatcherManager(File systemDir, File userDir) {
        super(systemDir, userDir, new SuffixFileFilter("MediaTitles.xml", IOCase.INSENSITIVE));
    }

    public List<FileMatcher> getFileMatchers() {
        return matchers;
    }

    public void addMatcher(FileMatcher matcher) {
        if (matcher.getSourceFile() == null) {
            matcher.setSourceFile(getDefaultMediaTitlesFile());
        }

        if (matcher.getId() == null) {
            String id = null;
            if (matcher.getFileRegex() != null) {
                id = DigestUtils.md5Hex(matcher.getFileRegex().pattern());
            } else if (matcher.getFile() != null) {
                id = DigestUtils.md5Hex(matcher.getFile().getAbsolutePath());
            }
            if (id == null) {
                log.warn("Will not add the filematcher since it has no id");
                return;
            }
            matcher.setId(id);
        }

        FileMatcher fm = getMatcherForId(matcher.getId());
        if (fm != null) {
            log.info("Replacing file matcher: " + matcher);
            getFileMatchers().remove(matcher);
        }

        getFileMatchers().add(matcher);
    }

    public FileMatcher getMatcherForId(String id) {
        if (id == null)
            return null;
        for (FileMatcher f : getFileMatchers()) {
            if (id.equals(f.getId())) {
                return f;
            }
        }
        return null;
    }

    /**
     * For the given filePath, attempt to find a match that will identify the
     * metadata for the given item.
     *
     * @param filePath
     * @return
     */
    public FileMatcher getMatcher(String filePath) {
        if (filePath == null)
            return null;
        for (FileMatcher m : getFileMatchers()) {
            if (m.getFile() != null) {
                File f = new File(filePath);
                if (f.equals(m.getFile())) {
                    return m;
                }
            }

            if (m.getFileRegex() != null) {
                Matcher match = m.getFileRegex().matcher(filePath);
                if (match.find()) {
                    return m;
                }
            }
        }

        log.debug("No File Matchers for: " + filePath);
        return null;
    }

    @Override
    public void visitConfigurationFile(ConfigurationType type, File file) {
        log.info("Loading " + type + " media titles from " + file);
        try {
            List<FileMatcher> m = buildMatchers(file);
            if (m != null) {
                matchers.addAll(m);
            }
        } catch (Exception e) {
            log.warn("Failed to load matchers xml file: " + file, e);
        }
    }

    @Override
    public void loadConfigurations() {
        log.info("Begin loading Title Matchers");
        matchers.clear();
        accept(this);
        log.info("End loading Title Matchers");
    }

    public void addRegexMatcher(FileMatcher matcher) throws Exception {
        int pos = -1;
        for (int i = 0; i < getFileMatchers().size(); i++) {
            FileMatcher fm = getFileMatchers().get(i);
            if (fm.getFileRegex() != null && fm.getFileRegex().pattern().equals(matcher.getFileRegex().pattern())) {
                pos = i;
                break;
            }
        }
        if (pos != -1) {
            getFileMatchers().remove(pos);
        }
        addMatcher(matcher);
    }

    public File getDefaultMediaTitlesFile() {
        return new File(getUserFiles().getDir(), "MediaTitles.xml");
    }

    public synchronized int saveMatchers() throws IOException {
        File outfile = null;
        if (getUserFiles().getFiles() != null) {
            for (File f : getUserFiles().getFiles()) {
                if (f.getName().equals("MediaTitles.xml")) {
                    outfile = f;
                }
            }
        }

        if (outfile == null) {
            outfile = getDefaultMediaTitlesFile();
        }

        if (!outfile.getParentFile().exists()) {
            FileUtils.mkdirsQuietly(outfile.getParentFile());
        }
        List<FileMatcher> matchers = getMatchersForSource(outfile);
        log.info("Saving " + matchers.size() + " file matchers to " + outfile);
        FileOutputStream fos = new FileOutputStream(outfile);
        XmlFileMatcherSerializer ser = new XmlFileMatcherSerializer();
        ser.serialize(matchers, fos);
        fos.flush();
        fos.close();
        return matchers.size();
    }

    private List<FileMatcher> getMatchersForSource(File source) {
        List<FileMatcher> matchers = new ArrayList<FileMatcher>();
        for (FileMatcher fm : getFileMatchers()) {
            if (source.equals(fm.getSourceFile())) {
                matchers.add(fm);
            }
        }
        return matchers;
    }
}


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>@Font-Face Template</title>
<style type="text/css">
@font-face {
    font-family: 'MyWebFont';
    src: url('webfont.eot'); /* IE9 Compat Modes */
    src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
	    url('webfont.woff') format('woff'), /* Modern Browsers */
	    url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
	    url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
    font-family: 'MyWebFont', Arial, sans-serif;
}
</style>
</head>
<body>
</body>
</html>


text:
package appInspector;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;

public class Utils {

	static private Main mainApp;

	@SuppressWarnings("static-access")
	static public void printDebug(String msg)
	{
		if (mainApp.flag)
			System.out.println(msg);
	}

	static public String getDepth(int value) {
		String label = "";
		if (value == Main.NODE_TYPE_ROOT) label = "Root";
		if (value == Main.NODE_TYPE_PROJECT) label = "Project";
		if (value == Main.NODE_TYPE_ENV) label = "Env";
		if (value == Main.NODE_TYPE_DOCBASE) label = "Docbase";
		return label;
	}

	static public void savePreferences(String filename) {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("CONFIGURATION");
		    doc.appendChild(rootElement);
		    Element browser = doc.createElement("BROWSER");
		    browser.appendChild(doc.createTextNode("chrome"));
		    rootElement.appendChild(browser);
		    Element base = doc.createElement("BASE");
		    base.appendChild(doc.createTextNode("http:fut"));
		    rootElement.appendChild(base);
		    Element employee = doc.createElement("EMPLOYEE");
		    rootElement.appendChild(employee);
		    Element empName = doc.createElement("EMP_NAME");
		    empName.appendChild(doc.createTextNode("Anhorn, Irene"));
		    employee.appendChild(empName);
		    Element actDate = doc.createElement("ACT_DATE");
		    actDate.appendChild(doc.createTextNode("20131201"));
		    employee.appendChild(actDate);

		    TransformerFactory transformerFactory = TransformerFactory.newInstance();
		    Transformer transformer = transformerFactory.newTransformer();
		    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		    DOMSource source = new DOMSource(doc);
		    StreamResult result = new StreamResult(new File(filename));
		    transformer.transform(source, result);
		    System.out.println("File saved!");

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}
}


text:
package com.voxmecanica.vdk.core;

import android.speech.tts.UtteranceProgressListener;

import com.voxmecanica.vdk.api.DialogContext;
import com.voxmecanica.vdk.api.PartRenderer;
import com.voxmecanica.vdk.logging.Logger;
import com.voxmecanica.vdk.api.Part;

public class SpeechRenderer implements PartRenderer{
    private Logger LOG = new Logger("SpeechRenderer");
	private PartRenderer.OnCompleted onCompletedEvent;
	private Part part;
	private VoxRuntime runtime;

	public SpeechRenderer(DialogContext ctx, Part part, PartRenderer.OnCompleted onCompleted){
		runtime = ctx.getRuntime();
        this.part = part;
		onCompletedEvent = onCompleted;
	}

	@Override
	public void run() {
		String textToSpeak = part.getText();
		LOG.d("Rendering text [" + textToSpeak + "]");

		runtime.speakText(textToSpeak, new UtteranceProgressListener(){
            @Override
            public void onStart(String utteranceId) {
                LOG.d("Utterance [" + utteranceId + "] started OK");
            }

            @Override
            public void onDone(String utteranceId) {
                LOG.d("Utterance [" + utteranceId + "] completed OK");
                if(onCompletedEvent != null)
                    onCompletedEvent.completed(PartRenderer.RENDERING_OK);
            }

            @Override
            public void onError(String utteranceId) {
                LOG.d("Utterance [" + utteranceId + "] Failed.");
                if(onCompletedEvent != null)
                    onCompletedEvent.completed(PartRenderer.RENDERING_FAILED);
            }
        });
	}

}


text:
import React , {PropTypes} from 'react';
import { connect } from 'react-redux';
import doSomething from '../actions/actions';
import TextField from 'material-ui/lib/text-field';

const MessageText = (props) => {

	return (

			 yolo {props.text}

				<MyInputField />

	)
}

const Message = ({memory , clickHandler}) => (

 clickHandler(memory)}>  {memory.title}

	<MessageText text={memory.title}>
	</MessageText>

)

const MyInputField = () => {
	return (

		<TextField hintText="Hint Text"/>
	)
}

Message.propTypes = {
	memory :  PropTypes.shape({
		id: PropTypes.number.isRequired,
		title: PropTypes.string.isRequired
	}).isRequired,
	clickHandler : PropTypes.func.isRequired
}

//export default Message;

const mapStateToProps = (state) => {

	return {
		memory: state.memory
	}
}

const mapDispatchToProps = (dispatch) => {
	return {
		clickHandler: (memory) => {
			dispatch(doSomething(memory));
		}
	}
}

const SmartMessage = connect(
	mapStateToProps,
	mapDispatchToProps
)(Message) ;

export default SmartMessage;


text:
import argparse
import json
import traceback
from typing import *
from . import errors, utils
from .agent import Agent
from .core import environments, evaluate, make
from logging.config import dictConfig

parser = argparse.ArgumentParser(description="Kaggle Simulations")
parser.add_argument(
    "action",
    choices=["list", "evaluate", "run", "step", "load", "act", "dispose", "http-server"],
    help="List environments. Evaluate many episodes. Run a single episode. Step the environment. Load the environment. Start http server.",
)
parser.add_argument("--environment", type=str,
                    help="Environment to run against.")
parser.add_argument("--debug", type=bool, help="Print debug statements.")
parser.add_argument(
    "--agents", type=str, nargs="*", help="Agent(s) to run with the environment."
)
parser.add_argument(
    "--configuration",
    type=json.loads,
    help="Environment configuration to setup the environment.",
)
parser.add_argument(
    "--info",
    type=json.loads,
    help="Information about agents playing.",
)
parser.add_argument(
    "--steps",
    type=json.loads,
    help="Environment starting states (default=[resetState]).",
)
parser.add_argument(
    "--logs",
    type=json.loads,
    help="Environment starting logs (default=[]).",
)
parser.add_argument(
    "--state",
    type=json.loads,
    help="Single agent state used for evaluation (default={}).",
)
parser.add_argument(
    "--episodes", type=int, help="Number of episodes to evaluate (default=1)"
)
parser.add_argument(
    "--render",
    type=json.loads,
    help="Response from run, step, or load. Calls environment render (default={mode='json'}).",
)
parser.add_argument(
    "--display",
    type=str,
    help="Shortcut to the --render {mode=''} argument (default json).",
)
parser.add_argument(
    "--port", type=int, help="http-server Port (default=8000)."
)
parser.add_argument(
    "--host", type=str, help="http-server Host (default=127.0.0.1)."
)
parser.add_argument(
    "--in", type=str, help="Episode replay file to load. Only works when the action is load."
)
parser.add_argument(
    "--out", type=str, help="Output file to write the results of the episode. Does nothing in http-server mode."
)
parser.add_argument(
    "--log", type=str, help="Agent log file to write the std out, resource, and step timing for each agent. Also used to load logs from a file with the load action."
)

def render(args, env):
    mode = \
        args.display \
        if args.display is not None \
        else utils.get(args.render, str, "json", path=["mode"])

    if mode == "human" or mode == "ansi" or mode == "txt":
        args.render["mode"] = "ansi"
    elif mode == "ipython" or mode == "html":
        args.render["mode"] = "html"
    elif mode == "webm" or mode == "video":
        args.render["mode"] = "webm"
    else:
        args.render["mode"] = "json"
    result = env.render(**args.render)
    return result

def action_list(args):
    return json.dumps([*environments])

def action_evaluate(args):
    return json.dumps(
        evaluate(
            args.environment, args.agents, args.configuration, args.steps, args.episodes
        )
    )

cached_agent = None

def action_act(args):
    global cached_agent
    if len(args.agents) != 1:
        return {"error": "One agent must be provided."}
    raw = args.agents[0]

    env = make(args.environment, args.configuration, args.info, state=args.state, debug=args.debug)

    is_first_run = cached_agent is None or cached_agent.raw != raw
    if is_first_run:
        cached_agent = Agent(raw, env)
    observation = utils.get(args.state, dict, {}, ["observation"])
    action, log = cached_agent.act(observation)
    if isinstance(action, errors.DeadlineExceeded):
        action = "DeadlineExceeded"
    elif isinstance(action, BaseException):
        action = "BaseException::" + str(action)

    if args.log_path is not None:
        with open(args.log_path, mode="a") as log_file:
            if not is_first_run:
                log_file.write(",\n ")
            json.dump([log], log_file)

    return {"action": action}

def action_step(args):
    env = {"logs": args.logs}
    try:
        env = make(args.environment, args.configuration, args.info, args.steps, args.logs, args.debug)
        runner = env.__agent_runner(args.agents)
        env.step(runner.act())
    finally:
        if args.log_path is not None:
            with open(args.log_path, mode="a") as log_file:
                json.dump(env.logs[-1], log_file)
                log_file.write(",")
    return render(args, env)

def action_run(args):
    # Create a fake env so we can make the real env in our try body
    env = utils.structify({"logs": args.logs})
    try:
        env = make(args.environment, args.configuration, args.info, args.steps, args.logs, args.debug)
        env.run(args.agents)
    finally:
        if args.log_path is not None:
            with open(args.log_path, mode="w") as log_file:
                json.dump(env.logs, log_file, indent=2)
    return render(args, env)

def action_load(args):
    if args.log_path is not None:
        with open(args.log_path, mode="r") as log_file:
            args.logs = json.load(log_file)

    if args.in_path is not None:
        with open(args.in_path, mode="r") as replay_file:
            json_args = json.load(replay_file)
        env = make(json_args["name"], json_args["configuration"], json_args["info"], json_args["steps"], args.logs, args.debug)
    else:
        env = make(args.environment, args.configuration, args.info, args.steps, args.logs, args.debug)
    return render(args, env)

disposed = True

# This method is only called at the end of an episode to write the final array brace in the logs file and dispose the cached agent to force reinitialization
def action_dispose(args):
    global cached_agent, disposed
    if disposed:
        return "Already disposed"

    cached_agent = None
    if args.log_path is not None:
        with open(args.log_path, mode="a") as log_file:
            log_file.write("]")
    disposed = True
    return "Successfully disposed"

def parse_args(args):
    return utils.structify(
        {
            "action": utils.get(args, str, "list", ["action"]),
            "agents": utils.get(args, list, [], ["agents"]),
            "configuration": utils.get(args, dict, {}, ["configuration"]),
            "environment": args.get("environment", args.get("name", None)),
            "episodes": utils.get(args, int, 1, ["episodes"]),
            "state": utils.get(args, dict, {}, ["state"]),
            "steps": utils.get(args, list, [], ["steps"]),
            "logs": utils.get(args, list, [], ["logs"]),
            "render": utils.get(args, dict, {"mode": "json"}, ["render"]),
            "display": utils.get(args, str, None, ["display"]),
            "debug": utils.get(args, bool, False, ["debug"]),
            "host": utils.get(args, str, "127.0.0.1", ["host"]),
            "port": utils.get(args, int, 8000, ["port"]),
            "in_path": utils.get(args, str, None, ["in"]),
            "out_path": utils.get(args, str, None, ["out"]),
            "log_path": utils.get(args, str, None, ["log"]),
            "info": utils.get(args, dict, {}, ["info"]),
        }
    )

def action_handler(args):
    try:
        if args.action == "list":
            return action_list(args)
        if args.action == "http-server":
            return {"error": "Already running a http server."}
        if args.action == "act":
            return action_act(args)
        if args.action == "dispose":
            return action_dispose(args)
        if args.action == "load":
            return action_load(args)

        if args.environment is None:
            return {"error": "Environment required."}

        if args.action == "evaluate":
            return action_evaluate(args)
        if args.action == "step":
            return action_step(args)
        if args.action == "run":
            return action_run(args)

        return {"error": "Unknown Action"}
    except Exception as e:
        return {"error": str(e), "trace": traceback.format_exc()}

log_path: Optional[str] = None

def action_http(args):
    from flask import Flask, request

    if args.log_path is not None:
        global log_path
        log_path = args.log_path

    # Setup logging to console for Flask
    dictConfig({
        'version': 1,
        'formatters': {'default': {
            'format': '%(levelname)s: %(message)s',
        }},
        'handlers': {'wsgi': {
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout',
            'formatter': 'default'
        }},
        'root': {
            'level': 'INFO',
            'handlers': ['wsgi']
        }
    })

    app = Flask(__name__, static_url_path="", static_folder="")
    app.route("/", methods=["GET", "POST"])(lambda: http_request(request))
    app.run(args.host, args.port, debug=args.debug, use_reloader=args.debug)

def http_request(request):
    # Set CORS headers for the preflight request
    if request.method == "OPTIONS":
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET",
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Max-Age": "3600",
        }

        return "", 204, headers

    headers = {"Access-Control-Allow-Origin": "*"}
    params = request.args.to_dict()
    for key in list(params.keys()):
        if key.endswith("[]"):
            params[key.replace("[]", "")] = request.args.getlist(key)
            del params[key]
        elif key.endswith("{}"):
            params[key.replace("{}", "")] = json.loads(params[key])
            del params[key]

    body = request.get_json(silent=True, force=True) or {}
    args = {**params, **body}
    if "render" in args and isinstance(args["render"], str):
        # Manually deserialize render argument
        # We should eventually refactor this to use the same deserializer as the cmd line arg parser
        args["render"] = json.loads(args["render"])
    args = parse_args(args)
    if args.log_path is None:
        args.log_path = log_path

    global disposed
    # Write the opening array brace for the logs file if there is a logs file.
    if disposed and args["action"] != "dispose" and args.log_path is not None:
        with open(args.log_path, mode="w") as log_file:
            log_file.write("[")
        disposed = False

    resp = action_handler(args)
    return resp, 200, headers

def main():
    args = parse_args(vars(parser.parse_args()))
    if args.action == "http-server":
        action_http(args)
    else:
        result = action_handler(args)
        if args.out_path is None:
            print(result)
        else:
            with open(args.out_path, encoding="utf-8", mode="w") as out_file:
                out_file.write(str(result))

        return 0

if __name__ == "__main__":
    main()


text:
let infoFn: Function = () => {
    throw new Error(`
        No toast implementation has been specified. To fix this:
        A) call useDefaultImplementations
        or
        B) call setInfo to specify a toast function.
        `);
};

export function info(message: string) {
    infoFn(message);
}

export function setInfo(fn: (m: string) => void) {
    infoFn = fn;
}


text:
//
//  indexTableViewCell.m
//  wenku8
//
//  Created by wbuntu on 15/3/22.
//  Copyright (c) 2015年 wbuntu. All rights reserved.
//

#import "indexTableViewCell.h"
//@implementation CTView
//
//-(instancetype)initWithFrame:(CGRect)frame
//{
//    self = [super initWithFrame:frame];
//    if (self) {
//        self.opaque=YES;
//        self.backgroundColor = [UIColor colorWithRed:249.0/255 green:234.0/255 blue:188.0/255 alpha:1];
//    }
//    return self;
//}
//
//-(void)drawRect:(CGRect)rect
//{
//    [super drawRect:rect];
//    [_bookCover drawInRect:CGRectMake(8, 6, 60, 90)];
//    NSMutableParagraphStyle *para = [[NSMutableParagraphStyle alloc] init];
//    para.lineBreakMode = NSLineBreakByCharWrapping;
//    para.alignment = NSTextAlignmentLeft;
//    [_bookTitle drawInRect:CGRectMake(76, 6, 236, 100) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],NSParagraphStyleAttributeName:para}];
//}
//@end

@interface indexTableViewCell()

@end
@implementation indexTableViewCell
-(void)awakeFromNib
{
    [super awakeFromNib];
    /*
    _cover.layer.shadowOffset = CGSizeMake(2, 2);
    _cover.layer.shadowColor = [UIColor blackColor].CGColor;
    _cover.layer.shadowOpacity = 0.9;
     */
}
-(void)setCellWithBook:(bookElement*)book
{
    int bookId = book.bookId;
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"cover/%ds.jpg",bookId]];
    if ([manager fileExistsAtPath:path]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            UIImage *im = [UIImage imageWithContentsOfFile:path];
            //opaque:NO 不透明
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(60, 90), NO, 0.0);
            [im drawInRect:CGRectMake(0, 0, 60, 90)];
            UIImage *other = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            dispatch_async(dispatch_get_main_queue(), ^{
                _cover.image = other;
                _title.text = book.bookTitle;
            });
        });
    }
    else
    {
        NSString *bookImage = [NSString stringWithFormat:CAWImageUrl,bookId];
        [[CAWNetwork defaultManager] dataTaskWithString:bookImage completionHandler:^(NSData *data) {
                [data writeToFile:path atomically:YES];
                UIImage *im = [UIImage imageWithContentsOfFile:path];
                //opaque:NO 不透明
                UIGraphicsBeginImageContextWithOptions(CGSizeMake(60, 90), NO, 0.0);
                [im drawInRect:CGRectMake(0, 0, 60, 90)];
                UIImage *other = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();
                dispatch_async(dispatch_get_main_queue(), ^{
                    _cover.image = other;
                    _title.text = book.bookTitle;
                });
        }];
    }

}
@end


text:
require 'uri'
require 'fileutils'

class Gem::Source
  FILES = {
    :released   => 'specs',
    :latest     => 'latest_specs',
    :prerelease => 'prerelease_specs',
  }

  def initialize(uri)
    unless uri.kind_of? URI
      uri = URI.parse(uri.to_s)
    end

    @uri = uri
    @api_uri = nil
  end

  attr_reader :uri

  def api_uri
    require 'rubygems/remote_fetcher'
    @api_uri ||= Gem::RemoteFetcher.fetcher.api_endpoint uri
  end

  def <=>(other)
    case other
    when Gem::Source::Installed,
         Gem::Source::Local,
         Gem::Source::SpecificFile then
      -1
    when Gem::Source then
      if !@uri
        return 0 unless other.uri
        return 1
      end

      return -1 if !other.uri

      @uri.to_s <=> other.uri.to_s
    else
      nil
    end
  end

  include Comparable

  def ==(other)
    case other
    when self.class
      @uri == other.uri
    else
      false
    end
  end

  alias_method :eql?, :==

  def hash
    @uri.hash
  end

  ##
  # Returns the local directory to write +uri+ to.

  def cache_dir(uri)
    # Correct for windows paths
    escaped_path = uri.path.sub(/^\/([a-z]):\//i, '/\\1-/')
    File.join Gem.spec_cache_dir, "#{uri.host}%#{uri.port}", File.dirname(escaped_path)
  end

  def update_cache?
    @update_cache ||= File.stat(Gem.user_home).uid == Process.uid
  end

  def fetch_spec(name)
    fetcher = Gem::RemoteFetcher.fetcher

    spec_file_name = name.spec_name

    uri = @uri + "#{Gem::MARSHAL_SPEC_DIR}#{spec_file_name}"

    cache_dir = cache_dir uri

    local_spec = File.join cache_dir, spec_file_name

    if File.exist? local_spec then
      spec = Gem.read_binary local_spec
      spec = Marshal.load(spec) rescue nil
      return spec if spec
    end

    uri.path << '.rz'

    spec = fetcher.fetch_path uri
    spec = Gem.inflate spec

    if update_cache? then
      FileUtils.mkdir_p cache_dir

      open local_spec, 'wb' do |io|
        io.write spec
      end
    end

    # TODO: Investigate setting Gem::Specification#loaded_from to a URI
    Marshal.load spec
  end

  ##
  # Loads +type+ kind of specs fetching from +@uri+ if the on-disk cache is
  # out of date.
  #
  # +type+ is one of the following:
  #
  # :released   => Return the list of all released specs
  # :latest     => Return the list of only the highest version of each gem
  # :prerelease => Return the list of all prerelease only specs
  #

  def load_specs(type)
    file       = FILES[type]
    fetcher    = Gem::RemoteFetcher.fetcher
    file_name  = "#{file}.#{Gem.marshal_version}"
    spec_path  = @uri + "#{file_name}.gz"
    cache_dir  = cache_dir spec_path
    local_file = File.join(cache_dir, file_name)
    retried    = false

    FileUtils.mkdir_p cache_dir if update_cache?

    spec_dump = fetcher.cache_update_path spec_path, local_file, update_cache?

    begin
      Gem::NameTuple.from_list Marshal.load(spec_dump)
    rescue ArgumentError
      if update_cache? && !retried
        FileUtils.rm local_file
        retried = true
        retry
      else
        raise Gem::Exception.new("Invalid spec cache file in #{local_file}")
      end
    end
  end

  def download(spec, dir=Dir.pwd)
    fetcher = Gem::RemoteFetcher.fetcher
    fetcher.download spec, @uri.to_s, dir
  end

  def pretty_print q # :nodoc:
    q.group 2, '[Remote:', ']' do
      q.breakable
      q.text @uri.to_s
    end
  end

end

require 'rubygems/source/installed'
require 'rubygems/source/specific_file'
require 'rubygems/source/local'


text:
package com.show.tt.DB.entity;

// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS

// KEEP INCLUDES - put your custom includes here

import com.show.tt.config.DBConstant;
import com.show.tt.protobuf.helper.EntityChangeEngine;
/**
 * 这个类不同与其他自动生成代码
 * 需要依赖conten与display 依赖不同的状态
 * */
// KEEP INCLUDES END
/**
 * Entity mapped to table Message.
 */
public class MessageEntity implements java.io.Serializable {

    protected Long id;
    protected int msgId;
    protected int fromId;
    protected int toId;
    /** Not-null value. */
    protected String sessionKey;
    /** Not-null value. */
    protected String content;
    protected int msgType;
    protected int displayType;
    protected int status;
    protected int created;
    protected int updated;

    // KEEP FIELDS - put your custom fields here

    protected boolean isGIfEmo;
    // KEEP FIELDS END

    public MessageEntity() {
    }

    public MessageEntity(Long id) {
        this.id = id;
    }

    public MessageEntity(Long id, int msgId, int fromId, int toId, String sessionKey, String content, int msgType, int displayType, int status, int created, int updated) {
        this.id = id;
        this.msgId = msgId;
        this.fromId = fromId;
        this.toId = toId;
        this.sessionKey = sessionKey;
        this.content = content;
        this.msgType = msgType;
        this.displayType = displayType;
        this.status = status;
        this.created = created;
        this.updated = updated;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getMsgId() {
        return msgId;
    }

    public void setMsgId(int msgId) {
        this.msgId = msgId;
    }

    public int getFromId() {
        return fromId;
    }

    public void setFromId(int fromId) {
        this.fromId = fromId;
    }

    public int getToId() {
        return toId;
    }

    public void setToId(int toId) {
        this.toId = toId;
    }

    /** Not-null value. */
    public String getSessionKey() {
        return sessionKey;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    /** Not-null value. */
    public String getContent() {
        return content;
    }

    /** Not-null value; ensure this value is available before it is saved to the database. */
    public void setContent(String content) {
        this.content = content;
    }

    public int getMsgType() {
        return msgType;
    }

    public void setMsgType(int msgType) {
        this.msgType = msgType;
    }

    public int getDisplayType() {
        return displayType;
    }

    public void setDisplayType(int displayType) {
        this.displayType = displayType;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public int getCreated() {
        return created;
    }

    public void setCreated(int created) {
        this.created = created;
    }

    public int getUpdated() {
        return updated;
    }

    public void setUpdated(int updated) {
        this.updated = updated;
    }

    // KEEP METHODS - put your custom methods here
    /**
     * -----根据自身状态判断的---------
     */
    public int getSessionType() {
        switch (msgType) {
            case  DBConstant.MSG_TYPE_SINGLE_TEXT:
            case  DBConstant.MSG_TYPE_SINGLE_AUDIO:
                return DBConstant.SESSION_TYPE_SINGLE;
            case DBConstant.MSG_TYPE_GROUP_TEXT:
            case DBConstant.MSG_TYPE_GROUP_AUDIO:
                return DBConstant.SESSION_TYPE_GROUP;
            default:
                //todo 有问题
                return DBConstant.SESSION_TYPE_SINGLE;
        }
    }

    public String getMessageDisplay() {
        switch (displayType){
            case DBConstant.SHOW_AUDIO_TYPE:
                return DBConstant.DISPLAY_FOR_AUDIO;
            case DBConstant.SHOW_ORIGIN_TEXT_TYPE:
                return content;
            case DBConstant.SHOW_IMAGE_TYPE:
                return DBConstant.DISPLAY_FOR_IMAGE;
            case DBConstant.SHOW_MIX_TEXT:
                return DBConstant.DISPLAY_FOR_MIX;
            default:
                return DBConstant.DISPLAY_FOR_ERROR;
        }
    }

    @Override
    public String toString() {
        return "MessageEntity{" +
                "id=" + id +
                ", msgId=" + msgId +
                ", fromId=" + fromId +
                ", toId=" + toId +
                ", content='" + content + '\'' +
                ", msgType=" + msgType +
                ", displayType=" + displayType +
                ", status=" + status +
                ", created=" + created +
                ", updated=" + updated +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof MessageEntity)) return false;

        MessageEntity that = (MessageEntity) o;

        if (created != that.created) return false;
        if (displayType != that.displayType) return false;
        if (fromId != that.fromId) return false;
        if (msgId != that.msgId) return false;
        if (msgType != that.msgType) return false;
        if (status != that.status) return false;
        if (toId != that.toId) return false;
        if (updated != that.updated) return false;
        if (!content.equals(that.content)) return false;
        if (!id.equals(that.id)) return false;
        if (!sessionKey.equals(that.sessionKey)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id.hashCode();
        result = 31 * result + msgId;
        result = 31 * result + fromId;
        result = 31 * result + toId;
        result = 31 * result + sessionKey.hashCode();
        result = 31 * result + content.hashCode();
        result = 31 * result + msgType;
        result = 31 * result + displayType;
        result = 31 * result + status;
        result = 31 * result + created;
        result = 31 * result + updated;
        return result;
    }

    /**
     * 获取会话的sessionId
     * @param isSend
     * @return
     */
    public int getPeerId(boolean isSend){
        if(isSend){
            /**自己发出去的*/
            return toId;
        }else{
            /**接受到的*/
            switch (getSessionType()){
                case DBConstant.SESSION_TYPE_SINGLE:
                    return fromId;
                case DBConstant.SESSION_TYPE_GROUP:
                    return toId;
                default:
                    return toId;
            }
        }
    }

    public byte[] getSendContent(){
        return null;
    }

    public boolean isGIfEmo() {
        return isGIfEmo;
    }

    public void setGIfEmo(boolean isGIfEmo) {
        this.isGIfEmo = isGIfEmo;
    }

    public boolean isSend(int loginId){
        boolean isSend = (loginId==fromId)?true:false;
        return isSend;
    }

    public String buildSessionKey(boolean isSend){
        int sessionType = getSessionType();
        int peerId = getPeerId(isSend);
        sessionKey = EntityChangeEngine.getSessionKey(peerId,sessionType);
        return sessionKey;
    }
    // KEEP METHODS END

}


text: /* TODO : the required functions if the compiler does not have variadic macros */


text:
typedef enum : NSUInteger {
    AnimationTypePresent,
    AnimationTypeDismiss,
} AnimationType;

@interface PDTransitionAnimator : NSObject<UIViewControllerAnimatedTransitioning>
@property (nonatomic, assign) AnimationType animationType;
@end