text:
<?php
namespace Skalda\TestLinkAPI;

use Skalda\TestLinkAPI\Entities\Attachment;
use Skalda\TestLinkAPI\Entities\BaseEntity;
use Skalda\TestLinkAPI\Entities\Build;
use Skalda\TestLinkAPI\Entities\Keyword;
use Skalda\TestLinkAPI\Entities\TestPlan;
use Skalda\TestLinkAPI\Entities\PlanTestCase;
use Skalda\TestLinkAPI\Entities\Platform;
use Skalda\TestLinkAPI\Entities\TestProject;
use Skalda\TestLinkAPI\Entities\Step;
use Skalda\TestLinkAPI\Entities\TestCase;
use Skalda\TestLinkAPI\Entities\PlanTestCaseExecution;
use Skalda\TestLinkAPI\Entities\PlanTestCaseInstance;
use Skalda\TestLinkAPI\Entities\TestSuite;
use Skalda\TestLinkAPI\Entities\User;
use IXR\Client as XMLRPC;

class Client
{
	private $serverURL = null;

	/** @var XMLRPC\Client */
	private $client = null;

	private $apiKey = null;

	/**
	 * Client constructor.
	 * @param string $serverUrl
	 */
	public function __construct($serverUrl)
	{
		$this->client;
		$this->serverURL = $serverUrl;
	}

	/**
	 * Sets API key for current user
	 * @param string $apiKey
	 */
	public function setAPIKey($apiKey)
	{
		$this->apiKey = $apiKey;
	}

	/**
	 * Check connectivity to TestLink API
	 * @return bool
	 */
	public function checkConnectivity()
	{
		try {
			return $this->_makeCall('tl.ping') === 'Hello!';
		} catch (TestLinkAPIException $e) {
			return false;
		}
	}

	/**
	 * Check extensions
	 * @return bool
	 */
	public function checkExtensions()
	{
		try {
			return $this->_makeCall('tl.isExtended');
		} catch (TestLinkAPIException $e) {
			return false;
		}
	}

	/**
	 * Check if $apiKey is valid
	 * @param $apiKey
	 * @return bool
	 */
	public function checkApiKey($apiKey)
	{
		try {
			$response = $this->_makeCall('tl.checkDevKey', ['devKey' => $apiKey]);
		} catch (TestLinkAPIException $e) {
			return false;
		}

		return $response;
	}

	/**
	 * Gets TestLink version
	 * @return string
	 */
	public function getTestLinkVersion()
	{
		return $this->_makeCall('tl.testLinkVersion');
	}

	/**
	 * Gets information about API
	 * @return string
	 */
	public function getAboutApi()
	{
		return $this->_makeCall('tl.about');
	}

	/**
	 * @return TestProject[]
	 */
	public function getProjects()
	{
		$response = $this->_makeSignCall('tl.getProjects');
		$results = [];
		if(is_array($response)) {
			foreach ($response as $project) {
				$results[] = TestProject::createFromArray($this, $project);
			}
		}

		return $results;
	}

	/**
	 * @param $id
	 * @return TestProject|boolean
	 */
	public function getProjectById($id)
	{
		$response = $this->_makeSignCall('tl.getProjectById', ['testprojectid' => $id]);
		if(is_array($response)) {
			return TestProject::createFromArray($this, $response);
		}
		return false;
	}

	/**
	 * @param $id
	 * @return TestPlan[]
	 */
	public function getPlansByProject(TestProject $project)
	{
		$response = $this->_makeSignCall('tl.getProjectTestPlans', ['testprojectid' => $project->id]);
		$results = [];
		if(is_array($response)) {
			foreach ($response as $testPlan) {
				$plan = TestPlan::createFromArray($this, $testPlan);
				$plan->setTestProject($project);
				$results[] = $plan;
			}
		}
		return $results;
	}

	/**
	 * @param $id
	 * @return TestPlan|boolean
	 */
	public function getPlanById($id)
	{
		$response = $this->_makeSignCall('tl.getTestPlanById', ['testplanid' => $id]);
		if(is_array($response)) {
			return TestPlan::createFromArray($this, $response);
		}
		return false;
	}

	/**
	 * @param TestPlan $plan
	 * @return Build[]
	 */
	public function getBuildsByPlan(TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getBuildsForTestPlan', ['testplanid' => $plan->id]);

		$results = [];
		if(is_array($response)) {
			foreach ($response as $build) {
				$build = Build::createFromArray($this, $build);
				$build->setTestPlan($plan);
				$results[] = $build;
			}
		}
		return $results;
	}

	/**
	 * @param $id
	 * @param TestPlan $plan
	 * @return Build|bool
	 */
	public function getBuildById($id, TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getBuildById', ['testplanid' => $plan->id, 'buildid' => $id]);
		if(is_array($response)) {
			$build = Build::createFromArray($this, $response);
			$build->setTestPlan($plan);
			return $build;
		}

		return false;
	}

	/**
	 * @param TestPlan $plan
	 * @return Platform[]
	 */
	public function getPlatformsByPlan(TestPlan $plan)
	{
		try {
			$response = $this->_makeSignCall('tl.getTestPlanPlatforms', ['testplanid' => $plan->id]);

			$results = [];
			if(is_array($response)) {
				foreach ($response as $plat) {
					$platform = Platform::createFromArray($this, $plat);
					$platform->setTestPlan($plan);
					$results[] = $platform;
				}
			}
			return $results;
		} catch (TestLinkAPIException $e) {
			if($e->getCode() == 3041) {
				return [];
			}
		}
	}

	/**
	 * @param TestPlan $plan
	 * @return mixed
	 */
	public function getExecPerBuildByPlan(TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getExecCountersByBuild', ['testplanid' => $plan->id]);

		return $response;
	}

	/**
	 * @param TestPlan $plan
	 * @param bool $withPath
	 * @param Build|null $build
	 * @param Platform|null $platform
	 * @return PlanTestCase[]
	 */
	public function getPlanTestCasesBy(TestPlan $plan, $withPath = true, Build $build = null, Platform $platform = null)
	{
		if(!$build) {
			$build = $this->getLatestBuildByPlan($plan);
		}
		$args = [
			'testplanid' => $plan->id,
			'getstepsinfo' => true,
		];
		if($build) {
			$args['buildid'] = $build->id;
		}

		if($platform) {
			$args['platformid'] = $platform->id;
		}

		$response = $this->_makeSignCall('tl.getTestCasesForTestPlan', $args);
		$results = [];

		if(is_array($response)) {
			foreach ($response as $testCase) {
				$results[] = new PlanTestCase($this, $plan, $build, $testCase);
			}

			if ($withPath) {
				$results = $this->getAllFullPath($results);
			}
		}

		return $results;
	}

	/**
	 * @param int $testCaseId
	 * @return TestCase|bool
	 */
	public function getTestCaseById($testCaseId)
	{
		$args = [
			'testcaseid' => $testCaseId,
		];
		$response = $this->_makeSignCall('tl.getTestCase', $args);

		if(is_array($response) && isset($response[0])) {
			return TestCase::createFromArray($this, $response[0]);
		} else {
			return false;
		}
	}

	/**
	 * @param PlanTestCase $testCase
	 * @return TestCase|bool
	 */
	public function getTestCaseByPlanTestCase(PlanTestCase $testCase)
	{
		$args = [
			'testcaseid' => $testCase->id,
			'version' => (int)$testCase->version,
		];

		$response = $this->_makeSignCall('tl.getTestCase', $args);

		if(is_array($response) && isset($response[0])) {
			return TestCase::createFromArray($this, $response[0]);
		} else {
			return false;
		}
	}

