text:
//-----------------------------------------------------------------------
// <copyright file="NFBehaviour.cs">
//     Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFActor>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.ObjectModel;

namespace NFrame
{
    public class NFILogicModule : NFBehaviour
    {
        public NFIPluginManager GetMng()
        {
            return mxMng;
        }
        public void SetMng(NFIPluginManager xMng)
        {
            mxMng = xMng;
        }
        private NFIPluginManager mxMng;
    }
}


text:
#include<gtest/gtest.h>

#include<ramen/math/line.hpp>

using namespace ramen::math;

TEST( Line, All)
{
}

int main( int argc, char **argv)
{
    ::testing::InitGoogleTest( &argc, argv);
    return RUN_ALL_TESTS();
}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Collybia pseudopura Dennis

### Remarks
null


text:
package org.snf4j.core.codec.bytes;

import java.nio.ByteBuffer;
import java.util.List;

import org.snf4j.core.IByteBufferHolder;
import org.snf4j.core.SingleByteBufferHolder;
import org.snf4j.core.codec.IDecoder;
import org.snf4j.core.session.ISession;

/**
 * A decoder transforming an array of bytes into a {@link IByteBufferHolder}.
 *
 * @author SNF4J.ORG
 */
public class ArrayToBufferHolderDecoder extends ArrayToBufferHolderCodec implements IDecoder<byte[], IByteBufferHolder> {

	private final boolean allocate;

	/**
	 * Constructs a decoder with a specified allocation mode.
	 *
	 * @param allocate the allocation mode determining if the buffer in the output
	 *                 buffer holder should be allocated by the session's allocator
	 *                 or the buffer should wrap the input array.
	 */
	public ArrayToBufferHolderDecoder(boolean allocate) {
		this.allocate = allocate;
	}

	/**
	 * Constructs a decoder with no buffer allocation (only by wrapping the input array)
	 */
	public ArrayToBufferHolderDecoder() {
		allocate = false;
	}

	@Override
	public void decode(ISession session, byte[] data, List<IByteBufferHolder> out) throws Exception {
		if (allocate) {
			ByteBuffer b = session.allocate(data.length);

			b.put(data).flip();
			out.add(new SingleByteBufferHolder(b));
		}
		else {
			out.add(new SingleByteBufferHolder(ByteBuffer.wrap(data)));
		}
	}

}


text:
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives
import os
import re
from hashlib import sha1

import sphinx
from sphinx.builders import Builder

# note: Really a workaround for some internal Sphinx changes.
#       See VisualDirective.name_source_snippet for details
if sphinx.version_info < (1, 5, 0):
    from sphinx.ext.autodoc import AutodocReporter as ReporterInQuestion
else:
    from sphinx.util.docutils import LoggingReporter as ReporterInQuestion

try:
    from gen_example import render_snippet
except ImportError as error:
    render_snippet = None
    print (
        "Could not import snippet renderer. "
        "Will use static resources. Import error: %s" %
        error
    )

VISUAL_EXAMPLES_DIR = "visual_examples"

# todo: maybe should be more generic from sphinx conf
SOURCE_DIR = os.path.join(os.path.dirname(__file__))

def flag(argument):
    """Reimplement directives.flag to return True instead of None
    Check for a valid flag option (no argument) and return ``None``.
    (Directive option conversion function.)

    Raise ``ValueError`` if an argument is found.
    """
    if argument and argument.strip():
        raise ValueError('no argument is allowed; "%s" supplied' % argument)
    else:
        return True

def nonnegative_int_list(argument):
    if ',' in argument:
        entries = argument.split(',')
    else:
        entries = argument.split()
    return [directives.nonnegative_int(entry) for entry in entries]

def click_list(argument):
    value = nonnegative_int_list(argument)

    if len(value) != 2:
        ValueError("argument must contain 3 non-negative values")

    return value

class WrapsDirective(Directive):
    has_content = True

    def run(self):
        head = nodes.paragraph()
        head.append(nodes.inline("Wraps API:", "Wraps API: "))

        source = '\n'.join(self.content.data)
        literal_node = nodes.literal_block(source, source)
        literal_node['laguage'] = 'C++'

        return [head, literal_node]

class VisualDirective(Directive):
    has_content = True

    final_argument_whitespace = True
    option_spec = {
        'title': directives.unchanged,
        'introduction': directives.unchanged,
        'inter': directives.unchanged,

        'width': directives.positive_int,
        'height': directives.positive_int,
        'auto_layout': flag,
        'click': click_list,

    }

    def run(self):
        source = '\n'.join(self.content.data)
        literal = nodes.literal_block(source, source)
        literal['visualnodetype'] = True
        literal['language'] = 'python'

        # docutils document model is insane!
        head1 = nodes.paragraph()

        introduction = self.options.pop('introduction', "Example:")
        head1.append(nodes.inline(introduction, introduction))

        inter = self.options.pop('inter', "Outputs:")
        head2 = nodes.paragraph()
        head2.append(
            nodes.section("foo", nodes.inline(inter, inter))
        )

        directive_nodes = [
            head1,
            literal,
            head2,
            self.get_image_node(source)
        ]

        return directive_nodes

    def name_source_snippet(self, source):
        env = self.state.document.settings.env

        if (
            # note: This is series of hacks due to internal Sphinx changes
            #       In Sphinx==1.4.8 it was enough to check against
            #       AutodocReporter. Now it become really complicated.
            #       We should redo this in future if we will have more
            #       similar problems
            isinstance(self.state.reporter, ReporterInQuestion) and
            self.state.parent and self.state.parent.parent and
            self.state.parent.parent.children[0]['names']
        ):
            # If it is generated by autodoc then autogenerate title from
            # the function/method/class signature
            # note: hacky assumption that this is a signature node
            signature_node = self.state.parent.parent.children[0]
            signature = signature_node['names'][0]
            occurence = env.new_serialno(signature)

            name = signature + '_' + str(occurence)
        else:
            # If we could not quess then use explicit title or hexdigest
            name = self.options.get('title', sha1(source.encode()).hexdigest())

        return self.phrase_to_filename(name)

    def phrase_to_filename(self, phrase):
        """Convert phrase to normilized file name."""
        # remove non-word characters
        name = re.sub(r"[^\w\s\.]", '', phrase.strip().lower())
        # replace whitespace with underscores
        name = re.sub(r"\s+", '_', name)

        return name + '.png'

    def get_image_node(self, source):
        file_name = self.name_source_snippet(source)
        file_path = os.path.join(VISUAL_EXAMPLES_DIR, file_name)

        env = self.state.document.settings.env

        if all([
            render_snippet,
            env.config['render_examples'],
            not os.environ.get('SPHINX_DISABLE_RENDER', False),
        ]):
            try:
                render_snippet(
                    source, file_path,
                    output_dir=SOURCE_DIR, **self.options
                )
            except:
                print("problematic code:\n%s" % source)
                raise

        img = nodes.image()
        img['uri'] = "/" + file_path
        return img

class VisualBuilder(Builder):
    """
    Collects visual examples in the documentation for testing purpose.
    """
    name = 'vistest'

    def get_outdated_docs(self):
        return self.env.found_docs

    def write(self, build_docnames, updated_docnames, method='update'):
        # todo: monkey patching, rewrite
        self.snippets = []

        if build_docnames is None:
            build_docnames = sorted(self.env.all_docs)

        for docname in build_docnames:
            # no need to resolve the doctree
            doctree = self.env.get_doctree(docname)
            self.snippets.extend(self.collect_doc(docname, doctree))

    @staticmethod
    def traverse_condition(node):
        return isinstance(
            node, nodes.literal_block
        ) and 'visualnodetype' in node

    def collect_doc(self, docname, doctree):
        return [
            (node.source, node.astext())
            for node in doctree.traverse(self.traverse_condition)
        ]

def setup(app):
    app.add_config_value('render_examples', False, 'html')
    app.add_directive('wraps', WrapsDirective)
    app.add_directive('visual-example', VisualDirective)
    app.add_builder(VisualBuilder)

    return {'version': '0.1'}


text:
#ifndef __DrakeCollisionModel_H__
#define __DrakeCollisionModel_H__

