text:
<?php

/**
 * Tests for apiCreate in ProblemController
 *
 * @author joemmanuel
 */
require_once 'libs/FileHandler.php';

class CreateProblemTest extends OmegaupTestCase {

	/**
	 * Basic test for creating a problem
	 */
	public function testCreateValidProblem() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest();
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("testplan", $response["uploaded_files"][10]);

		// Verify data in DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);

		// Check that we only retreived 1 element
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify contest was found
		$this->assertNotNull($problem);
		$this->assertNotNull($problem->getProblemId());

		// Verify DB data
		$this->assertEquals($r["title"], $problem->getTitle());
		$this->assertEquals(substr($r["title"], 0, 32), $problem->getAlias());
		$this->assertEquals($r["validator"], $problem->getValidator());
		$this->assertEquals($r["time_limit"], $problem->getTimeLimit());
		$this->assertEquals($r["memory_limit"], $problem->getMemoryLimit());
		$this->assertEquals($r["order"], $problem->getOrder());
		$this->assertEquals($r["source"], $problem->getSource());
		$this->assertEqualSets($r["languages"], $problem->getLanguages());
		$this->assertEquals(0, $problem->slow);
		$this->assertEquals(10000, $problem->stack_limit);

		// Verify author username -> author id conversion
		$user = UsersDAO::getByPK($problem->getAuthorId());
		$this->assertEquals($user->getUsername(), $r["author_username"]);

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;

		$this->assertFileExists($targetpath . "testplan");
		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "en.html");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "en.markdown");

		// Default data
		$this->assertEquals(0, $problem->getVisits());
		$this->assertEquals(0, $problem->getSubmissions());
		$this->assertEquals(0, $problem->getAccepted());
		$this->assertEquals(0, $problem->getDifficulty());
	}

	/**
	 * Basic test for slow problems
	 */
	public function testSlowQueue() {
		// Get the problem data
		$problemData = ProblemsFactory::getRequest();
		$r = $problemData["request"];
		$r['time_limit'] = 8000;
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("testplan", $response["uploaded_files"][10]);

		// Verify data in DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);

		// Check that we only retreived 1 element
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify contest was found
		$this->assertNotNull($problem);

		// Verify DB data
		$this->assertEquals(1, $problem->slow);
	}

	/**
	 * Basic test for slow problems
	 */
	public function testSlowQueueWithWallLimit() {
		// Get the problem data
		$problemData = ProblemsFactory::getRequest();
		$r = $problemData["request"];
		$r['time_limit'] = 8000;
		$r['overall_wall_time_limit'] = 20000;
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("testplan", $response["uploaded_files"][10]);

		// Verify data in DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);

		// Check that we only retreived 1 element
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify contest was found
		$this->assertNotNull($problem);

		// Verify DB data
		$this->assertEquals(0, $problem->slow);
	}

	/**
	 * Basic test for creating a problem
	 */
	public function testCreateValidProblemWithINCases() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . 'mrkareltastic.zip');
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("cases/g1.train0.in", $response["uploaded_files"][0]);
		$this->assertEquals("cases/g1.train0.out", $response["uploaded_files"][1]);

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $r["alias"] . DIRECTORY_SEPARATOR;

		$this->assertFileExists($targetpath . "testplan");
		$this->assertFileExists($targetpath . "cases/in/g1.train0.in");
		$this->assertFileExists($targetpath . "cases/out/g1.train0.out");
		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");
	}

	/**
	 * Test that sends incomplete requests
	 */
	public function testRequiredParameters() {

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Array of valid keys
		$valid_keys = array(
			"title",
			"validator",
			"time_limit",
			"memory_limit",
			"source",
			"languages",
		);

		foreach ($valid_keys as $key) {

			// Get the problem data
			$problemData = ProblemsFactory::getRequest();
			$r = $problemData["request"];
			$problemAuthor = $problemData["author"];

			// Login user
			$r["auth_token"] = $this->login($problemAuthor);

			// Unset key
			unset($r[$key]);

			try {

				// Call the API
				$response = ProblemController::apiCreate($r);
			} catch (InvalidParameterException $e) {
				// We're OK, clean up our mess and continue
				unset($_REQUEST);
				continue;
			}

			$this->fail("Exception was expected. Parameter: " . $key);
		}
	}

	/**
	 * Test that sends invalid languages.
	 */
	public function testInvalidLanguage() {

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		foreach (array("abc", "c,cpp,cows", "java,coffee,espresso") as $languages) {
			// Get the problem data
			$problemData = ProblemsFactory::getRequest();
			$r = $problemData["request"];
			$problemAuthor = $problemData["author"];

			// Login user
			$r["auth_token"] = $this->login($problemAuthor);
			$r["languages"] = $languages;
			try {
				// Call the API
				$response = ProblemController::apiCreate($r);
			} catch (InvalidParameterException $e) {
				// We're OK, clean up our mess and continue
				unset($_REQUEST);
				continue;
			}
			$this->fail("Exception was expected. Language set: $languages");
		}
	}

	/**
	 * Test that we are able to submit a problem without testplan
	 */
	public function testValidProblemNoTestplan() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . "triangulos.zip");
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("cases/1.in", $response["uploaded_files"][0]);

		// Verify data in DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);

		// Check that we only retreived 1 element
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify contest was found
		$this->assertNotNull($problem);
		$this->assertNotNull($problem->getProblemId());

		// Verify DB data
		$this->assertEquals($r["title"], $problem->getTitle());
		$this->assertEquals(substr($r["title"], 0, 32), $problem->getAlias());
		$this->assertEquals($r["validator"], $problem->getValidator());
		$this->assertEquals($r["time_limit"], $problem->getTimeLimit());
		$this->assertEquals($r["memory_limit"], $problem->getMemoryLimit());
		$this->assertEquals($r["order"], $problem->getOrder());
		$this->assertEquals($r["source"], $problem->getSource());

		// Verify author username -> author id conversion
		$user = UsersDAO::getByPK($problem->getAuthorId());
		$this->assertEquals($user->getUsername(), $r["author_username"]);

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;

		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");

		// Default data
		$this->assertEquals(0, $problem->getVisits());
		$this->assertEquals(0, $problem->getSubmissions());
		$this->assertEquals(0, $problem->getAccepted());
		$this->assertEquals(0, $problem->getDifficulty());
	}

	/**
	 * Test that we are able to submit a problem without testplan
	 */
	public function testValidProblemWithNonUTF8CharsInStmt() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . "nonutf8stmt.zip");
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Verify response
		$this->assertEquals("ok", $response["status"]);

		// Get problem info from DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;
		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.markdown");

		// Verify we have the accents, lol
		$markdown_contents = file_get_contents($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.markdown");
		if (strpos($markdown_contents, "ó") === false) {
			$this->fail("ó not found when expected.");
		}

		$html_contents = file_get_contents($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");
		if (strpos($html_contents, "ó") === false) {
			$this->fail("ó not found when expected.");
		}
	}

	/**
	 * Test that image upload works.
	 */
	public function testImageUpload() {
		$imageSha1 = '27938919b32434b39486d04db57d5b8dccbe881b';
		$imageExtension = 'jpg';
		$imageAbsoluteUrl = 'http://i.imgur.com/fUkvDkw.png';

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . "imagetest.zip");
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Verify response
		$this->assertEquals("ok", $response["status"]);

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $r["alias"] . DIRECTORY_SEPARATOR;
		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.markdown");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "bunny.jpg");
		$this->assertFileExists(IMAGES_PATH . $imageSha1 . "." . $imageExtension);

		// Verify that all the images are there.
		$html_contents = file_get_contents($targetpath . "statements" . DIRECTORY_SEPARATOR . "es.html");
		$this->assertContains("assertContains("assertContains("assertContains("![Saluda](" . IMAGES_URL_PATH . "$imageSha1.$imageExtension)", $markdown_contents);
		// And the direct URL.
		$this->assertContains("![Saluda]($imageAbsoluteUrl)", $markdown_contents);
		// And the unmodified, not found image.
		$this->assertContains("![404](notfound.jpg)", $markdown_contents);
	}

	/**
	 * Test that we can produce a valid alias from the title
	 */
	public function testConstructAliasFromTitle() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest();
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Set a valid "complex" title
		$r["title"] = "Lá Venganza Del Malvado Dr. Liraaa";

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);

		// Validate
		// Verify response
		$this->assertEquals("ok", $response["status"]);
		$this->assertEquals("testplan", $response["uploaded_files"][10]);

		// Verify data in DB
		$problem_mask = new Problems();
		$problem_mask->setTitle($r["title"]);
		$problems = ProblemsDAO::search($problem_mask);

		// Check that we only retreived 1 element
		$this->assertEquals(1, count($problems));
		$problem = $problems[0];

		// Verify contest was found
		$this->assertNotNull($problem);
		$this->assertNotNull($problem->getProblemId());

		// Verify DB data
		$this->assertEquals($r["title"], $problem->getTitle());

		// Verify problem contents were copied
		$targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;

		$this->assertFileExists($targetpath . "testplan");
		$this->assertFileExists($targetpath . "cases");
		$this->assertFileExists($targetpath . "statements" . DIRECTORY_SEPARATOR . "en.html");
	}

	/**
	 * Basic test for uploadin problem without statement
	 *
	 * @expectedException InvalidParameterException
	 */
	public function testCreateProblemWithoutStatement() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . "nostmt.zip");
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);
	}

	/**
	 * Basic test for uploadin problem missing outputs
	 *
	 * @expectedException InvalidParameterException
	 */
	public function testCreateProblemMissingOutput() {

		// Get the problem data
		$problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . "missingout.zip");
		$r = $problemData["request"];
		$problemAuthor = $problemData["author"];

		// Login user
		$r["auth_token"] = $this->login($problemAuthor);

		// Get File Uploader Mock and tell Omegaup API to use it
		FileHandler::SetFileUploader($this->createFileUploaderMock());

		// Call the API
		$response = ProblemController::apiCreate($r);
	}
}


