text:
#region license

#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CapCom.Framework;
using CapCom.Toolbar;
using Contracts;
using Contracts.Parameters;
using Contracts.Agents;
using FinePrint;
using FinePrint.Contracts.Parameters;
using FinePrint.Utilities;
using UnityEngine;
using ContractParser;
using ProgressParser;
using System.IO;

namespace CapCom
{
	[CC_KSPAddonImproved(CC_KSPAddonImproved.Startup.TimeElapses | CC_KSPAddonImproved.Startup.Editor, false)]
	public class CapCom : CC_MBE
	{
		private static CapCom instance;
		private static string version;
		private static CapComSettings settings = null;
		private CapComWindow window;
		private CC_StockToolbar appButton;
		private CC_Toolbar toolbar;

		private const string filePath = "PluginData/Settings";

		private static bool textureLoaded = false;

		private static bool loaded;

		protected override void Awake()
		{
			if (loaded)
			{
				Destroy(gameObject);
				return;
			}

			loaded = true;

			if (!textureLoaded)
			{
				textureLoaded = true;

				Texture original = null;

				foreach (Texture2D t in Resources.FindObjectsOfTypeAll<Texture2D>())
				{
					if (t.name == "SpriteAtlasTexture-MissionControl (Group 0)-1024x1024-fmt5")
					{
						LogFormatted("Texture Found...");
						original = t;
						break;
					}
				}

				if (original == null)
				{
					LogFormatted("Error loading Mission Control Center Texture atlas; some CapCom UI elements will not appear correctly");
					return;
				}

				Texture2D missionControlTexture = new Texture2D(original.width, original.height);

				var rt = RenderTexture.GetTemporary(original.width, original.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB, 1);

				Graphics.Blit(original, rt);

				RenderTexture.active = rt;

				missionControlTexture.ReadPixels(new Rect(0, 0, original.width, original.height), 0, 0);

				RenderTexture.active = null;
				RenderTexture.ReleaseTemporary(rt);

				rt = null;

				original = null;

				missionControlTexture.Apply();

				CapComSkins.texturesFromAtlas(missionControlTexture);

				Destroy(missionControlTexture);
			}

			CapComSkins.currentFlag = GameDatabase.Instance.GetTexture(HighLogic.CurrentGame.flagURL, false);

			int i = 0;
			while (CapComSkins.currentFlag == null && i < AgentList.Instance.Agencies.Count)
			{
				CapComSkins.currentFlag = AgentList.Instance.Agencies[i].LogoScaled;
				i++;
			}

			Assembly assembly = AssemblyLoader.loadedAssemblies.GetByAssembly(Assembly.GetExecutingAssembly()).assembly;
			var ainfoV = Attribute.GetCustomAttribute(assembly, typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
			switch (ainfoV == null)
			{
				case true: version = ""; break;
				default: version = ainfoV.InformationalVersion; break;
			}
		}

		protected override void Start()
		{
			instance = this;

			if (HighLogic.CurrentGame.Mode != Game.Modes.CAREER)
				Destroy(this);

			if (settings == null)
			{
				settings = new CapComSettings(filePath);

				//if (settings.useKSPStyle)
				//{
				//	CapComSkins.initializeKSPSkins();
				//	CC_SkinsLibrary.SetCurrent("CCKSPSkin");
				//}
				//else
				//{
				//	CapComSkins.initializeUnitySkins();
				//	CC_SkinsLibrary.SetCurrent("CCUnitySkin");
				//}
			}

			window = gameObject.AddComponent<CapComWindow>();

			if (ToolbarManager.ToolbarAvailable && !settings.stockToolbar)
			{
				if (toolbar == null)
					toolbar = gameObject.AddComponent<CC_Toolbar>();
				if (appButton != null)
					Destroy(appButton);
			}
			else
			{
				if (appButton == null)
					appButton = gameObject.AddComponent<CC_StockToolbar>();
				if (toolbar != null)
					Destroy(toolbar);
			}

			contractParser.onContractsParsed.Add(onContractsLoaded);
			contractParser.onContractStateChange.Add(refreshList);
			progressParser.onProgressParsed.Add(onProgressLoaded);
			GameEvents.Contract.onContractsListChanged.Add(onListChanged);
		}

		protected override void OnDestroy()
		{
			loaded = false;

			if (appButton != null)
				Destroy(appButton);

			if (toolbar != null)
				Destroy(toolbar);

			if (window != null)
				Destroy(window);

			contractParser.onContractsParsed.Remove(onContractsLoaded);
			contractParser.onContractStateChange.Remove(refreshList);
			progressParser.onProgressParsed.Remove(onProgressLoaded);
			GameEvents.Contract.onContractsListChanged.Remove(onListChanged);

			instance = null;
		}

		#region Public Accessors

		public static CapCom Instance
		{
			get { return instance; }
		}

		public CapComWindow Window
		{
			get { return window; }
		}

		public static CapComSettings Settings
		{
			get { return settings; }
		}

		public CC_Toolbar Toolbar
		{
			get { return toolbar; }
			set { toolbar = value; }
		}

		public CC_StockToolbar StockToolbar
		{
			get { return appButton; }
			set { appButton = value; }
		}

		public static string Version
		{
			get { return version; }
		}

		#endregion

		#region Events

		private void onContractsLoaded()
		{
			StartCoroutine(loadContracts());
		}

		private void onProgressLoaded()
		{
			StartCoroutine(loadProgress());
		}

		private void onListChanged()
		{
			window.refreshContracts(false);
		}

		#endregion

		#region Methods

		private IEnumerator loadContracts()
		{
			int i = 0;

			while (!contractParser.Loaded && i < 200)
			{
				i++;
				yield return null;
			}

			window.refreshContracts(true);
		}

		private IEnumerator loadProgress()
		{
			int i = 0;

			while (!progressParser.Loaded && i < 200)
			{
				i++;
				yield return null;
			}

			window.updateProgress();
		}

		private void refreshList(Contract c)
		{
			window.refreshContracts(false);

			if (c == null)
				return;

			if (c.ContractState != Contract.State.Active)
				return;

			contractContainer cc = contractParser.getActiveContract(c.ContractGuid);

			if (cc == null)
				return;

			if (cc.Initialized)
				return;

			for (int i = 0; i < cc.ParameterCount; i++)
			{
				parameterContainer p = cc.getParameterFull(i);

				if (p == null)
					continue;

				customStartup(p);
			}

			cc.Initialized = true;
		}

		private void customStartup(parameterContainer p)
		{
			Type t = p.CParam.GetType();
			GameScenes s = HighLogic.LoadedScene;

			try
			{
				if (t == typeof(ReachDestination) && s == GameScenes.FLIGHT && FlightGlobals.ActiveVessel != null)
				{
					if (p.CParam.State == ParameterState.Incomplete && ((ReachDestination)p.CParam).checkVesselDestination(FlightGlobals.ActiveVessel))
					{
						MethodInfo m = (typeof(ContractParameter)).GetMethod("SetComplete", BindingFlags.NonPublic | BindingFlags.Instance);

						if (m == null)
							return;

						m.Invoke(p.CParam, null);
					}
					else if (p.CParam.State == ParameterState.Complete && !((ReachDestination)p.CParam).checkVesselDestination(FlightGlobals.ActiveVessel))
					{
						MethodInfo m = (typeof(ContractParameter)).GetMethod("SetIncomplete", BindingFlags.NonPublic | BindingFlags.Instance);

						if (m == null)
							return;

						m.Invoke(p.CParam, null);
					}
				}
				else if (t == typeof(ReachSituation) && s == GameScenes.FLIGHT && FlightGlobals.ActiveVessel != null)
				{
					if (p.CParam.State == ParameterState.Incomplete && ((ReachSituation)p.CParam).checkVesselSituation(FlightGlobals.ActiveVessel))
					{
						MethodInfo m = (typeof(ContractParameter)).GetMethod("SetComplete", BindingFlags.NonPublic | BindingFlags.Instance);

						if (m == null)
							return;

						m.Invoke(p.CParam, null);
					}
					else if (p.CParam.State == ParameterState.Complete && !((ReachSituation)p.CParam).checkVesselSituation(FlightGlobals.ActiveVessel))
					{
						MethodInfo m = (typeof(ContractParameter)).GetMethod("SetIncomplete", BindingFlags.NonPublic | BindingFlags.Instance);

						if (m == null)
							return;

						m.Invoke(p.CParam, null);
					}
				}
				else if (t == typeof(SpecificOrbitParameter) && s == GameScenes.FLIGHT)
				{
					((SpecificOrbitParameter)p.CParam).SetupRenderer();
				}
				else if (t == typeof(VesselSystemsParameter) && s == GameScenes.FLIGHT)
				{
					VesselSystemsParameter sys = (VesselSystemsParameter)p.CParam;

					MethodInfo m = (typeof(VesselSystemsParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke(sys, null);

					if (!sys.requireNew)
						return;

					Vessel v = FlightGlobals.ActiveVessel;

					if (v == null)
						return;

					if (v.situation != Vessel.Situations.PRELAUNCH)
						return;

					uint launchID = v.Parts.Min(r => r.launchID);

					sys.launchID = launchID;
				}
				else if (t == typeof(SurveyWaypointParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(SurveyWaypointParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((SurveyWaypointParameter)p.CParam, null);

					if (p.Way == null)
						return;

					var waypoints = WaypointManager.Instance().Waypoints;

					if (waypoints.Contains(p.Way))
						return;

					WaypointManager.AddWaypoint(p.Way);
				}
				else if (t == typeof(StationaryPointParameter) && s == GameScenes.FLIGHT)
				{
					if (p.Way == null)
						return;

					var waypoints = WaypointManager.Instance().Waypoints;

					if (waypoints.Contains(p.Way))
						return;

					WaypointManager.AddWaypoint(p.Way);
				}
				else if (t == typeof(AsteroidParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(AsteroidParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((AsteroidParameter)p.CParam, null);
				}
				else if (t == typeof(CrewCapacityParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(CrewCapacityParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((CrewCapacityParameter)p.CParam, null);
				}
				else if (t == typeof(CrewTraitParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(CrewTraitParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((CrewTraitParameter)p.CParam, null);
				}
				else if (t == typeof(KerbalDestinationParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(KerbalDestinationParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((KerbalDestinationParameter)p.CParam, null);
				}
				else if (t == typeof(KerbalTourParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(KerbalTourParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((KerbalTourParameter)p.CParam, null);
				}
				else if (t == typeof(LocationAndSituationParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(LocationAndSituationParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((LocationAndSituationParameter)p.CParam, null);
				}
				else if (t == typeof(MobileBaseParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(MobileBaseParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((MobileBaseParameter)p.CParam, null);
				}
				else if (t == typeof(PartRequestParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(PartRequestParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((PartRequestParameter)p.CParam, null);
				}
				else if (t == typeof(ProgressTrackingParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(ProgressTrackingParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((ProgressTrackingParameter)p.CParam, null);
				}
				else if (t == typeof(ResourceExtractionParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(ResourceExtractionParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((ResourceExtractionParameter)p.CParam, null);
				}
				else if (t == typeof(VesselDestinationParameter) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(VesselDestinationParameter)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((VesselDestinationParameter)p.CParam, null);
				}
				else if (t == typeof(RecoverKerbal) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(RecoverKerbal)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((RecoverKerbal)p.CParam, null);
				}
				else if (t == typeof(RecoverPart) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(RecoverPart)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((RecoverPart)p.CParam, null);
				}
				else if (t == typeof(AcquirePart) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(AcquirePart)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((AcquirePart)p.CParam, null);
				}
				else if (t == typeof(AcquireCrew) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(AcquireCrew)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((AcquireCrew)p.CParam, null);
				}
				else if (t == typeof(PartTest) && s == GameScenes.FLIGHT)
				{
					MethodInfo m = (typeof(PartTest)).GetMethod("OnRegister", BindingFlags.NonPublic | BindingFlags.Instance);

					if (m == null)
						return;

					m.Invoke((PartTest)p.CParam, null);

					if (((PartTest)p.CParam).hauled)
						return;

					AvailablePart targetPart = ((PartTest)p.CParam).tgtPartInfo;

					if (targetPart == null)
						return;

					for (int i = 0; i < FlightGlobals.Vessels.Count; i++)
					{
						Vessel v = FlightGlobals.Vessels[i];

						if (v == null)
							continue;

						if (!v.loaded)
							continue;

						for (int j = 0; j < v.Parts.Count; j++)
						{
							Part part = v.Parts[j];

							if (part == null)
								continue;

							if (part.partInfo != targetPart)
								continue;

							var mods = part.FindModulesImplementing<ModuleTestSubject>();

							for (int k = 0; k < mods.Count; k++)
							{
								ModuleTestSubject test = mods[k];

								if (test == null)
									continue;

								test.Events["RunTestEvent"].active = true;
							}
						}
					}
				}
			}
			catch (Exception e)
			{
				LogFormatted("Error while forcing Contract Parameter activation:\n{0}", e);
			}
		}

		#endregion

	}
}


text:
<?php

class Github_Tests_Api_IssueTest extends Github_Tests_ApiTest
{
    public function testGetList()
    {
        $api = $this->getApiMock();

        $api->expects($this->once())
            ->method('get')
            ->with('issues/list/ornicar/php-github-api/open');

        $api->getList('ornicar', 'php-github-api', 'open');
    }

    protected function getApiClass()
    {
        return 'Github_Api_Issue';
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "nebula/mysql_client/mysql_client_util.h"

#include <string>
#include <map>

#include "nebula/mysql_client/mysql_client.h"

// std::vector<CdbConnPoolManager*> g_db_conn_pools;
// db::CdbConnPoolManager* g_db_conn_pool = nullptr;
// db::CdbConnPoolManager* g_db_conn_pool = nullptr;

namespace {
/*
std::shared_ptr<db::CdbConnPoolManager> Make(const std::string db_name) {
  db::DBAddrInfo db_addr;
  db_addr.host = "localhost";
  db_addr.port = 3307;
  db_addr.user = "root";
  db_addr.passwd = "";
  db_addr.db_name = db_name;
  db_addr.db_type = "mysql";

  auto db_conn_pool = std::make_shared<db::CdbConnPoolManager>();
  db_conn_pool->Initialize(db_addr);
  return db_conn_pool;
}

db::CdbConnPoolManager* GetDBConnPool(const std::string& db_name) {
  // TODO(@benqi): 有问题
  static std::map<std::string, std::shared_ptr<db::CdbConnPoolManager>> g_db_conn_pools;

  auto it = g_db_conn_pools.find(db_name);
  if (it==g_db_conn_pools.end()) {
    auto db_conn_pool = Make(db_name);
    g_db_conn_pools[db_name] = db_conn_pool;
    return db_conn_pool.get();
  } else {
    return it->second.get();
  }
}
 */
}

#if 0
int SqlQuery(const std::string& db_name, QueryWithResult& q) {
  int rv = 0;

  std::string query_string;
  q.SerializeToQuery(query_string);
  DCHECK(!query_string.empty());
  // TODO(@benqi): 这里可能会出错返回
  auto db_conn_pool = GetDBConnPool(db_name);
  db::ScopedPtr_DatabaseConnection db_conn(db_conn_pool);
  // -1

  std::unique_ptr<db::QueryAnswer> answ(db_conn->Query(query_string));
  if (answ.get() != NULL) {
    // bool is_empty;
    rv = static_cast<int>(answ->GetRowCount());
    // LOG(INFO) << "rv = " << rv;
    if(rv > 0) {
      while (answ->FetchRow()) {
        auto r = q.ParseFrom(*answ);
        if (r == BaseQueryResult::BREAK) {
          // 只处理一个
          rv = 1;
          break;
        } else if (r == BaseQueryResult::ERROR) {
          rv = -3;
          break;
        } else if (r == BaseQueryResult::CONTINUE) {
          // 继续
        }
      }
    }
  } else {
    rv = -2;
  }

  return rv;
}

int64_t SqlExecuteInsertID(const std::string& db_name, const BaseSqlQuery& query) {
  std::string query_string;
  query.SerializeToQuery(query_string);
  DCHECK(!query_string.empty());

  // TODO(@benqi): 这里可能会出错返回,出错返回
  auto db_conn_pool = GetDBConnPool(db_name);
  db::ScopedPtr_DatabaseConnection db_conn(db_conn_pool);
  return db_conn->ExecuteInsertID(query_string);
}

int SqlExecute(const std::string& db_name, const BaseSqlQuery& query) {
  std::string query_string;
  query.SerializeToQuery(query_string);
  DCHECK(!query_string.empty());

  // TODO(@benqi): 这里可能会出错返回,出错返回
  auto db_conn_pool = GetDBConnPool(db_name);

  db::ScopedPtr_DatabaseConnection db_conn(db_conn_pool);
  return db_conn->Execute(query_string);
}

#endif

int DoStorageQuery(const std::string& db_name, MakeQueryStringFunc make_q, MakeQueryResultFunc make_r) {
  int rv = 0;

  std::string query_string;
  make_q(query_string);
  if (query_string.empty()) {
    LOG(ERROR) << "DoStorageQuery - make_q error, query_string is empty!!!";
    return -2;
  }

  // TODO(@benqi): 这里可能会出错返回
  auto db_conn_pool = GetMysqlConnPool(db_name);
  // auto conn_pool = mysql_client.GetConnPool("nebula_platform");
  // auto r = conn_pool->Query(q);

  // db::ScopedPtr_DatabaseConnection db_conn(db_conn_pool);
  // -1
  auto query_result = db_conn_pool->Query(query_string);
  // std::unique_ptr<db::QueryAnswer> answ(db_conn->Query(query_string));
  if (query_result) {
    // bool is_empty;
    rv = static_cast<int>(query_result->GetRowCount());
    // LOG(INFO) << "rv = " << rv;
    if(rv > 0) {
      while (query_result->FetchRow()) {
        auto r = make_r(*query_result.result_set);
        if (r == QResultCode::BREAK) {
          // 只处理一个
          rv = 1;
          break;
        } else if (r == QResultCode::ERROR) {
          rv = -3;
          break;
        } else if (r == QResultCode::CONTINUE) {
          // 继续
        }
      }
    }
  } else {
    rv = -2;
  }

  return rv;
}

int64_t DoStorageInsertID(const std::string& db_name, MakeQueryStringFunc make_q) {
  std::string query_string;
  make_q(query_string);
  if (query_string.empty()) {
    LOG(ERROR) << "DoStorageInsertID - make_q error, query_string is empty!!!";
    return -2;
  }

  // TODO(@benqi): 这里可能会出错返回,出错返回
  auto db_conn_pool = GetMysqlConnPool(db_name);
  return db_conn_pool->ExecuteInsertID(query_string);
}

int DoStorageExecute(const std::string& db_name, MakeQueryStringFunc make_q) {
  std::string query_string;
  make_q(query_string);
  if (query_string.empty()) {
    LOG(ERROR) << "DoStorageExecute - make_q error, query_string is empty!!!";
    return -2;
  }

  // TODO(@benqi): 这里可能会出错返回,出错返回
  auto db_conn_pool = GetMysqlConnPool(db_name);
  return db_conn_pool->Execute(query_string);
}


text:
package banking.domain;

public class SavingsAccount extends Account {

  private double   interestRate;

  public SavingsAccount(double bal, double rate) {
    super(bal);
    interestRate = rate;
  }
}


text:
/* globals describe, it */
import * as assert from 'assert';
import xs from 'xstream';
import Collection from '../src/collection';

function Widget ({props$}) {
  return {
    state$: props$
  };
}

describe('Collection.pluck', () => {
  it('handles adding items', (done) => {
    const props$ = xs.create().startWith({foo: 'bar'});

    const collection$ = Collection(Widget, {}, xs.of(
      {props$},
      {props$: xs.of({baz: 'quix'})}
    ));

    const states$ = Collection.pluck(collection$, item => item.state$);

    const expected = [
      [],
      [],
      [{foo: 'bar'}],
      [{foo: 'bar'}, {baz: 'quix'}]
    ];

    states$.take(expected.length).addListener({
      next (val) {
        assert.deepEqual(val, expected.shift());
      },
      error (err) { done(err); },
      complete () {
        assert.equal(expected.length, 0);
        done();
      }
    });
  });
});


text:
<?php

/**
 * PHP version 7.3
 *
 * @category CustomMethods
 * @package  RetailCrm\Api\ResourceGroup
 */

namespace RetailCrm\Api\ResourceGroup;

use RetailCrm\Api\Component\RequestSender;
use RetailCrm\Api\Exception\Client\HandlerException;

/**
 * Class CustomMethods
 *
 * @category CustomMethods
 * @package  RetailCrm\Api\ResourceGroup
 *
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CustomMethods extends AbstractApiResourceGroup
{
    /** @var \RetailCrm\Api\Interfaces\RequestSenderInterface|null */
    private $requestSender;

    /** @var array<string, callable|\RetailCrm\Api\Component\CustomApiMethod> */
    private $methods = [];

    /**
     * Register custom method in the resource group. You can use invokable class for easier implementation.
     *
     * Registered callable should accept three arguments:
     *  - `RequestSenderInterface`
     *  - Array with the request data (may be null or empty if not provided - this is the case for get requests).
     *  - Context data - may contain any data. You can use the context for anything you like.
     *
     * Example with the `CustomApiMethod` wrapper:
     *
     * ```php
     * use RetailCrm\Api\Component\CustomApiMethod;
     * use RetailCrm\Api\Enum\RequestMethod;
     * use RetailCrm\Api\Factory\SimpleClientFactory;
     * use RetailCrm\Api\Interfaces\ApiExceptionInterface;
     *
     * $client = SimpleClientFactory::createClient('https://test.simla.com', 'apiKey');
     * $client->customMethods->register('settings', new CustomApiMethod(RequestMethod::GET, 'settings'));
     * ```
     *
     * Sometimes `CustomApiMethod` may feel too simple to do certain tasks in the methods. That's why it is possible
     * to register custom callable. Let's register a custom method that returns array of available scopes:
     *
     * use RetailCrm\Api\Enum\RequestMethod;
     * use RetailCrm\Api\Factory\SimpleClientFactory;
     * use RetailCrm\Api\Interfaces\ApiExceptionInterface;
     * use RetailCrm\Api\Interfaces\RequestSenderInterface;
     *
     * ```php
     * $client = SimpleClientFactory::createClient('https://test.simla.com', 'apiKey');
     * $client->customMethods->register(
     *     'scopes',
     *     static function (RequestSenderInterface $sender, $data, array $context) {
     *         return $sender->send(
     *             RequestMethod::GET,
     *             sprintf('https://%s/api/credentials', $sender->host()),
     *             $data
     *         )['scopes'];
     *     }
     * );
     * ```
     *
     * Check `call()` method to learn how to call registered methods.
     *
     * @see self::call
     * @see \RetailCrm\Api\Interfaces\RequestSenderInterface
     * @see RequestSender
     * @see \RetailCrm\Api\Component\CustomApiMethod
     *
     * @param string                                            $name
     * @param callable|\RetailCrm\Api\Component\CustomApiMethod $sender
     */
    public function register(string $name, callable $sender): void
    {
        if (null === $this->requestSender) {
            $this->requestSender = new RequestSender($this);
        }

        $this->methods[$name] = $sender;
    }

    /**
     * Calls custom method, returns array response.
     *
     * Usage:
     *
     * ```php
     * $client->customMethods->call('scopes');
     * ```
     *
     * Second parameter should be provided for POST requests or query data. Third parameter is used to pass anything
     * you like to the callable during the method call (logger, for example).
     *
     * This implementation is also used in the `__call` magic method. It works like this:
     *
     * ```php
     * $client->customMethods->scopes($data, 'any', 'other', 'params');
     * ```
     * will make this call:
     * ```php
     * $client->customMethods->call('scopes', $data, ['any', 'other', 'params']);
     * ```
     *
     * Full example for the settings method:
     *
     * ```php
     * use RetailCrm\Api\Component\CustomApiMethod;
     * use RetailCrm\Api\Enum\RequestMethod;
     * use RetailCrm\Api\Factory\SimpleClientFactory;
     * use RetailCrm\Api\Interfaces\ApiExceptionInterface;
     *
     * $client = SimpleClientFactory::createClient('https://azgalot.retailcrm.ru', '9y3e3ohX1NGqAausgg5ACMWPv5Z4iXQF');
     * $client->customMethods->register('settings', new CustomApiMethod(RequestMethod::GET, 'settings'));
     *
     * try {
     *     // It will work because 'settings' method was registered before
     *     $settings = $client->customMethods->settings();
     * } catch (ApiExceptionInterface $exception) {
     *     echo sprintf(
     *         'Error from RetailCRM API (status code: %d): %s',
     *         $exception->getStatusCode(),
     *         $exception->getMessage()
     *     );
     *
     *     if (count($exception->getErrorResponse()->errors) > 0) {
     *         echo PHP_EOL . 'Errors: ' . implode(', ', $exception->getErrorResponse()->errors);
     *     }
     *
     *     return;
     * }
     *
     * echo 'Timezone: ' . $settings['settings']['timezone']['value'];
     * ```
     *
     * @param string                          $name
     * @param array<int|string, mixed>|object $data
     * @param array<int|string, mixed>        $context
     *
     * @return array<int|string, mixed>|object
     * @throws \RetailCrm\Api\Interfaces\ApiExceptionInterface
     * @throws \RetailCrm\Api\Interfaces\ClientExceptionInterface
     * @throws \RetailCrm\Api\Exception\Api\AccountDoesNotExistException
     * @throws \RetailCrm\Api\Exception\Api\ApiErrorException
     * @throws \RetailCrm\Api\Exception\Api\MissingCredentialsException
     * @throws \RetailCrm\Api\Exception\Api\MissingParameterException
     * @throws \RetailCrm\Api\Exception\Api\ValidationException
     * @throws \RetailCrm\Api\Exception\Client\HandlerException
     * @throws \RetailCrm\Api\Exception\Client\HttpClientException
     */
    public function call(string $name, $data = [], array $context = [])
    {
        if (null === $this->requestSender || !array_key_exists($name, $this->methods)) {
            throw new HandlerException(sprintf('Cannot find custom method with name "%s"', $name));
        }

        return $this->methods[$name]($this->requestSender, $data, $context);
    }

    /**
     * Calls custom method, returns array response.
     *
     * @param string                   $name
     * @param array<int|string, mixed> $arguments
     *
     * @return array<int|string, mixed>|object
     * @throws \RetailCrm\Api\Interfaces\ApiExceptionInterface
     * @throws \RetailCrm\Api\Interfaces\ClientExceptionInterface
     * @throws \RetailCrm\Api\Exception\Api\AccountDoesNotExistException
     * @throws \RetailCrm\Api\Exception\Api\ApiErrorException
     * @throws \RetailCrm\Api\Exception\Api\MissingCredentialsException
     * @throws \RetailCrm\Api\Exception\Api\MissingParameterException
     * @throws \RetailCrm\Api\Exception\Api\ValidationException
     * @throws \RetailCrm\Api\Exception\Client\HandlerException
     * @throws \RetailCrm\Api\Exception\Client\HttpClientException
     *@see \RetailCrm\Api\ResourceGroup\CustomMethods::call()
     *
     */
    public function __call(string $name, array $arguments)
    {
        $data = [];
        $context = [];

        if (count($arguments) > 0) {
            if (!is_array($arguments[0]) && !is_object($arguments[0])) {
                throw new HandlerException(sprintf(
                    '$data must be of type array or object, %s given',
                    gettype($arguments[0])
                ));
            }

            $data = $arguments[0];
        }

        if (count($arguments) > 1) {
            if (!is_array($arguments[1])) {
                throw new HandlerException(sprintf(
                    '$context must be of type array, %s given',
                    gettype($arguments[1])
                ));
            }

            $context = $arguments[1];
        }

        return $this->call($name, $data, $context);
    }
}


text:
'use strict';

// MODULES //

var isObject = require( '@stdlib/assert/is-plain-object' );
var format = require( '@stdlib/string/format' );
var copy = require( '@stdlib/utils/copy' );
var Stream = require( './main.js' );

// MAIN //

/**
* Returns an inspect stream with `objectMode` set to `true`.
*
* @param {Options} [options] - stream options
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the `Buffer` level for when `write()` starts returning `false`
* @param {boolean} [options.allowHalfOpen=false] - specifies whether the stream should remain open even if one side ends
* @param {boolean} [options.readableObjectMode=false] - specifies whether the readable side should be in object mode
* @param {Callback} clbk - callback to invoke upon receiving data
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {TypeError} must provide a callback function
* @returns {InspectStream} inspect stream
*
* @example
* function log( chunk, idx ) {
*     console.log( 'index: %d', idx );
*     console.log( chunk );
* }
*
* var stream = objectMode( log );
*
* stream.write( {'value': 'a'} );
* stream.write( {'value': 'b'} );
* stream.write( {'value': 'c'} );
*
* stream.end();
*
* // prints: index: 0
* // prints: {'value': 'a'}
* // prints: index: 1
* // prints: {'value': 'b'}
* // prints: index: 2
* // prints: {'value': 'c'}
*/
function objectMode( options, clbk ) {
	var opts;
	var cb;
	if ( arguments.length > 1 ) {
		if ( !isObject( options ) ) {
			throw new TypeError( format( 'invalid argument. Options argument must be an object. Value: `%s`.', options ) );
		}
		opts = copy( options );
		cb = clbk;
	} else {
		opts = {};
		cb = options;
	}
	opts.objectMode = true;
	return new Stream( opts, cb );
}

// EXPORTS //

module.exports = objectMode;


text:
int main(int, char* argv[])
{
	RenderParams params;
	params.width = 1024;
	params.height = 768;
	params.MSAA = 8;
	params.fullscreen = false;

	App* app = new App();
	Scene* scene = nullptr;
	//scene = new SceneDeferred(app, params);
	scene = new SceneSSAO(app, params);
	app->fire(scene);

	SAFE_DELETE(app);

	return 0;
}


text:
/*
Author: Adam Austin
Date: 01/27/2017
*/

#ifndef VENDINGMACHINE_H
#define VENDINGMACHINE_H

#include <iostream>
#include <array>
#include "Item.h"

using namespace std;

const int PRODUCT_COUNT = 20;

class VendingMachine
{
	public:
	VendingMachine();
	void assignProductLocation(Item);
	void printContents();
	Item getItemAtIndex(int);
	void removeItemAtIndex(int);
	void centerText(string, int);
	void centerDouble(double, int);

	private:
	Item merchandise[PRODUCT_COUNT];
};

#endif // VENDINGMACHINE_H


text:
(function()
{
"use strict";

angular.module("hcontroller.directives", []).
  //
  // Version directive
  directive("version", function(version) {
    return {
      replace: true,
      restrict: "E",
      template: "
AngualrJS v{{ver}}
",
      link: function(scope)
      {
        scope.ver = angular.version.full;
      }
    };
  });
})();


text:
SpectrumLine::SpectrumLine(){
  this->randomize();
  lineHeight = 2;
}

void SpectrumLine::randomize(){
  lineHeight = random(0, LED_HEIGHT-1);
}

void SpectrumLine::run(Sign &sign, EffectData &data){
  data.shouldStep = true;

  uint8_t min = min(FREQ_COUNT, LED_WIDTH);
  sign.off();

  for(uint8_t i=0; i< min; i++){
    Pixel* pixel = sign.pixel(i, lineHeight);
    pixel->hue[0] = map(data.freqAmp[i],0,data.maxFreqAmp[i],0,0xFFFF);
  }
}

void SpectrumLine::setConfig(uint8_t kConfig){
  switch(kConfig){
    case BOTTOM_BUBBLES_CONFIG:
      lineHeight = 0;
      break;

    case CENTER_SPECTRUM_CONFIG:
      lineHeight = LED_Y_CENTER;
      break;
  }
}

void SpectrumLine::push(IrInput input){
  Effect::push(input);

  switch(input){
    case UP: if(lineHeight < LED_HEIGHT-1){ ++lineHeight;} break;
    case DOWN: if(lineHeight > 0){ --lineHeight;} break;
  }
}


text:
package com.alibaba.jstorm.daemon.nimbus;

import backtype.storm.Config;
import backtype.storm.generated.InvalidTopologyException;
import com.alibaba.jstorm.cluster.Common;
import com.alibaba.jstorm.cluster.StormConfig;
import com.alibaba.jstorm.metric.MetricUtils;
import org.jboss.netty.util.internal.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class TopologyNettyMgr {
    private static Logger LOG = LoggerFactory.getLogger(TopologyNettyMgr.class);
    private Map nimbusConf;
    private ConcurrentHashMap<String, Boolean> setting = new ConcurrentHashMap<String, Boolean>();

    public TopologyNettyMgr(Map conf) {
        nimbusConf = conf;

    }

    protected boolean getTopology(Map conf) {
        return MetricUtils.isEnableNettyMetrics(conf);
    }

    public boolean getTopology(String topologyId) {
        try {
            String topologyName = Common.topologyIdToName(topologyId);

            Boolean isEnable = setting.get(topologyName);
            if (isEnable != null) {
                return isEnable;
            }

            Map topologyConf = StormConfig.read_nimbus_topology_conf(nimbusConf, topologyId);

            isEnable = getTopology(topologyConf);
            setting.put(topologyName, isEnable);
            LOG.info("{} netty metrics setting is {}", topologyName, isEnable);
            return isEnable;

        } catch (Exception e) {
            LOG.info("Failed to get {} netty metrics setting ", topologyId);
            return true;
        }

    }

    public void setTopology(Map conf) {
        String topologyName = (String) conf.get(Config.TOPOLOGY_NAME);
        if (topologyName == null) {
            LOG.info("No topologyName setting");
            return;
        }

        boolean isEnable = getTopology(conf);

        setting.put(topologyName, isEnable);

        LOG.info("{} netty metrics setting is {}", topologyName, isEnable);
        return;

    }

    public void rmTopology(String topologyId) {
        String topologyName;
        try {
            topologyName = Common.topologyIdToName(topologyId);
            setting.remove(topologyName);
            LOG.info("Remove {} netty metrics setting ", topologyName);
        } catch (InvalidTopologyException ignored) {
        }

    }

}


text:
//
//  APCOnboarding.h
//  APCAppCore
//
// Copyright (c) 2015, Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1.  Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2.  Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3.  Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

#import <UIKit/UIKit.h>
#import "APCOnboardingTask.h"

#import <ResearchKit/ResearchKit.h>

@protocol APCOnboardingDelegate;
@class APCScene;

NS_ASSUME_NONNULL_BEGIN

@interface APCOnboarding : NSObject

@property (nonatomic, readonly) APCOnboardingTask *onboardingTask;

@property (nonatomic, strong) ORKStep *__nullable currentStep;

@property (nonatomic, strong) NSMutableDictionary *sceneData;

@property (nonatomic, weak) id <APCOnboardingDelegate> __nullable delegate;

@property (nonatomic, readonly) APCOnboardingTaskType taskType;

- (instancetype)initWithDelegate:(id<APCOnboardingDelegate>)object taskType:(APCOnboardingTaskType)taskType;

- (nullable UIViewController *)viewControllerForSceneIdentifier:(NSString *)identifier;

- (void)setScene:(APCScene *)scene forIdentifier:(NSString *)identifier;

- (nullable UIViewController *)nextScene;

- (void)popScene;

- (BOOL)isSignInSupported;

@end

@protocol APCOnboardingDelegate <APCOnboardingTaskDelegate>

@required

/**
 *  Return the scene for the desired type, or nil if the scene should be skipped.
 */
- (nullable APCScene *)onboarding:(APCOnboarding *)onboarding sceneOfType:(NSString *)type;

@end

/**
 *  Simple container to hold on to a specific view controller in a storyboard.
 */
@interface APCScene : NSObject

/** Refers to StoryboardID. */
@property (nonatomic, strong) NSString *name;

/** The name of the storyboard. */
@property (nonatomic, strong) NSString *storyboardName;

/** Defaults to the bundle this class resides in. */
@property (nonatomic, strong) NSBundle *bundle;

- (instancetype)initWithName:(NSString *)name inStoryboard:(NSString *)storyboardName;

/** Instantiates the view controller as defined by this scene. */
- (nullable UIViewController *)instantiateViewController;

@end

NS_ASSUME_NONNULL_END


text:
package ru.job4j.web;

import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
 * Класс AttributeStorage реалиует сущность Хранилище атрибутов.
 *
 * @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
 * @version 2018-05-28
 * @since 2018-05-28
 */
public class AttributeStorage {
    /**
     * Атрибуты.
     */
    private ConcurrentHashMap<String, Object> attributes = new ConcurrentHashMap<>();
    /**
     * Установить хранилище атрибутов.
     * @param req HTTP-запрос.
     */
    public void set(HttpServletRequest req) {
        // Mock setAttribute
        Mockito.doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                String key = invocation.getArgumentAt(0, String.class);
                Object value = invocation.getArgumentAt(1, Object.class);
                attributes.put(key, value);
                //System.err.println("Storage <<< key: " + key + ", val:" + value);
                return null;
            }
        }).when(req).setAttribute(Mockito.anyString(), Mockito.anyObject());
        // Mock getAttribute
        Mockito.doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                String key = invocation.getArgumentAt(0, String.class);
                Object value = attributes.get(key);
                //System.err.println("Storage >>> key: " + key + ", val: " + value);
                return value;
            }
        }).when(req).getAttribute(Mockito.anyString());
    }
}


text:
// From starkbank-ecdsa, minimal interface of PublicKey
declare class PublicKey {
  toString(encode?: boolean): string;
  static fromPem(pem: string): PublicKey;
  static fromDer(der: string): PublicKey;
  static fromString(key: string): PublicKey;
}

declare class EventWebhook {
    /**
     *
     * @param {string} publicKey verification key under Mail Settings
     * @return {PublicKey} A public key using the ECDSA algorithm
     */
    convertPublicKeyToECDSA(publicKey: string): PublicKey;

    /**
     *
     * @param {PublicKey} publicKey elliptic curve public key
     * @param {string|Buffer} payload event payload in the request body
     * @param {string} signature value obtained from the 'X-Twilio-Email-Event-Webhook-Signature' header
     * @param {string} timestamp value obtained from the 'X-Twilio-Email-Event-Webhook-Timestamp' header
     * @return {Boolean} true or false if signature is valid
     */
    verifySignature(publicKey: PublicKey, payload: string|Buffer, signature: string, timestamp: string): boolean;
}

/*
 * This class lists headers that get posted to the webhook. Read the docs for
 * more details: https://sendgrid.com/docs/for-developers/tracking-events/event
 */
declare class EventWebhookHeader {
    static SIGNATURE(): string;
    static TIMESTAMP(): string
}

export {
    EventWebhook,
    EventWebhookHeader,
};


text:
<?php

namespace Application\Entity;

use Doctrine\ORM\Mapping as ORM;

use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\Date;

/**
 *
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="container_type",type="string")
 * @ORM\DiscriminatorMap({"container" = "Container","schematic" = "Schematic","lesson" = "Lesson","graphic" = "Graphic"})
 * @ORM\Table(name="Container")
 *
 *
 */

class Schematic implements InputFilterAwareInterface
{
    private $columnsize;

    protected $inputFilter;
    protected $em;

    public function exchangeArray($data)
    {
        $this->id = (isset($data['id'])) ? $data['id'] : null;
        $this->username = (isset($data['username'])) ? $data['username'] : null;
        $this->original = (isset($data['original'])) ? $data['original'] : null;
        $this->title= (isset($data['title'])) ? $data['title'] : null;
        $this->background= (isset($data['background'])) ? $data['background'] : null;
        $this->frame = (isset($data['frame'])) ? $data['frame'] : null;
        $this->backgroundwidth  = (isset($data['backgroundwidth'])) ? $data['backgroundwidth'] : null;
        $this->backgroundheight = (isset($data['backgroundheight'])) ? $data['backgroundheight'] : null;
	$this->bgColor = (isset($data['bgColor'])) ? $data['bgColor'] : null;
        $this->items = (isset($data['items'])) ? $data['items'] : null;
	$this->container_type = (isset($data['container_type'])) ? $data['container_type'] : null;
    }
    public function setEntityManager($em)
    {
	$this->em = $em;
    }
    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
			$factory = new InputFactory();

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'id',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'username',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'original',
                'required' => false,
                'options' => array(
                	'format' => 'Ymd'
				)
            ))
			);

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'title',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'container_type',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'background',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'bgColor',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'frame',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'backgroundheight',
                'required' => false,
            )));

            $inputFilter->add(
            	$factory->createInput(array(
                'name' => 'backgroundwidth',
                'required' => false,
            )));

            $this->inputFilter = $inputFilter;
        }
        return $this->inputFilter;
    }
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not Used");
    }
    public function getArrayCopy()
    {
        return get_object_vars($this);
    }
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="wordage", type="string", length=255, nullable=false)
     */
    /**
     * @var string
     */
    private $username;

    /**
     * @var string
     *
     * @ORM\Column(name="original", type="string", length=255, nullable=false)
     */
    private $original;

    /**
     * @var string
     *
     * @ORM\Column(name="bgColor", type="string", length=50, nullable=false)
     */
    private $bgColor;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="text", length=255, nullable=false)
     */
    private $title;

    private $container_type;

    /**
     * @var boolean
     *
     * @ORM\Column(name="background", type="boolean", nullable=false)
     */
    private $background;

    /**
     * @var boolean
     *
     * @ORM\Column(name="frame", type="boolean", nullable=false)
     */
    private $frame;

    /**
     * @var integer
     *
     * @ORM\Column(name="backgroundwidth", type="integer", nullable=false)
     *
     */
    private $backgroundwidth;

    /**
     * @var integer
     *
     * @ORM\Column(name="backgroundheight", type="integer", nullable=false)
     *
     */
    private $backgroundheight;

    private $items;

    public function getItems()
    {
	return $this->items;
    }
    public function setItems($itemsArray)
    {
	$this->items = $itemsArray;
    }
    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set username
     *
     * @param string $username
     * @return Container
     */
    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername()
    {
        return $this->username;
    }

    /**
     * Set original_date
     *
     * @param \DateTime $originalDate
     * @return Container
     */
    public function setOriginalDate($originalDate)
    {
        $this->original = $originalDate;

        return $this;
    }

    /**
     * Get original_date
     *
     * @return \DateTime
     */
    public function getOriginalDate()
    {
        return $this->original;
    }

    /**
     * Set bgColor
     *
     * @param string $bgColor
     * @return Container
     */
    public function setBgColor($bgColor)
    {
	$this->bgColor = $bgColor;
    }
    /**
     * Get bgColor
     *
     * @return string
     */
    public function getBgColor()
    {
        return $this->bgColor;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Container
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set container_type
     *
     * @param string $container_type
     * @return Container
     */
    public function setContainerType($container_type)
    {
        $this->container_type = $container_type;

        return $this;
    }

    /**
     * Get container type
     *
     * @return string
     */
    public function getContainerType()
    {
        return $this->container_type;
    }

    /**
     * Set background
     *
     * @param string $background
     * @return Container
     */
    public function setBackground($background)
    {
        $this->background = $background;

        return $this;
    }

    /**
     * Get background
     *
     * @return string
     */
    public function getBackground()
    {
        return $this->background;
    }

    /**
     * Set frame
     *
     * @param boolean $frame
     * @return Container
     */
    public function setFrame($frame)
    {
        $this->frame = $frame;

        return $this;
    }

    /**
     * Get frame
     *
     * @return boolean
     */
    public function getFrame()
    {
        return $this->frame;
    }

    /**
     * Set backgroundwidth
     *
     * @param integer $backgroundwidth
     * @return Container
     */
    public function setBackgroundwidth($backgroundwidth)
    {
        $this->backgroundwidth = $backgroundwidth;

        return $this;
    }

    /**
     * Get backgroundwidth
     *
     * @return integer
     */
    public function getBackgroundwidth()
    {
        return $this->backgroundwidth;
    }

    /**
     * Set backgroundheight
     *
     * @param integer $backgroundheight
     * @return Container
     */
    public function setBackgroundheight($backgroundheight)
    {
        $this->backgroundheight = $backgroundheight;

        return $this;
    }

    /**
     * Get backgroundheight
     *
     * @return integer
     */
    public function getBackgroundheight()
    {
        return $this->backgroundheight;
    }
}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class Sso_Cache_Base</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Class Sso_Cache_Base

Description

					Description |
															Methods (details)

Sso Cache

The Sso Cache provides a caching abstraction layer.

			Located in /Cache/Base.php (line 13)

Method Summary

			Description |
												Methods (details)

											Sso_Cache_Base
										__construct
											(Sso_Cache_Backend_Interface $backend)

											void
										add
											(string $name, mixed $value, [int $ttl = 0])

											void
										del
											(string $name)

											mixed
										get
											(string $name)

											Sso_Cache_Backend_Interface
										getBackend
										()

											boolean
										has
											(string $name)

											void
										set
											(string $name, mixed $value, [int $ttl = 0])

Methods

			Description |
																Methods (details)

		Constructor __construct (line 30)

Create a new instance and encapsulate the passed Sso_Cache_Backend.

access: public

		Sso_Cache_Base

			__construct

					(Sso_Cache_Backend_Interface $backend)

				Sso_Cache_Backend_Interface
				$backend

		add (line 69)

Add the key with the given $name to the cache with the given $value only if it does not  currently exist. Can also give a $timeout in seconds.

access: public

		void

			add

					(string $name, mixed $value, [int $ttl = 0])

				string
				$name

				mixed
				$value

				int
				$ttl

		del (line 80)

Delete the key with the given $name.

access: public

		void

			del

					(string $name)

				string
				$name

		get (line 42)

Retrieve the key with $name from the cache.

access: public

		mixed

			get

					(string $name)

				string
				$name

		getBackend (line 102)

Retrieve the currently configured backend.

access: public

		Sso_Cache_Backend_Interface

			getBackend

				()

		has (line 91)

Return boolean true of false if the key with the given $name exists or not.

access: public

		boolean

			has

					(string $name)

				string
				$name

		set (line 55)

Set the key with the given $name to $value. Can also give a $timeout seconds.

access: public

		void

			set

					(string $name, mixed $value, [int $ttl = 0])

				string
				$name

				mixed
				$value

				int
				$ttl

		Documentation generated on Fri, 24 Jul 2009 17:12:42 +0100 by phpDocumentor 1.4.2


text:
package space.pxls.auth;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.json.JSONObject;
import space.pxls.App;

public class GoogleAuthService extends AuthService {
    public GoogleAuthService(String id) {
        super(id, App.getConfig().getBoolean("oauth.google.enabled"), App.getConfig().getBoolean("oauth.google.registrationEnabled"));
    }

    @Override
    public String getRedirectUrl(String state) {
        return "https://accounts.google.com/o/oauth2/v2/auth?" +
                "scope=profile%20email&" +
                "access_type=online&" +
                "include_granted_scopes=true&" +
                "state=" + state + "&" +
                "redirect_uri=" + getCallbackUrl() + "&" +
                "response_type=code&" +
                "client_id=" + App.getConfig().getString("oauth.google.key");
    }

    @Override
    public String getToken(String code) throws UnirestException {
        HttpResponse<JsonNode> response = Unirest.post("https://www.googleapis.com/oauth2/v4/token")
                .header("User-Agent", "pxls.space")
                .field("grant_type", "authorization_code")
                .field("code", code)
                .field("redirect_uri", getCallbackUrl())
                .field("client_id", App.getConfig().getString("oauth.google.key"))
                .field("client_secret", App.getConfig().getString("oauth.google.secret"))
                .asJson();

        JSONObject json = response.getBody().getObject();

        if (json.has("error")) {
            return null;
        } else {
            return json.getString("access_token");
        }
    }

    @Override
    public String getIdentifier(String token) throws UnirestException {
        HttpResponse<JsonNode> me = Unirest.get("https://www.googleapis.com/oauth2/v1/userinfo")
                .header("Authorization", "Bearer " + token)
                .header("User-Agent", "pxls.space")
                .asJson();
        JSONObject json = me.getBody().getObject();
        if (json.has("error")) {
            return null;
        } else {
            return json.getString("id");
        }
    }

    public String getName() {
        return "Google";
    }

    @Override
    public void reloadEnabledState() {
        this.enabled = App.getConfig().getBoolean("oauth.google.enabled");
        this.registrationEnabled = App.getConfig().getBoolean("oauth.google.registrationEnabled");
    }
}


text:
package com.automation.seletest.core.aspectJ;

import com.automation.seletest.core.selenium.configuration.SessionControl;
import com.automation.seletest.core.selenium.threads.SessionContext;
import com.automation.seletest.core.services.annotations.JSHandle;
import com.automation.seletest.core.services.annotations.RetryFailure;
import com.automation.seletest.core.services.annotations.VerifyLog;
import com.automation.seletest.core.services.utilities.LogUtils;
import com.automation.seletest.core.spring.AsyncSeletestExecutor;
import com.automation.seletest.core.testNG.assertions.SoftAssert;
import com.thoughtworks.selenium.SeleniumException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.openqa.selenium.TimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.testng.Reporter;

/**
 * Error Handling Aspect class.
 * @author Giannis Papadakis(mailTo:gpapadakis84@gmail.com)
 *
 */
@Aspect
@Component
@Slf4j
public class ExceptionHandler extends SeletestPointCuts {

    /**The log service*/
    @Autowired
    LogUtils report;

    /** Environment instance*/
    @Autowired
    Environment env;

    @Autowired
    AsyncSeletestExecutor executor;

    /**
     * Handle Exceptions...
     * @param pjp ProceedingJoinPoint
     * @return value from ProceedingJoinPoint
     * @throws Throwable
     */
    @Around(value="logPOs() || actionsBuilderController() || takeScreenCap() || waitConditions() || sendMail()")
    public Object handleException(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue = null;
        try {
            returnValue = pjp.proceed();
            String arguments=arguments(pjp).isEmpty() ? "" : "for["+arguments(pjp)+"]";
            if(pjp.getSignature().toString().contains("pageObjects")) {
                report.warn("Page Object function: "+pjp.getSignature().getName()+" "+arguments+" executed successfully");
            }
        } catch (Exception ex) {
            if (ex instanceof TimeoutException || ex instanceof SeleniumException) {
                if(Reporter.getCurrentTestResult().getAttribute("verification")==null) {
                    report.error("Exception: "+ex.getMessage().split("\n")[0]);
                }
                throw ex;
            } else{
                log.warn(String.format("%s: Failed with exception '%s'",pjp.getSignature().toString().substring(pjp.getSignature().toString().lastIndexOf(".")),ex.getMessage()));
            }
        }
        return returnValue;
    }

    /**
     * Around Advice for
     * @param pjp ProceedingJoinPoint
     * @return value from ProceedingJoinPoint
     * @throws Throwable
     */
    @Around("componentsStatus()")
    public Object handleReturningFunctions(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue;
        try {
            returnValue= pjp.proceed();
        } catch (Exception ex) {
            returnValue=handleExceptionReturn(pjp);
        }
        return returnValue;
    }

    /**
     * Around advice with custom annotation for retrying execution of JoinPoint
     * @param pjp ProceedingJoinPoint
     * @param retry RetryFailure
     * @return value from ProceedingJoinPoint
     * @throws Throwable
     */
    @Around("retryExecution(retry)")
    public Object retry(ProceedingJoinPoint pjp, RetryFailure retry) throws Throwable {
        Object returnValue = null;
        for (int attemptCount = 1; attemptCount <= (1+retry.retryCount()); attemptCount++) {
            try {
                returnValue = pjp.proceed();
                report.info("Command: "+pjp.getSignature().getName()+" for ["+arguments(pjp)+"] executed!","\"color:#3366FF; font-weight: 500;\"");
                break;
            } catch (Exception ex) {
                handleRetryException(pjp, ex, attemptCount, retry);
            }
        }
        return returnValue;
    }

    /**
     * Around advice for performing JS scripts
     * @param pjp ProceedingJoinPoint
     * @param js JSHandle
     * @return Object returning value
     * @throws Throwable
     */
    @Around("jsHandle(js)")
    public Object executeJS(ProceedingJoinPoint pjp, JSHandle js) throws Throwable {
        Object returnValue;
        SessionControl.webController().changeStyle((pjp).getArgs()[0],"backgroundColor", env.getProperty("color_action"));
        SessionControl.webController().changeStyle((pjp).getArgs()[0],"borderStyle", env.getProperty("dotted"));
        returnValue = pjp.proceed();
        return returnValue;
    }

    /**
     * Around advice for verification methods (log output of assertion, highlight elements and take screenshots on failures)
     * @param pjp ProceedingJoinPoint
     * @return proxied object
     * @throws Throwable
     */
    @Around("logVerify(verify)")
    public Object verify(ProceedingJoinPoint pjp, VerifyLog verify) throws Throwable {
        Object returnValue;
        try {
            Reporter.getCurrentTestResult().setAttribute("verification", true);
            returnValue = pjp.proceed();
            if(!((SessionContext.getSession().getAssertion()).getAssertion() instanceof SoftAssert)) {
                if((pjp).getArgs().length==1) {
                    report.info(env.getProperty(verify.message())+" "+(pjp).getArgs()[0]+" "+env.getProperty(verify.messagePass()), "color:green; margin-left:20px;");
                } else {
                    report.info(env.getProperty(verify.message())+" "+(pjp).getArgs()[0]+" "+env.getProperty(verify.messagePass()) + " "+(pjp).getArgs()[1], "color:green; margin-left:20px;");
                } if(verify.highlight()) {
                    SessionControl.webController().changeStyle((pjp).getArgs()[0],"backgroundColor", env.getProperty("color_pass"));
                }
            }
        } catch(AssertionError ex) {
            report.verificationError("[Failed Assertion]: "+env.getProperty(verify.message())+" "+arguments(pjp)+" "+env.getProperty(verify.messageFail()));
            if(verify.screenShot()) {
                SessionControl.webController().takeScreenShot();
            } if(verify.highlight()){
                SessionControl.webController().changeStyle((pjp).getArgs()[0],"backgroundColor",  env.getProperty("color_fail"));
            }
            throw ex;
        }
        return returnValue;
    }

    /**
     * Around functions of web controller
     * @param pjp ProceedingJoinPoint
     * @return Objec returning value
     * @throws Throwable
     */
    @Around("webControl()")
    public Object webControl(ProceedingJoinPoint pjp) throws Throwable {
        Object returnValue;
        Reporter.getCurrentTestResult().removeAttribute("verification");
        returnValue = pjp.proceed();
        return returnValue;
    }

    /**
     * Method for handling exceptions....
     * @param pjp ProceedingJoinPoint
     * @param ex  Throwable
     * @param attemptCount integer retries
     * @param retry RetryFailure
     * @throws Throwable
     */
    private void handleRetryException(ProceedingJoinPoint pjp, Throwable ex, int attemptCount, RetryFailure retry) throws Throwable {
        if (ex instanceof TimeoutException || ex instanceof SeleniumException) {
            log.debug("Do not retry execution due to exception {}", ex.getMessage());
            throw ex;
        } if (attemptCount == 1 + retry.retryCount()) {
            log.debug("Retry execution exceeded for method {}",invokedMethod(pjp));
            throw new RuntimeException(retry.message()+" for method: "+invokedMethod(pjp), ex);
        } else {
            report.error(String.format("%s: Attempt %d of %d failed with exception '%s'. Will retry immediately. %s",
                    pjp.getSignature().toString().substring(pjp.getSignature().toString().lastIndexOf(".")),
                    attemptCount,
                    retry.retryCount(),
                    ex.getClass().getCanonicalName(),
                    ex.getMessage()));
            Thread.sleep(retry.sleepMillis());
        }
    }

    /**
     * Handle exceptions for Boolean-Integer returning type methods in web controller
     * @param pjp ProceedingJoinPoint
     * @return returning value
     * @throws Throwable
     */
    private Object handleExceptionReturn(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature ) pjp.getSignature();
        Class<?> returnType = signature.getReturnType();
        if(returnType.getName().compareTo("int")==0){
            log.debug("Return 0 value for method {}",invokedMethod(pjp));
            return 0;
        } else if(returnType.getName().compareTo("boolean")==0){
            log.debug("Return false value for method {}",invokedMethod(pjp));
            return false;
        }
        return null;
    }

}


text:
import { hbs } from 'ember-cli-htmlbars';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';

module('Integration | Helper | {{pipe-action}}', function(hooks) {
  setupRenderingTest(hooks);

  test('it can be used as a closure action', async function(assert) {
    let value = 0;

    this.add = (x, y) => x + y;
    this.square = (x) => x * x;
    this.squareRoot = (x) => value = Math.sqrt(x);

    await render(hbs`
      {{#let (pipe-action this.add this.square this.squareRoot) as |calculate|}}
        <button {{on "click" (fn calculate 2 4)}}>
          Calculate
        </button>
      {{/let}}
    `);

    assert.equal(value, '0', 'precond - should render 0');

    await click('button');

    assert.equal(value, '6', 'should render 6');
  });
});


text:
<?php

namespace Nkt\UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="users", indexes={
 *     @ORM\Index(name="vk_id", columns={"vk_id"}),
 *     @ORM\Index(name="twitter_id", columns={"twitter_id"})
 * })
 */
class User implements UserInterface
{
    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     * @var string
     *
     * @ORM\Column(type="string", length=255)
     */
    private $username;
    /**
     * @var integer
     *
     * @ORM\Column(name="twitter_id", type="integer", nullable=true)
     */
    private $twitterId;
    /**
     * @var integer
     *
     * @ORM\Column(name="vk_id", type="integer", nullable=true)
     */
    private $vkId;
    /**
     * @var string
     * @ORM\Column(nullable=true)
     */
    private $email;

    public function getId()
    {
        return $this->id;
    }

    public function setUsername($username)
    {
        $this->username = $username;

        return $this;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setTwitterId($twitterId)
    {
        $this->twitterId = $twitterId;

        return $this;
    }

    public function getTwitterId()
    {
        return $this->twitterId;
    }

    public function getRoles()
    {
        return ['ROLE_USER'];
    }

    public function getPassword()
    {
        return null;
    }

    public function getSalt()
    {
        return null;
    }

    public function eraseCredentials()
    {
    }

    public function getVkId()
    {
        return $this->vkId;
    }

    public function setVkId($vkId)
    {
        $this->vkId = $vkId;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}


text:
package examples.csci567.actionbarexample;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "ActionBarExample";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }
            //Create instance of MainActivityFragment class
            MainActivityFragment mainFragment = new MainActivityFragment();

            // In case this activity was started with special instructions from an
            // Intent, pass the Intent's extras to the fragment as arguments
            mainFragment.setArguments(getIntent().getExtras());
            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, mainFragment).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        // Associate searchable configuration with the SearchView
        SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {
                Log.d(TAG, "onQueryTextSubmit: " + s);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Log.d(TAG, "onQueryTextChange: " + s);
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //switch through menu items, default return handle by parent class.
        switch (id) {
            case R.id.action_message:
                sendMessage("Hello World");
                return true;
            case R.id.action_settings:
                //Launch method to start preferences activity for manipulating settings
                //openSettings();
                // Display the fragment as the main content
                FragmentManager mFragmentManager = getFragmentManager();
                FragmentTransaction mFragmentTransaction = mFragmentManager.beginTransaction();
                PrefsFragment mPrefsFragment = new PrefsFragment();
                mFragmentTransaction.replace(R.id.fragment_container, mPrefsFragment).addToBackStack("MainActivityFragment");
                mFragmentTransaction.commit();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void sendMessage(String message){
        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.setData(Uri.parse("sms:"));
        sendIntent.putExtra("sms_body", message);
        startActivity(sendIntent);
    }
}


text:
package net.wildbill22.wizcraft.items;

public class ItemBat extends ModItems {
	public static final String name = "bat";

	protected ItemBat(){
		super(name, name);
//		maxStackSize=1;
	}
	/*public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, int i, int j, int k, int l){
		itemstack.stackSize--;
		return true;
	}*/
}


text:
/**
 *
 * This rule will add a `country` attribute to the user based on their ip address.
 *
 * Example geoip object:
 *
 * ```
 * "geoip": {
 *     "country_code": "AR",
 *     "country_code3": "ARG",
 *     "country_name": "Argentina",
 *     "region": "05",
 *     "city": "Cordoba",
 *     "latitude": -31.41349983215332,
 *     "longitude": -64.18109893798828,
 *     "continent_code": "SA",
 *     "time_zone": "America/Argentina/Cordoba"
 * }
 * ```
 *
 * @title Add country to the user profile
 * @overview Add a country attribute to the user based on their IP address.
 * @gallery true
 * @category enrich profile
 */

function addCountry(user, context, callback) {
  if (context.request.geoip) {
    context.idToken['https://example.com/country'] =
      context.request.geoip.country_name;
    context.idToken['https://example.com/timezone'] =
      context.request.geoip.time_zone;
  }

  callback(null, user, context);
}


text:
package com.ctrip.xpipe.exception;

import java.net.SocketException;

import org.springframework.web.client.HttpStatusCodeException;

/**
 * @author wenchao.meng
 *
 * Aug 28, 2016
 */
public class ExceptionUtils {

	public static Throwable getRootCause(Throwable th){

		if(th == null){
			return null;
		}

		Throwable cause = th.getCause();
		if(cause == null){
			return th;
		}

		return getRootCause(cause);
	}

	public static boolean isSocketIoException(Throwable th){

		while(true){

			if(th == null){
				break;
			}
			if(th instanceof SocketException){
				return true;
			}
			th = th.getCause();
		}

		return false;
	}

	public static String extractExtraMessage(Throwable throwable){

		Throwable rootExeption = getRootCause(throwable);

		if(rootExeption instanceof HttpStatusCodeException){
			return "response body:" + ((HttpStatusCodeException) rootExeption).getResponseBodyAsString();
		}

		return null;
	}

	public static boolean xpipeExceptionLogMessage(Throwable throwable) {

		if(throwable instanceof XpipeException){
			return ((XpipeException) throwable).isOnlyLogMessage();
		}
		if(throwable instanceof XpipeRuntimeException){
			return ((XpipeRuntimeException) throwable).isOnlyLogMessage();
		}
		return false;
	}
}


text:
/**
 * Provides the implementation of the data reflection API.
 *
Data Impl Reflection

 * This package contains the implementation of the
 * {@link net.sf.mmm.data.api.reflection data reflection API}.
 */
package net.sf.mmm.data.impl.reflection;


text:
package com.sksamuel.scapegoat.inspections.collections

import com.sksamuel.scapegoat.PluginRunner
import org.scalatest.{ FreeSpec, Matchers, OneInstancePerTest }

/** @author Stephen Samuel */
class ArrayEqualsTest extends FreeSpec with Matchers with PluginRunner with OneInstancePerTest {

  override val inspections = Seq(new ArrayEquals)

  "ArrayEquals" - {
    "should report warning" - {
      "for comparing two arrays using ==" in {

        val code = """class Test {
                     val a = Array(1,2,3)
                     val b = Array(1,2,3)
                     println(a == b)
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 1
      }

      "for comparing two arrays using !=" in {

        val code = """class Test {
                     val a = Array(1,2,3)
                     val b = Array(1,2,3)
                     println(a != b)
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 1
      }
    }
    "should not report warning" - {
      "for comparing two arrays using deep" in {

        val code = """class Test {
                     val a = Array(1,2,3)
                     val b = Array(1,2,3)
                     println(a.deep == b.deep)
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
      "for comparing an array to null" in {

        val code = """class Test {
                     val a = Array(1,2,3)
                     println(a != null)
                     println(a == null)
                    } """.stripMargin

        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
      "for arrays parameters to a case class" in {
        val code = """case class StemmerOverrideTokenFilter(name: String, rules: Array[String])"""
        compileCodeSnippet(code)
        compiler.scapegoat.feedback.warnings.size shouldBe 0
      }
    }
  }
}


text:
namespace GroupDocs.Viewer.AspNetMvc.Core.Licensing
{
    internal interface IViewerLicenser
    {
        void SetLicense();
    }
}


text:
exports.index = function(req, res){
	res.render('home/index', {
		title: 'Testing MapBox!'
	});
};


text:
This document describes how to set up your development environment to build and test Angular.
It also explains the basic mechanics of using `git`, `node`, and `npm`.

* [Prerequisite Software](#prerequisite-software)
* [Getting the Sources](#getting-the-sources)
* [Installing NPM Modules](#installing-npm-modules)
* [Building](#building)
* [Running Tests Locally](#running-tests-locally)

See the [contribution guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md)
if you'd like to contribute to Angular.

## Prerequisite Software

Before you can build and test Angular, you must install and configure the
following products on your development machine:

* [Git](http://git-scm.com) and/or the **GitHub app** (for [Mac](http://mac.github.com) or
  [Windows](http://windows.github.com)); [GitHub's Guide to Installing
  Git](https://help.github.com/articles/set-up-git) is a good source of information.

* [Node.js](http://nodejs.org), (version specified in the engines field of [`package.json`](../package.json)) which is used to run a development web server,
  run tests, and generate distributable files.

* [Yarn](https://yarnpkg.com) (version specified in the engines field of [`package.json`](../package.json)) which is used to install dependencies.

* [Java Development Kit](http://www.oracle.com/technetwork/es/java/javase/downloads/index.html) which is used
  to execute the selenium standalone server for e2e testing.

* (Optional for now) [Bazel](https://bazel.build/), please follow instructions in [BAZEL.md](https://github.com/angular/angular/blob/master/docs/BAZEL.md)

## Getting the Sources

Fork and clone the Angular repository:

1. Login to your GitHub account or create one by following the instructions given
   [here](https://github.com/signup/free).
2. [Fork](http://help.github.com/forking) the [main Angular
   repository](https://github.com/angular/angular).
3. Clone your fork of the Angular repository and define an `upstream` remote pointing back to
   the Angular repository that you forked in the first place.

```shell
# Clone your GitHub repository:
git clone git@github.com:<github username>/angular.git

# Go to the Angular directory:
cd angular

# Add the main Angular repository as an upstream remote to your repository:
git remote add upstream https://github.com/angular/angular.git
```
## Installing NPM Modules

Next, install the JavaScript modules needed to build and test Angular:

```shell
# Install Angular project dependencies (package.json)
yarn install
```

**Optional**: In this document, we make use of installed npm package scripts and binaries
(stored under `./node_modules/.bin`) by prefixing these command invocations with `$(yarn bin)`; in
particular `gulp` and `protractor` commands.

## Windows only

In order to create the right symlinks, run **as administrator**:
```shell
./scripts/windows/create-symlinks.sh
```

Before submitting a PR, do not forget to remove them:
```shell
 ./scripts/windows/remove-symlinks.sh
 ```

## Building

To build Angular run:

```shell
./build.sh
```

* Results are put in the dist folder.

## Running Tests Locally

To run tests:

```shell
$ ./test.sh node             # Run all angular tests on node

$ ./test.sh browser          # Run all angular tests in browser

$ ./test.sh browserNoRouter  # Optionally run all angular tests without router in browser

$ ./test.sh router           # Optionally run only the router tests in browser
```

You should execute the 3 test suites before submitting a PR to github.

See [DEBUG.md](DEBUG.md) for information on debugging the code while running the unit tests.

All the tests are executed on our Continuous Integration infrastructure and a PR could only be merged once the tests pass.

- CircleCI fails if your code is not formatted properly,
- Travis CI fails if any of the test suites described above fails.

##  Formatting your source code

Angular uses [clang-format](http://clang.llvm.org/docs/ClangFormat.html) to format the source code. If the source code
is not properly formatted, the CI will fail and the PR can not be merged.

You can automatically format your code by running:

``` shell
$ gulp format
```

## Linting/verifying your source code

You can check that your code is properly formatted and adheres to coding style by running:

``` shell
$ gulp lint
```

## Publishing snapshot builds

When a build of any branch on the upstream fork angular/angular is green on CircleCI,
it automatically publishes build artifacts
to repositories in the Angular org, eg. the `@angular/core` package is published to
http://github.com/angular/core-builds.

You may find that your un-merged change needs some validation from external participants.
Rather than requiring them to pull your Pull Request and build Angular locally, you can
publish the `*-builds` snapshots just like our Travis build does.

First time, you need to create the github repositories:

``` shell
$ export TOKEN=[get one from https://github.com/settings/tokens]
$ CREATE_REPOS=1 TRAVIS= ./scripts/ci/publish-build-artifacts.sh [github username]
```

For subsequent snapshots, just run

``` shell
$ ./scripts/publish/publish-build-artifacts.sh [github username]
```

The script will publish the build snapshot to a branch with the same name as your current branch,
and create it if it doesn't exist.


text:
=head1 NAME

PPIx::Regexp::Token::Unmatched - Represent an unmatched right bracket

=head1 SYNOPSIS

 use PPIx::Regexp::Dumper;
 PPIx::Regexp::Dumper->new( 'qr{)}smx' )
     ->print();

=head1 INHERITANCE

C<PPIx::Regexp::Token::Unmatched> is a
L<PPIx::Regexp::Token|PPIx::Regexp::Token>.

C<PPIx::Regexp::Token::Unmatched> has no descendants.

=head1 DESCRIPTION

This class is used to represent an unmatched right bracket of any sort -
parenthesis, square bracket, curly bracket, or whatever.

This class is not generated by the tokenizer; instead the lexer
reblesses a
L<PPIx::Regexp::Token::Structure|PPIx::Regexp::Token::Structure> into it
when it is found to be unmatched.

=head1 METHODS

This class provides no public methods beyond those provided by its
superclass.

=cut

package PPIx::Regexp::Token::Unmatched;

use strict;
use warnings;

use base qw{ PPIx::Regexp::Token };

our $VERSION = '0.028';

# Return true if the token can be quantified, and false otherwise
# sub can_be_quantified { return };

1;

__END__

=head1 SUPPORT

Support is by the author. Please file bug reports at
L<http://rt.cpan.org>, or in electronic mail to the author.

=head1 AUTHOR

Thomas R. Wyant, III F<wyant at cpan dot org>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009-2012 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
of the licenses in the directory LICENSES.

This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut

# ex: set textwidth=72 :


text:
* Full talk
* Lightning Talk

## Abstract
Short and punchy.  A few sentences.

## Description
A few paragraphs.

## Audience
Who is the audience for?

## Outcomes/Conclusions
What will the audience get out of this talk? What do I want them to come
away with?

## Outline

hard because
- browsers + devices
- async
- http & servers
- event lifecycle + document.ready

- unit testing
- "integration testing" without the server
- you need both

## Submitted to

## Given at


text:
package org.wso2.carbon.apimgt.impl.template;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;
import org.apache.velocity.VelocityContext;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;

/**
 * Set the uri templates as the resources
 */
public class ResourceConfigContext extends ConfigContextDecorator {
    //private static final Log log = LogFactory.getLog(ResourceConfigContext.class);

    private API api;

    public ResourceConfigContext(ConfigContext context, API api) {
        super(context);
        this.api = api;
    }

    public void validate() throws APIManagementException {
        if (api.getUriTemplates() == null || api.getUriTemplates().isEmpty()) {
            throw new APIManagementException("At least one resource is required");
        }
    }

    public VelocityContext getContext() {
        VelocityContext context = super.getContext();

        context.put("resources", api.getUriTemplates());
        context.put("faultSequence", api.getFaultSequence());
        context.put("apiStatus", api.getStatus());

        return context;  //To change body of implemented methods use File | Settings | File Templates.
    }
}


text:
guid: f697bb5c-51af-4d18-85df-32243736dcfc
type: Live
reformat: True
shortenReferences: True
categories: mnemonics
scopes: InVBTypeMember(languageLevel=Vb8); InVBTypeAndNamespace(languageLevel=Vb8)
parameterOrder: methodname
methodname-expression: constant("SomeMethod")
---

# ml.f

A subroutine.

```
Public Sub $methodname$()
```


text:
<?php
namespace Chamilo\Application\Weblcms\Storage\DataClass;

use Chamilo\Application\Weblcms\Rights\WeblcmsRights;
use Chamilo\Libraries\Storage\DataClass\DataClass;

/**
 *
 * @package application.lib.weblcms.course
 */

/**
 * This class describes a CourseModule data object
 *
 * @author Hans De Bisschop
 */
class CourseModule extends DataClass
{

    /**
     * CourseModule properties
     */
    const PROPERTY_COURSE_CODE = 'course_id';
    const PROPERTY_NAME = 'name';
    const PROPERTY_VISIBLE = 'visible';
    const PROPERTY_SECTION = 'section';
    const PROPERTY_SORT = 'sort';

    /**
     * Get the default properties
     *
     * @return array The property names.
     */
    public static function get_default_property_names($extended_property_names = array())
    {
        return parent::get_default_property_names(
            array(
                self::PROPERTY_COURSE_CODE,
                self::PROPERTY_NAME,
                self::PROPERTY_VISIBLE,
                self::PROPERTY_SECTION,
                self::PROPERTY_SORT));
    }

    /**
     * Returns the course_code of this CourseModule.
     *
     * @return the course_code.
     */
    public function get_course_code()
    {
        return $this->get_default_property(self::PROPERTY_COURSE_CODE);
    }

    /**
     * Sets the course_code of this CourseModule.
     *
     * @param course_code
     */
    public function set_course_code($course_code)
    {
        $this->set_default_property(self::PROPERTY_COURSE_CODE, $course_code);
    }

    /**
     * Returns the name of this CourseModule.
     *
     * @return the name.
     */
    public function get_name()
    {
        return $this->get_default_property(self::PROPERTY_NAME);
    }

    /**
     * Sets the name of this CourseModule.
     *
     * @param name
     */
    public function set_name($name)
    {
        $this->set_default_property(self::PROPERTY_NAME, $name);
    }

    /**
     * Returns the visible of this CourseModule.
     *
     * @return the visible.
     */
    public function get_visible()
    {
        return $this->get_default_property(self::PROPERTY_VISIBLE);
    }

    /**
     * Sets the visible of this CourseModule.
     *
     * @param visible
     */
    public function set_visible($visible)
    {
        $this->set_default_property(self::PROPERTY_VISIBLE, $visible);
    }

    /**
     * Returns the section of this CourseModule.
     *
     * @return the section.
     */
    public function get_section()
    {
        return $this->get_default_property(self::PROPERTY_SECTION);
    }

    /**
     * Sets the section of this CourseModule.
     *
     * @param section
     */
    public function set_section($section)
    {
        $this->set_default_property(self::PROPERTY_SECTION, $section);
    }

    /**
     * Returns the sort of this CourseModule.
     *
     * @return the sort.
     */
    public function get_sort()
    {
        return $this->get_default_property(self::PROPERTY_SORT);
    }

    /**
     * Sets the sort of this CourseModule.
     *
     * @param sort
     */
    public function set_sort($sort)
    {
        $this->set_default_property(self::PROPERTY_SORT, $sort);
    }

    public static function convert_tools($tools, $course_code = null, $course_type_tools = false, $form = null)
    {
        $tools_array = array();

        foreach ($tools as $index => $tool)
        {
            $tool_visible = 1;
            if ($course_type_tools)
            {
                $tool_visible = $tool->get_visible_default();
                $tool = $tool->get_name();
            }

            $element_default = $tool . "elementdefaulte";
            $course_module = new CourseModule();
            $course_module->set_course_code($course_code);
            $course_module->set_name($tool);
            $course_module->set_visible(
                (! is_null($form) ? $form->parse_checkbox_value($form->getSubmitValue($element_default)) : $tool_visible));
            $course_module->set_section("basic");
            $course_module->set_sort($index);
            $tools_array[] = $course_module;
        }
        return $tools_array;
    }

    public function create($create_in_batch = false)
    {
        $succes = parent::create();
        if (! $succes)
        {
            return false;
        }

        return WeblcmsRights::getInstance()->create_location_in_courses_subtree(
            WeblcmsRights::TYPE_COURSE_MODULE,
            $this->get_id(),
            WeblcmsRights::getInstance()->get_courses_subtree_root_id($this->get_course_code()),
            $this->get_course_code(),
            $create_in_batch);
    }

    public function delete()
    {
        $location = WeblcmsRights::getInstance()->get_weblcms_location_by_identifier_from_courses_subtree(
            WeblcmsRights::TYPE_COURSE_MODULE,
            $this->get_id(),
            $this->get_course_code());
        if ($location)
        {
            if (! $location->delete())
            {
                return false;
            }
        }
        return parent::delete();
    }
}


text:
package com.cvnhan.androidcr.utils;

import android.os.Handler;
import android.os.Looper;

public class ThreadUtils {
    private ThreadUtils() {
    }

    public static void runOnUiThread(final Runnable runnable) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            new Handler(Looper.getMainLooper()).post(runnable);
        } else {
            runnable.run();
        }
    }
}


text:
// -------------------------------------------------------------------------- //
// ------------------------------ Allow/deny -------------------------------- //
// -------------------------------------------------------------------------- //

/**
 * Wether or not the broadcast is allowed
 * @param {Object} data Data of the message
 * @param {Socket} from From socket
 */
Streamy.BroadCasts.allow = function(data, from) {
  return true;
};

// -------------------------------------------------------------------------- //
// -------------------------------- Handlers -------------------------------- //
// -------------------------------------------------------------------------- //

/**
 * Attach the broadcast message handler
 * @param {Object} data Data object
 * @param {Socket} from Socket emitter
 */
Streamy.on('__broadcast__', function(data, from) {

  // Check for sanity
  if(!data.__msg || !data.__data)
    return;

  // Check if the server allows this direct message
  if(!Streamy.BroadCasts.allow(data, from))
      return;

  // Attach the sender ID to the inner data
  data.__data.__from = Streamy.id(from);

  // And then emit the message
  Streamy.broadcast(data.__msg, data.__data, data.__except);
});

// -------------------------------------------------------------------------- //
// ------------------------------- Overrides -------------------------------- //
// -------------------------------------------------------------------------- //

Streamy.broadcast = function(message, data, except) {
  if(!_.isArray(except))
    except = [except];

  _.each(Streamy.sockets(), function(sock) {
    if(except.indexOf(Streamy.id(sock)) !== -1)
      return;

    Streamy.emit(message, data, sock);
  });
};