	/**
	 * @param PlanTestCaseInstance $testCaseInstance
	 * @return PlanTestCaseExecution|bool
	 */
	public function getLastExecutionByTestCaseInstance(PlanTestCaseInstance $testCaseInstance)
	{
		if($testCaseInstance->getBuild()) {
			$args = [
				'testcaseid' => $testCaseInstance->getTestCase()->id,
				'testplanid' => $testCaseInstance->getTestCase()->getTestPlan()->id,
				'buildid' => $testCaseInstance->getBuild()->id,
			];

			if ($testCaseInstance->getPlatform()) {
				$args['platformid'] = $testCaseInstance->getPlatform()->id;
			}

			$response = $this->_makeSignCall('tl.getLastExecutionResult', $args);

			if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
				$result = PlanTestCaseExecution::createFromArray($this, $response[0]);
				$result->setTestCaseInstance($testCaseInstance);
				return $result;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	/**
	 * @param BaseEntity[] $entities
	 * @return array
	 */
	public function getAllFullPath(array $entities)
	{
		$query = [];
		foreach($entities as $entity) {
			$query[] = (int) $entity->id;
		}
		$response = $this->_makeSignCall('tl.getFullPath', ['nodeid' => $query]);
		foreach($entities as $entity) {
			if(isset($response[$entity->id])) {
				$entity->setFullPath($response[$entity->id]);
			}
		}

		return $entities;
	}

	/**
	 * @param TestPlan $plan
	 * @return Build
	 */
	public function getLatestBuildByPlan(TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getLatestBuildForTestPlan', ['testplanid' => $plan->id]);
		$result = Build::createFromArray($this, $response);
		$result->setTestPlan($plan);

		return $result;
	}

	/**
	 * @param TestPlan $plan
	 * @param string $name
	 * @param string $notes
	 * @param bool $active
	 * @param bool $open
	 * @param string $releaseDate
	 * @return int|bool
	 */
	public function createBuild(TestPlan $plan, $name, $notes, $active, $open, $releaseDate)
	{
		$args = [
			'testplanid' => $plan->id,
			'buildname' => $name,
			'buildnotes' => $notes,
			'active' => $active,
			'open' => $open,
			'releasedate' => $releaseDate,
		];
		$response = $this->_makeSignCall('tl.createBuild', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestPlan $plan
	 * @return TestSuite[]
	 */
	public function getTestSuitesByPlan(TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getTestSuitesForTestPlan', ['testplanid' => $plan->id]);

		$results = [];

		if(is_array($response)) {
			foreach ($response as $testSuite) {
				$testSuite = TestSuite::createFromArray($this, $testSuite);
				$results[] = $testSuite;
			}
		}
		return $results;
	}

	/**
	 * @param string $name
	 * @param string $prefix
	 * @param string $notes
	 * @param bool $active
	 * @param bool $public
	 * @param bool $optionRequirements
	 * @param bool $optionTestPriority
	 * @param bool $optionAutomation
	 * @param bool $optionInventory
	 * @return int|bool
	 */
	public function createTestProject($name, $prefix, $notes, $active = true, $public = true, $optionRequirements = true, $optionTestPriority = true, $optionAutomation = true, $optionInventory = true)
	{
		$args = [
			'testprojectname' => $name,
			'testcaseprefix' => $prefix,
			'notes' => $notes,
			'active' => $active,
			'public' => $public,
			'options' => [
				'requirementsEnabled' => $optionRequirements,
				'testPriorityEnabled' => $optionTestPriority,
				'automationEnabled' => $optionAutomation,
				'inventoryEnabled' => $optionInventory,
			]
		];
		$response = $this->_makeSignCall('tl.createTestProject', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestSuite $testSuite
	 * @param bool $deep
	 * @param bool $keywords
	 * @return TestCase[]
	 */
	public function getTestCasesByTestSuite(TestSuite $testSuite, $deep = true, $keywords = false)
	{
		$args = [
			'testsuiteid' => $testSuite->id,
			'deep' => $deep,
			'details' => 'full',
			'keywords' => $keywords,
		];

		$response = $this->_makeSignCall('tl.getTestCasesForTestSuite', $args);

		$results = [];

		if(is_array($response)) {
			foreach ($response as $tc) {
				$testCase = TestCase::createFromArray($this, $tc);
				$results[] = $testCase;
			}
		}
		return $results;

	}

	/**
	 * @param TestProject $project
	 * @param TestSuite $testSuite
	 * @param User $user
	 * @param $name
	 * @param $summary
	 * @param array $steps
	 * @param $preconditions
	 * @return int|bool
	 */
	public function createTestCase(TestProject $project, TestSuite $testSuite, User $user, $name, $summary, array $steps, $preconditions)
	{
		$args = [
			'testcasename' => $name,
			'testsuiteid' => $testSuite->id,
			'testprojectid' => $project->id,
			'summary' => $summary,
			'preconditions' => $preconditions,
			'authorlogin' => $user->login,
		];

		foreach($steps as $step) {
			$args['steps'][] = [
				'step_number' => $step->step_number,
				'actions' => $step->actions,
				'expected_results' => $step->expected_results,
				'execution_type' => $step->execution_type,
			];
		}

		$response = $this->_makeSignCall('tl.createTestCase', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestProject $project
	 * @return TestSuite[]
	 */
	public function getFirstLevelTestSuitesByProject(TestProject $project)
	{
		$response = $this->_makeSignCall('tl.getFirstLevelTestSuitesForTestProject', ['testprojectid' => $project->id]);

		$results = [];

		if(is_array($response)) {
			foreach ($response as $ts) {
				$testSuite = TestSuite::createFromArray($this, $ts);
				$results[] = $testSuite;
			}
		}
		return $results;

	}

	/**
	 * @param TestCase $testCase
	 * @return Attachment[]
	 */
	public function getAttachmentsByTestCase(TestCase $testCase)
	{
		$response = $this->_makeSignCall('tl.getTestCaseAttachments', ['testcaseid' => $testCase->testcase_id]);

		$results = [];

		if(is_array($response)) {
			foreach ($response as $attach) {
				$attachment = Attachment::createFromArray($this, $attach);
				$results[] = $attachment;
			}
		}
		return $results;

	}

	/**
	 * @param TestProject $project
	 * @param TestSuite $testSuite
	 * @param $name
	 * @param $details
	 * @param TestSuite|null $parent
	 * @return int|bool
	 */
	public function updateTestSuite(TestProject $project, TestSuite $testSuite, $name, $details, TestSuite $parent = null)
	{
		$args = [
			'testsuiteid' => $testSuite->id,
			'testprojectid' => $project->id,
			'testsuitename' => $name,
			'details' => $details,
		];

		if($parent) {
			$args['parentid'] = $parent->id;
		}

		$response = $this->_makeSignCall('tl.updateTestSuite', $args);

		if (is_array($response) && isset($response[0]) && isset($response[0]['status'])) {
			return $response[0]['status'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestProject $project
	 * @param string $name
	 * @param string $details
	 * @param TestSuite|null $parent
	 * @return int|bool
	 */
	public function createTestSuite(TestProject $project, $name, $details, TestSuite $parent = null)
	{
		$args = [
			'testprojectid' => $project->id,
			'testsuitename' => $name,
			'details' => $details,
		];

		if($parent) {
			$args['parentid'] = $parent->id;
		}

		$response = $this->_makeSignCall('tl.createTestSuite', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestProject $project
	 * @param string $name
	 * @param string $notes
	 * @param bool $active
	 * @param bool $public
	 * @return int|bool
	 */
	public function createTestPlan(TestProject $project, $name, $notes, $active = true, $public = true)
	{
		$args = [
			'prefix' => $project->prefix,
			'testplanname' => $name,
			'notes' => $notes,
			'active' => $active,
			'public' => $public,
		];

		$response = $this->_makeSignCall('tl.createTestPlan', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param PlanTestCaseExecution $testCaseExecution
	 * @return int|bool
	 */
	public function deleteExecution(PlanTestCaseExecution $testCaseExecution)
	{
		$args = [
			'executionid' => (int)$testCaseExecution->id,
		];

		$response = $this->_makeSignCall('tl.deleteExecution', $args);

		if (is_array($response) && isset($response[0]) && $response[0]['id'] != -1) {
			return $response[0]['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param int $id
	 * @return TestSuite
	 */
	public function getTestSuiteById($id)
	{
		$response = $this->_makeSignCall('tl.getTestSuiteByID', ['testsuiteid' => $id]);

		$result = TestSuite::createFromArray($this, $response);
		return $result;

	}

	/**
	 * @param TestSuite $testSuite
	 * @return TestSuite[]
	 */
	public function getTestSuitesByTestSuite(TestSuite $testSuite)
	{
		$response = $this->_makeSignCall('tl.getTestSuitesForTestSuite', ['testsuiteid' => $testSuite->id]);

		$results = [];

		if(is_array($response) && !isset($response['id'])) {
			foreach ($response as $ts) {
				$testSuite = TestSuite::createFromArray($this, $ts);
				$results[] = $testSuite;
			}
		} elseif (is_array($response) && isset($response['id'])){
			$results[] = TestSuite::createFromArray($this, $response);
		}
		return $results;
	}

	/**
	 * @param TestPlan $plan
	 * @return mixed
	 */
	public function getTotalsByPlan(TestPlan $plan)
	{
		$response = $this->_makeSignCall('tl.getTotalsForTestPlan', ['testplanid' => $plan->id]);

		return $response;

	}

	/**
	 * @param string $username
	 * @return bool
	 */
	public function doesUserExist($username)
	{
		$response = $this->_makeSignCall('tl.doesUserExist', ['user' => $username]);

		return $response;
	}

	/**
	 * @param TestProject $project
	 * @param string $filename
	 * @param string $filetype
	 * @param string $content
	 * @param string|null $title
	 * @param string|null $description
	 * @return mixed
	 */
	public function uploadTestProjectAttachment(TestProject $project, $filename, $filetype, $content, $title = null, $description = null)
	{
		$args = [
			'testprojectid' => $project->id,
			'filename' => $filename,
			'filetype' => $filetype,
			'content' => $content,
		];

		if($title) {
			$args['title'] = $title;
		}

		if($description) {
			$args['description'] = $description;
		}

		$response = $this->_makeSignCall('tl.uploadTestProjectAttachment', $args);

		return $response;
	}

	/**
	 * @param TestSuite $testSuite
	 * @param string $filename
	 * @param string $filetype
	 * @param string $content
	 * @param string|null $title
	 * @param string|null $description
	 * @return mixed
	 */
	public function uploadTestSuiteAttachment(TestSuite $testSuite, $filename, $filetype, $content, $title = null, $description = null)
	{
		$args = [
			'testsuiteid' => $testSuite->id,
			'filename' => $filename,
			'filetype' => $filetype,
			'content' => $content,
		];

		if($title) {
			$args['title'] = $title;
		}

		if($description) {
			$args['description'] = $description;
		}

		$response = $this->_makeSignCall('tl.uploadTestSuiteAttachment', $args);

		return $response;
	}

	/**
	 * @param TestCase $testCase
	 * @param string $filename
	 * @param string $filetype
	 * @param string $content
	 * @param string|null $title
	 * @param string|null $description
	 * @return mixed
	 */
	public function uploadTestCaseAttachment(TestCase $testCase, $filename, $filetype, $content, $title = null, $description = null)
	{
		$args = [
			'testcaseid' => $testCase->id,
			'filename' => $filename,
			'filetype' => $filetype,
			'content' => $content,
		];

		if($title) {
			$args['title'] = $title;
		}

		if($description) {
			$args['description'] = $description;
		}

		$response = $this->_makeSignCall('tl.uploadTestCaseAttachment', $args);

		return $response;
	}

	/**
	 * @param PlanTestCaseExecution $testCaseExecution
	 * @param string $filename
	 * @param string $filetype
	 * @param string $content
	 * @param string|null $title
	 * @param string|null $description
	 * @return mixed
	 */
	public function uploadExecutionAttachment(PlanTestCaseExecution $testCaseExecution, $filename, $filetype, $content, $title = null, $description = null)
	{
		$args = [
			'executionid' => $testCaseExecution->id,
			'filename' => $filename,
			'filetype' => $filetype,
			'content' => $content,
		];

		if($title) {
			$args['title'] = $title;
		}

		if($description) {
			$args['description'] = $description;
		}

		$response = $this->_makeSignCall('tl.uploadExecutionAttachment', $args);

		return $response;
	}

	/**
	 * @param TestCase $testCase
	 * @param Step[] $steps
	 * @param int|null $version
	 * @param string $action
	 * @return mixed
	 */
	public function createTestCaseSteps(TestCase $testCase, array $steps, $version = null, $action = 'create')
	{
		$args = [
			'testcaseid' => $testCase->testcase_id,
			'action' => $action,
		];

		if($version) {
			$args['version'] = $version;
		}

		foreach($steps as $step) {
			$args['steps'][] = [
				'step_number' => $step->step_number,
				'actions' => $step->actions,
				'expected_results' => $step->expected_results,
				'execution_type' => $step->execution_type,
			];
		}

		$response = $this->_makeSignCall('tl.createTestCaseSteps', $args);

		return true;

	}

	/**
	 * @param TestCase $testCase
	 * @param Step[] $steps
	 * @param int|null $version
	 * @return mixed
	 */
	public function deleteTestCaseSteps(TestCase $testCase, array $steps, $version = null)
	{
		$args = [
			'testcaseid' => $testCase->testcase_id,
		];

		if($version) {
			$args['version'] = $version;
		}

		foreach($steps as $step) {
			$args['steps'][] = $step->step_number;
		}

		$response = $this->_makeSignCall('tl.deleteTestCaseSteps', $args);

		return true;
	}

	/**
	 * @param TestProject $project
	 * @param string $name
	 * @param string $notes
	 * @return int|bool
	 */
	public function createPlatform(TestProject $project, $name, $notes)
	{
		$args = [
			'testprojectname' => $project->name,
			'platformname' => $name,
			'notes' => $notes,
		];

		$response = $this->_makeSignCall('tl.createPlatform', $args);

		if (is_array($response) && $response['id'] != -1) {
			return $response['id'];
		} else {
			return false;
		}
	}

	/**
	 * @param TestProject $project
	 * @return Platform[]
	 */
	public function getPlatformsByProject(TestProject $project)
	{
		try {
			$response = $this->_makeSignCall('tl.getProjectPlatforms', ['testprojectid' => $project->id]);

			$results = [];
			if (is_array($response)) {
				foreach ($response as $plat) {
					$platform = Platform::createFromArray($this, $plat);
					$results[] = $platform;
				}
			}
			return $results;
		} catch (TestLinkAPIException $e) {
			if($e->getCode() == 3041) {
				return [];
			}
		}
	}

	/**
	 * @param TestPlan $plan
	 * @param Platform $platform
	 * @return bool
	 */
	public function assignPlatformToPlan(TestPlan $plan, Platform $platform)
	{
		$args = [
			'testplanid' => $plan->id,
			'platformname' => $platform->name,
		];

		$response = $this->_makeSignCall('tl.addPlatformToTestPlan', $args);

		return true;
	}

	/**
	 * @param TestPlan $plan
	 * @param Platform $platform
	 * @return bool
	 */
	public function removePlatformFromPlan(TestPlan $plan, Platform $platform)
	{
		$args = [
			'testplanid' => $plan->id,
			'platformname' => $platform->name,
		];

		$response = $this->_makeSignCall('tl.removePlatformFromTestPlan', $args);

		return true;
	}

	/**
	 * @param string $login
	 * @return User|bool
	 */
	public function getUserByLogin($login)
	{
		$args = [
			'user' => $login,
		];

		$response = $this->_makeSignCall('tl.getUserByLogin', $args);

		if(isset($response[0])) {
			return User::createFromArray($this, $response[0]);
		}

		return false;
	}

	/**
	 * @param $id
	 * @return User|bool
	 */
	public function getUserById($id)
	{
		$args = [
			'userid' => $id,
		];

		$response = $this->_makeSignCall('tl.getUserByID', $args);

		if(isset($response[0])) {
			return User::createFromArray($this, $response[0]);
		}

		return false;
	}

	/**
	 * @param TestCase $testCase
	 * @param int|null $version
	 * @param string|null $name
	 * @param string|null $summary
	 * @param Step[] $steps
	 * @param string|null $preconditions
	 * @return mixed
	 */
	public function updateTestCase(TestCase $testCase, $version = null, $name = null, $summary = null, array $steps = [], $preconditions = null)
	{
		$args = [
			'testcaseexternalid' => $testCase->full_tc_external_id,
		];

		if($version) {
			$args['version'] = $version;
		}

		if($name) {
			$args['name'] = $name;
		}

		if($summary) {
			$args['summary'] = $summary;
		}

		if($preconditions) {
			$args['preconditions'] = $preconditions;
		}

		if($steps) {
			foreach ($steps as $step) {
				$args['steps'][] = [
					'step_number' => $step->step_number,
					'actions' => $step->actions,
					'expected_results' => $step->expected_results,
					'execution_type' => $step->execution_type,
				];
			}
		}

		$response = $this->_makeSignCall('tl.updateTestCase', $args);

		return isset($response['status_ok'])?$response['status_ok']:false;
	}

	/**
	 * @param User $user
	 * @param PlanTestCaseInstance $testCaseInstance
	 * @return mixed
	 */
	public function assignTestCaseInstanceToUser(User $user, PlanTestCaseInstance $testCaseInstance)
	{
		$args = [
			'user' => $user->login,
			'testplanid' => $testCaseInstance->getBuild()->testplan_id,
			'testcaseexternalid' => $testCaseInstance->getTestCase()->getTestCase()->full_tc_external_id,
			'buildid' => $testCaseInstance->getBuild()->id,
		];

		if($testCaseInstance->getPlatform()) {
			$args['platformid'] = $testCaseInstance->getPlatform()->id;
		}

		$response = $this->_makeSignCall('tl.assignTestCaseExecutionTask', $args);

		return isset($response['status'])?$response['status']:false;
	}

	/**
	 * @param User|null $user
	 * @param PlanTestCaseInstance $testCaseInstance
	 * @return mixed
	 */
	public function removeTestCaseInstanceFromUser(User $user = null, PlanTestCaseInstance $testCaseInstance)
	{
		$args = [
			'testplanid' => $testCaseInstance->getBuild()->testplan_id,
			'testcaseexternalid' => $testCaseInstance->getTestCase()->getTestCase()->full_tc_external_id,
			'buildid' => $testCaseInstance->getBuild()->id,
		];

		if($testCaseInstance->getPlatform()) {
			$args['platformid'] = $testCaseInstance->getPlatform()->id;
		}

		if($user) {
			$args['user'] = $user->login;
		} else {
			$args['action'] = 'unassignAll';
		}

		$response = $this->_makeSignCall('tl.unassignTestCaseExecutionTask', $args);

		return isset($response['status'])?$response['status']:false;
	}

	/**
	 * @param PlanTestCaseInstance $testCaseInstance
	 * @return User|bool
	 */
	public function getUserByAssignedTestCaseInstance(PlanTestCaseInstance $testCaseInstance)
	{
		$args = [
			'testplanid' => $testCaseInstance->getBuild()->testplan_id,
			'testcaseexternalid' => $testCaseInstance->getTestCase()->getTestCase()->full_tc_external_id,
			'buildid' => $testCaseInstance->getBuild()->id,
		];

		if($testCaseInstance->getPlatform()) {
			$args['platformid'] = $testCaseInstance->getPlatform()->id;
		}

		$response = $this->_makeSignCall('tl.getTestCaseAssignedTester', $args);

		if(isset($response[0])) {
			return User::createFromArray($this, $response[0]);
		}

		return false;
	}

	/**
	 * @param TestProject $project
	 * @return Keyword[]
	 */
	public function getKeywordsByProject(TestProject $project)
	{
		$args = [
			'testprojectid' => $project->id,
		];

		$response = $this->_makeSignCall('tl.getProjectKeywords', $args);

		$results = [];

		if(is_array($response)) {
			foreach ($response as $kw) {
				$keyword = Keyword::createFromArray($this, ['name' => $kw]);
				$results[] = $keyword;
			}
		}

		return $results;
	}

	/**
	 * @param TestCase $testCase
	 * @return Keyword[]
	 */
	public function getKeywordsByTestCase(TestCase $testCase)
	{

		$args = [
			'testcaseid' => $testCase->testcase_id,
		];

		$response = $this->_makeSignCall('tl.getTestCaseKeywords', $args);

		$results = [];

		if(is_array($response) && isset($response[$testCase->testcase_id])) {
			foreach($response[$testCase->testcase_id] as $kw) {
				$keyword = Keyword::createFromArray($this, ['name' => $kw]);
				$results[] = $keyword;
			}
		}

		return $results;
	}

	/**
	 * @param TestPlan $plan
	 * @return mixed
	 */
	public function deleteTestPlan(TestPlan $plan)
	{
		$args = [
			'testplanid' => $plan->id,
		];

		$response = $this->_makeSignCall('tl.deleteTestPlan', $args);

		return isset($response[0]['status'])?$response[0]['status']:false;
	}

	/**
	 * @param TestCase $testCase
	 * @param Keyword[] $keywords
	 * @return bool
	 */
	public function assignKeywordsToTestCase(TestCase $testCase, array $keywords)
	{
		$args['keywords'] = [];
		foreach ($keywords as $keyword) {
			$args['keywords'][$testCase->full_tc_external_id][] = $keyword->name;
		}

		$response = $this->_makeSignCall('tl.addTestCaseKeywords', $args);

		return isset($response['status_ok'])?$response['status_ok']:false;
	}

	/**
	 * @param TestCase $testCase
	 * @param Keyword[] $keywords
	 * @return bool
	 */
	public function removeKeywordsFromTestCase(TestCase $testCase, array $keywords)
	{
		$args['keywords'] = [];
		foreach ($keywords as $keyword) {
			$args['keywords'][$testCase->full_tc_external_id][] = $keyword->name;
		}

		$response = $this->_makeSignCall('tl.removeTestCaseKeywords', $args);

		return isset($response['status_ok'])?$response['status_ok']:false;
	}

	/**
	 * @param TestProject $project
	 * @return mixed
	 */
	public function deleteTestProject(TestProject $project)
	{
		$args = [
			'prefix' => $project->prefix,
		];

		$response = $this->_makeSignCall('tl.deleteTestProject', $args);

		return isset($response[0]['status'])?$response[0]['status']:false;
	}

	/**
	 * @param int $testCaseId
	 * @param string $status
	 * @param string $notes
	 * @param int $testPlanId
	 * @param int $buildId
	 * @param int|null $platformId
	 * @param array|null $steps
	 * @return mixed
	 */
	public function reportExecution($testCaseId, $status, $notes, $testPlanId, $buildId, $platformId = null, array $steps = null)
	{
		$args = [
			'testcaseid' => $testCaseId,
			'status' => $status,
			'notes' => $notes,
			'testplanid' => $testPlanId,
			'buildid' => $buildId,
		];
		if($platformId) {
			$args['platformid'] = $platformId;
		}

		if($steps) {
			$args['steps'] = $steps;
		}

		$response = $this->_makeSignCall('tl.reportTCResult', $args);
		return $response[0]['status'];
	}

	/**
	 * @param string $method
	 * @param array|null $args
	 * @return mixed
	 */
	protected function _makeCall($method, $args = null)
	{
		$this->getClient()->query($method, $args);
		if($this->getClient()->isError()) {
			throw new TestLinkAPIException($this->getClient()->getErrorMessage(), $this->getClient()->getErrorCode());
		}
		return $this->checkResponse($this->getClient()->getResponse());
	}

	/**
	 * @param string $method
	 * @param array|null $args
	 * @return mixed
	 */
	protected function _makeSignCall($method, $args = null)
	{
		$args['devKey'] = $this->apiKey;
		return $this->_makeCall($method, $args);
	}

	protected function checkResponse($response)
	{
		if(is_array($response)) {
			foreach($response as $res) {
				if (isset($res['code']) && $res['code'] != null) {
					throw new TestLinkAPIException($res['message'], $res['code']);
				} elseif (isset($res['status_ok']) && $res['status_ok'] != null && $res['status_ok'] == 0) {
					throw new TestLinkAPIException($res['msg'], $res['status_ok']);
				}
			}
		}

		return $response;
	}

	public function setClient($client)
	{
		$this->client = $client;
	}

	/**
	 * @return XMLRPC\Client
	 */
	protected function getClient()
	{
		if(!$this->client) {
			$this->client = new XMLRPC\Client($this->serverURL);
		}
		return $this->client;
	}
}


text:
package comzhuoyue.coolweather.activity;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import comzhuoyue.coolweather.R;
import comzhuoyue.coolweather.db.CoolWeatherDB;
import comzhuoyue.coolweather.model.City;
import comzhuoyue.coolweather.model.County;
import comzhuoyue.coolweather.model.Province;
import comzhuoyue.coolweather.util.HttpCallbackListener;
import comzhuoyue.coolweather.util.HttpUtil;
import comzhuoyue.coolweather.util.Utilty;

public class ChooseAreaActivity extends Activity  {
	private TextView title;
	private ListView listView;
	private ArrayAdapter<String> mAdapter;
	private final static int LEVEL_PROVINCE = 0;
	private final static int LEVEL_CITY = 1;
	private final static int LEVEL_COUNTY = 2;
	private List<String> dataList = new ArrayList<String>();
	private ProgressDialog progressDialog;
	private CoolWeatherDB coolWeatherDB;
	private int currentLevel;// µ±Ç°Ñ¡Öеļ¶±ð

	private List<Province> provinceList;// Ê¡Áбí
	private List<County> countyList;// Ê¡Áбí
	private Province selectedProvince;// Ñ¡ÖеÄÊ¡
	private City selectedCity;// Ñ¡ÖеÄÊÐ
	private List<City> citiesList;

	//ÅжÏÊÇ·ñ´ÓWeatherActivityÖÐÌøת
	private boolean isFromWeatherActivity;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
		SharedPreferences preferences= getSharedPreferences("weather", MODE_PRIVATE);
		if(preferences.getBoolean("citySelected", false)&&!isFromWeatherActivity){
			Intent intent = new Intent(this,WeatherActivity.class);
			startActivity(intent);
			finish();
			return;
		}

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);

		title = (TextView) findViewById(R.id.title_text);
		listView = (ListView) findViewById(R.id.listView);

		mAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, dataList);

		listView.setAdapter(mAdapter);
		coolWeatherDB = CoolWeatherDB.getInstance(this);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (LEVEL_PROVINCE == currentLevel) {
					selectedProvince = provinceList.get(position);
					queryCity();
				}else if(LEVEL_CITY==currentLevel){//Êм¶ÁÐ±í±»Ñ¡ÖУ¬²éÕÒÏؼ¶Áбí
					selectedCity = citiesList.get(position);
					queryCounties();
				}else if(LEVEL_COUNTY==currentLevel){
					County county = countyList.get(position);
					Intent intent = new Intent(ChooseAreaActivity.this,WeatherActivity.class);
					intent.putExtra("countyCode", county.getCountyCode());
					startActivity(intent);
					finish();
				}

			}
		});
		queryProvinces();
	}

	/**
	 * ²éѯËùÓÐÊ¡µÄÊý¾Ý
	 */
	private void queryProvinces() {
		provinceList = coolWeatherDB.loadProvince();
		if(provinceList.size()>0){
			dataList.clear();
			for (Province province : provinceList) {
				dataList.add(province.getProvinceName());
			}
			mAdapter.notifyDataSetChanged();
			listView.setSelection(0);
			title.setText("Öйú");
			currentLevel = LEVEL_PROVINCE;
		}else{
			queryFormServer(null, "province");
		}
	}

	/**
	 * ²éѯËùÓÐÊеÄÁÐ±í£¬ÏÈ´ÓÊý¾Ý¿âÖÐÕÒ£¬ÕÒ²»µ½£¬ÔÚÉÏÍøÕÒ
	 */
	private void queryCity() {
		citiesList = coolWeatherDB.loadCity(selectedProvince.getId());
		if(citiesList.size()>0){//ÔÚÊý¾Ý¿âÖÐÕÒµ½ÁË
			dataList.clear();
			for (City city : citiesList) {
				dataList.add(city.getCityName());
			}
			mAdapter.notifyDataSetChanged();//¸üÐÂui
			listView.setSelection(0);
			title.setText(selectedProvince.getProvinceName());
			currentLevel = LEVEL_CITY;
		}else{//ÁªÍø²éÕÒ
			queryFormServer(selectedProvince.getProvinceCode(), "city");

		}
	}

	/**
	 * ²éѯËùÓÐÏØ
	 */
	private void queryCounties() {
		countyList = coolWeatherDB.loadCounty(selectedCity.getId());
		if(countyList.size()>0){
			dataList.clear();
			for (County county : countyList) {
				dataList.add(county.getCountyName());
			}
			mAdapter.notifyDataSetChanged();
			title.setText(selectedCity.getCityName());
			currentLevel =LEVEL_COUNTY;
		}else{
			queryFormServer(selectedCity.getCityCode(), "county");
		}

	}

	/**
	 * ²éѯ·þÎñÆ÷ÉϵÄÊý¾Ý
	 * @param code ÉÏÒ»¼¶µÄ´úºÅ
	 * ÕâÊDzéÕÒÊеÄurl£¬0101ÊÇÊ¡µÄ´úºÅ
	 * http://www.weather.com.cn/data/list3/city0101.xml
	 */
	private void queryFormServer(final String code,final String type) {
		String address;
		if(!TextUtils.isEmpty(code)){
			address = "http://www.weather.com.cn/data/list3/city"+code+".xml";
		}else{
			address = "http://www.weather.com.cn/data/list3/city.xml";
		}
		showProgressDialog();
		HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {

			@Override
			public void OnFinished(String response) {
				boolean result = false;
				if("province".equals(type)){//Èç¹ûÀàÐÍÊÇÊ¡¼¶
					result = Utilty.handlerProvinceData(coolWeatherDB, response);
				}else if("city".equals(type)){
					result = Utilty.handlerCityData(coolWeatherDB, response,selectedProvince.getId());
				}else if("county".equals(type)){
					result = Utilty.handlerCountyData(coolWeatherDB, response,selectedCity.getId());
				}
				if(result){
					//ͨ¹ýrunUiThread£¨£©·½·¨»Øµ÷Ö÷Ï̴߳¦ÀíÂß¼
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							closeprogressDialog();
							if("province".equals(type)){
								queryProvinces();
							}else if("city".equals(type)){
								queryCity();
							}else if("county".equals(type)){
								queryCounties();
							}
						}

					});
				}
			}

			@Override
			public void onError(Exception e) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						closeprogressDialog();
						Toast.makeText(ChooseAreaActivity.this, "¼ÓÔØʧ°Ü", Toast.LENGTH_SHORT).show();
					}
				});
			}

		});
	}

	/**
	 * ÏÔʾ½ø¶È¿ò
	 */
	private void showProgressDialog() {
		if(progressDialog==null){
			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("ÕýÔÚ¼ÓÔØ...");
			//ÉèÖõã»÷¶Ô»°¿òÍâÃæµÄʱºò¶Ô»°¿ò²»Ïûʧ
			progressDialog.setCanceledOnTouchOutside(false);
		}
		progressDialog.show();
	}
	/**
	 * ¹Ø±Õ½ø¶ÈÌõ¶Ô»°¿ò
	 */
	private void closeprogressDialog() {
		if(progressDialog!=null){
			progressDialog.dismiss();
		}
	}

	/**
	 * ²»»áback·µ»Ø¼ü£¬¸ù¾Ýµ±Ç°µÄ¼¶±ðÀ´Åжϣ¬´ËʱӦ¸Ã·µ»ØÊУ¬Ê¡£¬ÏØÁÐ±í»¹ÊÇÍ˳ö
	 */
	@Override
	public void onBackPressed() {
		if(currentLevel==LEVEL_COUNTY){
			queryCity();
		}else if(currentLevel == LEVEL_CITY){
			queryProvinces();
		}else{
			if(isFromWeatherActivity){
				Intent intent = new Intent(this,WeatherActivity.class);
				startActivity(intent);
			}
			finish();
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
#include <utility>
#include <algorithm>

#include "caf/node_id.hpp"
#include "caf/actor_addr.hpp"
#include "caf/serializer.hpp"
#include "caf/deserializer.hpp"
#include "caf/actor_namespace.hpp"

#include "caf/detail/logging.hpp"
#include "caf/detail/singletons.hpp"
#include "caf/detail/actor_registry.hpp"

namespace caf {

actor_namespace::backend::~backend() {
  // nop
}

actor_namespace::proxy_entry::proxy_entry() {
  // nop
}

actor_namespace::proxy_entry::proxy_entry(actor_proxy::anchor_ptr ptr)
    : ptr_(std::move(ptr)) {
  // nop
}

actor_namespace::proxy_entry::~proxy_entry() {
  reset(exit_reason::remote_link_unreachable);
}

void actor_namespace::proxy_entry::reset(uint32_t rsn) {
  if (! ptr_)
    return;
  auto ptr = ptr_->get();
  ptr_.reset();
  if (ptr)
    ptr->kill_proxy(rsn);
}

actor_namespace::actor_namespace(backend& be) : backend_(be) {
  // nop
}

void actor_namespace::write(serializer* sink, const actor_addr& addr) const {
  CAF_ASSERT(sink != nullptr);
  if (! addr) {
    node_id::host_id_type zero;
    std::fill(zero.begin(), zero.end(), 0);
    sink->write_value(static_cast<actor_id>(0));         // actor id
    sink->write_raw(node_id::host_id_size, zero.data()); // host id
    sink->write_value(static_cast<uint32_t>(0));         // process id
  } else {
    // register locally running actors to be able to deserialize them later
    if (! addr.is_remote()) {
      auto reg = detail::singletons::get_actor_registry();
      reg->put(addr.id(), actor_cast<abstract_actor_ptr>(addr));
    }
    auto pinf = addr.node();
    sink->write_value(addr.id());                                  // actor id
    sink->write_raw(node_id::host_id_size, pinf.host_id().data()); // host id
    sink->write_value(pinf.process_id());                          // process id
  }
}

actor_addr actor_namespace::read(deserializer* source) {
  CAF_ASSERT(source != nullptr);
  node_id::host_id_type hid;
  auto aid = source->read<uint32_t>();                 // actor id
  source->read_raw(node_id::host_id_size, hid.data()); // host id
  auto pid = source->read<uint32_t>();                 // process id
  node_id this_node = detail::singletons::get_node_id();
  if (aid == 0 && pid == 0) {
    // 0:0 identifies an invalid actor
    return invalid_actor_addr;
  }
  if (pid == this_node.process_id() && hid == this_node.host_id()) {
    // identifies this exact process on this host, ergo: local actor
    auto a = detail::singletons::get_actor_registry()->get(aid);
    // might be invalid
    return a ? a->address() : invalid_actor_addr;
  }
  // identifies a remote actor; create proxy if needed
  return get_or_put({pid, hid}, aid)->address();
}

size_t actor_namespace::count_proxies(const key_type& node) {
  auto i = proxies_.find(node);
  return (i != proxies_.end()) ? i->second.size() : 0;
}

std::vector<actor_proxy_ptr> actor_namespace::get_all() const {
  std::vector<actor_proxy_ptr> result;
  for (auto& outer : proxies_) {
    for (auto& inner : outer.second) {
      if (inner.second) {
        auto ptr = inner.second->get();
        if (ptr)
          result.push_back(std::move(ptr));
      }
    }
  }
  return result;
}

std::vector<actor_proxy_ptr>
actor_namespace::get_all(const key_type& node) const {
  std::vector<actor_proxy_ptr> result;
  auto i = proxies_.find(node);
  if (i == proxies_.end())
    return result;
  auto& submap = i->second;
  for (auto& kvp : submap) {
    if (kvp.second) {
      auto ptr = kvp.second->get();
      if (ptr)
        result.push_back(std::move(ptr));
    }
  }
  return result;
}

actor_proxy_ptr actor_namespace::get(const key_type& node, actor_id aid) {
  auto& submap = proxies_[node];
  auto i = submap.find(aid);
  if (i != submap.end()) {
    auto res = i->second->get();
    if (! res) {
      submap.erase(i); // instance is expired
    }
    return res;
  }
  return nullptr;
}

actor_proxy_ptr actor_namespace::get_or_put(const key_type& node,
                                            actor_id aid) {
  auto& submap = proxies_[node];
  auto& anchor = submap[aid];
  actor_proxy_ptr result;
  if (anchor) {
    result = anchor->get();
  }
  // replace anchor if we've created one using the default ctor
  // or if we've found an expired one in the map
  if (! anchor || ! result) {
    result = backend_.make_proxy(node, aid);
    if (result) {
      anchor = result->get_anchor();
    }
  }
  return result;
}

bool actor_namespace::empty() const {
  return proxies_.empty();
}

void actor_namespace::erase(const key_type& inf) {
  CAF_LOG_TRACE(CAF_TARG(inf, to_string));
  proxies_.erase(inf);
}

void actor_namespace::erase(const key_type& inf, actor_id aid, uint32_t rsn) {
  CAF_LOG_TRACE(CAF_TARG(inf, to_string) << ", " << CAF_ARG(aid));
  auto i = proxies_.find(inf);
  if (i != proxies_.end()) {
    auto& submap = i->second;
    auto j = submap.find(aid);
    if (j == submap.end())
      return;
    j->second.reset(rsn);
    submap.erase(j);
    if (submap.empty())
      proxies_.erase(i);
  }
}

void actor_namespace::clear() {
  proxies_.clear();
}

} // namespace caf


text:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AuditTableModule} from '../../components/audit_table';
import {AuditView} from './audit_view';

export * from './audit_view';

@NgModule({
  declarations: [
    AuditView,
  ],
  exports: [
    AuditView,
  ],
  imports: [
    AuditTableModule,
    BrowserModule,
  ],
})
export class AuditViewModule {
}


text:
package org.apache.geode.internal.memcached;

import org.apache.logging.log4j.Logger;

import org.apache.geode.cache.Cache;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.cache.CacheService;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.logging.internal.log4j.api.LogService;
import org.apache.geode.management.internal.beans.CacheServiceMBeanBase;
import org.apache.geode.memcached.GemFireMemcachedServer;

/**
 * Service loaded at cache initialization that starts the {@link GemFireMemcachedServer}
 * if {@link ConfigurationProperties#MEMCACHED_PORT} is set.
 */
public class GeodeMemcachedService implements CacheService {
  private static final Logger logger = LogService.getLogger();
  private GemFireMemcachedServer memcachedServer;

  @Override
  public boolean init(Cache cache) {
    InternalCache internalCache = (InternalCache) cache;
    startMemcachedServer(internalCache);

    return true;
  }

  private void startMemcachedServer(InternalCache internalCache) {
    InternalDistributedSystem system = internalCache.getInternalDistributedSystem();
    int port = system.getConfig().getMemcachedPort();
    if (port != 0) {
      String protocol = system.getConfig().getMemcachedProtocol();
      assert protocol != null;
      String bindAddress = system.getConfig().getMemcachedBindAddress();
      assert bindAddress != null;
      if (bindAddress.equals(DistributionConfig.DEFAULT_MEMCACHED_BIND_ADDRESS)) {
        logger.info("Starting GemFireMemcachedServer on port {} for {} protocol",
            new Object[] {port, protocol});
      } else {
        logger.info("Starting GemFireMemcachedServer on bind address {} on port {} for {} protocol",
            new Object[] {bindAddress, port, protocol});
      }
      this.memcachedServer =
          new GemFireMemcachedServer(bindAddress, port,
              GemFireMemcachedServer.Protocol.valueOf(protocol.toUpperCase()));
      this.memcachedServer.start();
    }
  }

  @Override
  public void close() {
    stopMemcachedServer();
  }

  private void stopMemcachedServer() {
    if (this.memcachedServer != null) {
      logger.info("GemFireMemcachedServer is shutting down");
      this.memcachedServer.shutdown();
    }
  }

  @Override
  public Class<? extends CacheService> getInterface() {
    return GeodeMemcachedService.class;
  }

  @Override
  public CacheServiceMBeanBase getMBean() {
    return null;
  }
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Input;
using Prism.Mvvm;
using Prism.Regions;
using TipsySheep.Logic.Core;
using TipsySheep.Logic.Core.EFStatements;
using TipsySheep.Logic.Core.HelpClasses;
using TipsySheep.UI.Views;
using TipsySheep.UI.Interfaces;
using Prism.Commands;
using TipsySheep.Shared.Contracts;

namespace TipsySheep.Logic.ViewModels
{
    public class SpecificationsViewModel : BindableBase, INavigationAware, IRegionMemberLifetime, IConfirmNavigationRequest, INotifySearchText, ISpecificationsViewModel
    {
        #region PropertyChanged for Static Properties
        public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged
         = delegate
         {
         };
        public event PropertyChangedEventHandler TextChanged;

        private static void NotifyStaticPropertyChanged(string propertyName)
        {
            StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        #region Fields
        private static string bezeichnung;

        private Fluent.Button trigger;
        public bool KeepAlive => false;
        private string searchText;
        private System.Windows.Visibility isVisible;
        private readonly IRegionManager regionManager;
        private Specifications view;
        private ICollection genericDataGridColumn;
        #endregion

        #region Properties
        public static string Bezeichnung
        {
            get { return bezeichnung; }
            set { bezeichnung = value; NotifyStaticPropertyChanged(nameof(Bezeichnung)); }
        }

        public static long Id { get; private set; }

        public string SearchText
        {
            get { return searchText; }
            set { searchText = value; OnTextChanged(SearchText); }
        }

        public ICollection GenericDataGridColumn
        {
            get { return genericDataGridColumn; }
            set { genericDataGridColumn = value; OnPropertyChanged(nameof(GenericDataGridColumn)); }
        }

        public System.Windows.Visibility Visible
        {
            get { return isVisible; }
            set { isVisible = value; OnPropertyChanged(nameof(Visible)); }
        }

        public ICommand MouseDoubleClickCommand { get; }
        public ICommand MouseDownCommand { get; }
        public ICommand SaveButtonCommand { get; }

        public ICommand CancelButtonCommand { get; }

        public ICommand EnterKeyDown { get; }
        public GenericCommand BackButtonCommand { get; private set; }
        #endregion

        #region Constructors
        public SpecificationsViewModel(IRegionManager regionManager)
        {
            this.regionManager = regionManager;
            BackButtonCommand = new GenericCommand(this.onBackButtonReleased);
            CancelButtonCommand = new GenericCommand(this.onCancelButtonReleased);
            SaveButtonCommand = new GenericCommand(this.onSaveButtonReleased);
            MouseDoubleClickCommand = new DelegateCommand<IEnumerable>(this.DataContainer_MouseDoubleClick);
            MouseDownCommand = new DelegateCommand<object>(this.textBox_Name_KeyDown);
            EnterKeyDown = new GenericCommand(this.onEnterKeyReleased);
            Visible = System.Windows.Visibility.Hidden; // Set default visibility.
        }
        #endregion

        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
        {
            continuationCallback(true);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext) => true;

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            //not implemented
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            trigger = navigationContext.Parameters["trigger"] as Fluent.Button;
            view = navigationContext.Parameters["view"] as Specifications;
            FillDataGrid();
        }

        private void FillDataGrid()
        {
            switch (trigger.Name)
            {
                case "buttonRaces":
                    GenericDataGridColumn = DbInfo.RaceCollection() as ICollection;
                    break;

                case "buttonPurchase":
                    GenericDataGridColumn = DbInfo.PurchaseCollection() as ICollection;
                   break;

                case "buttonDispatch":
                    GenericDataGridColumn = DbInfo.DispatchCollection() as ICollection;
                   break;
            }
        }

        private void onSaveButtonReleased(object obj)
        {
            DbUpdate.UpdateSpecificationAsync(trigger.Name, Id, Bezeichnung);
            FillDataGrid(); // Update des DataGrids
            Visible = System.Windows.Visibility.Hidden;
        }

        private void onCancelButtonReleased(object obj)
        {
            Bezeichnung = null;
            Id = -1;
            Visible = System.Windows.Visibility.Hidden;
        }

        private void onBackButtonReleased(object obj)
        {
            new GlobalFunctions().GoToStartScreen();
        }

        private void onEnterKeyReleased(object obj)
        {
            onSaveButtonReleased(obj);
        }

        public void LoadBezeichnungIntoTextBox(IEnumerable list)
        {
            List<DbInfo.SpecificationColumns> _list = list.Cast<DbInfo.SpecificationColumns>().ToList();
            try
            {
                Bezeichnung = _list[0].Bezeichnung;
                Id = _list[0].Id;
                Visible = System.Windows.Visibility.Visible;
            }
            catch (ArgumentOutOfRangeException)
            {
            }
        }

        public void OnTextChanged(string name)
        {
            TextChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            if (!string.IsNullOrEmpty(name))
            {
                switch (trigger.Name)
                {
                    case "buttonRaces":
                        GenericDataGridColumn = DbInfo.RaceCollection(name) as ICollection;
                        break;

                    case "buttonPurchase":
                        GenericDataGridColumn = DbInfo.PurchaseCollection(name) as ICollection;
                        break;

                    case "buttonDispatch":
                        GenericDataGridColumn = DbInfo.DispatchCollection(name) as ICollection;
                        break;
                }
            }
            else
            {
                FillDataGrid();
            }
        }

        private void DataContainer_MouseDoubleClick(IEnumerable items)
        {
            LoadBezeichnungIntoTextBox(items);
        }

        private void textBox_Name_KeyDown(object sender)
        {
            EnterKeyDown.Execute(sender);
        }
    }
}


text:
<?php

namespace Dvd\Entity;

use Doctrine\ORM\Mapping as ORM;
use Dvd\Entity\Fonctions;
use Dvd\Entity\Movies;
use Dvd\Entity\Stars;

/**
 * MoviesStarsFonctions
 *
 * @ORM\Table(name="movies_stars_fonctions", indexes={@ORM\Index(name="id_star", columns={"id_star"}), @ORM\Index(name="id_fonction", columns={"id_fonction"}), @ORM\Index(name="IDX_237B097CF3DBB35F", columns={"id_movie"})})
 * @ORM\Entity
 */
class MoviesStarsFonctions
{
    /**
     * @var Movies
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Dvd\Entity\Movies")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_movie", referencedColumnName="id")
     * })
     */
    private $idMovie;

    /**
     * @var Stars
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Dvd\Entity\Stars")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_star", referencedColumnName="id")
     * })
     */
    private $idStar;

    /**
     * @var Fonctions
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Dvd\Entity\Fonctions")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_fonction", referencedColumnName="id")
     * })
     */
    private $idFonction;

    /**
     * Set idMovie
     *
     * @param Movies $idMovie
     * @return MoviesStarsFonctions
     */
    public function setIdMovie(Movies $idMovie)
    {
        $this->idMovie = $idMovie;

        return $this;
    }

    /**
     * Get idMovie
     *
     * @return Movies
     */
    public function getIdMovie()
    {
        return $this->idMovie;
    }

    /**
     * Set idStar
     *
     * @param Stars $idStar
     * @return MoviesStarsFonctions
     */
    public function setIdStar(Stars $idStar)
    {
        $this->idStar = $idStar;

        return $this;
    }

    /**
     * Get idStar
     *
     * @return Stars
     */
    public function getIdStar()
    {
        return $this->idStar;
    }

    /**
     * Set idFonction
     *
     * @param Fonctions $idFonction
     * @return MoviesStarsFonctions
     */
    public function setIdFonction(Fonctions $idFonction)
    {
        $this->idFonction = $idFonction;

        return $this;
    }

    /**
     * Get idFonction
     *
     * @return Fonctions
     */
    public function getIdFonction()
    {
        return $this->idFonction;
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Geopetalum brunescens Earle, 1906

### Remarks
null


text:
<?php
// Autogenerated by Translator Builder

return [

        'meta_title' => 'Talented Europe | Unisce i giovani talenti e i datori di lavoro di tutta Europa',

        'tagline' => 'Unisce
 i giovani talenti e i datori di lavoro
 di tutta Europa',

        'days' => 'giorni',

        'hours' => 'ore',

        'minutes' => 'minuti',

        'seconds' => 'secondi',

        'more' => 'per saperne di più',

        'what_is_title' => 'Che cos\'è Talented Europe?',

        'what_is_cta' => 'Scopri di più! Scarica la brochure!',

        'what_is_text_1' => 'Potete immaginare la possibilità di poter assumere i migliori studenti di qualsiasi paese d\'Europa? Vorreste far parte di un\'élite studentesca in Europa? Migliaia di compagnie avranno un accesso diretto alle vostre informazioni di contatto; migliore sarà la vostra valutazione, maggiori saranno le vostre opportunità di trovare un buon lavoro.',

        'what_is_text_2' => 'Questa è l'offerta che Talented Europe ti propone. Una vetrina in cui vengono messi in mostra i migliori studenti di tutta Europa. Un'idea semplice che unisce i datori di lavoro agli studenti. Il punto d'incontro per eccellenza.',

        'subscribe_title' => 'Registrati e segui i nostri aggiornamenti.',

        'subscribe_text' => 'Ricevi notifiche di tutti gli eventi e le novità su Talented Europe',

        'subscribe_form_placeholder' => 'Inserisci indirizzo email',

        'subscribe_btn_text' => 'registrati',

        'subscribe_follow_text' => 'oppure seguici su',

        'subscribe_text_question' => 'Ricevi news di Talented Europe nella tua casella di posta elettronica.
 Sentiti di libero di rispondere alla nostra domanda: Che cosa significa talento per te?',

        'meta_description' => 'Un progetto Erasmus Plus che permette ai migliori studenti di trovare posti di lavoro e stage in tutta Europa molto più facilmente.',

        'coming_soon' => 'Prossimamente',

        'search_placeholder' => 'Che cosa stai cercando?',

        'search_where' => 'Dove',

        'search_btn' => 'Cerca',

        'statistics_title' => 'Statistiche',

        'contacts' => 'Contatti tra studenti e imprese',

        'companies_institutions' => 'Imprese e istituzioni',

        'students_title' => 'Studenti di talento',

        'no_students' => 'Nessuno studente disponibile',

        'join_talented_europe_today' => 'Unisciti al Talented Europe oggi!',

        'talented_for_students' => 'Per studenti - Talented Europe aumenterà la possibilità di trovare un lavoro con il supporto dei vostri tutors e vi metterà in contatto con le imprese e i professionisti per trovare tirocini nelle imprese o ottenere il vostro primo lavoro',

        'talented_for_employers' => 'Per imprese e professionisti - Talented Europe vi metterá in contatto con i giovani studenti di talento di tutta Europa e vi aiuterà a incontrare la persona adeguata che puó contribuire al successo della vostra impresa con il talento e le competenze specifiche che sta cercando.',

        'go_to_app' => 'Passare all\'app',

        'what_is_text_1_txt' => 'Potete immaginare la possibilità di poter assumere i migliori studenti di qualsiasi paese d\'Europa? Vorreste far parte di un\'élite studentesca in Europa? Migliaia di compagnie avranno un accesso diretto alle vostre informazioni di contatto; migliore sarà la vostra valutazione, maggiori saranno le vostre opportunità di trovare un buon lavoro.',

        'what_is_text_2_txt' => 'Questa è l'offerta che Talented Europe ti propone. Una vetrina in cui vengono messi in mostra i migliori studenti di tutta Europa. Un'idea semplice che unisce i datori di lavoro agli studenti. Il punto d'incontro per eccellenza.',

];


text:
function apt-history(){
      case "$1" in
        install)
              cat /var/log/dpkg.log | grep 'install '
              ;;
        upgrade|remove)
              cat /var/log/dpkg.log | grep $1
              ;;
        rollback)
              cat /var/log/dpkg.log | grep upgrade | \
                  grep "$2" -A10000000 | \
                  grep "$3" -B10000000 | \
                  awk '{print $4"="$5}'
              ;;
        *)
              cat /var/log/dpkg.log
              ;;
      esac
}

DIR_THIS="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source $DIR_THIS/bash_setup_common.bash

source $DIR_THIS/../ros/setup_ros_ubuntu_common.bash  # This uses env var DISTRO_ROS_LINUX.

# 20160716 git ssh issue https://github.com/130s/hut_10sqft/issues/64
eval $(ssh-agent) >> /dev/null  # This doesn't complete the solution to https://github.com/130s/hut_10sqft/issues/64. In the downstream bash config, ssh-add needs to be run with the path of specific ssh key files.

# For git
export EDITOR=emacs

# 20160716 git ssh issue https://github.com/130s/hut_10sqft/issues/64
# Added in https://github.com/130s/hut_10sqft/pull/65
# 20170916 To workaround https://github.com/130s/hut_10sqft/issues/67#issuecomment-330153887 upon scp, tentatively decided to comment this out. Each time accessing remote server that requires password (e.g. github.com), manually run ssh-add command (only once per terminal).
#if [ -f ~/.ssh/id_rsa ]; then ssh-add ~/.ssh/id_rsa; fi  # Key is for github


text:
void sleep_for_ms(int milliseconds);

#endif


text:
using Cofoundry.Domain.CQS;
using Cofoundry.Plugins.ErrorLogging.Domain;
using Cofoundry.Web;
using Cofoundry.Web.Admin;
using Microsoft.AspNetCore.Mvc;

namespace Cofoundry.Plugins.ErrorLogging.Admin;

public class ErrorsApiController : BaseAdminApiController
{
    private readonly IQueryExecutor _queryExecutor;
    private readonly IApiResponseHelper _apiResponseHelper;

    public ErrorsApiController(
        IQueryExecutor queryExecutor,
        IApiResponseHelper apiResponseHelper
        )
    {
        _queryExecutor = queryExecutor;
        _apiResponseHelper = apiResponseHelper;
    }

    public async Task<IActionResult> Get([FromQuery] SearchErrorSummariesQuery query)
    {
        if (query == null) query = new SearchErrorSummariesQuery();

        var results = await _queryExecutor.ExecuteAsync(query);
        return _apiResponseHelper.SimpleQueryResponse(results);
    }

    public async Task<IActionResult> GetById(int errorId)
    {
        var query = new GetErrorDetailsByIdQuery(errorId);
        var result = await _queryExecutor.ExecuteAsync(query);

        return _apiResponseHelper.SimpleQueryResponse(result);
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('orchestra', '0002_auto_20141229_1543'),
    ]

    operations = [
        migrations.AddField(
            model_name='project',
            name='short_description',
            field=models.CharField(default='', max_length=100),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='project',
            name='task_class',
            field=models.IntegerField(
                choices=[(0, 'Training tasks'), (1, 'A real task')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='step',
            name='worker_type',
            field=models.IntegerField(choices=[(0, 'Human'), (1, 'Machine')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='task',
            name='status',
            field=models.IntegerField(choices=[(0, 'Awaiting Processing'), (1, 'Processing'), (
                2, 'Pending Review'), (3, 'Reviewing'), (4, 'Post-review Processing'), (5, 'Complete')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='taskassignment',
            name='status',
            field=models.IntegerField(
                choices=[(0, 'Procesing'), (1, 'Submitted')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='workercertification',
            name='role',
            field=models.IntegerField(
                choices=[(0, 'Entry-level'), (1, 'Reviewer')]),
            preserve_default=True,
        ),
        migrations.AlterField(
            model_name='workercertification',
            name='task_class',
            field=models.IntegerField(
                choices=[(0, 'Training tasks'), (1, 'A real task')]),
            preserve_default=True,
        ),
    ]


text:
class AddDailyIssueLimitToUser < ActiveRecord::Migration[4.2]
  def change
    add_column :users, :daily_issue_limit, :integer
  end
end


text:
<?php

namespace zpt\cdt\bin;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * This class encapsulates the process for copying the user content of a site to
 * another site.
 *
 * @author Philip Graham <philip@zeptech.ca>
 */
class CopyUserContentProcess implements LifecycleProcess
{

	private $source;
	private $target;

	public function __construct($source, $target) {
		$this->source = $source;
		$this->target = $target;
	}

	public function execute(LoggerInterface $logger = null) {
		if ($logger === null) {
			$logger = new NullLogger();
		}

		$usrRelDirs = [ 'target/usr', 'target/htdocs/usr' ];
		foreach ($usrRelDirs as $usrRelDir) {
			$usrSrc = "$this->source/$usrRelDir";
			$usrTgt = "$this->target/$usrRelDir";
			if (file_exists($usrSrc)) {
				$logger->info("Copying user content from $usrSrc to $usrTgt");
				passthru("cp -a $usrSrc $usrTgt");
			} else {
				$logger->warning("User content $usrSrc does not exist");
				$logger->info("Creating user content directory: $usrTgt");
				mkdir($usrTgt, 0775, true);
			}
			$logger->debug("Giving web server user (www-data) write access to user " .
				"content directory: $usrTgt");
			chgrp($usrTgt, 'www-data');
		}
	}
}


text:
require('./angular-locale_ia');
module.exports = 'ngLocale';


text:
module Zuora::Objects
  class Amendment < Base
    belongs_to :subscription

    validates_presence_of :subscription_id, :name
    validates_length_of :name, :maximum => 100
    validates_inclusion_of :auto_renew, :in => [true, false], :allow_nil => true
    validates_length_of :code, :maximum => 50, :allow_nil => true
    validates_datetime_of :contract_effective_date, :allow_nil => true
    validates_datetime_of :customer_acceptance_date, :allow_nil => true
    validates_datetime_of :effective_date, :allow_nil => true
    validates_datetime_of :service_activation_date, :if => Proc.new { |a| a.status == 'PendingAcceptance' }
    validates_length_of :description, :maximum => 500, :allow_nil => true
    validates_numericality_of :initial_term, :if => Proc.new { |a| a.type == 'TermsAndConditions' }
    validates_numericality_of :renewal_term, :if => Proc.new { |a| a.type == 'TermsAndConditions' }
    validates_date_of :term_start_date, :if => Proc.new { |a| a.type == 'TermsAndConditions' }
    validates_presence_of :destination_account_id, :if => Proc.new {|a| a.type == 'OwnerTransfer' }
    validates_presence_of :destination_invoice_owner_id, :if => Proc.new {|a| a.type == 'OwnerTransfer' }
    validates_inclusion_of :status, :in => ["Completed", "Cancelled", "Draft", "Pending Acceptance", "Pending Activation"]
    validates_inclusion_of :term_type, :in => ['TERMED', 'EVERGREEN'], :allow_nil => true
    validates_inclusion_of :type, :in => ['Cancellation', 'NewProduct', 'OwnerTransfer', 'RemoveProduct', 'Renewal', 'UpdateProduct', 'TermsAndConditions']

    define_attributes do
      read_only :created_by_id, :created_date, :updated_by_id, :updated_date
      defaults :status => 'Draft'
      write_only :rate_plan_data
    end
  end
end


text:
@class DVTDocumentLocation, DVTFileDataType, DVTFilePath, IDEFileReference, IDENavigableItem, NSArray, NSImage, NSString;

@interface IDEContainerItemSnapshot : NSObject <IDEKeyDrivenNavigableItemRepresentedObject>
{
    NSString *_name;
    NSImage *_image;
    DVTDocumentLocation *_contentDocumentLocation;
    DVTFileDataType *_documentType;
    id _originalObject;
    NSArray *_subitems;
    BOOL _leaf;
    BOOL _isMajorGroup;
    DVTFilePath *_filePath;
    IDENavigableItem *_primaryChildItem;
    BOOL _showSubitems;
}

@property(getter=isLeaf) BOOL leaf; // @synthesize leaf=_leaf;
@property(readonly) BOOL showSubitems; // @synthesize showSubitems=_showSubitems;
@property(retain) NSArray *subitems; // @synthesize subitems=_subitems;
@property(readonly) IDENavigableItem *primaryChildItem; // @synthesize primaryChildItem=_primaryChildItem;
@property(readonly) DVTFilePath *filePath; // @synthesize filePath=_filePath;
@property(readonly) id originalObject; // @synthesize originalObject=_originalObject;
@property(readonly) BOOL isMajorGroup; // @synthesize isMajorGroup=_isMajorGroup;
@property(readonly) DVTFileDataType *navigableItem_documentType; // @synthesize navigableItem_documentType=_documentType;
@property(readonly) DVTDocumentLocation *navigableItem_contentDocumentLocation; // @synthesize navigableItem_contentDocumentLocation=_contentDocumentLocation;
@property(readonly) NSImage *navigableItem_image; // @synthesize navigableItem_image=_image;
@property(retain, nonatomic) NSString *navigableItem_name; // @synthesize navigableItem_name=_name;
- (void).cxx_destruct;
@property(readonly, copy) NSString *description;
- (id)initWithNavigableItem:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) IDEFileReference *navigableItem_fileReference;
@property(readonly) NSString *navigableItem_groupIdentifier;
@property(readonly) BOOL navigableItem_isLeaf;
@property(readonly) BOOL navigableItem_isMajorGroup;
@property(readonly) NSString *navigableItem_toolTip;
@property(readonly) Class superclass;

@end


text:
<?php
namespace App\Exception;
/**
 * Used for errors when using the file system.
 */
class FileException extends \Exception
{
    public function __construct($message) {
        parent::__construct($message, 0, null);
    }

    public static function create($format, ...$args) {
        return new FileException(vsprintf($format, $args));
    }
}


text:
from __future__ import print_function, division

import os
from pdb import set_trace
from time import time

import pandas as pd
from utils import list2dataframe
from tuner.devol import tune, default_opt, weka_instance

classifiers = {
    "rf": "weka.classifiers.trees.RandomForest",
    "c45": "weka.classifiers.trees.J48",
    "j48": "weka.classifiers.trees.J48",
    "cart": "weka.classifiers.trees.SimpleCart",
    "logistic": "weka.classifiers.functions.Logistic",
}

def csv_as_ndarray(fname):
    if isinstance(fname, str):
        dframe = pd.read_csv(fname)
    elif isinstance(fname, pd.core.frame.DataFrame):
        dframe = fname

    # dframe.loc[dframe[dframe.columns[-1]] > 0, dframe.columns[-1]] = 1.0
    # set_trace()
    ndarray = dframe.values.tolist()
    return ndarray

def get_actuals(fname):
    if isinstance(fname, str):
        dframe = pd.read_csv(fname)
    if isinstance(fname, list):
        dframe = list2dataframe(fname)
    elif isinstance(fname, pd.core.frame.DataFrame):
        dframe = fname

    return dframe[dframe.columns[-1]].values.tolist()

def classify(train, test, name="RF", tuning=False):
    jvm.start()

    if isinstance(train, list) and isinstance(test, list):
        train = weka_instance(train)
        trn_data = converters.load_any_file(train)
        test = weka_instance(test)
        tst_data = converters.load_any_file(test)

    elif os.path.isfile(train) and os.path.isfile(test):
        trn_data = converters.load_any_file(train)
        tst_data = converters.load_any_file(test)

    else:
        trn = csv_as_ndarray(train)
        tst = csv_as_ndarray(test)

        trn_data = converters.ndarray_to_instances(trn, relation="Train")
        tst_data = converters.ndarray_to_instances(tst, relation="Test")

    trn_data.class_is_last()
    tst_data.class_is_last()

    # t = time()
    if tuning:
        opt = tune(train)
    else:
        opt = default_opt
    # print("Time to tune: {} seconds".format(time() - t))

    cls = Classifier(classname=classifiers[name.lower()], options=opt)

    cls.build_classifier(trn_data)

    distr = [cls.distribution_for_instance(inst)[1] for inst in tst_data]
    preds = [cls.classify_instance(inst) for inst in tst_data]

    jvm.stop()

    return preds, distr

def __test_learners():
    data_dir = "../data/Jureczko/ant/"
    train = os.path.join(data_dir, "ant-1.3.csv")
    test = os.path.join(data_dir, "ant-1.4.csv")
    act, prd = classify(train, test)
    set_trace()
    return

if __name__ == "__main__":
    data_dir = "../data/Jureczko/ant/"
    __test_learners()
    # classify(data_dir)
    # load_and_print(data_dir)


text:
// Generated by xsd compiler for android/java
// DO NOT CHANGE!
package ebay.apis.eblbasecomponents;

/**
 *
 * This type is deprecated because Coss Promotions are no longer supported in the APIs.
 *
 *
 */
public enum MerchandizingPrefCodeType {

    /**
     *
   *
   * Seller allows item cross-promotion.
   *
     */
    OPT_IN("OptIn"),

    /**
     *
   *
   * Seller does not allow item cross-promotion.
   *
     */
    OPT_OUT("OptOut"),

    /**
     *
   *
   * Reserved for internal or future use.
   *
     */
    CUSTOM_CODE("CustomCode");

    private final String value;

    MerchandizingPrefCodeType(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static MerchandizingPrefCodeType fromValue(String v) {
        if (v != null) {
            for (MerchandizingPrefCodeType c: MerchandizingPrefCodeType.values()) {
                if (c.value.equals(v)) {
                    return c;
                }
            }
        }
        throw new IllegalArgumentException(v);
    }
}


text:
function create() {
  if [ "$#" -ne 1 ]
  then
        echo "Incorrect number of arguments"
        echo "Please specify the name of the new fiddle"
        exit 59
  fi

  fiddleSubDir="dojo"
  bornOnDate=$(date +"%m-%d-%y";)
  echo ${bornOnDate}

  #try
  (
      if [[ -d "../fiddles/${fiddleSubDir}/$1" ]]; then rm -R "../fiddles/${fiddleSubDir}/$1"; fi
      $(cp -rf "../fiddles/${fiddleSubDir}/template" "../fiddles/${fiddleSubDir}/$1") || exit 1
      $(voidSubstr '{{FiddleName}}' $1 "../fiddles/${fiddleSubDir}/$1/index.html";) || exit 2
      $(voidSubstr '{{BornOnDate}}' ${bornOnDate} "../fiddles/${fiddleSubDir}/$1/index.html";) || exit 2
      $(voidSubstr '{{FiddleName}}' $1 "../fiddles/${fiddleSubDir}/$1/README.markdown";) || exit 3
      $(voidSubstr '{{BornOnDate}}' ${bornOnDate} "../fiddles/${fiddleSubDir}/$1/README.markdown";) || exit 3
  )
  #catch
  _rc=$?
  case ${_rc} in
      0)  echo "Done. The \"../fiddles/${fiddleSubDir}/$1\" directory has been initialized."
          ;;
      1)  echo "foo bar! failed to create the \"../fiddles/${fiddleSubDir}/$1\" directory."
          ;;
      2)  echo "foo bar! failed trying to update the ../fiddles/${fiddleSubDir}/$1/index.html file."
          if [[ -d "../fiddles/${fiddleSubDir}/$1" ]]; then rm -R "../fiddles/${fiddleSubDir}/$1"; fi
          ;;
      3)  echo "foo bar! failed trying to update the ../fiddles/${_fiddleSubDir}/$1/README.markdown file."
          if [[ -d "../fiddles/${fiddleSubDir}/$1" ]]; then rm -R "../fiddles/${fiddleSubDir}/$1"; fi
          ;;
      *)  echo "foo bar! Something went wrong."
          if [[ -d "../fiddles/${fiddleSubDir}/$1" ]]; then rm -R "../fiddles/${fiddleSubDir}/$1"; fi
          ;;
  esac
  #finally
  exit ${_rc}

}


text:
model_root = File.dirname(__FILE__)
Dir["#{model_root}/*.rb"].each {|file| require file }


text:
$(document).ready(function(){

	$( "#menuradio" ).buttonset();
	$( "#loginradio" ).buttonset();
	$('input#logout_button').on('click',function(){
		window.location.replace('../user/logout');

	});
	$('input#profile_button').on('click',function(){
	//	window.location.replace('profile');
		$.ajax({
				  	type:'get',
					dataType: 'html',
					url: "../user/profile",
					success: function (response) {
						$('#content').html(response);
					}
				})

	});
	$('input#menu_admindash_button').on('click',function(){
		//	window.location.replace('profile');
			$.ajax({
					  	type:'get',
						dataType: 'html',
						url: "../admin_user/index",
						success: function (response) {
							$('#content').html(response);
						}
					})

		});
	$('input#menu_dash_button').on('click',function(){
			//	window.location.replace('profile');
				$.ajax({
						  	type:'get',
							dataType: 'html',
							url: "../user/dashboard",
							success: function (response) {
								$('#content').html(response);
							}
						})

			});
	$('input#menu_car_button').on('click',function(){
				//	window.location.replace('profile');
					$.ajax({
							  	type:'get',
								dataType: 'html',
								url: "../user/carstock",
								success: function (response) {
									$('#content').html(response);
								}
							})

				});

});


text:
Pogeo
=====

A Cython extension for geographic computation using Google's S2 library.


text:
package app.arsh.omniknightapp.view.adapters.viewholder;

import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import app.arsh.omniknightapp.R;

/**
 * Created by arash on 10/21/16.
 */

public class WeatherViewHolder extends RecyclerView.ViewHolder {

    TextView cityName;
    TextView cityWeatherDescriptionTextView;
    TextView weatherCondition;
    ImageView weatherImage;
    CheckBox removeCheckBox;

    public WeatherViewHolder(View itemView) {
        super(itemView);
        cityName = (TextView) itemView.findViewById(R.id.cityNameTextView);
        cityWeatherDescriptionTextView = (TextView) itemView.findViewById(R.id.cityWeatherDescriptionTextView);
        weatherCondition = (TextView) itemView.findViewById(R.id.weatherCondition);
        weatherImage = (ImageView) itemView.findViewById(R.id.cityFlagImageView);
        removeCheckBox = (CheckBox) itemView.findViewById(R.id.checkBox);
        cv = (CardView)itemView.findViewById(R.id.cardView);

    }

    private final CardView cv;

    public CardView getCv() {
        return cv;
    }

    public TextView getcityWeatherDescriptionTextView() {
        return cityWeatherDescriptionTextView;
    }

    public void setcityWeatherDescriptionTextView(TextView humidity) {
        this.cityWeatherDescriptionTextView = humidity;
    }

    public TextView getCityName() {
        return cityName;
    }

    public void setCityName(TextView cityName) {
        this.cityName = cityName;
    }

    public ImageView getWeatherImage() {
        return weatherImage;
    }

    public void setWeatherImage(ImageView weatherImage) {
        this.weatherImage = weatherImage;
    }
    public TextView getWeatherCondition() {
        return weatherCondition;
    }

    public void setWeatherCondition(TextView capitalTextView) {
        this.weatherCondition = capitalTextView;
    }

    public CheckBox getRemoveCheckBox() {
        return removeCheckBox;
    }

    public void setRemoveCheckBox(CheckBox removeCheckBox) {
        this.removeCheckBox = removeCheckBox;
    }
}