text:
create table brokers (
  brokey bigserial primary key,
  broname varchar(100) unique not null,
  broendpoint varchar(100) unique not null
)

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
module Rsched
    ( app
    ) where

import Control.Exception (SomeException)
import Control.Exception.Lifted (handle)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (Value, encode, object, (.=))
import Data.Aeson.Parser (json)
import Data.Conduit (($$))
import Data.Conduit.Attoparsec (sinkParser)
import Data.Text ( Text )
import Network.HTTP.Types (Method, status200, status400)
import Network.Wai (Application, Request, Response, responseLBS)
import Network.Wai.Conduit (sourceRequestBody)

import qualified Rsched.Job as J

app :: Application
app req sendResponse = handle (sendResponse . invalidJson) $ do
  value <- sourceRequestBody req $$ sinkParser json
  newValue <- liftIO $ modValue req value
  sendResponse $ responseLBS
    status200
    [("Content-Type", "application/json")]
    $ encode newValue

invalidJson :: SomeException -> Response
invalidJson ex = responseLBS
  status400
  [("Content-Type", "application/json")]
  $ encode $ object
    [ ("message" .= show ex)
    ]

modValue :: Request -> Value -> IO Value
modValue req value = do
  return value


text:
<!DOCTYPE html>

    <title>Articles by David Lange - DIANA HEP</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="https://diana-hep.org/images/favicon.ico" rel="icon">

        <meta name="author" content="DIANA HEP" />

        <meta property="og:site_name" content="DIANA HEP" />
        <meta property="og:type" content="website"/>
        <meta property="og:title" content="DIANA HEP"/>
        <meta property="og:url" content="https://diana-hep.org"/>
        <meta property="og:description" content="DIANA HEP"/>

        <link rel="stylesheet" href="https://diana-hep.org/theme/css/bootstrap.cosmo.min.css" type="text/css"/>
    <link href="https://diana-hep.org/theme/css/font-awesome.min.css" rel="stylesheet">

    <link href="https://diana-hep.org/theme/css/pygments/default.css" rel="stylesheet">
    <link rel="stylesheet" href="https://diana-hep.org/theme/css/style.css" type="text/css"/>

    <link rel="stylesheet" href="https://diana-hep.org/theme/css/dianahep-styles.css" type="text/css"/>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

Team

Activities/Products

DIANA Fellows

Blog

S2I2 workshop at NCSA