#include <memory>
#include <unordered_map>

#include <Eigen/Dense>
#include <Eigen/StdVector>

#include "Element.h"
#include "PointPair.h"
#include "drake/drakeCollision_export.h"

namespace DrakeCollision {
typedef std::pair<ElementId, ElementId> ElementIdPair;

class DRAKECOLLISION_EXPORT Model {
 public:
  Model() {}

  virtual ~Model(){};

  /** \brief Add a collision element to this model.
  * \param element the collision element to be added to this model
  * \return an ElementId that uniquely identifies the added element within
  * this model
  */
  virtual ElementId addElement(const Element& element);

  bool removeElement(const ElementId& id);

  /** \brief Get a read-only pointer to a collision element in this model.
   * \param id an ElementId corresponding to the desired collision element
   * \return a read-only pointer to the collision element corresponding to
   * the given id or nullptr if no such collision element is present in the
   * model.
   */
  virtual const Element* readElement(ElementId id);

  virtual void getTerrainContactPoints(ElementId id0,
                                       Eigen::Matrix3Xd& terrain_points);

  /** \brief Perform any operations needed to bring the model up-to-date
   * after making changes to its collision elements
   */
  virtual void updateModel(){};

  /** \brief Change the element-to-world transform of a specified collision
   * element.
   * \param id an ElementId corresponding to the element to be updated
   * \param T_local_to_world the new value for the element-to-world
   * transform
   */
  virtual bool updateElementWorldTransform(
      const ElementId id, const Eigen::Isometry3d& T_local_to_world);

  /** \brief Compute the points of closest approach between all eligible
   * pairs of collision elements drawn from a specified set of elements
   * \param ids_to_check the vector of ElementId for which the all-to-all
   * collision detection should be performed
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \param[out] closest_points reference to a vector of PointPair objects
   * that contains the closest point information after this method is
   * called
   * \return true if this method ran successfully
   */
  virtual bool closestPointsAllToAll(const std::vector<ElementId>& ids_to_check,
                                     const bool use_margins,
                                     std::vector<PointPair>& closest_points) {
    return false;
  };

  /** \brief Compute the points of closest approach between all eligible
   * pairs of collision elements in this model
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \param[out] closest_points reference to a vector of PointPair objects
   * that contains the closest point information after this method is
   * called
   * \return true if this method ran successfully
   */
  virtual bool collisionPointsAllToAll(const bool use_margins,
                                       std::vector<PointPair>& points) {
    return false;
  };

  /** \brief Compute the points of closest approach between specified pairs
   * of collision elements
   * \param id_pairs vector of ElementIdPair specifying which pairs of
   * elements to consider
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \param[out] closest_points reference to a vector of PointPair objects
   * that contains the closest point information after this method is
   * called
   * \return true if this method ran successfully
   */
  virtual bool closestPointsPairwise(const std::vector<ElementIdPair>& id_pairs,
                                     const bool use_margins,
                                     std::vector<PointPair>& closest_points) {
    return false;
  };

  /** \brief Compute closest distance from each point to any surface in the
   * collision model utilizing Bullet's collision detection code.
   * \param points Matrix of points computing distance from.
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \param[out] closest_points a vector of PointPair objects containing
   * the signed distances
   */
  virtual void collisionDetectFromPoints(
      const Eigen::Matrix3Xd& points, bool use_margins,
      std::vector<PointPair>& closest_points){};

  /** \brief Compute the set of potential collision points for all
   * eligible pairs of collision geometries in this model. This includes
   * the points of closest approach, but may also include additional points
   * that are "close" to being in contact. This can be useful when
   * simulating scenarios in which two collision elements have more than
   * one point of contact.
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \return a vector of PointPair objects containing the potential
   * collision points
   */
  virtual std::vector<PointPair> potentialCollisionPoints(
      const bool use_margins) {
    return std::vector<PointPair>();
  };

  /** \brief Given a vector of points in world coordinates, returns the
   * indices of those points within a specified distance of any collision
   * geometry in the model.
   * \param points a vector of points in world coordinates
   * \param collision_threshold points are considered "in collision" if
   * they lie within this distance of any collision geometry
   * \return a vector containing the indices of those points that are "in
   * collision" with the model.
   */
  virtual std::vector<size_t> collidingPoints(
      const std::vector<Eigen::Vector3d>& points, double collision_threshold) {
    return std::vector<size_t>();
  };

  /** \brief Returns true if any of the given points are within a specified
   * distance of the collision geometries in this model.
   * \param points a vector of points in world coordinates
   * \param collision_threshold points are considered "in collision" if
   * they lie within this distance of any collision geometry
   * \return a boolean value indicating if any points are "in collision"
   */
  virtual bool collidingPointsCheckOnly(
      const std::vector<Eigen::Vector3d>& points, double collision_threshold) {
    return false;
  };

  /** Performs raycasting collision detecting (like a LIDAR / laser rangefinder)
   *
   * \param origin 3 x N matrix in which each column specifies the position
   * of a ray's origin in world coordinates.  if origin is 3x1, then the same
   *origin is used for all raycasts
   * \param ray_endpoint 3 x N matrix in which each column specifies a
   * second point on the corresponding ray
   * \param use_margins flag indicating whether or not to use the version
   * of this model with collision margins
   * \param[out] distance to the first collision, or -1 on no collision
   * \return true if this method ran successfully
   */
  virtual bool collisionRaycast(const Eigen::Matrix3Xd& origin,
                                const Eigen::Matrix3Xd& ray_endpoint,
                                bool use_margins, Eigen::VectorXd& distances,
                                Eigen::Matrix3Xd& normals) {
    return false;
  };

 protected:
  std::unordered_map<ElementId, std::unique_ptr<Element> > elements;

 private:
  Model(const Model&) {}
  Model& operator=(const Model&) { return *this; }
};
}

#endif


text:
package com.dianping.example.activityloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.GetChars;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import dalvik.system.DexClassLoader;