Many of us will attend the first S2I2 workshop beginning tomorrow at NCSA in Urbana, Illinois to discuss collaboration the challenges
towards growing successful collaborations between HEP and computer science research communities. The workshop agenda
can be found [here][http://hep.physics.illinois.edu/hepg/S2I2-HEP-CS-WKSHP/home.html].

                    more ...

Links

ROOT

NSF SI2

IRIS-HEP

S2I2-HEP

Jetscape

rootpy

scikit-learn

RooStats

Conferences

Contact

twitter

github

YouTube

Indico

Google Group

Vidyo Room


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Kew Bull. 19(1): 49 (1964)

#### Original name
Mycena veneta G. Stev.

### Remarks
null


text:
package org.acme.funqy;

import io.quarkus.funqy.Funq;

public class GreetingFunction {

    @Funq
    public String myFunqyGreeting(Person friend) {
        return "Hello " + friend.getName();
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__unsigned_int_fscanf_add_61b.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-61b.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: add
 *    GoodSink: Ensure there will not be an overflow before adding 1 to data
 *    BadSink : Add 1 to data, which can cause an overflow
 * Flow Variant: 61 Data flow: data returned from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

unsigned int CWE190_Integer_Overflow__unsigned_int_fscanf_add_61b_badSource(unsigned int data)
{
    /* POTENTIAL FLAW: Use a value input from the console */
    fscanf (stdin, "%u", &data);
    return data;
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
unsigned int CWE190_Integer_Overflow__unsigned_int_fscanf_add_61b_goodG2BSource(unsigned int data)
{
    /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
    data = 2;
    return data;
}

/* goodB2G() uses the BadSource with the GoodSink */
unsigned int CWE190_Integer_Overflow__unsigned_int_fscanf_add_61b_goodB2GSource(unsigned int data)
{
    /* POTENTIAL FLAW: Use a value input from the console */
    fscanf (stdin, "%u", &data);
    return data;
}

#endif /* OMITGOOD */


text:
package com.badlogic.gdx.physics.box2d;

import java.util.Iterator;

import org.jbox2d.collision.AABB;
import org.jbox2d.common.Settings;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.joints.JointEdge;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.JointDef.JointType;
import com.badlogic.gdx.physics.box2d.joints.DistanceJoint;
import com.badlogic.gdx.physics.box2d.joints.FrictionJoint;
import com.badlogic.gdx.physics.box2d.joints.MouseJoint;
import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint;
import com.badlogic.gdx.physics.box2d.joints.PulleyJoint;
import com.badlogic.gdx.physics.box2d.joints.RevoluteJoint;
import com.badlogic.gdx.physics.box2d.joints.RopeJoint;
import com.badlogic.gdx.physics.box2d.joints.WeldJoint;
import com.badlogic.gdx.physics.box2d.joints.WheelJoint;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.ObjectMap;

/** The world class manages all physics entities, dynamic simulation, and asynchronous queries. The world also contains efficient
 * memory management facilities.
 * @author mzechner */
public final class World implements Disposable {
	org.jbox2d.dynamics.World world;
	Vec2 tmp = new Vec2();
	Vector2 tmp2 = new Vector2();
	ObjectMap<org.jbox2d.dynamics.Body, Body> bodies = new ObjectMap<org.jbox2d.dynamics.Body, Body>();
	ObjectMap<org.jbox2d.dynamics.Fixture, Fixture> fixtures = new ObjectMap<org.jbox2d.dynamics.Fixture, Fixture>();
	ObjectMap<org.jbox2d.dynamics.joints.Joint, Joint> joints = new ObjectMap<org.jbox2d.dynamics.joints.Joint, Joint>();

	/** Construct a world object.
	 * @param gravity the world gravity vector.
	 * @param doSleep improve performance by not simulating inactive bodies. */
	public World (Vector2 gravity, boolean doSleep) {
		world = new org.jbox2d.dynamics.World(tmp.set(gravity.x, gravity.y));
		world.setAllowSleep(doSleep);
	}

	/** Register a destruction listener. The listener is owned by you and must remain in scope. */
	public void setDestructionListener (DestructionListener listener) {
	}

	/** Register a contact filter to provide specific control over collision. Otherwise the default filter is used
	 * (b2_defaultFilter). The listener is owned by you and must remain in scope. */
	public void setContactFilter (final ContactFilter filter) {
		if (filter != null) {
			world.setContactFilter(new org.jbox2d.callbacks.ContactFilter() {
				@Override
				public boolean shouldCollide (org.jbox2d.dynamics.Fixture fixtureA, org.jbox2d.dynamics.Fixture fixtureB) {
					return filter.shouldCollide(fixtures.get(fixtureA), fixtures.get(fixtureB));
				}
			});
		} else {
			world.setContactFilter(new org.jbox2d.callbacks.ContactFilter());
		}
	}

	/** Register a contact event listener. The listener is owned by you and must remain in scope. */
	Contact tmpContact = new Contact(this);
	Manifold tmpManifold = new Manifold();
	ContactImpulse tmpImpulse = new ContactImpulse();

	public void setContactListener (final ContactListener listener) {
		if (listener != null) {
			world.setContactListener(new org.jbox2d.callbacks.ContactListener() {
				@Override
				public void beginContact (org.jbox2d.dynamics.contacts.Contact contact) {
					tmpContact.contact = contact;
					listener.beginContact(tmpContact);
				}

				@Override
				public void endContact (org.jbox2d.dynamics.contacts.Contact contact) {
					tmpContact.contact = contact;
					listener.endContact(tmpContact);
				}

				@Override
				public void preSolve (org.jbox2d.dynamics.contacts.Contact contact, org.jbox2d.collision.Manifold oldManifold) {
					tmpContact.contact = contact;
					tmpManifold.manifold = oldManifold;
					listener.preSolve(tmpContact, tmpManifold);
				}

				@Override
				public void postSolve (org.jbox2d.dynamics.contacts.Contact contact, org.jbox2d.callbacks.ContactImpulse impulse) {
					tmpContact.contact = contact;
					tmpImpulse.impulse = impulse;
					listener.postSolve(tmpContact, tmpImpulse);
				}
			});
		} else {
			world.setContactListener(null);
		}
	}

	/** Create a rigid body given a definition. No reference to the definition is retained.
	 * @warning This function is locked during callbacks. */
	public Body createBody (BodyDef def) {
		org.jbox2d.dynamics.BodyDef bd = new org.jbox2d.dynamics.BodyDef();
		bd.active = def.active;
		bd.allowSleep = def.allowSleep;
		bd.angle = def.angle;
		bd.angularDamping = def.angularDamping;
		bd.angularVelocity = def.angularVelocity;
		bd.awake = def.awake;
		bd.bullet = def.bullet;
		bd.fixedRotation = def.fixedRotation;
		bd.gravityScale = def.gravityScale;
		bd.linearDamping = def.linearDamping;
		bd.linearVelocity.set(def.linearVelocity.x, def.linearVelocity.y);
		bd.position.set(def.position.x, def.position.y);
		if (def.type == BodyType.DynamicBody) bd.type = org.jbox2d.dynamics.BodyType.DYNAMIC;
		if (def.type == BodyType.StaticBody) bd.type = org.jbox2d.dynamics.BodyType.STATIC;
		if (def.type == BodyType.KinematicBody) bd.type = org.jbox2d.dynamics.BodyType.KINEMATIC;

		org.jbox2d.dynamics.Body b = world.createBody(bd);
		Body body = new Body(this, b);
		bodies.put(b, body);
		return body;
	}

	/** Destroy a rigid body given a definition. No reference to the definition is retained. This function is locked during
	 * callbacks.
	 * @warning This automatically deletes all associated shapes and joints.
	 * @warning This function is locked during callbacks. */
	public void destroyBody (Body body) {
		world.destroyBody(body.body);
		bodies.remove(body.body);
		for (Fixture fixture : body.fixtures) {
			fixtures.remove(fixture.fixture);
		}
		JointEdge jointEdge = body.body.getJointList();
		while (jointEdge != null) {
			joints.remove(jointEdge.joint);
		}
	}

	/** Create a joint to constrain bodies together. No reference to the definition is retained. This may cause the connected bodies
	 * to cease colliding.
	 * @warning This function is locked during callbacks. */
	public Joint createJoint (JointDef def) {
		org.jbox2d.dynamics.joints.JointDef jd = def.toJBox2d();
		org.jbox2d.dynamics.joints.Joint j = world.createJoint(jd);
		Joint joint = null;
		if (def.type == JointType.DistanceJoint) joint = new DistanceJoint(this, (org.jbox2d.dynamics.joints.DistanceJoint)j);
		if (def.type == JointType.FrictionJoint) joint = new FrictionJoint(this, (org.jbox2d.dynamics.joints.FrictionJoint)j);
		if (def.type == JointType.GearJoint) joint = new DistanceJoint(this, (org.jbox2d.dynamics.joints.DistanceJoint)j);
		if (def.type == JointType.MouseJoint) joint = new MouseJoint(this, (org.jbox2d.dynamics.joints.MouseJoint)j);
		if (def.type == JointType.PrismaticJoint) joint = new PrismaticJoint(this, (org.jbox2d.dynamics.joints.PrismaticJoint)j);
		if (def.type == JointType.PulleyJoint) joint = new PulleyJoint(this, (org.jbox2d.dynamics.joints.PulleyJoint)j);
		if (def.type == JointType.RevoluteJoint) joint = new RevoluteJoint(this, (org.jbox2d.dynamics.joints.RevoluteJoint)j);
		if (def.type == JointType.RopeJoint) joint = new RopeJoint(this, (org.jbox2d.dynamics.joints.RopeJoint)j);
		if (def.type == JointType.WeldJoint) joint = new WeldJoint(this, (org.jbox2d.dynamics.joints.WeldJoint)j);
		if (def.type == JointType.WheelJoint) joint = new WheelJoint(this, (org.jbox2d.dynamics.joints.WheelJoint)j);
		if (joint == null) throw new GdxRuntimeException("Joint type '" + def.type + "' not yet supported by GWT backend");
		joints.put(j, joint);
		return joint;
	}

	/** Destroy a joint. This may cause the connected bodies to begin colliding.
	 * @warning This function is locked during callbacks. */
	public void destroyJoint (Joint joint) {
		joint.setUserData(null);
		world.destroyJoint(joint.joint);
		joints.remove(joint.joint);
	}

	/** Take a time step. This performs collision detection, integration, and constraint solution.
	 * @param timeStep the amount of time to simulate, this should not vary.
	 * @param velocityIterations for the velocity constraint solver.
	 * @param positionIterations for the position constraint solver. */
	public void step (float timeStep, int velocityIterations, int positionIterations) {
		world.step(timeStep, velocityIterations, positionIterations);
	}

	/** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The
	 * default behavior is modified by calling SetAutoClearForces. The purpose of this function is to support sub-stepping.
	 * Sub-stepping is often used to maintain a fixed sized time step under a variable frame-rate. When you perform sub-stepping
	 * you will disable auto clearing of forces and instead call ClearForces after all sub-steps are complete in one pass of your
	 * game loop. {@link #setAutoClearForces(boolean)} */
	public void clearForces () {
		world.clearForces();
	}

	/** Enable/disable warm starting. For testing. */
	public void setWarmStarting (boolean flag) {
		world.setWarmStarting(flag);
	}

	/** Enable/disable continuous physics. For testing. */
	public void setContinuousPhysics (boolean flag) {
		world.setContinuousPhysics(flag);
	}

	/** Get the number of broad-phase proxies. */
	public int getProxyCount () {
		return world.getProxyCount();
	}

	/** Get the number of bodies. */
	public int getBodyCount () {
		return world.getBodyCount();
	}

	/** Get the number of joints. */
	public int getJointCount () {
		return world.getJointCount();
	}

	/** Get the number of contacts (each may have 0 or more contact points). */
	public int getContactCount () {
		return world.getContactCount();
	}

	/** Change the global gravity vector. */
	public void setGravity (Vector2 gravity) {
		world.setGravity(tmp.set(gravity.x, gravity.y));
	}

	public Vector2 getGravity () {
		Vec2 gravity = world.getGravity();
		return tmp2.set(gravity.x, gravity.y);
	}

	/** Is the world locked (in the middle of a time step). */
	public boolean isLocked () {
		return world.isLocked();
	}

	/** Set flag to control automatic clearing of forces after each time step. */
	public void setAutoClearForces (boolean flag) {
		world.setAutoClearForces(flag);
	}

	/** Get the flag that controls automatic clearing of forces after each time step. */
	public boolean getAutoClearForces () {
		return world.getAutoClearForces();
	}

	/** Query the world for all fixtures that potentially overlap the provided AABB.
	 * @param callback a user implemented callback class.
	 * @param lowerX the x coordinate of the lower left corner
	 * @param lowerY the y coordinate of the lower left corner
	 * @param upperX the x coordinate of the upper right corner
	 * @param upperY the y coordinate of the upper right corner */
	AABB aabb = new AABB();

	public void QueryAABB (final QueryCallback callback, float lowerX, float lowerY, float upperX, float upperY) {
		// FIXME pool QueryCallback?
		aabb.lowerBound.set(lowerX, lowerY);
		aabb.upperBound.set(upperX, upperY);
		world.queryAABB(new org.jbox2d.callbacks.QueryCallback() {
			@Override
			public boolean reportFixture (org.jbox2d.dynamics.Fixture f) {
				Fixture fixture = fixtures.get(f);
				return callback.reportFixture(fixture);
			}
		}, aabb);
	}

	/** Returns the list of {@link Contact} instances produced by the last call to {@link #step(float, int, int)}. Note that the
	 * returned list will have O(1) access times when using indexing. contacts are created and destroyed in the middle of a time
	 * step. Use {@link ContactListener} to avoid missing contacts
	 * @return the contact list */
	Array<Contact> contacts = new Array<Contact>();

	public Array<Contact> getContactList () {
		// FIXME pool contacts
		org.jbox2d.dynamics.contacts.Contact contactList = world.getContactList();
		contacts.clear();
		while (contactList != null) {
			Contact contact = new Contact(this, contactList);
			contacts.add(contact);
			contactList = contactList.m_next;
		}
		return contacts;
	}

	/** @return all bodies currently in the simulation */
	public void getBodies (Array<Body> bodies) {
		bodies.clear();
		bodies.ensureCapacity(this.bodies.size);
		for (Iterator<Body> iter = this.bodies.values(); iter.hasNext();) {
			bodies.add(iter.next());
		}
	}

	/** @return all joints currently in the simulation */
	public void getJoints (Array<Joint> joints) {
		joints.clear();
		joints.ensureCapacity(this.joints.size);
		for (Iterator<Joint> iter = this.joints.values(); iter.hasNext();) {
			joints.add(iter.next());
		}
	}

	public void dispose () {
	}

	/** Sets the box2d velocity threshold globally, for all World instances.
	 * @param threshold the threshold, default 1.0f */
	public static void setVelocityThreshold (float threshold) {
		Settings.velocityThreshold = threshold;
	}

	/** @return the global box2d velocity threshold. */
	public static float getVelocityThreshold () {
		return Settings.velocityThreshold;
	}

	/** Ray-cast the world for all fixtures in the path of the ray. The ray-cast ignores shapes that contain the starting point.
	 * @param callback a user implemented callback class.
	 * @param point1 the ray starting point
	 * @param point2 the ray ending point */
	Vec2 point1 = new Vec2();
	Vec2 point2 = new Vec2();
	Vector2 point = new Vector2();
	Vector2 normal = new Vector2();

	public void rayCast (final RayCastCallback callback, Vector2 point1, Vector2 point2) {
		// FIXME pool RayCastCallback?
		world.raycast(new org.jbox2d.callbacks.RayCastCallback() {
			@Override
			public float reportFixture (org.jbox2d.dynamics.Fixture f, Vec2 p, Vec2 n, float fraction) {
				return callback.reportRayFixture(fixtures.get(f), point.set(p.x, p.y), normal.set(n.x, n.y), fraction);
			}
		}, this.point1.set(point1.x, point1.y), this.point2.set(point2.x, point2.y));
	}
}


text:
G5SiblingDeployer::Application.config.session_store :cookie_store, key: '_g5-sibling-deployer_session'

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# G5SiblingDeployer::Application.config.session_store :active_record_store


text:
from pyvex.const import get_type_size
from claripy.fp import FSORT_FLOAT, FSORT_DOUBLE

from .... import sim_options as o
from ....errors import UnsupportedIRExprError, SimExpressionError

def SimIRExpr_Const(_, state, expr):
    return translate_irconst(state, expr.con)

def translate_irconst(state, c):
    size = get_type_size(c.type)
    if isinstance(c.value, int):
        return state.solver.BVV(c.value, size)
    elif isinstance(c.value, float):
        if o.SUPPORT_FLOATING_POINT not in state.options:
            raise UnsupportedIRExprError("floating point support disabled")
        if size == 32:
            return state.solver.FPV(c.value, FSORT_FLOAT)
        elif size == 64:
            return state.solver.FPV(c.value, FSORT_DOUBLE)
        else:
            raise SimExpressionError("Unsupported floating point size: %d" % size)
    raise SimExpressionError("Unsupported constant type: %s" % type(c.value))


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AWCircleFramedImageView</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>

</resources>


text:
require 'rails_helper'

describe Collection do

  let(:van_gogh) { User.create!(name: "Van Gogh",
                               email: "van@gogh.com",
                               password:"testing1234",
                               statement: "This is the test statement",
                               artist: true,
                               avatar: File.new("#{Rails.root}/public/imgs/favicon125x108.png")) }

  let(:test_collection) {Collection.create!(name: "Test Collection",
                                            description: "A test of a collection")}

  describe "A collection is created correctly" do

    it "Creates a collection object" do
      expect(test_collection).to be_a(Collection)
    end

    it "The collection has a name" do
      expect(test_collection.name).to eq("Test Collection")
    end

    it "The collection has a description" do
      expect(test_collection.description).to eq("A test of a collection")
    end

    it "The collection belongs to a user" do
      van_gogh.collections << test_collection
      expect(test_collection.user.name).to eq("Van Gogh")
    end
  end

end


text:
return {
  postgres = {
    up = [[
      DO $$
      BEGIN
        ALTER TABLE IF EXISTS ONLY "ratelimiting_metrics" ADD "ttl" TIMESTAMP WITH TIME ZONE;
      EXCEPTION WHEN DUPLICATE_COLUMN THEN
        -- Do nothing, accept existing state
      END$$;

      DO $$
      BEGIN
        CREATE INDEX IF NOT EXISTS "ratelimiting_metrics_ttl_idx" ON "ratelimiting_metrics" ("ttl");
      EXCEPTION WHEN UNDEFINED_TABLE THEN
        -- Do nothing, accept existing state
      END$$;
    ]],
  },

  cassandra = {
    up = [[
    ]],
  },
}


text:
local cfg = require "_config"()
local twitter = require "luatwit"
local util = require "luatwit.util"

-- initialize the twitter client
local oauth_params = util.load_keys(cfg.app_keys, cfg.user_keys)
local client = twitter.api.new(oauth_params)

-- get an username from arguments
local username = select(1, ...)

local user, err
if username then
    -- get info about the specified user
    user, err = client:get_user{ screen_name = username }
else
    -- get info about the logged user
    user, err = client:verify_credentials()
end
assert(user, tostring(err))

-- print it
local profile = [[
Name: @$screen_name ($name)
Bio: $description
Location: $location
Followers: $followers_count, Following: $friends_count, Listed: $listed_count
Tweets: $statuses_count, Favs: $favourites_count
Member since: $created_at]]

print((profile:gsub("$([%w_]+)", user)))


text:
<?xml version='1.0' encoding='UTF-8'?>
<Info location="atomicimshow.m" type="File" />


text:
#ifndef __AUDIO_H__
#define __AUDIO_H__

#include "audio_pipe.h"

/* AUDIO command */
#define _AUDIO_CTL(a) (RT_DEVICE_CTRL_BASE(Sound) + a)

#define AUDIO_CTL_GETCAPS                   _AUDIO_CTL(1)
#define AUDIO_CTL_CONFIGURE                 _AUDIO_CTL(2)
#define AUDIO_CTL_START                     _AUDIO_CTL(3)
#define AUDIO_CTL_STOP                      _AUDIO_CTL(4)
#define AUDIO_CTL_GETBUFFERINFO             _AUDIO_CTL(5)

/* Audio Device Types */
#define AUDIO_TYPE_QUERY                    0x00
#define AUDIO_TYPE_INPUT                    0x01
#define AUDIO_TYPE_OUTPUT                   0x02
#define AUDIO_TYPE_MIXER                    0x04

/* Supported Sampling Rates */
#define AUDIO_SAMP_RATE_8K                  0x0001
#define AUDIO_SAMP_RATE_11K                 0x0002
#define AUDIO_SAMP_RATE_16K                 0x0004
#define AUDIO_SAMP_RATE_22K                 0x0008
#define AUDIO_SAMP_RATE_32K                 0x0010
#define AUDIO_SAMP_RATE_44K                 0x0020
#define AUDIO_SAMP_RATE_48K                 0x0040
#define AUDIO_SAMP_RATE_96K                 0x0080
#define AUDIO_SAMP_RATE_128K                0x0100
#define AUDIO_SAMP_RATE_160K                0x0200
#define AUDIO_SAMP_RATE_172K                0x0400
#define AUDIO_SAMP_RATE_192K                0x0800

/* Supported Bit Rates */
#define AUDIO_BIT_RATE_22K                  0x01
#define AUDIO_BIT_RATE_44K                  0x02
#define AUDIO_BIT_RATE_48K                  0x04
#define AUDIO_BIT_RATE_96K                  0x08
#define AUDIO_BIT_RATE_128K                 0x10
#define AUDIO_BIT_RATE_160K                 0x20
#define AUDIO_BIT_RATE_172K                 0x40
#define AUDIO_BIT_RATE_192K                 0x80

/* Support Dsp(input/output) Units controls */
#define AUDIO_DSP_PARAM                     0           /* get/set all params */
#define AUDIO_DSP_SAMPLERATE                1           /* samplerate */
#define AUDIO_DSP_CHANNELS                  2           /* channels */
#define AUDIO_DSP_SAMPLEBITS                3           /* sample bits width */

/* Supported Mixer Units controls */
#define AUDIO_MIXER_QUERY                   0x0000
#define AUDIO_MIXER_MUTE                    0x0001
#define AUDIO_MIXER_VOLUME                  0x0002
#define AUDIO_MIXER_BASS                    0x0004
#define AUDIO_MIXER_MID                     0x0008
#define AUDIO_MIXER_TREBLE                  0x0010
#define AUDIO_MIXER_EQUALIZER               0x0020
#define AUDIO_MIXER_LINE                    0x0040
#define AUDIO_MIXER_DIGITAL                 0x0080
#define AUDIO_MIXER_MIC                     0x0100
#define AUDIO_MIXER_VITURAL                 0x0200
#define AUDIO_MIXER_EXTEND                  0x8000    /* extend mixer command */

#define AUDIO_VOLUME_MAX                    (100)
#define AUDIO_VOLUME_MIN                    (0)

#define CFG_AUDIO_REPLAY_QUEUE_COUNT        4

enum
{
    AUDIO_STREAM_REPLAY = 0,
    AUDIO_STREAM_RECORD,
    AUDIO_STREAM_LAST = AUDIO_STREAM_RECORD,
};

/* the preferred number and size of audio pipeline buffer for the audio device */
struct rt_audio_buf_info
{
    rt_uint8_t *buffer;
    rt_uint16_t block_size;
    rt_uint16_t block_count;
    rt_uint32_t total_size;
};

struct rt_audio_device;
struct rt_audio_caps;
struct rt_audio_configure;
struct rt_audio_ops
{
    rt_err_t (*getcaps)(struct rt_audio_device *audio, struct rt_audio_caps *caps);
    rt_err_t (*configure)(struct rt_audio_device *audio, struct rt_audio_caps *caps);
    rt_err_t (*init)(struct rt_audio_device *audio);
    rt_err_t (*start)(struct rt_audio_device *audio, int stream);
    rt_err_t (*stop)(struct rt_audio_device *audio, int stream);
    rt_size_t (*transmit)(struct rt_audio_device *audio, const void *writeBuf, void *readBuf, rt_size_t size);
    /* get page size of codec or private buffer's info */
    void (*buffer_info)(struct rt_audio_device *audio, struct rt_audio_buf_info *info);
};

struct rt_audio_configure
{
    rt_uint32_t samplerate;
    rt_uint16_t channels;
    rt_uint16_t samplebits;
};

struct rt_audio_caps
{
    int main_type;
    int sub_type;

    union
    {
        rt_uint32_t mask;
        int     value;
        struct rt_audio_configure config;
    } udata;
};

struct rt_audio_replay
{
    struct rt_mempool *mp;
    struct rt_data_queue queue;
    struct rt_mutex lock;
    struct rt_completion cmp;
    struct rt_audio_buf_info buf_info;
    rt_uint8_t *write_data;
    rt_uint16_t write_index;
    rt_uint16_t read_index;
    rt_uint32_t pos;
    rt_uint8_t event;
    rt_bool_t activated;
};

struct rt_audio_record
{
    struct rt_audio_pipe pipe;
    rt_bool_t activated;
};

struct rt_audio_device
{
    struct rt_device           parent;
    struct rt_audio_ops        *ops;
    struct rt_audio_replay     *replay;
    struct rt_audio_record     *record;
};

rt_err_t    rt_audio_register(struct rt_audio_device *audio, const char *name, rt_uint32_t flag, void *data);
void        rt_audio_tx_complete(struct rt_audio_device *audio);
void        rt_audio_rx_done(struct rt_audio_device *audio, rt_uint8_t *pbuf, rt_size_t len);

/* Device Control Commands */
#define CODEC_CMD_RESET             0
#define CODEC_CMD_SET_VOLUME        1
#define CODEC_CMD_GET_VOLUME        2
#define CODEC_CMD_SAMPLERATE        3
#define CODEC_CMD_EQ                4
#define CODEC_CMD_3D                5

#define CODEC_VOLUME_MAX            (63)

#endif /* __AUDIO_H__ */


text:
package org.apache.pig.backend.hadoop.accumulo;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Uses a fixed length array and will not grow in size dynamically like the
 * {@link java.io.ByteArrayOutputStream}.
 */
public class FixedByteArrayOutputStream extends OutputStream {

    private int i;
    byte out[];

    public FixedByteArrayOutputStream(byte out[]) {
        this.out = out;
    }

    @Override
    public void write(int b) throws IOException {
        out[i++] = (byte) b;
    }

    @Override
    public void write(byte b[], int off, int len) throws IOException {
        System.arraycopy(b, off, out, i, len);
        i += len;
    }

}


text:
package universalelectricity.api.core.grid;

/**
 * Any node that is part of a grid system such as a power network
 */
public interface IGridNode extends INode, IConnector
{
    /** Sets the grid reference */
    public void setGrid(IGrid grid);

    /** Gets the grid reference */
    public IGrid getGrid();
}


text: A tool for learning english words


text:
thread_local size_t CurrentDepth = 0;
thread_local size_t CurrentDepthLocal = 0;

void Timer::Start() {
  m_TID = GetCurrentThreadId();
  m_Depth = CurrentDepth++;
  m_SessionID = Message::GSessionID;
  m_Start = OrbitTicks();
}

void Timer::Stop() {
  m_End = OrbitTicks();
  --CurrentDepth;
}

ScopeTimer::ScopeTimer(const char* a_Name) { m_Timer.Start(); }

ScopeTimer::~ScopeTimer() { m_Timer.Stop(); }

LocalScopeTimer::LocalScopeTimer() : millis_(nullptr) { ++CurrentDepthLocal; }

LocalScopeTimer::LocalScopeTimer(double* millis) : millis_(millis) {
  ++CurrentDepthLocal;
  timer_.Start();
}

LocalScopeTimer::LocalScopeTimer(const std::string& message)
    : millis_(nullptr), message_(message) {
  std::string tabs;
  for (size_t i = 0; i < CurrentDepthLocal; ++i) {
    tabs += "  ";
  }
  PRINT(absl::StrFormat("%sStarting %s...\n", tabs.c_str(), message_.c_str()));

  ++CurrentDepthLocal;
  timer_.Start();
}

LocalScopeTimer::~LocalScopeTimer() {
  timer_.Stop();
  --CurrentDepthLocal;

  if (millis_ != nullptr) {
    *millis_ = timer_.ElapsedMillis();
  }

  if (!message_.empty()) {
    std::string tabs;
    for (size_t i = 0; i < CurrentDepthLocal; ++i) {
      tabs += "  ";
    }

    PRINT(absl::StrFormat("%s%s took %f ms.\n", tabs.c_str(), message_.c_str(),
                          timer_.ElapsedMillis()));
  }
}

void ConditionalScopeTimer::Start(const char* a_Name) {
  m_Timer.Start();
  m_Active = true;
}

ConditionalScopeTimer::~ConditionalScopeTimer() {
  if (m_Active) {
    m_Timer.Stop();
  }
}


text: console.log('just a simple javascript here nothin to see');


text:
package com.msh.room.dto.response;

import com.msh.room.dto.event.PlayerEventType;
import com.msh.room.dto.room.record.DaytimeRecord;
import com.msh.room.dto.room.record.NightRecord;
import com.msh.room.dto.room.record.SheriffRecord;
import com.msh.room.dto.room.seat.PlayerSeatInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangruiqian on 2017/5/3.
 */
public class PlayerDisplayInfo {
    private List<PlayerEventType> acceptableEventTypeList;

    private PlayerSeatInfo playerInfo;
    private List<PlayerSeatInfo> playerSeatInfoList;
    private NightRecord nightRecord;
    private DaytimeRecord daytimeRecord;
    private SheriffRecord sheriffRecord;

    private String gameResult;

    public PlayerDisplayInfo() {
    }

    public PlayerSeatInfo getPlayerInfo() {
        return playerInfo;
    }

    public void setPlayerInfo(PlayerSeatInfo playerInfo) {
        this.playerInfo = playerInfo;
    }

    public List<PlayerSeatInfo> getPlayerSeatInfoList() {
        return playerSeatInfoList;
    }

    public void setPlayerSeatInfoList(List<PlayerSeatInfo> playerSeatInfoList) {
        this.playerSeatInfoList = playerSeatInfoList;
    }

    public void addPlayerSeatInfo(PlayerSeatInfo seatInfo) {
        if (playerSeatInfoList == null) {
            playerSeatInfoList = new ArrayList<>();
        }
        playerSeatInfoList.add(seatInfo);
    }

    public List<PlayerEventType> getAcceptableEventTypeList() {
        return acceptableEventTypeList;
    }

    public void setAcceptableEventTypeList(List<PlayerEventType> acceptableEventTypeList) {
        this.acceptableEventTypeList = acceptableEventTypeList;
    }

    public void addAcceptableEventType(PlayerEventType type) {
        if (this.acceptableEventTypeList == null) {
            this.acceptableEventTypeList = new ArrayList<>();
        }
        acceptableEventTypeList.add(type);
    }

    public NightRecord getNightRecord() {
        return nightRecord;
    }

    public void setNightRecord(NightRecord nightRecord) {
        this.nightRecord = nightRecord;
    }

    public DaytimeRecord getDaytimeRecord() {
        return daytimeRecord;
    }

    public void setDaytimeRecord(DaytimeRecord daytimeRecord) {
        this.daytimeRecord = daytimeRecord;
    }

    public SheriffRecord getSheriffRecord() {
        return sheriffRecord;
    }

    public void setSheriffRecord(SheriffRecord sheriffRecord) {
        this.sheriffRecord = sheriffRecord;
    }

    public String getGameResult() {
        return gameResult;
    }

    public void setGameResult(String gameResult) {
        this.gameResult = gameResult;
    }
}


text:
using namespace std;

extern "C" {

	VirtualMachine *v;

	void createVirtualMachine() {
		if (v) {
			delete v;
		}
		v = new VirtualMachine;
	}

	void cosmos_run(int numFiles, const char **files, errorCallback onError, progressCallback onProgress, finishedCallback onFinish) {

		dispatch_queue_t queue = dispatch_queue_create("cosmos", NULL);

		dispatch_async(queue, ^{

			createVirtualMachine();

			vector<string> filePaths;
			for (int i = 0; i < numFiles; i++) {
				string s = string(files[i]);
				filePaths.push_back(s);
			}

			v->compileFiles(filePaths, ^(double progress, string fileName) {
				dispatch_async(dispatch_get_main_queue(), ^{
					onProgress(progress, fileName.c_str());
				});
			}, ^() {
				dispatch_async(dispatch_get_main_queue(), ^{
					onFinish();
					delete v;
				});
			});

		});
	}

}


text:
package org.apache.flink.yarn;

import org.apache.flink.util.OperatingSystem;
import org.apache.flink.util.TestLogger;

import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.apache.flink.yarn.YarnTestUtils.generateFilesInDirectory;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

/**
 * Tests for verifying file staging during submission to YARN works.
 */
public class YarnFileStageTest extends TestLogger {

	private static final String LOCAL_RESOURCE_DIRECTORY = "stage_test";

	@ClassRule
	public static final TemporaryFolder CLASS_TEMP_DIR = new TemporaryFolder();

	@Rule
	public TemporaryFolder tempFolder = new TemporaryFolder();

	private static MiniDFSCluster hdfsCluster;

	private static Path hdfsRootPath;

	private org.apache.hadoop.conf.Configuration hadoopConfig;

	// ------------------------------------------------------------------------
	//  Test setup and shutdown
	// ------------------------------------------------------------------------

	@BeforeClass
	public static void createHDFS() throws Exception {
		Assume.assumeTrue(!OperatingSystem.isWindows());

		final File tempDir = CLASS_TEMP_DIR.newFolder();

		org.apache.hadoop.conf.Configuration hdConf = new org.apache.hadoop.conf.Configuration();
		hdConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tempDir.getAbsolutePath());

		MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(hdConf);
		hdfsCluster = builder.build();
		hdfsRootPath = new Path(hdfsCluster.getURI());
	}

	@AfterClass
	public static void destroyHDFS() {
		if (hdfsCluster != null) {
			hdfsCluster.shutdown();
		}
		hdfsCluster = null;
		hdfsRootPath = null;
	}

	@Before
	public void initConfig() {
		hadoopConfig = new org.apache.hadoop.conf.Configuration();
		hadoopConfig.set(org.apache.hadoop.fs.FileSystem.FS_DEFAULT_NAME_KEY, hdfsRootPath.toString());
	}

	/**
	 * Verifies that nested directories are properly copied with a <tt>hdfs://</tt> file
	 * system (from a <tt>file:///absolute/path</tt> source path).
	 */
	@Test
	public void testCopyFromLocalRecursiveWithScheme() throws Exception {
		final FileSystem targetFileSystem = hdfsRootPath.getFileSystem(hadoopConfig);
		final Path targetDir = targetFileSystem.getWorkingDirectory();

		testRegisterMultipleLocalResources(targetFileSystem, targetDir, LOCAL_RESOURCE_DIRECTORY, tempFolder, true, false);
	}

	/**
	 * Verifies that nested directories are properly copied with a <tt>hdfs://</tt> file
	 * system (from a <tt>/absolute/path</tt> source path).
	 */
	@Test
	public void testCopyFromLocalRecursiveWithoutScheme() throws Exception {
		final FileSystem targetFileSystem = hdfsRootPath.getFileSystem(hadoopConfig);
		final Path targetDir = targetFileSystem.getWorkingDirectory();

		testRegisterMultipleLocalResources(targetFileSystem, targetDir, LOCAL_RESOURCE_DIRECTORY, tempFolder, false, false);
	}

	/**
	 * Verifies that a single file is properly copied.
	 */
	@Test
	public void testCopySingleFileFromLocal() throws IOException, URISyntaxException, InterruptedException {
		final FileSystem targetFileSystem = hdfsRootPath.getFileSystem(hadoopConfig);
		final Path targetDir = targetFileSystem.getWorkingDirectory();

		testCopySingleFileFromLocal(targetFileSystem, targetDir, LOCAL_RESOURCE_DIRECTORY, tempFolder);
	}

	@Test
	public void testRegisterMultipleLocalResourcesWithRemoteFiles() throws Exception {
		final FileSystem targetFileSystem = hdfsRootPath.getFileSystem(hadoopConfig);
		final Path targetDir = targetFileSystem.getWorkingDirectory();

		testRegisterMultipleLocalResources(targetFileSystem, targetDir, LOCAL_RESOURCE_DIRECTORY, tempFolder, true, true);
	}

	/**
	 * Verifies that nested directories are properly copied and registered with the given filesystem and paths.
	 *
	 * @param targetFileSystem
	 * 		file system of the target path
	 * @param targetDir
	 * 		target path (URI like <tt>hdfs://...</tt>)
	 * @param localResourceDirectory
	 * 		the directory that localResource are uploaded to
	 * @param tempFolder
	 * 		JUnit temporary folder rule to create the source directory with
	 * @param addSchemeToLocalPath
	 * 		whether add the <tt>file://</tt> scheme to the local path to copy from
	 * @param useRemoteFiles
	 *      whether register the local resource with remote files
	 */
	static void testRegisterMultipleLocalResources(
			FileSystem targetFileSystem,
			Path targetDir,
			String localResourceDirectory,
			TemporaryFolder tempFolder,
			boolean addSchemeToLocalPath,
			boolean useRemoteFiles) throws Exception {

		// directory must not yet exist
		assertFalse(targetFileSystem.exists(targetDir));

		final File srcDir = tempFolder.newFolder();

		final HashMap<String /* (relative) path */, /* contents */ String> srcFiles = new HashMap<>(4);

		// create and fill source files
		srcFiles.put("1", "Hello 1");
		srcFiles.put("2", "Hello 2");
		srcFiles.put("nested/3", "Hello nested/3");
		srcFiles.put("nested/4/5", "Hello nested/4/5");
		srcFiles.put("test.jar", "JAR Content");

		generateFilesInDirectory(srcDir, srcFiles);

		final Path srcPath;
		if (useRemoteFiles) {
			srcPath = new Path(hdfsRootPath.toString() + "/tmp/remoteFiles");
			hdfsCluster.getFileSystem().copyFromLocalFile(new Path(srcDir.getAbsolutePath()), srcPath);
		} else {
			if (addSchemeToLocalPath) {
				srcPath = new Path("file://" + srcDir.getAbsolutePath());
			} else {
				srcPath = new Path(srcDir.getAbsolutePath());
			}
		}

		// copy the created directory recursively:
		try {
			final List<Path> remotePaths = new ArrayList<>();

			final ApplicationId applicationId = ApplicationId.newInstance(0, 0);
			final YarnApplicationFileUploader uploader = YarnApplicationFileUploader.from(
				targetFileSystem,
				targetDir,
				Collections.emptyList(),
				applicationId,
				DFSConfigKeys.DFS_REPLICATION_DEFAULT);

			final List<String> classpath = uploader.registerMultipleLocalResources(
				Collections.singletonList(srcPath),
				localResourceDirectory,
				LocalResourceType.FILE);

			final Path basePath = new Path(localResourceDirectory, srcPath.getName());
			final Path nestedPath = new Path(basePath, "nested");
			assertThat(
				classpath,
				containsInAnyOrder(
					basePath.toString(),
					nestedPath.toString(),
					new Path(nestedPath, "4").toString(),
					new Path(basePath, "test.jar").toString()));

			final Map<String, LocalResource> localResources = uploader.getRegisteredLocalResources();
			assertEquals(srcFiles.size(), localResources.size());

			final Path workDir = ConverterUtils
				.getPathFromYarnURL(
					localResources.get(new Path(localResourceDirectory, new Path(srcPath.getName(), "1")).toString())
						.getResource()).getParent();

			verifyDirectoryRecursive(targetFileSystem, workDir, srcFiles);

		} finally {
			// clean up
			targetFileSystem.delete(targetDir, true);
		}
	}

	/**
	 * Verifies a single file is properly uploaded.
	 * @param targetFileSystem file system of the target path
	 * @param targetDir target path (URI like <tt>hdfs://...</tt>)
	 * @param localResourceDirectory the directory that localResource are uploaded to
	 * @param temporaryFolder JUnit temporary folder rule to create the source directory with
	 * @throws IOException if error occurs when accessing the file system
	 * @throws URISyntaxException if the format of url has errors when converting a given url to hadoop path
	 */
	private static void testCopySingleFileFromLocal(
		FileSystem targetFileSystem,
		Path targetDir,
		String localResourceDirectory,
		TemporaryFolder temporaryFolder) throws IOException, InterruptedException, URISyntaxException {

		final File srcDir = temporaryFolder.newFolder();

		final String localFile = "local.jar";
		final String localFileContent = "Local Jar Content";

		final HashMap<String /* (relative) path */, /* contents */ String> srcFiles = new HashMap<>(4);
		srcFiles.put(localFile, localFileContent);

		generateFilesInDirectory(srcDir, srcFiles);
		try {
			final List<Path> remotePaths = new ArrayList<>();

			final ApplicationId applicationId = ApplicationId.newInstance(0, 0);
			final YarnApplicationFileUploader uploader = YarnApplicationFileUploader.from(
				targetFileSystem,
				targetDir,
				Collections.emptyList(),
				applicationId,
				DFSConfigKeys.DFS_REPLICATION_DEFAULT);

			final List<String> classpath = uploader.registerMultipleLocalResources(
				Collections.singletonList(new Path(srcDir.getAbsolutePath(), localFile)),
				localResourceDirectory,
				LocalResourceType.FILE);

			assertThat(classpath, containsInAnyOrder(new Path(localResourceDirectory, localFile).toString()));

			final Map<String, LocalResource> localResources = uploader.getRegisteredLocalResources();
			final Path workDir = ConverterUtils.getPathFromYarnURL(
				localResources.get(new Path(localResourceDirectory, localFile).toString()).getResource()).getParent();
			verifyDirectoryRecursive(targetFileSystem, workDir, srcFiles);
		} finally {
			targetFileSystem.delete(targetDir, true);
		}
	}

	/**
	 * Verifies the content and name of file in the directory {@code worDir} are same with {@code expectedFiles}.
	 * @param targetFileSystem the filesystem type of {@code workDir}
	 * @param workDir the directory verified
	 * @param expectedFiles the expected name and content of the files
	 * @throws IOException if error occurs when visiting the {@code workDir}
	 * @throws InterruptedException if the sleep is interrupted.
	 */
	private static void verifyDirectoryRecursive(
		FileSystem targetFileSystem,
		Path workDir,
		Map<String, String> expectedFiles)
		throws IOException, InterruptedException {

		final HashMap<String /* (relative) path */, /* contents */ String> targetFiles =
			new HashMap<>();
		final RemoteIterator<LocatedFileStatus> targetFilesIterator =
			targetFileSystem.listFiles(workDir, true);
		final int workDirPrefixLength =
			workDir.toString().length() + 1; // one more for the concluding "/"
		while (targetFilesIterator.hasNext()) {
			final LocatedFileStatus targetFile = targetFilesIterator.next();

			int retries = 5;
			do {
				try (FSDataInputStream in = targetFileSystem.open(targetFile.getPath())) {
					String absolutePathString = targetFile.getPath().toString();
					String relativePath = absolutePathString.substring(workDirPrefixLength);
					targetFiles.put(relativePath, in.readUTF());

					assertEquals("extraneous data in file " + relativePath, -1, in.read());
					break;
				} catch (FileNotFoundException e) {
					// For S3, read-after-write may be eventually consistent, i.e. when trying
					// to access the object before writing it; see
					// https://docs.aws.amazon.com/AmazonS3/latest/dev/Introduction.html#ConsistencyModel
					// -> try again a bit later
					Thread.sleep(50);
				}
			} while ((retries--) > 0);
		}
		assertThat(targetFiles, equalTo(expectedFiles));
	}
}


text:
package cn.neil.bean;

/**
 * 为满足要求的显示格式,新建该类,并将Doc转化成该类,然后json化,打印
 *
 * @author Neil
 *
 */
public class SimplifiedDoc {
	private String title;
	private String anchorman;
	private String info;
	private int totalPlayCount;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAnchorman() {
		return anchorman;
	}

	public void setAnchorman(String anchorman) {
		this.anchorman = anchorman;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}

	public int getTotalPlayCount() {
		return totalPlayCount;
	}

	public void setTotalPlayCount(int totalPlayCount) {
		this.totalPlayCount = totalPlayCount;
	}

	/**
	 * 将Doc类进行简化
	 *
	 * @param doc
	 *            doc类对象
	 * @return 简化的SimplifiedDoc对象
	 */
	public static SimplifiedDoc simplify(Doc doc) {
		if (doc == null)
			return null;
		SimplifiedDoc result = new SimplifiedDoc();
		result.setAnchorman(doc.getNickname());
		result.setTotalPlayCount(doc.getPlay());
		result.setInfo(doc.getIntro());
		result.setTitle(doc.getTitle());
		return result;
	}
}


text:
#ifndef TENSORFLOW_LITE_DELEGATES_GPU_COMMON_TASKS_SPECIAL_THIN_POINTWISE_FUSER_H_
#define TENSORFLOW_LITE_DELEGATES_GPU_COMMON_TASKS_SPECIAL_THIN_POINTWISE_FUSER_H_

#include <map>
#include <set>
#include <string>
#include <vector>

#include "tensorflow/lite/delegates/gpu/common/model.h"
#include "tensorflow/lite/delegates/gpu/common/precision.h"
#include "tensorflow/lite/delegates/gpu/common/selectors/subgraph.h"
#include "tensorflow/lite/delegates/gpu/common/task/tensor_desc.h"

namespace tflite {
namespace gpu {

absl::Status TryThinPointwiseFuser(
    const GpuInfo& gpu_info, CalculationsPrecision precision,
    const GraphFloat32& graph, NodeId first_node_id,
    const std::map<ValueId, TensorDescriptor>& tensor_descriptors,
    std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph);

}  // namespace gpu
}  // namespace tflite

#endif  // TENSORFLOW_LITE_DELEGATES_GPU_COMMON_TASKS_SPECIAL_THIN_POINTWISE_FUSER_H_


text:
@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    imagePicker = [[UIImagePickerController alloc] init];

    // initialize
    NSString *API_KEY = _API_KEY;
    NSString *API_SECRET = _API_SECRET;

    [FaceppAPI initWithApiKey:API_KEY andApiSecret:API_SECRET andRegion:APIServerRegionCN];

    // turn on the debug mode
    [FaceppAPI setDebugMode:TRUE];
}

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

-(IBAction)pickFromCameraButtonPressed:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:imagePicker animated:YES];
    } else {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"failed to camera"
                              message:@""
                              delegate:nil
                              cancelButtonTitle:@"OK!"
                              otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
        [alert release];
    }
}