public class ActivityLoader extends ListActivity {
    private static final String tag = ActivityLoader.class.getSimpleName();
    private List<Map<String, String>> data = new ArrayList<Map<String, String>>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addItem("[ Launch SampleActivity ]", null);
        addItem("[ Default.apk ]", null);
        try {
            AssetManager asset = getAssets();
            for (String s : asset.list("apks")) {
                addItem(s, "apks/" + s);
            }
        } catch (Exception e) {
        }

        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_1,
                new String[] { "title" }, new int[] { android.R.id.text1 });
        setListAdapter(adapter);
    }

    private void addItem(String title, String path) {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title", title);
        map.put("path", path);
        data.add(map);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        if (position == 0) {
            Intent i = new Intent("com.dianping.intent.action.SAMPLE_ACTIVITY");
            startActivity(i);
            return;
        }
        if (position == 1) {
            MyApplication.CUSTOM_LOADER = null;
            return;
        }
        Map<String, String> item = data.get(position);
        String title = item.get("title");
        String path = item.get("path");

        try {
            File file_dex = copyAsset2Dir(title, path);

            File file_outdex = getDir("outdex", Context.MODE_PRIVATE);
            Log.e(tag," optimized dex path:"+ file_outdex.getAbsolutePath());
            file_outdex.mkdir();
            DexClassLoader dcl = new DexClassLoader(file_dex.getAbsolutePath(), file_outdex.getAbsolutePath(), null,
                    MyApplication.ORIGINAL_LOADER.getParent());
            MyApplication.CUSTOM_LOADER = dcl;

            Toast.makeText(this, title + " loaded, try launch again", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "Unable to load " + title, Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            MyApplication.CUSTOM_LOADER = null;
        }
    }

    private File copyAsset2Dir(String file_title, String file_path) throws IOException, FileNotFoundException {
        File dex = getDir("dex", Context.MODE_PRIVATE);
        dex.mkdir();
        File file_dex = new File(dex, file_title);
        Log.e(tag, "path:"+file_path+"copy to:"+file_dex.getAbsolutePath());
        InputStream fis = getAssets().open(file_path);
        FileOutputStream fos = new FileOutputStream(file_dex);
        byte[] buffer = new byte[0xFF];
        int len;
        while ((len = fis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fis.close();
        fos.close();
        return file_dex;
    }
}


text:
//Problem 1. JavaScript literals
//Assign all the possible JavaScript literals to different variables.
//Maybe I will miss something so, please be good :D

var int = 12345;
var float = 12.345;
var arrayNumbers = [1, 2, 3, 4.5];
var string = 'string';
var object = {age: 100, name: 'bai gosho'};
var func = function () { return; }; //That one looks like delegate to me, i've seen it on other homework
var nullValue = null;
var undefinedValue = undefined;
var boolean = true; //if the cup is half empty for u, maybe u want to se the value false?


text:
// App.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include <exdisp.h>
#include <comdef.h>
#include <string>
#include "WinSys.h"
#include <shellapi.h>
#include "Util.h"
#include "MDbgHelper.h"
#include <shellapi.h>
#include <CommDlg.h>
#include "PyException.h"

#ifdef _DEBUG
#undef _DEBUG
#include <Python.h>
#define _DEBUG
#else
#include <Python.h>
#endif

#include<boost/python.hpp>
#include "PyFrameCreator.hpp"
#include "PyModuleImport.h"
using namespace boost::python;

extern "C" void SwitchToOtherPythonTread()
{
	static boost::python::handle<>* _module = NULL; // Module handle.
	try
	{
		if (!_module)
		{
			_module = new boost::python::handle<>(
				PyImport_ImportModule("PyFrameBase"));
		}
		bool ret = boost::python::call_method<bool>(_module->get(), "GiveUp");
	}
	catch(boost::python::error_already_set const &)
	{
		std::string err = parse_python_exception();
		PyLog().LogText(err.c_str());
		PyErr_Clear();
	}
	catch (...)
	{
		if (PyErr_Occurred())
		{
			std::string err = parse_python_exception();
			PyLog().LogText(err.c_str());
			PyErr_Clear();
		}
	}
}

#ifndef XN_PYTHON_EXTEND

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nCmdShow)
{
	CMDbgHelper::Instance()->SetFilter(MiniDumpWithHandleData | MiniDumpFilterModulePaths | MiniDumpWithThreadInfo);

    CPaintManagerUI::SetInstance(hInstance);
    //CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T("skin"));

    HRESULT Hr = ::CoInitialize(NULL);
    if( FAILED(Hr) )
        return 0;

	// ³õ'»¯python
	Py_Initialize();

	PyEval_InitThreads();

	// ½«µ±Ç°Ä¿Â¼¼ÓÈëpython»·¾³±äÁ¿
	CString pathA = GetExeFolder();
	//pathA.Replace('\\', '/');
	try
	{
/*		PyRun_SimpleString("import sys");
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27')    \n").c_str());
		PyRun_SimpleString((std::string("if not '") + (LPCSTR)pathA + "\\DLLs' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\DLLs')    \n").c_str()
			);
		PyRun_SimpleString("import sys");
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27')    \n").c_str());
		PyRun_SimpleString(
			"import pywintypes    \n"
			"    pywintypes.__import_pywin32_system_module__(\"pythoncom\", globals())         \n"
			);

		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32')    \n").c_str());
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32com' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32com')    \n").c_str());
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32comext' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32comext')    \n").c_str());
*/
		//PyRun_SimpleString((std::string("if not '") + (LPCSTR)pathA + "\\DLLs' in sys.path: \n"
		//	"    sys.path.append('" + (LPCSTR)pathA + "\\DLLs')    \n").c_str()
		//	);
	}
	catch(boost::python::error_already_set const &)
	{
		std::string err = parse_python_exception();
		PyLog().LogText(err.c_str());
		PyErr_Clear();
	}
	catch (...)
	{
		if (PyErr_Occurred())
		{
			std::string err = parse_python_exception();
			PyLog().LogText(err.c_str());
			PyErr_Clear();
		}
	}

	// ×¢²áPyÄ£¿é
	PyExtentInit();

	// µ÷ÓÃPyMainÄ£¿éµÄPyAppInit, ¸Ãº¯ÊýÊdzÌÐòÈë¿Ú
	boost::python::handle<>* _module = NULL; // Module handle.
	try
	{
		_module = new boost::python::handle<>(
			PyImport_ImportModule("PyMain"));
		bool ret = boost::python::call_method<bool>(_module->get(), "PyAppInit");
		//CPaintManagerUI::MessageLoop();
	}
	catch(boost::python::error_already_set const &)
	{
		std::string err = parse_python_exception();
		PyLog().LogText(err.c_str());
		PyErr_Clear();
	}
	catch (...)
	{
		if (PyErr_Occurred())
		{
			std::string err = parse_python_exception();
			PyLog().LogText(err.c_str());
			PyErr_Clear();
		}
	}

	if (_module)
		delete _module;

	// Boost.Python doesn't support Py_Finalize yet, so don't call it!

    ::CoUninitialize();
    return 0;
}

#else

HINSTANCE g_hInstance;

static int RunDui(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nCmdShow)
{
	CMDbgHelper::Instance()->SetFilter(MiniDumpWithHandleData | MiniDumpFilterModulePaths | MiniDumpWithThreadInfo);

	CPaintManagerUI::SetInstance(hInstance);
	//CPaintManagerUI::SetResourcePath(CPaintManagerUI::GetInstancePath() + _T("skin"));

	HRESULT Hr = ::CoInitialize(NULL);
	if( FAILED(Hr) )
		return 0;

	// ³õ'»¯python
	Py_Initialize();

	// ½«µ±Ç°Ä¿Â¼¼ÓÈëpython»·¾³±äÁ¿
	CString pathA = GetExeFolder();
	//pathA.Replace('\\', '/');
	try
	{
/*
		PyRun_SimpleString("import sys");
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27')    \n").c_str());
		PyRun_SimpleString((std::string("if not '") + (LPCSTR)pathA + "\\DLLs' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\DLLs')    \n").c_str()
			);
		PyRun_SimpleString("import sys");
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27')    \n").c_str());
		PyRun_SimpleString(
			"import pywintypes    \n"
			"    pywintypes.__import_pywin32_system_module__(\"pythoncom\", globals())         \n"
			);

		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32')    \n").c_str());
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32com' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32com')    \n").c_str());
		PyRun_SimpleString(
			(std::string("if not '") + (LPCSTR)pathA + "\\Python27\\win32comext' in sys.path: \n"
			"    sys.path.append('" + (LPCSTR)pathA + "\\Python27\\win32comext')    \n").c_str());
*/
		//PyRun_SimpleString((std::string("if not '") + (LPCSTR)pathA + "\\DLLs' in sys.path: \n"
		//	"    sys.path.append('" + (LPCSTR)pathA + "\\DLLs')    \n").c_str()
		//	);
	}
	catch(boost::python::error_already_set const &)
	{
		std::string err = parse_python_exception();
		PyLog().LogText(err.c_str());
		PyErr_Clear();
	}
	catch (...)
	{
		if (PyErr_Occurred())
		{
			std::string err = parse_python_exception();
			PyLog().LogText(err.c_str());
			PyErr_Clear();
		}
	}

	// ×¢²áPyÄ£¿é
	PyExtentInit();

	// µ÷ÓÃPyMainÄ£¿éµÄPyAppInit, ¸Ãº¯ÊýÊdzÌÐòÈë¿Ú
	boost::python::handle<>* _module = NULL; // Module handle.
	try
	{
		_module = new boost::python::handle<>(
			PyImport_ImportModule("PyMain"));
		bool ret = boost::python::call_method<bool>(_module->get(), "PyAppInit");
		//CPaintManagerUI::MessageLoop();
	}
	catch(boost::python::error_already_set const &)
	{
		std::string err = parse_python_exception();
		PyLog().LogText(err.c_str());
		PyErr_Clear();
	}
	catch (...)
	{
		if (PyErr_Occurred())
		{
			std::string err = parse_python_exception();
			PyLog().LogText(err.c_str());
			PyErr_Clear();
		}
	}

	if (_module)
		delete _module;

	// Boost.Python doesn't support Py_Finalize yet, so don't call it!

	::CoUninitialize();
	return 0;
}

static PyObject* Run(PyObject* self, PyObject* args)
{
	RunDui(g_hInstance, NULL, NULL, 0);
	return Py_None;
}

BOOL APIENTRY DllMain( HMODULE hModule,
					  DWORD  ul_reason_for_call,
					  LPVOID lpReserved
					  )
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
		{
			g_hInstance = (HINSTANCE)hModule;
			break;
		}
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}

static PyMethodDef DuiMethods[]=
{
	{"Run",Run,METH_VARARGS, "run dui"},
	{NULL,NULL,0,NULL}
};

PyMODINIT_FUNC
init_PyDui4Win(void) {
	(void) Py_InitModule("_PyDui4Win",DuiMethods);
}

#endif


text:
#ifndef GrInOrderDrawBuffer_DEFINED
#define GrInOrderDrawBuffer_DEFINED

#include "GrDrawTarget.h"
#include "GrAllocPool.h"
#include "GrAllocator.h"
#include "GrPath.h"

#include "SkClipStack.h"
#include "SkStrokeRec.h"
#include "SkTemplates.h"

class GrGpu;
class GrIndexBufferAllocPool;
class GrVertexBufferAllocPool;

/**
 * GrInOrderDrawBuffer is an implementation of GrDrawTarget that queues up draws for eventual
 * playback into a GrGpu. In theory one draw buffer could playback into another. When index or
 * vertex buffers are used as geometry sources it is the callers the draw buffer only holds
 * references to the buffers. It is the callers responsibility to ensure that the data is still
 * valid when the draw buffer is played back into a GrGpu. Similarly, it is the caller's
 * responsibility to ensure that all referenced textures, buffers, and render-targets are associated
 * in the GrGpu object that the buffer is played back into. The buffer requires VB and IB pools to
 * store geometry.
 */
class GrInOrderDrawBuffer : public GrDrawTarget {
public:

    /**
     * Creates a GrInOrderDrawBuffer
     *
     * @param gpu        the gpu object where this will be played back
     *                   (possible indirectly). GrResources used with the draw
     *                   buffer are created by this gpu object.
     * @param vertexPool pool where vertices for queued draws will be saved when
     *                   the vertex source is either reserved or array.
     * @param indexPool  pool where indices for queued draws will be saved when
     *                   the index source is either reserved or array.
     */
    GrInOrderDrawBuffer(const GrGpu* gpu,
                        GrVertexBufferAllocPool* vertexPool,
                        GrIndexBufferAllocPool* indexPool);

    virtual ~GrInOrderDrawBuffer();

    /**
     * Empties the draw buffer of any queued up draws. This must not be called while inside an
     * unbalanced pushGeometrySource(). The current draw state and clip are preserved.
     */
    void reset();

    /**
     * This plays the queued up draws to another target. It also resets this object (i.e. flushing
     * is destructive). This buffer must not have an active reserved vertex or index source. Any
     * reserved geometry on the target will be finalized because it's geometry source will be pushed
     * before flushing and popped afterwards.
     *
     * @return false if the playback trivially drew nothing because nothing was recorded.
     *
     * @param target    the target to receive the playback
     */
    bool flushTo(GrDrawTarget* target);

    /**
     * This function allows the draw buffer to automatically flush itself to another target. This
     * means the buffer may internally call this->flushTo(target) when it is safe to do so.
     *
     * When the auto flush target is set to NULL (as it initially is) the draw buffer will never
     * automatically flush itself.
     */
    void setAutoFlushTarget(GrDrawTarget* target);

    // overrides from GrDrawTarget
    virtual bool geometryHints(size_t vertexSize,
                               int* vertexCount,
                               int* indexCount) const SK_OVERRIDE;
    virtual void clear(const GrIRect* rect,
                       GrColor color,
                       GrRenderTarget* renderTarget = NULL) SK_OVERRIDE;
    virtual void drawRect(const GrRect& rect,
                          const SkMatrix* matrix,
                          const GrRect* srcRects[],
                          const SkMatrix* srcMatrices[]) SK_OVERRIDE;

protected:
    virtual void clipWillBeSet(const GrClipData* newClip) SK_OVERRIDE;

private:
    enum Cmd {
        kDraw_Cmd           = 1,
        kStencilPath_Cmd    = 2,
        kSetState_Cmd       = 3,
        kSetClip_Cmd        = 4,
        kClear_Cmd          = 5,
    };

    class DrawRecord : public DrawInfo {
    public:
        DrawRecord(const DrawInfo& info) : DrawInfo(info) {}
        GrVertexLayout          fVertexLayout;
        const GrVertexBuffer*   fVertexBuffer;
        const GrIndexBuffer*    fIndexBuffer;
    };

    struct StencilPath {
        StencilPath();

        SkAutoTUnref<const GrPath>  fPath;
        SkStrokeRec                 fStroke;
        SkPath::FillType            fFill;
    };

    struct Clear {
        Clear() : fRenderTarget(NULL) {}
        ~Clear() { GrSafeUnref(fRenderTarget); }

        GrIRect         fRect;
        GrColor         fColor;
        GrRenderTarget* fRenderTarget;
    };

    // overrides from GrDrawTarget
    virtual void onDraw(const DrawInfo&) SK_OVERRIDE;
    virtual void onStencilPath(const GrPath*, const SkStrokeRec& stroke, SkPath::FillType) SK_OVERRIDE;
    virtual bool onReserveVertexSpace(size_t vertexSize,
                                      int vertexCount,
                                      void** vertices) SK_OVERRIDE;
    virtual bool onReserveIndexSpace(int indexCount,
                                     void** indices) SK_OVERRIDE;
    virtual void releaseReservedVertexSpace() SK_OVERRIDE;
    virtual void releaseReservedIndexSpace() SK_OVERRIDE;
    virtual void onSetVertexSourceToArray(const void* vertexArray,
                                          int vertexCount) SK_OVERRIDE;
    virtual void onSetIndexSourceToArray(const void* indexArray,
                                         int indexCount) SK_OVERRIDE;
    virtual void releaseVertexArray() SK_OVERRIDE;
    virtual void releaseIndexArray() SK_OVERRIDE;
    virtual void geometrySourceWillPush() SK_OVERRIDE;
    virtual void geometrySourceWillPop(const GeometrySrcState& restoredState) SK_OVERRIDE;
    virtual void willReserveVertexAndIndexSpace(size_t vertexSize,
                                                int vertexCount,
                                                int indexCount) SK_OVERRIDE;
    bool quickInsideClip(const SkRect& devBounds);

    // Attempts to concat instances from info onto the previous draw. info must represent an
    // instanced draw. The caller must have already recorded a new draw state and clip if necessary.
    int concatInstancedDraw(const DrawInfo& info);

    // we lazily record state and clip changes in order to skip clips and states that have no
    // effect.
    bool needsNewState() const;
    bool needsNewClip() const;

    // these functions record a command
    void            recordState();
    void            recordClip();
    DrawRecord*     recordDraw(const DrawInfo&);
    StencilPath*    recordStencilPath();
    Clear*          recordClear();

    enum {
        kCmdPreallocCnt          = 32,
        kDrawPreallocCnt         = 8,
        kStencilPathPreallocCnt  = 8,
        kStatePreallocCnt        = 8,
        kClipPreallocCnt         = 8,
        kClearPreallocCnt        = 4,
        kGeoPoolStatePreAllocCnt = 4,
    };

    SkAutoTUnref<const GrGpu> fGpu;

    SkSTArray<kCmdPreallocCnt, uint8_t, true>                          fCmds;
    GrSTAllocator<kDrawPreallocCnt, DrawRecord>                        fDraws;
    GrSTAllocator<kStatePreallocCnt, StencilPath>                      fStencilPaths;
    GrSTAllocator<kStatePreallocCnt, GrDrawState::DeferredState>       fStates;
    GrSTAllocator<kClearPreallocCnt, Clear>                            fClears;

    GrSTAllocator<kClipPreallocCnt, SkClipStack>        fClips;
    GrSTAllocator<kClipPreallocCnt, SkIPoint>           fClipOrigins;

    GrDrawTarget*                   fAutoFlushTarget;

    bool                            fClipSet;