-(IBAction)pickFromLibraryButtonPressed:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:imagePicker animated:YES];
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"failed to access photo library"
                              message:@""
                              delegate:nil
                              cancelButtonTitle:@"OK!"
                              otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
        [alert release];
    }
}

- (UIImage *)fixOrientation:(UIImage *)aImage {

    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }

    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

// Use facepp SDK to detect faces
-(void) detectWithImage: (UIImage*) image {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    FaceppResult *result = [[FaceppAPI detection] detectWithURL:nil orImageData:UIImageJPEGRepresentation(image, 1) mode:FaceppDetectionModeNormal attribute:FaceppDetectionAttributeNone];
    if (result.success) {
        double image_width = [[result content][@"img_width"] doubleValue] *0.01f;
        double image_height = [[result content][@"img_height"] doubleValue] * 0.01f;

        UIGraphicsBeginImageContext(image.size);
        [image drawAtPoint:CGPointZero];
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(context, 0, 0, 1.0, 1.0);
        CGContextSetLineWidth(context, image_width * 0.7f);

        // draw rectangle in the image
        int face_count = [[result content][@"face"] count];
        for (int i=0; i<face_count; i++) {
            double width = [[result content][@"face"][i][@"position"][@"width"] doubleValue];
            double height = [[result content][@"face"][i][@"position"][@"height"] doubleValue];
            CGRect rect = CGRectMake(([[result content][@"face"][i][@"position"][@"center"][@"x"] doubleValue] - width/2) * image_width,
                                     ([[result content][@"face"][i][@"position"][@"center"][@"y"] doubleValue] - height/2) * image_height,
                                     width * image_width,
                                     height * image_height);
            CGContextStrokeRect(context, rect);
        }

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        float scale = 1.0f;
        scale = MIN(scale, 280.0f/newImage.size.width);
        scale = MIN(scale, 257.0f/newImage.size.height);
        [imageView setFrame:CGRectMake(imageView.frame.origin.x,
                                       imageView.frame.origin.y,
                                       newImage.size.width * scale,
                                       newImage.size.height * scale)];
        [imageView setImage:newImage];
    } else {
        // some errors occurred
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:[NSString stringWithFormat:@"error message: %@", [result error].message]
                              message:@""
                              delegate:nil
                              cancelButtonTitle:@"OK!"
                              otherButtonTitles:nil];
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
        [alert release];
    }
    [image release];
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    [pool release];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    UIImage *sourceImage = info[UIImagePickerControllerOriginalImage];
    UIImage *imageToDisplay = [self fixOrientation:sourceImage];

    // perform detection in background thread
    [self performSelectorInBackground:@selector(detectWithImage:) withObject:[imageToDisplay retain]];

    [picker dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

-(void) dealloc {
    [imagePicker release];
    [super dealloc];
}
@end


text:
if __name__ == '__main__':
    import os
    import sys
    manage_file = os.path.join(sys.path[0], 'manage.py')
    command = '%s runserver' % manage_file
    os.system(command)


text:
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package json2

type ErrorCode int

const (
	E_PARSE       ErrorCode = -32700
	E_INVALID_REQ ErrorCode = -32600
	E_NO_METHOD   ErrorCode = -32601
	E_BAD_PARAMS  ErrorCode = -32602
	E_INTERNAL    ErrorCode = -32603
	E_SERVER      ErrorCode = -32000
)

type Error struct {
	// A Number that indicates the error type that occurred.
	Code ErrorCode `json:"code"` /* required */

	// A String providing a short description of the error.
	// The message SHOULD be limited to a concise single sentence.
	Message string `json:"message"` /* required */

	// A Primitive or Structured value that contains additional information about the error.
	Data interface{} `json:"data"` /* optional */
}

func (e *Error) Error() string {
	return e.Message
}


text:
package org.tsd.avwx.api;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Units implements Serializable {

    @JsonProperty(value = "Altimeter")
    private String altimeterUnits;

    @JsonProperty(value = "Altitude")
    private String altimterUnits;

    @JsonProperty(value = "Temperature")
    private String temperatureUnits;

    @JsonProperty(value = "Visibility")
    private String visibilityUnits;

    @JsonProperty(value = "Wind-Speed")
    private String windSpeed;

    public String getAltimeterUnits() {
        return altimeterUnits;
    }

    public void setAltimeterUnits(String altimeterUnits) {
        this.altimeterUnits = altimeterUnits;
    }

    public String getTemperatureUnits() {
        return temperatureUnits;
    }

    public void setTemperatureUnits(String temperatureUnits) {
        this.temperatureUnits = temperatureUnits;
    }

    public String getVisibilityUnits() {
        return visibilityUnits;
    }

    public void setVisibilityUnits(String visibilityUnits) {
        this.visibilityUnits = visibilityUnits;
    }

    public String getWindSpeed() {
        return windSpeed;
    }

    public void setWindSpeed(String windSpeed) {
        this.windSpeed = windSpeed;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("altimeterUnits", altimeterUnits)
                .append("altimterUnits", altimterUnits)
                .append("temperatureUnits", temperatureUnits)
                .append("visibilityUnits", visibilityUnits)
                .append("windSpeed", windSpeed)
                .toString();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>SelectDataViewBox</title>


text:
#include "squid.h"
#include "helper.h"
#include "mgr/Registration.h"
#include "SquidConfig.h"
#include "SquidTime.h"
#include "Store.h"
#include "wordlist.h"

#if SQUID_SNMP
#include "snmp_core.h"
#endif

/* MS VisualStudio Projects are monolitich, so we need the following
   #if to include the external DNS code in compile process when
   using external DNS.
 */
#if USE_DNSHELPER

static helper *dnsservers = NULL;

static void
dnsStats(StoreEntry * sentry)
{
    storeAppendPrintf(sentry, "Dnsserver Statistics:\n");
    helperStats(sentry, dnsservers);
}

static void
dnsRegisterWithCacheManager(void)
{
    Mgr::RegisterAction("dns", "Dnsserver Statistics", dnsStats, 0, 1);
}

void
dnsInit(void)
{
    wordlist *w;

    dnsRegisterWithCacheManager();

    if (!Config.Program.dnsserver)
        return;

    if (dnsservers == NULL)
        dnsservers = new helper("dnsserver");

    dnsservers->childs.updateLimits(Config.dnsChildren);

    dnsservers->ipc_type = IPC_STREAM;

    assert(dnsservers->cmdline == NULL);

    wordlistAdd(&dnsservers->cmdline, Config.Program.dnsserver);

    if (Config.onoff.res_defnames)
        wordlistAdd(&dnsservers->cmdline, "-D");

    for (w = Config.dns_nameservers; w != NULL; w = w->next) {
        wordlistAdd(&dnsservers->cmdline, "-s");
        wordlistAdd(&dnsservers->cmdline, w->key);
    }

    helperOpenServers(dnsservers);
}

void
dnsShutdown(void)
{
    if (!dnsservers)
        return;

    helperShutdown(dnsservers);

    wordlistDestroy(&dnsservers->cmdline);

    if (!shutting_down)
        return;

    delete dnsservers;
    dnsservers = NULL;
}

void
dnsSubmit(const char *lookup, HLPCB * callback, void *data)
{
    char buf[256];
    static time_t first_warn = 0;
    snprintf(buf, 256, "%s\n", lookup);

    if (dnsservers->stats.queue_size >= (int)dnsservers->childs.n_active && dnsservers->childs.needNew() > 0) {
        helperOpenServers(dnsservers);
    }

    if (dnsservers->stats.queue_size >= (int)(dnsservers->childs.n_running * 2)) {
        if (first_warn == 0)
            first_warn = squid_curtime;

        if (squid_curtime - first_warn > 3 * 60)
            fatal("DNS servers not responding for 3 minutes");

        debugs(34, DBG_IMPORTANT, "dnsSubmit: queue overload, rejecting " << lookup);

        callback(data, (char *)"$fail Temporary network problem, please retry later");

        return;
    }

    first_warn = 0;
    helperSubmit(dnsservers, buf, callback, data);
}

#if SQUID_SNMP
/*
 * The function to return the DNS via SNMP
 */
variable_list *
snmp_netDnsFn(variable_list * Var, snint * ErrP)
{
    variable_list *Answer = NULL;
    MemBuf tmp;
    debugs(49, 5, "snmp_netDnsFn: Processing request: " << Var->name[LEN_SQ_NET + 1] << " " << snmpDebugOid(Var->name, Var->name_length, tmp));
    *ErrP = SNMP_ERR_NOERROR;

    switch (Var->name[LEN_SQ_NET + 1]) {

    case DNS_REQ:
        Answer = snmp_var_new_integer(Var->name, Var->name_length,
                                      dnsservers->stats.requests,
                                      SMI_COUNTER32);
        break;

    case DNS_REP:
        Answer = snmp_var_new_integer(Var->name, Var->name_length,
                                      dnsservers->stats.replies,
                                      SMI_COUNTER32);
        break;

    case DNS_SERVERS:
        Answer = snmp_var_new_integer(Var->name, Var->name_length,
                                      dnsservers->childs.n_running,
                                      SMI_COUNTER32);
        break;

    default:
        *ErrP = SNMP_ERR_NOSUCHNAME;
        break;
    }

    return Answer;
}

#endif /* SQUID_SNMP */
#endif /* USE_DNSHELPER */


text:
CURRENT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# shellcheck source=scripts/helpers.sh
source "$CURRENT_DIR/helpers.sh"

# script global variables
gpu_low_icon=""
gpu_medium_icon=""
gpu_high_icon=""

gpu_low_default_icon="="
gpu_medium_default_icon="≡"
gpu_high_default_icon="≣"

# icons are set as script global variables
get_icon_settings() {
  gpu_low_icon=$(get_tmux_option "@gpu_low_icon" "$gpu_low_default_icon")
  gpu_medium_icon=$(get_tmux_option "@gpu_medium_icon" "$gpu_medium_default_icon")
  gpu_high_icon=$(get_tmux_option "@gpu_high_icon" "$gpu_high_default_icon")
}

print_icon() {
  local gpu_percentage
  local gpu_load_status
  gpu_percentage=$("$CURRENT_DIR"/gpu_percentage.sh | sed -e 's/%//')
  gpu_load_status=$(load_status "$gpu_percentage" "gpu")
  if [ "$gpu_load_status" == "low" ]; then
    echo "$gpu_low_icon"
  elif [ "$gpu_load_status" == "medium" ]; then
    echo "$gpu_medium_icon"
  elif [ "$gpu_load_status" == "high" ]; then
    echo "$gpu_high_icon"
  fi
}

main() {
  get_icon_settings
  print_icon "$1"
}
main "$@"


text: {{ page.content }}