    enum ClipProxyState {
        kUnknown_ClipProxyState,
        kValid_ClipProxyState,
        kInvalid_ClipProxyState
    };
    ClipProxyState                  fClipProxyState;
    SkRect                          fClipProxy;

    GrVertexBufferAllocPool&        fVertexPool;

    GrIndexBufferAllocPool&         fIndexPool;

    struct GeometryPoolState {
        const GrVertexBuffer*           fPoolVertexBuffer;
        int                             fPoolStartVertex;
        const GrIndexBuffer*            fPoolIndexBuffer;
        int                             fPoolStartIndex;
        // caller may conservatively over reserve vertices / indices.
        // we release unused space back to allocator if possible
        // can only do this if there isn't an intervening pushGeometrySource()
        size_t                          fUsedPoolVertexBytes;
        size_t                          fUsedPoolIndexBytes;
    };
    SkSTArray<kGeoPoolStatePreAllocCnt, GeometryPoolState> fGeoPoolStateStack;

    bool                            fFlushing;

    typedef GrDrawTarget INHERITED;
};

#endif


text:
"""Classify roads."""
from __future__ import print_function

import tensorflow as tf
import numpy as np

import glob
import cv2
import argparse

PARSER = argparse.ArgumentParser()
PARSER.add_argument('iterations', type=int, help='Number of iterations')
ARGS = PARSER.parse_args()

g = {} # globals

# Helper functions
def weight_variable(shape):
    """Creates weight tensor."""
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    """Creates bias tensor."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

def conv2d(x, weight):
    """Creates conv tensor."""
    return tf.nn.conv2d(x, weight, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    """Creates max pool tensor."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],
            padding='SAME')

def get_next_example(index):
    """Given index, returns next example."""

    image_filenames = glob.glob("./images/*.png")
    label_filenames = [e.replace("images", "labels") for e in image_filenames]

    #  if index in images.keys():
    if index in image_filenames:
        return g[index][0], g[index][1], len(image_filenames)

    real_index = index % len(image_filenames)

    image = np.reshape(cv2.imread(image_filenames[real_index]), [310*94*3])

    pre_label = cv2.imread(label_filenames[real_index])

    blue, green, red = (pre_label[:, :, 0], pre_label[:, :, 1],
            pre_label[:, :, 2])
    mask = (((red == 255) & (green == 0) & (blue == 0))
            | ((red == 255) & (green == 255) & (blue == 0)))

    label = np.zeros((pre_label.shape[0], pre_label.shape[1]), dtype=np.uint8)
    label[:, :][mask] = 255

    # This line turns on edge detection
    # label = cv2.Laplacian(label, -1)

    label = np.reshape(label, [78*24])

    g[index] = (image, label)

    return image, label, len(image_filenames)

def _create_main_graph(x_image):
    """Creates main graph."""
    # Define convolution layer 1 (32 features for each 10x10 patch)
    w_conv1 = weight_variable([10, 10, 3, 32])
    b_conv1 = bias_variable([32])

    h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)

    # Define convolution layer 2 (32 -> 64 features for each 10x10 patch)
    w_conv2 = weight_variable([10, 10, 32, 64])
    b_conv2 = bias_variable([64])

    h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)

    # Global Activation Pooling

    w_gap = weight_variable([1, 1, 64])
    #b_gap = bias_variable([1, 1, 64])

    h_pool2_rs = tf.reshape(h_pool2, [78, 24, 64])
    h_mul_gap = tf.mul(h_pool2_rs, w_gap)

    h_gap = tf.reduce_mean(h_mul_gap, 2)

    return h_gap

def create_graph(x, y_truth):
    """Creates graph."""
    # Reshape the input image
    x_image = tf.reshape(x, [-1, 310, 94, 3])

    h_gap = _create_main_graph(x_image)

    # Dropout
    keep_prob = tf.placeholder(tf.float32)
    h_gap_drop = tf.nn.dropout(h_gap, keep_prob)

    y_conv = tf.reshape(h_gap_drop, [78*24])

    # Loss
    loss = tf.sqrt(tf.reduce_mean(tf.square(tf.sub(y_truth, y_conv * 255))))

    return y_conv, loss, keep_prob

def main():
    """main method for roadClassify."""
    sess = tf.Session()

    # Placeholders
    x = tf.placeholder(tf.float32, [310*94*3])
    y_truth = tf.placeholder(tf.float32, [78*24])

    y_conv, loss, keep_prob = create_graph(x, y_truth)

    # Training parameters
    global_step = tf.Variable(1, name='global_step', trainable=False)
    train_step = tf.train.AdamOptimizer(1e-4).minimize(loss,
            global_step=global_step)
    correct_prediction = tf.equal(tf.round(y_conv) * 255, y_truth)
    accuracy = tf.reduce_mean(tf.to_float(correct_prediction))

    sess.run(tf.initialize_all_variables())

    saver = tf.train.Saver()

    #ckpt = tf.train.get_checkpoint_state("checkpoints/")
    #if ckpt and ckpt.model_checkpoint_path:
    #    saver.restore(sess, ckpt.model_checkpoint_path)
    saver.restore(sess, "final_weights.model")
    #    print "Model restored from latest checkpoint"
    #else:
    #    print "No checkpoints, runnning from scratch"

    for i in range(global_step.eval(session=sess),
            global_step.eval(session=sess)+ARGS.iterations):

        imgs, lbls, count = get_next_example(i % 3)

        print("step %d, loss %f, training accuracy %f"
                % (i,
                   sess.run(loss,
                       feed_dict={x: imgs, y_truth: lbls, keep_prob: 1.0}),
                   sess.run(accuracy,
                       feed_dict={x: imgs, y_truth: lbls, keep_prob: 1.0})))

        train_step.run(session=sess,
                feed_dict={x: imgs, y_truth: lbls, keep_prob: 1.0})

        if i % 100 == 0:
            saver.save(sess, "checkpoints/" + "model.ckpt",
                    global_step=global_step)

            imgs, lbls, count = get_next_example(0)
            cv2.imwrite("result.png", (
                (np.reshape(
                    sess.run(y_conv,
                        feed_dict={x: imgs, y_truth: lbls, keep_prob: 1.0}),
                    [24, 78])
                * 255) > 127) * 255)

            print("Loss: %f" % loss.eval(session=sess,
                feed_dict={x: imgs, y_truth: lbls, keep_prob: 1.0}))
            print("**** %d iterations/example ****" % (i / count))

    # uncomment if you want to save from trained model.
    #  if True:
        #  imgs, lbls, count = get_next_example(0) # 9 is fun
        #  result = sess.run(y_conv, feed_dict={x: imgs, y_truth: lbls,
            #  keep_prob: 1.0})
        #  result = ((np.reshape(result, [24, 78]) * 255) > 127) * 255

        #  fig = plt.figure()
        #  raw = fig.add_subplot(2, 1, 1)
        #  plt.imshow(np.reshape(imgs, [94, 310, 3]))
        #  raw.set_title("Raw Image")

        #  classified = fig.add_subplot(2, 1, 2)

        #  plt.imshow(result.astype(np.uint8), cmap='gray')
        #  classified.set_title("AgencyNet Output")
        #  plt.show()

        #  fig.savefig('composite.png')

if __name__ == '__main__': main()


text:
import * as React  from 'react';
import * as ReactDOM from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';

ReactDOM.render(
  <Router history={browserHistory} routes={routes} />,
  document.getElementById('app')
);


text:
class AddBodyTextColumnToComments < ActiveRecord::Migration
  def change
  	add_column :hubstats_comments, :body_text, :text
  end
end


text:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class MainHUDManager : MonoBehaviour
{
    /*--Properties of the class--*/

    // Intro HUD objects
    [Header("Intro HUD Objects"), SerializeField]
    private Text startText;

    // Main game HUD objects
    [Header("Main Game HUD Objects"), SerializeField]
    private Text mainScoreText;

    [SerializeField]
    private Text ballCountText;

    [SerializeField]
    private Text timeText;

    [SerializeField]
    private Text comboTitleText;

    [SerializeField]
    private Text comboBonusText;

    [SerializeField]
    private Text targetScoreText;

    // Pause menu HUD objects
    [Header("Pause Menu HUD Objects"), SerializeField]
    private Text currentScorePauseText;

    // Game over screen HUD objects
    [Header("Game Over HUD Objects"), SerializeField]
    private Text gameOverScoreText;

    [SerializeField]
    private Text gameOverScreenTitle;

    [SerializeField]
    private Text highestComboText;

    // HUD groups
    [Header("HUD Groups")]
    public GameObject introHUDGroup;
    public GameObject mainHUDGroup;
    public GameObject gameOverHUDGroup;
    public GameObject pauseHUDGroup;

    // HUD Animators
    [Header("HUD Animators")]
    public Animator gameOverPanelAnimator;
    public Animator pausePanelAnimator;

    public bool canShowGameOverPanel = true;

    /*-External References-*/
    GameManager gameManager;

    // Called before start
    public void Awake()
    {
        // Get the GameManager
        gameManager = FindObjectOfType<GameManager>();
    }

    // Use this for initialization
    void Start()
    {
        // Set all but the main HUD groups to be visible
        setHUDGroupVisibility(introHUDGroup, true);
        setHUDGroupVisibility(mainHUDGroup, false);
        setHUDGroupVisibility(gameOverHUDGroup, true);
        setHUDGroupVisibility(pauseHUDGroup, true);

        // Set the main score and ball count text content to 0
        setMainScoreTextContent("0");
        setBallCountContent("3");

        // Hide the combo text HUD objects
        setComboTextHUDContent(0, 0, false);

        // Set the content of the timeText HUD object
        setTimeTextContent(gameManager.timerMinutes, gameManager.timerSeconds);

        // Set the content of the target score text object
        targetScoreText.text = gameManager.getLevelTargetScore().ToString();
    }

    // Update is called once per frame
    void Update()
    {

    }

    // Set the visibility of HUD groups
    public void setHUDGroupVisibility(GameObject group, bool status)
    {
        group.SetActive(status);
    }

    /*--Main Game HUD Functions--*/

    // Set the content of the main score text object
    public void setMainScoreTextContent(string content)
    {
        mainScoreText.text = content;
    }

    // Set the content of the ball count text object
    public void setBallCountContent(string content)
    {
        ballCountText.text = content;
    }

    // Set the content of the timeText HUD object
    public void setTimeTextContent(int minute, int seconds)
    {
        // If the seconds given is greater than 9 then show the seconds whole number
        if (seconds > 9)
        {
            timeText.text = minute.ToString() + ":" + seconds.ToString();
        }

        // If the seconds given is less than 10 then add a "0" character before showing the seconds number
        if (seconds < 10)
        {
            timeText.text = minute.ToString() + ":0" + seconds.ToString();
        }
    }

    // Set the content of combo Text HUD objects
    public void setComboTextHUDContent(int comboSize, int comboBonus, bool visibilityStatus)
    {
        // If the HUD objects can be visible
        if (visibilityStatus == true)
        {
            // Set the content of the combo title object
            comboTitleText.text = comboSize.ToString() + "-Chain Combo";

            // Set the content of the combo bonus object
            comboBonusText.text = "+" + comboBonus.ToString();
        }

        // If the HUD objects cannot be visible then set the content to null
        if (visibilityStatus == false)
        {
            comboBonusText.text = "";
            comboTitleText.text = "";
        }
    }

    /*--Pause Menu HUD Functions--*/

    // Resume game wrapper
    public void resumeGameWrapper()
    {
        canShowGameOverPanel = true;
        gameManager.resumeGame();
    }

    // Set the content of the current score text object
    public void setCurrentScorePauseTextContent(string content)
    {
        currentScorePauseText.text = content;
    }

    /*--Game Over Screen HUD Functions--*/

    // Set the title for the game over screen
    public void setGameOverScreenTitle(string content)
    {
        gameOverScreenTitle.text = content;
    }

    // Set the content of the game over screen text object
    public void setGameOverScoreText(string content)
    {
        gameOverScoreText.text = content;
    }

    // Set the content for the highest combo text object
    public void setHighestComboTextContent(string content)
    {
        highestComboText.text = content;
    }

    /*-Animation Functions-*/

    // Slide the pause panel in
    public void slidePausePanelIn()
    {
        pausePanelAnimator.SetBool("isIdle", false);
        pausePanelAnimator.SetBool("isSlidingOut", false);
        pausePanelAnimator.SetBool("isSlidingIn", true);
    }

    // Slide the pause panel out
    public void slidePausePanelOut()
    {
        pausePanelAnimator.SetBool("isIdle", false);
        pausePanelAnimator.SetBool("isSlidingOut", true);
        pausePanelAnimator.SetBool("isSlidingIn", false);
    }

    // Slide the game over panel in
    public void slideGameOverPanelIn()
    {
        if (canShowGameOverPanel == true)
        {
            gameOverPanelAnimator.SetBool("isIdle", false);
            gameOverPanelAnimator.SetBool("isSlidingOut", false);
            gameOverPanelAnimator.SetBool("isSlidingIn", true);
        }
    }

    // Slide the game over panel out
    public void slideGameOverPanelOut()
    {
        gameOverPanelAnimator.SetBool("isIdle", false);
        gameOverPanelAnimator.SetBool("isSlidingOut", true);
        gameOverPanelAnimator.SetBool("isSlidingIn", false);
    }
}


text:
.class public interface abstract Lcom/google/android/gms/location/places/internal/zzf;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/android/gms/location/places/internal/zzf$zza;
    }
.end annotation

# virtual methods
.method public abstract zza(Lcom/google/android/gms/location/places/NearbyAlertRequest;Lcom/google/android/gms/location/places/internal/PlacesParams;Landroid/app/PendingIntent;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract zza(Lcom/google/android/gms/location/places/PlaceFilter;Lcom/google/android/gms/location/places/internal/PlacesParams;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract zza(Lcom/google/android/gms/location/places/PlaceReport;Lcom/google/android/gms/location/places/internal/PlacesParams;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract zza(Lcom/google/android/gms/location/places/PlaceRequest;Lcom/google/android/gms/location/places/internal/PlacesParams;Landroid/app/PendingIntent;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract zza(Lcom/google/android/gms/location/places/internal/PlacesParams;Landroid/app/PendingIntent;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract zzb(Lcom/google/android/gms/location/places/internal/PlacesParams;Landroid/app/PendingIntent;Lcom/google/android/gms/location/places/internal/zzi;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
import React from "react";
import HeadImg from "./HeadImg";
import HeadNav from "./HeadNav";
import Footer from "./Footer";
import '../css/Header.css';

export default class Header extends React.Component{
	constructor(props) {
        super(props);
        this.state = {
            sel: this.props.sel
        };
    }
	render() {
		return (
			<header className="Header">
				<HeadImg />
				<HeadNav sel={this.state.sel} />
				<Footer />
			</header>
		);
	}
}


text:
BINDIR=`dirname $0`

if [ -n "$BINDIR" ] ; then
    BENCH_HOME=`cd $BINDIR/.. > /dev/null 2>&1 && pwd`
    export BENCH_HOME
fi

if [ -z "$JAVA_HOME" ] ; then
    JAVA_HOME=/usr/dist/share/java,v1.5.0/5.x-sun4
    export JAVA_HOME;
fi

# Guess mode for FABAN_HOME
GUESS=""
if [ -z "${FABAN_HOME}" ] ; then
    # This would be the location if the sample
    # were run from the Faban distribution.
    FABAN_HOME=../../..
    FABAN_HOME=`cd ${FABAN_HOME} > /dev/null 2>&1 && pwd`
    export FABAN_HOME
    GUESS=true;
fi

if [ ! -f "${FABAN_HOME}/lib/fabandriver.jar" ] ; then
    if [ -n "${GUESS}" ] ; then
      echo "FABAN_HOME variable not set, exiting."
    else
      echo "Sorry, did not find Faban at FABAN_HOME=${FABAN_HOME}, exiting."
    fi
    exit 1
fi

# Set the necessary classpaths
CLASSPATH=${FABAN_HOME}/lib/fabancommon.jar:${FABAN_HOME}/lib/fabandriver.jar

for i in ${BENCH_HOME}/lib/*.jar
do
    CLASSPATH=${CLASSPATH}:$i
done

CLASSPATH=${CLASSPATH}:${BENCH_HOME}/build/classes

for i in ${SAMPLE_HOME}/lib/*.jar
do
    CLASSPATH=${CLASSPATH}:$i
done

export CLASSPATH

cd ../config


text:
import json
import onetimepass as otp
import os

from .version import __version__

class Error(Exception):
    pass

class Secrets(object):
    def __init__(self, filename, secrets):
        self.filename = filename
        self._secrets = secrets

    @staticmethod
    def from_file(filename):
        try:
            with open(os.path.expanduser(filename)) as secrets_file:
                secrets = json.loads(secrets_file.read())
        except IOError:
            secrets = {}

        return Secrets(filename, secrets)

    def save(self):
        with open(os.path.expanduser(self.filename), "w") as secrets_file:
            secrets_file.write(json.dumps(self._secrets))

    def add(self, name, secret):
        if name in self._secrets:
            raise Error("Secret %s already exists." % name)
        self._secrets[name] = secret

    def edit(self, name, secret):
        self._secrets[name] = secret

    def remove(self, name):
        if name not in self._secrets:
            raise Error("No such secret (%s)" % name)
        del self._secrets[name]

    def show_all(self):
        return list(self._secrets.keys())

    def show(self, name):
        if name not in self._secrets:
            raise Error("No such secret (%s)" % name)

        return otp.get_totp(self._secrets[name])


text:
package Path;

public class EmptyFilter implements IPathFilter
{
    public String DoFilter(String path)
    {
        return path;
    }
}


text:
<?php

namespace Jig\Utils;

use Exception;

/**
 * ServerUtils
 */
class ServerUtils
{

    /**
     * Determine whether a request has been made with AJAX
     *
     * @return bool
     */
    public static function requestIsXhr()
    {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
            $_SERVER['HTTP_X_REQUESTED_WITH']
        ) === 'xmlhttprequest';
    }

    /**
     * Make an educated guess on the URI that called the current script
     *
     * @param bool $qualified
     * @return string
     */
    public static function getScriptUri($qualified = false)
    {
        if (!empty($_SERVER['REQUEST_URI'])) {
            return $qualified ? self::getBaseUri() . '/' . ltrim(
                    $_SERVER['REQUEST_URI'],
                    '/'
                ) : $_SERVER['REQUEST_URI'];
        }
        if (!empty($_SERVER['REDIRECT_URL'])) {
            return $qualified ? self::getBaseUri() . '/' . ltrim(
                    $_SERVER['REDIRECT_URL'],
                    '/'
                ) : $_SERVER['REDIRECT_URL'];
        }
        $queryString = '';
        if (!empty($_SERVER['QUERY_STRING'])) {
            $queryString = $_SERVER['QUERY_STRING'];
        } else if (!empty($_SERVER['REDIRECT_QUERY_STRING'])) {
            $queryString = $_SERVER['REDIRECT_QUERY_STRING'];
        }
        $queryString = '?' . htmlspecialchars($queryString);
        $phpSelf     = '';
        if (!empty($_SERVER['PHP_SELF'])) {
            $phpSelf = $_SERVER['PHP_SELF'];
        } else if (!empty($_SERVER['SCRIPT_NAME'])) {
            $phpSelf = $_SERVER['SCRIPT_NAME'];
        }
        if ($phpSelf) {
            return $qualified ? self::getBaseUri() . '/' . ltrim(
                    $phpSelf . $queryString,
                    '/'
                ) : $phpSelf . $queryString;
        }
        return '';
    }

    /**
     * Get base uri (protocol + domain)
     *
     * @return string
     */
    public static function getBaseUri()
    {
        $server = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
        return rtrim(self::getProtocol() . '://' . $server, '/');
    }

    /**
     * Get protocol
     *
     * @return string
     */
    public static function getProtocol()
    {
        return 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "");
    }

    /**
     * Redirect to a different resource
     *
     * @param string $path to the resource without protocol and without host
     * @return bool|void
     */
    public static function redirect($path = '')
    {

        $redirection = self::getProtocol() . '://' . $_SERVER['HTTP_HOST'] . '/' . ltrim($path, '/');
        if (self::getScriptUri(true) === $redirection) {
            return false;
        }

        if ($redirection !== self::getScriptUri(true)) {
            header('Location: ' . $redirection, true, 301);
            exit(-1);
        }
        return false;
    }

    /**
     * Force a file to download
     *
     * @param $path
     * @param null $dwlFilename
     * @throws Exception
     */
    public static function forceDownload($path, $dwlFilename = null)
    {
        if (!is_file($path)) {
            throw new Exception(__METHOD__ . '() File ' . $path . ' doesn\'t exist!');
        }

        if (!$dwlFilename) {
            $dwlFilename = basename($path);
        }

        $content = file_get_contents($path);

        // initialize download
        header('Expires: Fri, 16 Sep 1983 00:00:01 GMT');
        header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header('Cache-control: private');
        header('Content-type: application/octet-stream');
        header('Content-Length: ' . strlen($content));
        header('Content-Disposition: ' . $dwlFilename);
        print($content);
        exit(-1);
    }

    public static function clientIpIs($ip)
    {
        return !empty($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] === $ip;
    }

    public static function protocolizeUri($uri)
    {
        $uri = ltrim($uri, '/');
        if (strpos($uri, '://') === false) {
            $uri = self::getServerProtocol() . '://' . $uri;
        }
        return $uri;
    }

}


text:
package scalingo

import "github.com/Scalingo/heroku2scalingo/Godeps/_workspace/src/gopkg.in/errgo.v1"

type Addon struct {
	ID              string         `json:"id"`
	ResourceID      string         `json:"resource_id"`
	PlanID          string         `json:"plan_id"`
	AddonProviderID string         `json:"addon_provider_id"`
	Plan            *Plan          `json:"plan"`
	AddonProvider   *AddonProvider `json:"addon_provider"`
}

type AddonsRes struct {
	Addons []*Addon `json:"addons"`
}

type AddonRes struct {
	Addon     Addon    `json:"addon"`
	Message   string   `json:"message,omitempty"`
	Variables []string `json:"variables,omitempty"`
}

func AddonsList(app string) ([]*Addon, error) {
	var addonsRes AddonsRes
	err := subresourceList(app, "addons", nil, &addonsRes)
	if err != nil {
		return nil, errgo.Mask(err, errgo.Any)
	}
	return addonsRes.Addons, nil
}

func AddonProvision(app, addon, planID string) (AddonRes, error) {
	var addonRes AddonRes
	err := subresourceAdd(app, "addons", AddonRes{Addon: Addon{AddonProviderID: addon, PlanID: planID}}, &addonRes)
	if err != nil {
		return AddonRes{}, errgo.Mask(err, errgo.Any)
	}
	return addonRes, nil
}

func AddonDestroy(app, addonID string) error {
	return subresourceDelete(app, "addons", addonID)
}

func AddonUpgrade(app, addonID, planID string) (AddonRes, error) {
	var addonRes AddonRes
	err := subresourceUpdate(app, "addons", addonID, AddonRes{Addon: Addon{PlanID: planID}}, &addonRes)
	if err != nil {
		return AddonRes{}, errgo.Mask(err, errgo.Any)
	}
	return addonRes, nil
}


text:
(function() {

	function main(argument) {
		let options = {
			target: '#graph',
			debug: false,
			width: 600,
			height: 600,
			callbacks: {
			  /*
			    Callbacks should only be overwritten on a need to basis.
			    See the section about callbacks below.
			  */
			},
			margin: {
			  top: 0,
			  right: 0,
			  bottom: 0,
			  left: 0
			},
			nodeWidth: 100,
			styles: {
			  node: 'node',
			  linage: 'linage',
			  marriage: 'marriage',
			  text: 'nodeText'
			}
		};

		let treeJson = d3.json("data.json", function(error, treeData) {
			dTree.init(treeData, options);
			console.log(treeData);
			console.log(error);
		});
	}

	window.addEventListener("load", main, true);
})();


text:
FROM greatbsky/tomcat:latest
MAINTAINER architect.bian
LABEL name="appserver" license="MIT" build-date="20170223"

ENV VERSION 1.0.0
ENV GM_VERSION 1.3.25

RUN yum update -y && yum install -y libjpeg libjpeg-devel libpng libpng-devel giflib giflib-devel freetype freetype-devel && cd /data/softs && wget -O GraphicsMagick.tar.gz https://sourceforge.net/projects/graphicsmagick/files/graphicsmagick/$GM_VERSION/GraphicsMagick-$GM_VERSION.tar.gz/download && tar -zxf GraphicsMagick.tar.gz && cd GraphicsMagick-$GM_VERSION && ./configure && make && make install && rm -rf /data/softs/*

CMD ["/data/env/tomcats/0/bin/catalina.sh", "run"]


text:
@implementation MessageModel

+ (id)messageModelWithDict:(NSDictionary *)dict{

  MessageModel *message = [[self alloc] init];
  message.text = dict[@"text"];
  message.time = dict[@"time"];
  message.type = [dict[@"type" ]intValue];

  return message;
}

@end


text:
#ifndef STATISTICS_GATHERER_H
#define	STATISTICS_GATHERER_H

#include <boost/type_traits.hpp> // boost::is_base_of

#include <mutation_accumulation/configuration/configuration/configuration_interface.h> // monte_carlo::Configuration_Interface
#include <mutation_accumulation/array/array3D.h> // array::Array3D
#include <mutation_accumulation/array/array2D.h> // array::Array2D

/*************************************************************************/

namespace monte_carlo {

    /**
     * abstract base class that stores statistics generated by Configuration class\n
     * defines the interface used by generate_statistics(..) \n
     * may use this class polymorphically (virtual destructor) \n
     * may not instantiate (ctor is protected)\n
     */
    template <class Configuration_type, class Results_type>
    class Statistics_Gatherer {
    public:

        typedef Configuration_type Configuration_t;
        typedef Results_type Results_t;

    protected:

        explicit Statistics_Gatherer() {

            /* check template parameter types to supplement "duck typing" */
            typedef typename Configuration_type::time_t time_type; // Item 42
            typedef typename Configuration_type::population_t population_type;
            BOOST_STATIC_ASSERT((boost::is_base_of<Configuration_Interface<time_type, population_type>, Configuration_type>::value));
        }

    public:

        /**
         * virtual destructor\n
         * ensures that objects can be deleted properly using interface base class pointers\n
         * this function is public so that one can call delete through a base-class pointer
         */
        virtual ~Statistics_Gatherer() {

        }

        /**
         * dump results of a particular trial\n
         * cannot pull the loop over pop, spe, node up to this level without also pulling up the size of the 3D array\n
         * (statistics for extinction times makes the problem concrete)
         */
        virtual void dump(const Configuration_type &configuration) = 0;

        /**
         * returns true if statistics of observed population have converged
         */
        virtual const bool converged() const = 0;

        /**
         * return results as 3D array so that number of pops, spe, and nodes can be retrieved \n
         */
        virtual const array::Array3D<Results_type> get_results_so_far() const = 0;

        /**
         * return whole-population results as 2D array so that number of spe, and nodes can be retrieved \n
         */
        virtual const array::Array2D<Results_type> get_results_so_far_whole() const = 0;

    };

}

#endif	/* STATISTICS_GATHERER_H */


text:
This document describes eventual additional steps that might be required to update between two versions of Kong. If nothing is described here for a particular version and platform, then assume the update will go smoothly.

## Update to Kong `0.5.0`

Migrating to 0.5.0 can be done **without downtime** by following those instructions. It is important that you be running Kong `0.4.2` and have the latest release of Python 2.7 on your system when executing those steps.

> Several changes were introduced in this version: some plugins and properties were renamed and the database schema slightly changed to introduce "plugins migrations". Now, each plugin can have its own migration if it needs to store data in your cluster. This is not a regular migration since the schema of the table handling the migrations itself changed.

##### 1. Configuration file

You will need to update your configuration file. Replace the `plugins_available` values with:

```yaml
plugins_available:
  - ssl
  - jwt
  - acl
  - cors
  - oauth2
  - tcp-log
  - udp-log
  - file-log
  - http-log
  - key-auth
  - hmac-auth
  - basic-auth
  - ip-restriction
  - mashape-analytics
  - request-transformer
  - response-transformer
  - request-size-limiting
  - rate-limiting
  - response-ratelimiting
```

You can still remove plugins you don't use for a lighter Kong.

Also replace the Cassandra `hosts` property with `contact_points`:

```yaml
properties:
  contact_points:
    - "..."
    - "..."
  timeout: 1000
  keyspace: kong
  keepalive: 60000
```

##### 2. Migration script

[This Python script](/scripts/migration.py) will take care of migrating your database schema should you execute the following instructions:

```shell
# First, make sure you are already running Kong 0.4.2

# Clone the Kong git repository if you don't already have it:
$ git clone https://github.com/Mashape/kong.git

# Go to the 'scripts/' folder:
$ cd kong/scripts

# Install the Python script dependencies:
$ pip install cassandra-driver pyyaml

# The script will use the first Cassandra contact point in your Kong configuration file
# (the first of the 'contact_points' property) so make sure it is valid and has the format 'host:port'.

# Run the migration script:
$ python migration.py -c /path/to/kong/config
```

If everything went well the script should print a success message. **At this point, your database is compatible with both Kong 0.4.2 and 0.5.0.** If you are running more than one Kong node, you simply have to follow step 3. for each one of them now.

##### 3. Upgrade without downtime

You can now update Kong to 0.5.0. Proceed as a regular update and install the package of your choice from the website. After updating, reload Kong to avoid downtime:

```shell
$ kong reload
```

##### 4. Purge your Cassandra cluster

Finally, once Kong has restarted in 0.5.0, run the migration script again, with the `--purge` flag:

```shell
$ python migration.py -c /path/to/kong/config --purge
```

Your cluster is now fully migrated to `0.5.0`.

##### Other changes to acknowledge

Some entities and properties were renamed to avoid confusion:

- Properties belonging to APIs entities have been renamed for clarity:
  - `public_dns` -> `request_host`
  - `path` -> `request_path`
  - `strip_path` -> `strip_request_path`
  - `target_url` -> `upstream_url`
- `plugins_configurations` have been renamed to `plugins`, and their `value` property has been renamed to `config` to avoid confusions.
- The Key authentication and Basic authentication plugins routes have changed:

```
Old route                             New route
/consumers/:consumer/keyauth       -> /consumers/:consumer/key-auth
/consumers/:consumer/keyauth/:id   -> /consumers/:consumer/key-auth/:id
/consumers/:consumer/basicauth     -> /consumers/:consumer/basic-auth
/consumers/:consumer/basicauth/:id -> /consumers/:consumer/basic-auth/:id
```

The old routes are still maintained but will be removed in upcoming versions. Consider them **deprecated**.

- Admin API:
  - The route to retrieve enabled plugins is now under `/plugins/enabled`.
  - The route to retrieve a plugin's configuration schema is now under `/plugins/schema/{plugin name}`.

## Update to Kong `0.4.2`

The configuration format for specifying the port of your Cassandra instance changed. Replace:

```yaml
cassandra:
  properties:
    hosts: "localhost"
    port: 9042
```

by:

```yaml
cassandra:
  properties:
    hosts:
      - "localhost:9042"
```

## Update to Kong `0.3.x`

Kong now requires a patch on OpenResty for SSL support. On Homebrew you will need to reinstall OpenResty.

#### Homebrew

```shell
$ brew update
$ brew reinstall mashape/kong/ngx_openresty
$ brew upgrade kong
```

#### Troubleshoot

If you are seeing a similar error on `kong start`:

```
nginx: [error] [lua] init_by_lua:5: Startup error: Cassandra error: Failed to prepare statement: "SELECT id FROM apis WHERE path = ?;". Cassandra returned error (Invalid): "Undefined name path in where clause ('path = ?')"
```

You can run the following command to update your schema:

```
$ kong migrations up
```

Please consider updating to `0.3.1` or greater which automatically handles the schema migration.