text:
"""This module tests the brillo sdk command."""

from __future__ import print_function

import mock
import os

from chromite.cbuildbot import constants
from chromite.cbuildbot import repository
from chromite.cli import command_unittest
from chromite.cli.brillo import brillo_sdk
from chromite.lib import bootstrap_lib
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import cros_build_lib_unittest
from chromite.lib import cros_test_lib
from chromite.lib import gs
from chromite.lib import gs_unittest
from chromite.lib import osutils
from chromite.lib import project_sdk
from chromite.lib import workspace_lib

# Unittests often access internals.
# pylint: disable=protected-access

class MockSdkCommand(command_unittest.MockCommand):
  """Mock out the `brillo sdk` command."""
  TARGET = 'chromite.cli.brillo.brillo_sdk.SdkCommand'
  TARGET_CLASS = brillo_sdk.SdkCommand
  COMMAND = 'sdk'

class BrilloSdkTest(cros_test_lib.MockTempDirTestCase):
  """Test class for brillo_sdk module functions."""

  def setUp(self):
    # Avoid self-updating for most tests.
    os.environ[brillo_sdk._BRILLO_SDK_NO_UPDATE] = '1'

    self.bootstrap_path = os.path.join(self.tempdir, 'bootstrap')
    self.sdk_path = os.path.join(self.tempdir, 'sdk')
    self.workspace_path = os.path.join(self.tempdir, 'workspace')
    osutils.SafeMakedirs(self.workspace_path)

    def fakeRepoRoot(d):
      bootstrap_checkouts = os.path.join(self.bootstrap_path,
                                         bootstrap_lib.SDK_CHECKOUTS)
      if d.startswith(self.sdk_path) or d.startswith(bootstrap_checkouts):
        return d
      return None

    self.PatchObject(project_sdk, 'FindRepoRoot', side_effect=fakeRepoRoot)

    # Prevent actually downloading a repository.
    self.mock_repo = self.PatchObject(repository, 'RepoRepository')

    # Prevent actual GS interaction.
    self.gs_mock = self.StartPatcher(gs_unittest.GSContextMock())
    self.gs_mock.SetDefaultCmdResult()

    # Looking up the 'latest' version from GS will return 4.5.6
    self.latest_version = '4.5.6'
    self.gs_mock.AddCmdResult(
        ['cat', constants.BRILLO_LATEST_RELEASE_URL],
        output=self.latest_version)

  def testResolveLatest(self):
    """Tests _ResolveLatest()."""
    result = brillo_sdk._ResolveLatest(gs.GSContext())
    self.assertEqual(self.latest_version, result)

  def testUpdateWorkspaceSdk(self):
    """Tests _UpdateWorkspaceSdk() with a numeric version."""
    brillo_sdk._UpdateWorkspaceSdk(
        gs.GSContext(), self.bootstrap_path, self.workspace_path, '1.2.3')

    # Given the explicit path and version, sync what we expect, and where.
    expected = [mock.call(mock.ANY,
                          os.path.join(self.tempdir,
                                       'bootstrap/sdk_checkouts/1.2.3'),
                          depth=1,
                          repo_cmd=mock.ANY),
                mock.call().Sync()]

    self.assertEqual(expected, self.mock_repo.mock_calls)

    # Update a second time, to ensure it does nothing the second time.
    brillo_sdk._UpdateWorkspaceSdk(
        gs.GSContext(), self.bootstrap_path, self.workspace_path, '1.2.3')

    self.assertEqual(expected, self.mock_repo.mock_calls)

  def testUpdateWorkspaceSdkLatest(self):
    """Tests _UpdateWorkspaceSdk() with 'latest'."""
    brillo_sdk._UpdateWorkspaceSdk(
        gs.GSContext(), self.bootstrap_path, self.workspace_path, 'latest')

    # Given the explicit path and version, sync what we expect, and where.
    expected = [mock.call(mock.ANY,
                          os.path.join(self.tempdir,
                                       'bootstrap/sdk_checkouts',
                                       self.latest_version),
                          depth=1,
                          repo_cmd=mock.ANY),
                mock.call().Sync()]

    self.assertEqual(expected, self.mock_repo.mock_calls)

  def testUpdateWorkspaceSdkTot(self):
    """Tests _UpdateWorkspaceSdk() with 'tot'."""
    brillo_sdk._UpdateWorkspaceSdk(
        gs.GSContext(), self.bootstrap_path, self.workspace_path, 'tot')

    # Given the explicit path and version, sync what we expect, and where.
    expected = [mock.call(constants.MANIFEST_URL,
                          os.path.join(self.tempdir,
                                       'bootstrap/sdk_checkouts/tot'),
                          groups='project_sdk',
                          repo_cmd=mock.ANY),
                mock.call().Sync()]

    self.assertEqual(expected, self.mock_repo.mock_calls)

    # Update a second time, to ensure it DOES update.
    brillo_sdk._UpdateWorkspaceSdk(
        gs.GSContext(), self.bootstrap_path, self.workspace_path, 'tot')

    self.assertEqual(2 * expected, self.mock_repo.mock_calls)

  def testDownloadSdk(self):
    """Tests DownloadSdk() with a numeric version."""
    brillo_sdk._DownloadSdk(gs.GSContext(), self.sdk_path, '1.2.3')

    # Given the explicit path and version, sync what we expect, and where.
    expected = [mock.call(mock.ANY,
                          self.sdk_path,
                          depth=1,
                          repo_cmd=mock.ANY),
                mock.call().Sync()]

    self.assertEqual(expected, self.mock_repo.mock_calls)

    # Verify that the right version number was written out.
    sdk_version_file = project_sdk.VersionFile(self.sdk_path)
    self.assertEqual('1.2.3', osutils.ReadFile(sdk_version_file))

  def testDownloadSdkFailureCleanup(self):
    """Tests DownloadSdk() with a numeric version."""

    # Create sdk_path, and put something in it so we confirm it's gone.
    osutils.Touch(os.path.join(self.sdk_path, 'contents'), makedirs=True)

    # Prep for failure via the repo mock.
    class FakeException(Exception):
      """Raised to simulate a failure."""

    self.mock_repo.side_effect = FakeException('Testing a failure.')

    # Run, and fail.
    with self.assertRaises(FakeException):
      brillo_sdk._DownloadSdk(gs.GSContext(), self.sdk_path, '1.2.3')

    # Make sure the SDK dir was cleaned up.
    self.assertFalse(os.path.exists(self.sdk_path))

class SdkVersionExistsTest(cros_test_lib.WorkspaceTestCase):
  """Tests for _SdkVersionExists()."""

  VALID_LOCAL_SDK_VERSION = '1.2.3'
  VALID_GS_SDK_VERSION = '4.5.6'
  VALID_GS_SDK_URL = brillo_sdk._GetSdkManifestUrl(VALID_GS_SDK_VERSION)

  class GSContextFake(object):
    """Fake GSContext class for Exists() functionality."""
    def Exists(self, url, **_kwargs):
      """Only VALID_GS_SDK_URL returns True."""
      return url == SdkVersionExistsTest.VALID_GS_SDK_URL

  def _VerifySdkVersionExists(self, version, expected):
    """Verifies _SdkVersionExists().

    Args:
      version: Version to pass in.
      expected: Expected result.
    """
    result = brillo_sdk._SdkVersionExists(self.GSContextFake(),
                                          self.bootstrap_path, version)
    self.assertEqual(expected, result)

  def testSdkVersionExists(self):
    """Tests the expected behavior."""
    self.CreateBootstrap(sdk_version=self.VALID_LOCAL_SDK_VERSION)

    self._VerifySdkVersionExists('tot', True)
    self._VerifySdkVersionExists('latest', True)
    self._VerifySdkVersionExists(self.VALID_LOCAL_SDK_VERSION, True)
    self._VerifySdkVersionExists(self.VALID_GS_SDK_VERSION, True)

    self._VerifySdkVersionExists('tot2', False)
    self._VerifySdkVersionExists('', False)

class BrilloSdkTestUpdateBootstrap(cros_test_lib.MockTempDirTestCase):
  """Test the bootstrap update functionality of brillo_sdk.

  This is a new class, to avoid mocks interfering with each other.
  """
  def setUp(self):
    if brillo_sdk._BRILLO_SDK_NO_UPDATE in os.environ:
      del os.environ[brillo_sdk._BRILLO_SDK_NO_UPDATE]

    self.bootstrap_path = os.path.join(self.tempdir, 'bootstrap')

    self.rc_mock = self.StartPatcher(cros_build_lib_unittest.RunCommandMock())
    self.rc_mock.SetDefaultCmdResult()

  def testUpdateBootstrap(self):
    """Tests _UpdateBootstrap()."""
    with self.assertRaises(commandline.ExecRequiredError):
      brillo_sdk._UpdateBootstrap(self.bootstrap_path)

    # Test we did the git pull before raising....
    self.rc_mock.assertCommandContains(
        ['git', 'pull'], cwd=self.bootstrap_path)

    # Test we updated our env before raising....
    self.assertIn(brillo_sdk._BRILLO_SDK_NO_UPDATE, os.environ)

  def testBootstrapAlreadyUpdated(self):
    """Tests _UpdateBootstrap() doesn't run if already updated."""
    # Mark that we already updated.
    os.environ[brillo_sdk._BRILLO_SDK_NO_UPDATE] = '1'

    # Try to update again (no exception raised).
    brillo_sdk._UpdateBootstrap(self.bootstrap_path)

    # Test we didn't run a git pull.
    self.assertEquals(0, self.rc_mock.call_count)

class BrilloSdkCommandTest(cros_test_lib.OutputTestCase,
                           cros_test_lib.WorkspaceTestCase):
  """Test class for our SdkCommand class."""

  def setUp(self):
    if brillo_sdk._BRILLO_SDK_NO_UPDATE in os.environ:
      del os.environ[brillo_sdk._BRILLO_SDK_NO_UPDATE]

    self.cmd_mock = None

    # Workspace is supposed to exist in advance.
    self.CreateBootstrap()
    self.CreateWorkspace()

    # Pretend we are outside the chroot, since this command only runs there.
    self.mock_inside = self.PatchObject(cros_build_lib, 'IsInsideChroot',
                                        return_value=False)

    # Need to mock this; since RunCommand() is mocked out, all the environment
    # checks would fail.
    self.verify_environment_mock = self.PatchObject(
        project_sdk, 'VerifyEnvironment', return_value=True)

    # Prevent repo operations.
    self.PatchObject(repository, 'PrepManifestForRepo')
    self.PatchObject(repository, 'RepoRepository')

    # Default to valid SDK version.
    self.sdk_version_exists_mock = self.PatchObject(
        brillo_sdk, '_SdkVersionExists', return_value=True)

  def SetupCommandMock(self, cmd_args):
    """Sets up the command mock."""
    self.cmd_mock = MockSdkCommand(cmd_args)
    self.StartPatcher(self.cmd_mock)

  def testHandleSelfUpdateAndRestart(self):
    """Tests that --update causes a re-exec."""
    self.SetupCommandMock(['--update', 'latest'])
    with self.assertRaises(commandline.ExecRequiredError):
      self.cmd_mock.inst.Run()

  def testHandleVersionOnlyNoUpdate(self):
    """Tests that `cros sdk` logs a version and doesn't re-exec."""
    self.SetupCommandMock([])
    workspace_lib.SetActiveSdkVersion(self.workspace_path, '1.2.3')

    with self.OutputCapturer():
      self.cmd_mock.inst.Run()
    self.AssertOutputContainsLine('1.2.3', check_stderr=True)

  def testHandleSelfUpdateAfterRestart(self):
    """Tests that --update doesn't re-exec a second time."""
    os.environ[brillo_sdk._BRILLO_SDK_NO_UPDATE] = '1'
    self.SetupCommandMock(['--update', 'latest'])
    self.cmd_mock.inst.Run()

  def testVerifyEnvironmentAfterSelfUpdate(self):
    """Tests that environment verification happens after self-update."""
    update_bootstrap_mock = self.PatchObject(brillo_sdk, '_UpdateBootstrap')
    self.verify_environment_mock.side_effect = (
        lambda: update_bootstrap_mock.called)
    self.SetupCommandMock(['--update', 'latest'])
    self.cmd_mock.inst.Run()

  def testInvalidUpdateVersion(self):
    """Tests --update with an invalid SDK version."""
    update_bootstrap_mock = self.PatchObject(brillo_sdk, '_UpdateBootstrap')
    update_workspace_sdk_mock = self.PatchObject(brillo_sdk,
                                                 '_UpdateWorkspaceSdk')
    self.sdk_version_exists_mock.return_value = False

    self.SetupCommandMock(['--update', 'bad_version'])
    with self.assertRaises(cros_build_lib.DieSystemExit):
      self.cmd_mock.inst.Run()

    # None of the update functions should have been called.
    self.assertFalse(update_bootstrap_mock.called)
    self.assertFalse(self.verify_environment_mock.called)
    self.assertFalse(update_workspace_sdk_mock.called)

  def testVersionOption(self):
    """Tests that --version prints to stdout."""
    self.SetupCommandMock(['--version'])
    workspace_lib.SetActiveSdkVersion(self.workspace_path, 'foo')

    with self.OutputCapturer():
      self.cmd_mock.inst.Run()
    self.AssertOutputContainsLine('foo')

  def testVersionOptionSdkNotFound(self):
    """Tests that --version errors out if a version can't be found."""
    self.SetupCommandMock(['--version'])

    with self.OutputCapturer():
      with self.assertRaises(cros_build_lib.DieSystemExit):
        self.cmd_mock.inst.Run()
    self.AssertOutputContainsLine('This workspace does not have an SDK.',
                                  check_stderr=True, check_stdout=False)


text:
@interface BPViewController : UIViewController <UITextFieldDelegate>

@end

redpajama_set_name: RedPajamaGithub


text:
import { DefaultAlignment, HeaderAlignment } from "./alignment.js";
import { FormatType } from "./formatter.js";

/**
 * Reads a property of an object if exists; otherwise uses a default value.
 *
 * @private
 * @param {*} obj - An object. If a non-object value is specified, the default value is used.
 * @param {string} key - A key (or property name).
 * @param {*} defaultVal - A default value that is used when a value does not exist.
 * @returns {*} A read value or the default value.
 */
export function _value(obj, key, defaultVal) {
  return (typeof obj === "object" && obj !== null && obj[key] !== undefined)
    ? obj[key]
    : defaultVal;
}

/**
 * Reads multiple properties of an object if exists; otherwise uses default values.
 *
 * @private
 * @param {*} obj - An object. If a non-object value is specified, the default value is used.
 * @param {Object} keys - An object that consists of pairs of a key and a default value.
 * @returns {Object} A new object that contains read values.
 */
export function _values(obj, keys) {
  const res = {};
  for (const [key, defaultVal] of Object.entries(keys)) {
    res[key] = _value(obj, key, defaultVal);
  }
  return res;
}

/**
 * Reads options for the formatter from an object.
 * The default values are used for options that are not specified.
 *
 * @param {Object} obj - An object containing options.
 * The available options and default values are listed below.
 *
 * | property name       | type                              | description                                             | default value            |
 * | ------------------- | --------------------------------- | ------------------------------------------------------- | ------------------------ |
 * | `leftMarginChars`   | {@link Set}<{@link string}> | A set of additional left margin characters.             | `new Set()`              |
 * | `formatType`        | {@link FormatType}                | Format type, normal or weak.                            | `FormatType.NORMAL`      |
 * | `minDelimiterWidth` | {@link number}                    | Minimum width of delimiters.                            | `3`                      |
 * | `defaultAlignment`  | {@link DefaultAlignment}          | Default alignment of columns.                           | `DefaultAlignment.LEFT`  |
 * | `headerAlignment`   | {@link HeaderAlignment}           | Alignment of header cells.                              | `HeaderAlignment.FOLLOW` |
 * | `textWidthOptions`  | {@link Object}                    | An object containing options for computing text widths. |                          |
 * | `smartCursor`       | {@link boolean}                   | Enables "Smart Cursor" feature.                         | `false`                  |
 *
 * The available options for `obj.textWidthOptions` are the following ones.
 *
 * | property name     | type                              | description                                           | default value |
 * | ----------------- | --------------------------------- | ----------------------------------------------------- | ------------- |
 * | `normalize`       | {@link boolean}                   | Normalizes texts before computing text widths.        | `true`        |
 * | `wideChars`       | {@link Set}<{@link string}> | A set of characters that should be treated as wide.   | `new Set()`   |
 * | `narrowChars`     | {@link Set}<{@link string}> | A set of characters that should be treated as narrow. | `new Set()`   |
 * | `ambiguousAsWide` | {@link boolean}                   | Treats East Asian Ambiguous characters as wide.       | `false`       |
 *
 * @returns {Object} - An object that contains complete options.
 */
export function options(obj) {
  const res = _values(obj, {
    leftMarginChars  : new Set(),
    formatType       : FormatType.NORMAL,
    minDelimiterWidth: 3,
    defaultAlignment : DefaultAlignment.LEFT,
    headerAlignment  : HeaderAlignment.FOLLOW,
    smartCursor      : false
  });
  res.textWidthOptions = _values(obj.textWidthOptions, {
    normalize      : true,
    wideChars      : new Set(),
    narrowChars    : new Set(),
    ambiguousAsWide: false
  });
  return res;
}


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Ecng.Collections;
using Ecng.Common;
using Nito.AsyncEx;
using StockSharp.Localization;
using StockSharp.Logging;

namespace StockSharp.Messages;

/// <summary>
/// Async message processor helper.
/// </summary>
public class AsyncMessageProcessor : BaseLogReceiver
{
	private class MessageQueueItem
	{
		public MessageQueueItem(Message msg, CancellationTokenSource cts)
		{
			Message = msg;

			IsControl = Message.Type
				is MessageTypes.Reset
				or MessageTypes.Connect
				or MessageTypes.Disconnect;

			IsTransaction = Message.Type
				is MessageTypes.OrderRegister
				or MessageTypes.OrderReplace
				or MessageTypes.OrderPairReplace
				or MessageTypes.OrderCancel
				or MessageTypes.OrderGroupCancel;

			Cts = cts;
		}

		public Message Message { get; }
		public CancellationTokenSource Cts { get; }
		public Task Task { get; set; }

		public bool IsStartedProcessing => Task != null;
		public bool IsProcessing => Task?.IsCompleted == false;
		public bool IsDone => Task?.IsCompleted == true;

		public bool IsCanceled => Cts.Token.IsCancellationRequested;

		public bool IsControl { get; }
		public bool IsTransaction { get; }
	}

	private readonly SynchronizedList<MessageQueueItem> _messages = new();

	private readonly SynchronizedList<(string name, Task task)> _childTasks = new();
	private readonly SynchronizedDictionary<long, CancellationTokenSource> _childTokens = new();

	private readonly AsyncManualResetEvent _processMessageEvt = new(false);
	private CancellationTokenSource _globalCts = new();

	private bool _isConnectionStarted, _isDisconnecting;

	private IAsyncMessageAdapter _adapter => (IAsyncMessageAdapter)Parent;

	/// <summary>
	/// Initialize <see cref="AsyncMessageProcessor"/>.
	/// </summary>
	public AsyncMessageProcessor(IAsyncMessageAdapter adapter)
	{
		Parent = adapter;
		// ReSharper disable once VirtualMemberCallInConstructor
		Name = $"async({adapter.Name})";
		Task.Run(ProcessMessagesAsync);
	}

	/// <inheritdoc />
	protected override void DisposeManaged()
	{
		base.DisposeManaged();
		_processMessageEvt.Set();
	}

	/// <summary>
	/// </summary>
	public bool EnqueueMessage(Message msg)
	{
		this.AddVerboseLog("enqueue: {0}", msg.Type);

		lock (_messages.SyncRoot)
		{
			if (msg is ResetMessage)
				CancelAndReplaceGlobalCts();

			_messages.Add(new MessageQueueItem(msg, _globalCts));
		}

		_processMessageEvt.Set();

		return true;
	}

	/// <summary>
	/// </summary>
	public void TryAddChildTask(string name, Task task)
	{
		if(!task.IsCompleted)
			_childTasks.Add((name, task));
	}

	/// <summary>
	/// </summary>
	public void TryAddChildTask(string name, ValueTask task)
	{
		if(!task.IsCompleted)
			_childTasks.Add((name, task.AsTask()));
	}

	private MessageQueueItem SelectNextMessage()
	{
		lock (_messages.SyncRoot)
		{
			var isControlProcessing = false;
			var isTransactionProcessing = false;

			foreach (var msg in _messages.Where(m => m.IsProcessing))
			{
				isControlProcessing |= msg.IsControl;
				isTransactionProcessing |= msg.IsTransaction;
			}

			// cant process anything in parallel while connect/disconnect/reset is processing
			if(isControlProcessing)
				return null;

			// if transaction is processing currently, we can process other non-exclusive messages in parallel (marketdata request for example)
			if(isTransactionProcessing)
				return _messages.FirstOrDefault(m => !m.IsStartedProcessing && !(m.IsControl || m.IsTransaction));

			return _messages.FirstOrDefault(m => !m.IsStartedProcessing);
		}
	}

	private void BeginProcessMessage(MessageQueueItem msg, Func<ValueTask> process)
	{
		if(msg.IsStartedProcessing)
			throw new ArgumentException($"processing is already started for {msg.Message}", nameof(msg));

		ValueTask wrapper()
		{
			try
			{
				if(msg.IsCanceled)
					throw new OperationCanceledException("canceled");

				var vt = process();

				if (vt.IsCompleted)
				{
					msg.Task = Task.CompletedTask;
					return vt;
				}

				msg.Task = vt.AsTask();
				msg.Task.ContinueWith(t =>
				{
					if(!t.IsCompletedSuccessfully)
						_adapter.HandleMessageException(msg.Message, t.IsFaulted ? t.Exception : new OperationCanceledException("canceled"));

					_processMessageEvt.Set(); // check next message
				});

				return vt;
			}
			catch (Exception e)
			{
				var tcs = AsyncHelper.CreateTaskCompletionSource(false);
				tcs.TrySetFrom(e);
				msg.Task = tcs.Task;

				_ = tcs.Task.Exception; // observe

				throw;
			}
		}

#pragma warning disable CA2012

		AsyncHelper.CatchHandle(
			wrapper,
			handleError:    e => _adapter.HandleMessageException(msg.Message, e),
			handleCancel:   e => _adapter.HandleMessageException(msg.Message, e),
			rethrowCancel:  false,
			rethrowErr:     false
		);

#pragma warning restore CA2012
	}

	private bool BeginProcessNextMessage()
	{
		var msg = SelectNextMessage();

		if(msg == null)
			return false;

		var token = _globalCts.Token;

		ValueTask processMarketDataMessage(MarketDataMessage md)
		{
			if (md.IsSubscribe)
			{
				var childToken = CreateChildTokenByTransId(md.TransactionId, token);
				TryAddChildTask($"sub{md.TransactionId}", _adapter.RunSubscriptionAsync(md, childToken));
			}
			else
			{
				TryCancelChildTokenByTransId(md.OriginalTransactionId);
			}

			return default;
		}

		BeginProcessMessage(msg, () =>
		{
			this.AddVerboseLog("beginprocess: {0}", msg.Message.Type);

			if(msg.IsControl)
				return msg.Message switch
				{
					ConnectMessage m    => ConnectAsync(m, token),
					DisconnectMessage m => DisconnectAsync(m),
					ResetMessage m      => ResetAsync(m),
					_                   => throw new ArgumentOutOfRangeException(nameof(msg), $"unexpected message {msg.Message.Type}")
				};

			if(!_isConnectionStarted || _isDisconnecting)
				throw new InvalidOperationException($"unable to process {msg.Message.Type} in this state. connStarted={_isConnectionStarted}, disconnecting={_isDisconnecting}");

			return msg.Message switch
			{
				SecurityLookupMessage m    => _adapter.SecurityLookupAsync(m, token),
				PortfolioLookupMessage m   => _adapter.PortfolioLookupAsync(m, token),
				BoardLookupMessage m       => _adapter.BoardLookupAsync(m, token),

				OrderStatusMessage m       => _adapter.OrderStatusAsync(m, token),

				OrderReplaceMessage m      => _adapter.ReplaceOrderAsync(m, token),
				OrderPairReplaceMessage m  => _adapter.ReplaceOrderPairAsync(m, token),
				OrderRegisterMessage m     => _adapter.RegisterOrderAsync(m, token),
				OrderCancelMessage m       => _adapter.CancelOrderAsync(m, token),
				OrderGroupCancelMessage m  => _adapter.CancelOrderGroupAsync(m, token),

				MarketDataMessage m        => processMarketDataMessage(m),

				_                          => _adapter.ProcessMessageAsync(msg.Message, token)
			};
		});

		return true;
	}

	private async Task ProcessMessagesAsync()
	{
		while (true)
		{
			await _processMessageEvt.WaitAsync();
			if(IsDisposeStarted)
				break;

			_processMessageEvt.Reset();

			lock(_messages.SyncRoot)
				_messages.RemoveWhere(m => m.IsDone);

			try
			{
				while(BeginProcessNextMessage()) {}
			}
			catch (Exception e)
			{
				this.AddErrorLog("error processing message: {0}", e);
			}
		}
	}

	private ValueTask ConnectAsync(ConnectMessage msg, CancellationToken token)
	{
		if(_isConnectionStarted)
			throw new InvalidOperationException(LocalizedStrings.Str1619);

		_isConnectionStarted = true;

		return _adapter.ConnectAsync(msg, token);
	}

	private async ValueTask DisconnectAsync(DisconnectMessage msg)
	{
		if(!_isConnectionStarted)
			throw new InvalidOperationException("not connected");

		if(_isDisconnecting)
			throw new InvalidOperationException("already disconnecting");

		_isDisconnecting = true;

		CancelAndReplaceGlobalCts();

		if(!await WhenChildrenComplete(_adapter.DisconnectTimeout.CreateTimeoutToken()))
			throw new InvalidOperationException("unable to complete disconnect. some tasks are still running.");

		await _adapter.DisconnectAsync(msg);

		_isDisconnecting = _isConnectionStarted = false;
	}

	private async ValueTask ResetAsync(ResetMessage msg)
	{
		_isDisconnecting = true;

		// token is already canceled in EnqueueMessage
		await AsyncHelper.CatchHandle(() => WhenChildrenComplete(_adapter.DisconnectTimeout.CreateTimeoutToken()));

		await _adapter.ResetAsync(msg); // reset must not throw.

		_isDisconnecting = _isConnectionStarted = false;
	}

	private void CancelAndReplaceGlobalCts()
	{
		_globalCts.Cancel();
		_globalCts = new();
	}

	private CancellationToken CreateChildTokenByTransId(long transactionId, CancellationToken parentToken)
	{
		var (cts, childToken) = parentToken.CreateChildToken();
		_childTokens.Add(transactionId, cts);
		return childToken;
	}

	private void TryCancelChildTokenByTransId(long transactionId) => _childTokens.TryGetAndRemove(transactionId)?.Cancel();

	private async Task<bool> WhenChildrenComplete(CancellationToken token)
	{
		var tasks = _childTasks.ToArray();
		var allComplete = true;

		await Task.WhenAll(tasks.Select(t => t.task.WithCancellation(token))).CatchHandle(finalizer: () =>
		{
			var incomplete = tasks.Where(t => !t.task.IsCompleted).Select(t => t.name).ToArray();
			if(incomplete.Any())
			{
				allComplete = false;
				this.AddErrorLog("following tasks were not completed: " + incomplete.Join(", "));
			}
		});

		return allComplete;
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="Date-Revision-yyyymmdd" content="20190206" />
    <meta http-equiv="Content-Language" content="en" />
    <title>Play! 2.x – Usage - general instructions</title>
    <link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" />
    <link rel="stylesheet" href="./css/site.css" />
    <link rel="stylesheet" href="./css/print.css" media="print" />

<link rel="stylesheet" href="./css/site.css" type="text/css" />

Play! 2.x

Last Published: 2019-02-06|

Version: 1.0.0-rc5

Overview

Introduction

Plugin goals

Usage

General instructions

Play 2.7.x

Play 2.6.x

Play 2.5.x

Play 2.4.x

Play 2.3.x

Play 2.2.x

Play 2.1.x

Migration

From previous plugin version

From Play 2.6.x to 2.7.x

From Play 2.5.x to 2.6.x

From Play 2.4.x to 2.5.x

From Play 2.3.x to 2.4.x

From Play 2.2.x to 2.3.x

From Play 2.1.x to 2.2.x

IDE integration

Eclipse/ScalaIDE

IntelliJ IDEA

Deploying

Default distribution

Custom distribution

WAR distribution

Other topics

Assets processing

Running in development mode

Multi-module builds

Modules

Play! 2.x Maven Plugin

Play! 2.x Provider API

Play! 2.x Providers

Play! 2.x Source Position Mappers

Play! 2.x Source Watcher API

Play! 2.x Source Watchers

Project Documentation

Project Information

Usage - general instructions

Different Play! versions support

Plugin supports following Play! Framework versions: 2.1.x, 2.2.x, 2.3.x, 2.4.x, 2.5.x and 2.6.x.

There are some configuration differences:

Play! Framework 2.1.x usage

Play! Framework 2.2.x usage

Play! Framework 2.3.x usage

Play! Framework 2.4.x usage

Play! Framework 2.5.x usage

Play! Framework 2.6.x usage

Using plugin SNAPSHOT versions

Add

            <pluginRepositories>
                <pluginRepository>
                    <id>sonatype-nexus-snapshots</id>
                    <name>Sonatype Nexus Snapshots</name>
                    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                </pluginRepository>
            </pluginRepositories>

to your project or better add

<settings>
    ...
    <profiles>
        ...
        <profile>
            <id>sonatype-snapshots-repo</id>

            <pluginRepositories>
                <pluginRepository>
                    <id>sonatype-nexus-snapshots</id>
                    <name>Sonatype Nexus Snapshots</name>
                    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
                    <releases>
                        <enabled>false</enabled>
                    </releases>
                </pluginRepository>
            </pluginRepositories>
        </profile>
        ...
    </profiles>

    <activeProfiles>
       <activeProfile>sonatype-snapshots-repo</activeProfile>
    </activeProfiles>
    ...
</settings>

to <tt>~/.m2/settings.xml</tt> file. More info: http://maven.apache.org/guides/mini/guide-multiple-repositories.html

Copyright ©2013–2019.
All rights reserved.


text:
package xeval

import (
	"github.com/juju/errors"
	"github.com/pingcap/tidb/expression"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tidb/util/types"
	"github.com/pingcap/tipb/go-tipb"
)

var jsonFunctions = map[tipb.ExprType]func([]types.Datum, *variable.StatementContext) (types.Datum, error){
	tipb.ExprType_JsonType:    expression.JSONType,
	tipb.ExprType_JsonExtract: expression.JSONExtract,
	tipb.ExprType_JsonUnquote: expression.JSONUnquote,
	tipb.ExprType_JsonMerge:   expression.JSONMerge,
	tipb.ExprType_JsonSet:     expression.JSONSet,
	tipb.ExprType_JsonInsert:  expression.JSONInsert,
	tipb.ExprType_JsonReplace: expression.JSONReplace,
}

func (e *Evaluator) evalJSONFunctions(expr *tipb.Expr) (d types.Datum, _ error) {
	var args = make([]types.Datum, 0, len(expr.Children))
	for _, child := range expr.Children {
		arg, err := e.Eval(child)
		if err != nil {
			return d, errors.Trace(err)
		}
		args = append(args, arg)
	}
	if fn, ok := jsonFunctions[expr.GetTp()]; ok {
		return fn(args, e.StatementCtx)
	}
	return d, errors.Errorf("the ExprType %d is not implemented", expr.GetTp())
}


text:
var url = 'https://api.unsplash.com/photos/random/';

// get an API key from
// https://unsplash.com/developers
var apikey = 'YOURAPIKEY';

// uncomment for a user prompt for primary color
// var primaryColor = prompt("Please enter a primary color:");

// uncomment for a width prompt
// var imageWidth = prompt("Please enter an image width:");

var uri = url + '?client_id=' + apikey + '&featured'; // [uncomment to add query or image width]+ '&query=' + primaryColor + '&width=' +  imageWidth;

// parse the JSON to get the goodies

$.getJSON( uri , function(data) {
         //alert(data.id);
         //alert(data.user.name);

document.getElementById("id").innerHTML=data.id;

document.getElementById("name").innerHTML=data.user.name;

document.getElementById("username").innerHTML=data.user.username;

// get thumbnail link
// document.getElementById("thumb").innerHTML=data.urls.thumb;
// put thumbnail in div
var thumby = document.getElementById('thumb');
var img = document.createElement('img');
img.src = data.urls.thumb;
thumby.appendChild(img);

// get small image link
// document.getElementById("small").innerHTML=data.urls.small;
// put thumbnail in div
var smally = document.getElementById('small');
var img = document.createElement('img');
img.src = data.urls.small;
smally.appendChild(img);

// get Full image link
// document.getElementById("full").innerHTML=data.urls.full;
// put thumbnail in div
var fully = document.getElementById('full');
var img = document.createElement('img');
img.src = data.urls.full;
fully.appendChild(img);

});


text:
from __future__ import print_function

import os
import sys
import tempfile

from target_test import FileSystemTargetTestMixin
from helpers import with_config, unittest

from boto.exception import S3ResponseError
from boto.s3 import key
from moto import mock_s3
from luigi import configuration
from luigi.s3 import FileNotFoundException, InvalidDeleteException, S3Client, S3Target

if (3, 4, 0) <= sys.version_info[:3] < (3, 4, 3):
    # spulec/moto#308
    raise unittest.SkipTest('moto mock doesn\'t work with python3.4')

AWS_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXX"
AWS_SECRET_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

class TestS3Target(unittest.TestCase, FileSystemTargetTestMixin):

    def setUp(self):
        f = tempfile.NamedTemporaryFile(mode='wb', delete=False)
        self.tempFileContents = (
            b"I'm a temporary file for testing\nAnd this is the second line\n"
            b"This is the third.")
        self.tempFilePath = f.name
        f.write(self.tempFileContents)
        f.close()
        self.mock_s3 = mock_s3()
        self.mock_s3.start()

    def tearDown(self):
        os.remove(self.tempFilePath)
        self.mock_s3.stop()

    def create_target(self, format=None):
        client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        client.s3.create_bucket('mybucket')
        return S3Target('s3://mybucket/test_file', client=client, format=format)

    def test_read(self):
        client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        client.s3.create_bucket('mybucket')
        client.put(self.tempFilePath, 's3://mybucket/tempfile')
        t = S3Target('s3://mybucket/tempfile', client=client)
        read_file = t.open()
        file_str = read_file.read()
        self.assertEqual(self.tempFileContents, file_str.encode('utf-8'))

    def test_read_no_file(self):
        t = self.create_target()
        self.assertRaises(FileNotFoundException, t.open)

    def test_read_iterator_long(self):
        # write a file that is 5X the boto buffersize
        # to test line buffering
        old_buffer = key.Key.BufferSize
        key.Key.BufferSize = 2
        try:
            tempf = tempfile.NamedTemporaryFile(mode='wb', delete=False)
            temppath = tempf.name
            firstline = ''.zfill(key.Key.BufferSize * 5) + os.linesep
            contents = firstline + 'line two' + os.linesep + 'line three'
            tempf.write(contents.encode('utf-8'))
            tempf.close()

            client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
            client.s3.create_bucket('mybucket')
            client.put(temppath, 's3://mybucket/largetempfile')
            t = S3Target('s3://mybucket/largetempfile', client=client)
            with t.open() as read_file:
                lines = [line for line in read_file]
        finally:
            key.Key.BufferSize = old_buffer

        self.assertEqual(3, len(lines))
        self.assertEqual(firstline, lines[0])
        self.assertEqual("line two" + os.linesep, lines[1])
        self.assertEqual("line three", lines[2])

class TestS3Client(unittest.TestCase):

    def setUp(self):
        f = tempfile.NamedTemporaryFile(mode='wb', delete=False)
        self.tempFilePath = f.name
        f.write(b"I'm a temporary file for testing\n")
        f.close()
        self.mock_s3 = mock_s3()
        self.mock_s3.start()

    def tearDown(self):
        os.remove(self.tempFilePath)
        self.mock_s3.stop()

    def test_init_with_environment_variables(self):
        os.environ['AWS_ACCESS_KEY_ID'] = 'foo'
        os.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
        # Don't read any exsisting config
        old_config_paths = configuration.LuigiConfigParser._config_paths
        configuration.LuigiConfigParser._config_paths = [tempfile.mktemp()]

        s3_client = S3Client()
        configuration.LuigiConfigParser._config_paths = old_config_paths

        self.assertEqual(s3_client.s3.gs_access_key_id, 'foo')
        self.assertEqual(s3_client.s3.gs_secret_access_key, 'bar')

    @with_config({'s3': {'aws_access_key_id': 'foo', 'aws_secret_access_key': 'bar'}})
    def test_init_with_config(self):
        s3_client = S3Client()
        self.assertEqual(s3_client.s3.access_key, 'foo')
        self.assertEqual(s3_client.s3.secret_key, 'bar')

    def test_put(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')
        s3_client.put(self.tempFilePath, 's3://mybucket/putMe')
        self.assertTrue(s3_client.exists('s3://mybucket/putMe'))

    def test_put_string(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')
        s3_client.put_string("SOMESTRING", 's3://mybucket/putString')
        self.assertTrue(s3_client.exists('s3://mybucket/putString'))

    def test_put_multipart_multiple_parts_non_exact_fit(self):
        """
        Test a multipart put with two parts, where the parts are not exactly the split size.
        """
        # 5MB is minimum part size
        part_size = (1024 ** 2) * 5
        file_size = (part_size * 2) - 5000
        self._run_multipart_test(part_size, file_size)

    def test_put_multipart_multiple_parts_exact_fit(self):
        """
        Test a multipart put with multiple parts, where the parts are exactly the split size.
        """
        # 5MB is minimum part size
        part_size = (1024 ** 2) * 5
        file_size = part_size * 2
        self._run_multipart_test(part_size, file_size)

    def test_put_multipart_less_than_split_size(self):
        """
        Test a multipart put with a file smaller than split size; should revert to regular put.
        """
        # 5MB is minimum part size
        part_size = (1024 ** 2) * 5
        file_size = 5000
        self._run_multipart_test(part_size, file_size)

    def test_put_multipart_empty_file(self):
        """
        Test a multipart put with an empty file.
        """
        # 5MB is minimum part size
        part_size = (1024 ** 2) * 5
        file_size = 0
        self._run_multipart_test(part_size, file_size)

    def test_exists(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')

        self.assertTrue(s3_client.exists('s3://mybucket/'))
        self.assertTrue(s3_client.exists('s3://mybucket'))
        self.assertFalse(s3_client.exists('s3://mybucket/nope'))
        self.assertFalse(s3_client.exists('s3://mybucket/nope/'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempfile')
        self.assertTrue(s3_client.exists('s3://mybucket/tempfile'))
        self.assertFalse(s3_client.exists('s3://mybucket/temp'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')
        self.assertTrue(s3_client.exists('s3://mybucket/tempdir0'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')
        self.assertTrue(s3_client.exists('s3://mybucket/tempdir1'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempdir2/subdir')
        self.assertTrue(s3_client.exists('s3://mybucket/tempdir2'))
        self.assertFalse(s3_client.exists('s3://mybucket/tempdir'))

    def test_get_key(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')
        s3_client.put(self.tempFilePath, 's3://mybucket/key_to_find')
        self.assertTrue(s3_client.get_key('s3://mybucket/key_to_find'))
        self.assertFalse(s3_client.get_key('s3://mybucket/does_not_exist'))

    def test_is_dir(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')
        self.assertTrue(s3_client.is_dir('s3://mybucket'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempdir0_$folder$')
        self.assertTrue(s3_client.is_dir('s3://mybucket/tempdir0'))

        s3_client.put(self.tempFilePath, 's3://mybucket/tempdir1/')
        self.assertTrue(s3_client.is_dir('s3://mybucket/tempdir1'))

        s3_client.put(self.tempFilePath, 's3://mybucket/key')
        self.assertFalse(s3_client.is_dir('s3://mybucket/key'))

    def test_remove(self):
        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')

        self.assertRaises(
            S3ResponseError,
            lambda: s3_client.remove('s3://bucketdoesnotexist/file')
        )

        self.assertFalse(s3_client.remove('s3://mybucket/doesNotExist'))

        s3_client.put(self.tempFilePath, 's3://mybucket/existingFile0')
        self.assertTrue(s3_client.remove('s3://mybucket/existingFile0'))
        self.assertFalse(s3_client.exists('s3://mybucket/existingFile0'))

        self.assertRaises(
            InvalidDeleteException,
            lambda: s3_client.remove('s3://mybucket/')
        )

        self.assertRaises(
            InvalidDeleteException,
            lambda: s3_client.remove('s3://mybucket')
        )

        s3_client.put(self.tempFilePath, 's3://mybucket/removemedir/file')
        self.assertRaises(
            InvalidDeleteException,
            lambda: s3_client.remove('s3://mybucket/removemedir', recursive=False)
        )

    def _run_multipart_test(self, part_size, file_size):
        file_contents = b"a" * file_size

        s3_path = 's3://mybucket/putMe'
        tmp_file = tempfile.NamedTemporaryFile(mode='wb', delete=True)
        tmp_file_path = tmp_file.name
        tmp_file.write(file_contents)
        tmp_file.flush()

        s3_client = S3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY)
        s3_client.s3.create_bucket('mybucket')
        s3_client.put_multipart(tmp_file_path, s3_path, part_size=part_size)
        self.assertTrue(s3_client.exists(s3_path))
        # b/c of https://github.com/spulec/moto/issues/131 have to
        # get contents to check size
        key_contents = s3_client.get_key(s3_path).get_contents_as_string()
        self.assertEqual(len(file_contents), len(key_contents))

        tmp_file.close()

if __name__ == '__main__':
    unittest.main()


text:
"""Tests for while loops in XLA."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import numpy as np

from tensorflow.compiler.tests import xla_test
from tensorflow.compiler.tf2xla.python import xla
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import function
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import map_fn
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

class WhileTest(xla_test.XLATestCase):

  def testSingletonLoopHandrolled(self):
    # Define a function for the loop body
    @function.Defun(dtypes.int32)
    def loop_body(step):
      step_out = step + constant_op.constant(1, dtype=dtypes.int32)
      return step_out

    # Define a function for the loop condition
    @function.Defun(dtypes.int32)
    def loop_cond(step):
      return step < 10

    with self.session() as sess:
      init_index = array_ops.placeholder(dtypes.int32, [])
      with self.test_scope():
        loop_outputs = xla.while_loop([init_index], loop_cond, loop_body)

      result = sess.run(loop_outputs, {init_index: 0})
      self.assertAllClose(result, [10], rtol=1e-3)

  def testCountingLoopHandrolled(self):
    # Define a function for the loop body
    @function.Defun(dtypes.int32, dtypes.float32)
    def loop_body(step, rsum):
      step_out = step + constant_op.constant(1, dtype=dtypes.int32)
      sum_out = rsum + constant_op.constant(1.5, dtype=dtypes.float32)
      return step_out, sum_out

    # Define a function for the loop condition
    @function.Defun(dtypes.int32, dtypes.float32)
    def loop_cond(step, rsum):
      del rsum
      return step < 10

    with self.session() as sess:
      init_index = array_ops.placeholder(dtypes.int32, [])
      init_sum = array_ops.placeholder(dtypes.float32, [])
      with self.test_scope():
        loop_outputs = xla.while_loop([init_index, init_sum], loop_cond,
                                      loop_body)

      result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0})
      self.assertAllClose(result, [10, 15.0], rtol=1e-3)
      no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0})
      self.assertAllClose(no_iters_result, [10, 0.0], rtol=1e-3)

  def testCountingLoopHandrolledC64(self):
    # Define a function for the loop body
    @function.Defun(dtypes.int32, dtypes.complex64)
    def loop_body(step, rsum):
      step_out = step + constant_op.constant(1, dtype=dtypes.int32)
      sum_out = rsum + constant_op.constant(1.5 + 2j, dtype=dtypes.complex64)
      return step_out, sum_out

    # Define a function for the loop condition
    @function.Defun(dtypes.int32, dtypes.complex64)
    def loop_cond(step, rsum):
      del rsum
      return step < 10

    with self.session() as sess:
      init_index = array_ops.placeholder(dtypes.int32, [])
      init_sum = array_ops.placeholder(dtypes.complex64, [])
      with self.test_scope():
        loop_outputs = xla.while_loop([init_index, init_sum], loop_cond,
                                      loop_body)

      result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0})
      self.assertAllClose(result[1], np.complex64(15 + 20j), rtol=1e-3)
      no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0})
      self.assertAllClose(no_iters_result[1], np.complex64(0), rtol=1e-3)

  def testLoopWithConstantOutput(self):
    # Define a function for the loop body
    @function.Defun(dtypes.int32, dtypes.int32)
    def loop_body(step, x):
      del x
      step_out = step + constant_op.constant(1, dtype=dtypes.int32)
      return (step_out, 7)

    # Define a function for the loop condition
    @function.Defun(dtypes.int32, dtypes.int32)
    def loop_cond(step, x):
      del x
      return step < 10

    with self.session() as sess:
      init_index = array_ops.placeholder(dtypes.int32, [])
      with self.test_scope():
        loop_outputs = xla.while_loop([init_index, 42], loop_cond, loop_body)

      result = sess.run(loop_outputs, {init_index: 0})
      self.assertAllClose(result, [10, 7], rtol=1e-3)

  def _testMaxItersSimple(self):
    if is_compile_on_demand():
      self.skipTest("list_ops are not supported in cpu_ondemand")
    with self.session() as sess, self.test_scope():
      xla_context = control_flow_ops.XLAControlFlowContext()
      xla_context.Enter()
      v = constant_op.constant(1.0)
      p = array_ops.placeholder(dtype=dtypes.int32)

      def create_while_loop():
        iterations = array_ops.size(p, name="iterations")
        r = control_flow_ops.while_loop(
            lambda *_: True,
            lambda i, x: (i + 1, v * x), (0, 1.0),
            maximum_iterations=iterations,
            name="outer")
        return array_ops.identity(r[1])

      output = create_while_loop()
      output = gradients_impl.gradients(output, v)[0]

      result = sess.run(output, feed_dict={p: [0, 0, 0]})
      print(result)
      xla_context.Exit()

  def testMaxItersSimple(self):
    self.skipTest("Fails with v1 control flow")
    # This fails with old control.
    # self._testMaxItersSimple()

  @test_util.enable_control_flow_v2
  def testMaxItersSimpleV2(self):
    self._testMaxItersSimple()

  def _testNestedWhileLoopWithMaxItersFromOuterContext(self):
    if is_compile_on_demand():
      self.skipTest("list_ops are not supported in cpu_ondemand")
    with self.session() as sess, self.test_scope():
      xla_context = control_flow_ops.XLAControlFlowContext()
      xla_context.Enter()
      v = constant_op.constant(1.0)
      p = array_ops.placeholder(dtype=dtypes.int32)

      def mid_body_builder(iterations):

        def mid_body(i, x):
          r = control_flow_ops.while_loop(
              lambda *_: True,
              lambda i, x: (i + 1, v * x), (0, x),
              maximum_iterations=iterations,
              name="inner")
          return (i + 1, gradients_impl.gradients(x + r[1], v)[0])

        return mid_body

      def outer_body(i, x):
        iterations = array_ops.size(p, name="iterations")
        return (i + 1, x + control_flow_ops.while_loop(
            lambda *_: True,
            mid_body_builder(iterations), (0, x),
            maximum_iterations=iterations,
            name="mid")[1])

      def create_while_loop():
        r = control_flow_ops.while_loop(
            lambda *_: True,
            outer_body, (0, 1.0),
            maximum_iterations=5,
            name="outer")
        return array_ops.identity(r[1])

      # p:placeholder
      # j = 0
      # i, x = 0, 1.
      # while j++ < 5:
      #   i1, x1 = 0, x
      #   while i1++ < len(p):
      #     i2, x2 = 0, x1
      #     while i2++ < len(p):
      #       x2 = v * x2
      #     x1 = grad(x1 + x2, v)
      #   x = x1
      # output = x
      output = create_while_loop()
      sess.run(output, feed_dict={p: [0, 0, 0]})
      xla_context.Exit()

  def testNestedWhileLoopWithMaxItersFromOuterContext(self):
    self._testNestedWhileLoopWithMaxItersFromOuterContext()

  @test_util.enable_control_flow_v2
  def testNestedWhileLoopWithMaxItersFromOuterContextV2(self):
    self._testNestedWhileLoopWithMaxItersFromOuterContext()

  @test_util.enable_control_flow_v2
  def testMap(self):
    if is_compile_on_demand():
      self.skipTest("list_ops are not supported in cpu_ondemand")
    with self.session(), self.test_scope():
      xla_context = control_flow_ops.XLAControlFlowContext()
      xla_context.Enter()
      nums = [1, 2, 3, 4, 5, 6]
      elems = constant_op.constant(nums, name="data")
      r = map_fn.map_fn(lambda x: math_ops.multiply(math_ops.add(x, 3), 2),
                        elems)
      self.assertAllEqual(r, np.array([(x + 3) * 2 for x in nums]))
      xla_context.Exit()

def is_compile_on_demand():
  return ("TF_XLA_FLAGS" in os.environ and
          "tf_xla_compile_on_demand" in os.environ["TF_XLA_FLAGS"])

if __name__ == "__main__":
  os.environ["TF_XLA_FLAGS"] = ("--tf_xla_min_cluster_size=2 " +
                                os.environ.get("TF_XLA_FLAGS", ""))
  test.main()


text:
#region  The MIT License (MIT)

#endregion
using System.Collections.Generic;
using Tag.Vows.Bean;

namespace Tag.Vows.Interface
{
    interface ITestGroup
    {
        void CheckTestToLoadTag(ITesBeforLoading tag);
    }
}


text:
<?php

declare(strict_types=1);

namespace ShlinkioTest\Shlink\Core\ShortUrl\Entity;

use Cake\Chronos\Chronos;
use PHPUnit\Framework\TestCase;
use Shlinkio\Shlink\Core\Exception\ShortCodeCannotBeRegeneratedException;
use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
use Shlinkio\Shlink\Core\ShortUrl\Model\ShortUrlCreation;
use Shlinkio\Shlink\Core\ShortUrl\Model\Validation\ShortUrlInputFilter;
use Shlinkio\Shlink\Importer\Model\ImportedShlinkUrl;
use Shlinkio\Shlink\Importer\Sources\ImportSource;

use function Functional\map;
use function range;
use function strlen;

use const Shlinkio\Shlink\DEFAULT_SHORT_CODES_LENGTH;

class ShortUrlTest extends TestCase
{
    /**
     * @test
     * @dataProvider provideInvalidShortUrls
     */
    public function regenerateShortCodeThrowsExceptionIfStateIsInvalid(
        ShortUrl $shortUrl,
        string $expectedMessage,
    ): void {
        $this->expectException(ShortCodeCannotBeRegeneratedException::class);
        $this->expectExceptionMessage($expectedMessage);

        $shortUrl->regenerateShortCode();
    }

    public function provideInvalidShortUrls(): iterable
    {
        yield 'with custom slug' => [
            ShortUrl::fromMeta(ShortUrlCreation::fromRawData(['customSlug' => 'custom-slug', 'longUrl' => ''])),
            'The short code cannot be regenerated on ShortUrls where a custom slug was provided.',
        ];
        yield 'already persisted' => [
            ShortUrl::createEmpty()->setId('1'),
            'The short code can be regenerated only on new ShortUrls which have not been persisted yet.',
        ];
    }

    /**
     * @test
     * @dataProvider provideValidShortUrls
     */
    public function regenerateShortCodeProperlyChangesTheValueOnValidShortUrls(
        ShortUrl $shortUrl,
    ): void {
        $firstShortCode = $shortUrl->getShortCode();

        $shortUrl->regenerateShortCode();
        $secondShortCode = $shortUrl->getShortCode();

        self::assertNotEquals($firstShortCode, $secondShortCode);
    }

    public function provideValidShortUrls(): iterable
    {
        yield 'no custom slug' => [ShortUrl::createEmpty()];
        yield 'imported with custom slug' => [ShortUrl::fromImport(
            new ImportedShlinkUrl(ImportSource::BITLY, '', [], Chronos::now(), null, 'custom-slug', null),
            true,
        )];
    }

    /**
     * @test
     * @dataProvider provideLengths
     */
    public function shortCodesHaveExpectedLength(?int $length, int $expectedLength): void
    {
        $shortUrl = ShortUrl::fromMeta(ShortUrlCreation::fromRawData(
            [ShortUrlInputFilter::SHORT_CODE_LENGTH => $length, 'longUrl' => ''],
        ));

        self::assertEquals($expectedLength, strlen($shortUrl->getShortCode()));
    }

    public function provideLengths(): iterable
    {
        yield [null, DEFAULT_SHORT_CODES_LENGTH];
        yield from map(range(4, 10), fn (int $value) => [$value, $value]);
    }
}


text:
<FindBugsFilter>
    <!--
    Currently Ignoring.
    findbugs reason:
    MS: May expose internal static state by storing a mutable object into a static field
    -->
    <Match>
        <Class name="org.ovirt.engine.core.searchbackend.BaseConditionFieldAutoCompleter" />
        <Bug pattern="MS_SHOULD_BE_FINAL" />
    </Match>
</FindBugsFilter>


text:
package com.infinities.keystone4j.jpa;

public class JpaProperties {

	public static String PERSISTENCE_UNIT_NAME = "com.infinities.keystone4j.jpa";
	public static String JPA_PROPERTIES_FILE = "jpa.properties";

	private JpaProperties() {

	}

}


text:
<?php

namespace Omnipay\ACHWorks\Message;

use DOMDocument;
use SimpleXMLElement;

/**
 * ACHWorks - Special function ACH to ACH transfer. From BankAccountA to BankAccountB
 */
class AchToAchRequest extends AuthorizeRequest
{
    public $transactionType = 'ACH2ACH';

    public function getData()
    {
         // This is a generic transaction that can be done for either Debit or Credit!
        // The caller must set mode $this->setMode('D') or $this->setMode('C');
        $data = $this->setupSendACHTrans();

        return $data;
    }
}


text:
package org.apache.geode.internal.cache.rollingupgrade;

import static org.apache.geode.test.awaitility.GeodeAwaitility.await;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.test.dunit.DistributedTestUtils;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.NetworkUtils;
import org.apache.geode.test.dunit.VM;

public class RollingUpgradeRollLocatorsWithOldServer extends RollingUpgrade2DUnitTestBase {

  /**
   * starts 3 locators and 1 server rolls all 3 locators and then the server
   */
  @Test
  public void testRollLocatorsWithOldServer() {
    final Host host = Host.getHost(0);
    VM locator1 = host.getVM(sourceConfiguration, 0);
    VM locator2 = host.getVM(sourceConfiguration, 1);
    VM server4 = host.getVM(sourceConfiguration, 3);

    int[] locatorPorts = AvailablePortHelper.getRandomAvailableTCPPorts(3);
    locator1.invoke(() -> DistributedTestUtils.deleteLocatorStateFile(locatorPorts));
    locator2.invoke(() -> DistributedTestUtils.deleteLocatorStateFile(locatorPorts));

    String hostName = NetworkUtils.getServerHostName();
    String locatorString = getLocatorString(locatorPorts);
    try {
      locator1.invoke(invokeStartLocator(hostName, locatorPorts[0], getTestMethodName(),
          getLocatorProperties(locatorString), true));

      // Locators before 1.4 handled configuration asynchronously.
      // We must wait for configuration configuration to be ready, or confirm that it is disabled.
      locator1.invoke(
          () -> await()
              .untilAsserted(() -> assertTrue(
                  !InternalLocator.getLocator().getConfig().getEnableClusterConfiguration()
                      || InternalLocator.getLocator().isSharedConfigurationRunning())));

      locator2.invoke(invokeStartLocator(hostName, locatorPorts[1], getTestMethodName(),
          getLocatorProperties(locatorString), false));

      invokeRunnableInVMs(invokeCreateCache(getSystemProperties(locatorPorts)), server4);

      locator1 = rollLocatorToCurrent(locator1, hostName, locatorPorts[0], getTestMethodName(),
          locatorString);
      locator2 = rollLocatorToCurrent(locator2, hostName, locatorPorts[1], getTestMethodName(),
          locatorString);

    } finally {
      invokeRunnableInVMs(true, invokeStopLocator(), locator1, locator2);
      invokeRunnableInVMs(true, invokeCloseCache(), server4);
    }
  }

}


text:
namespace faint{

// Event sent by MathTextCtrl when the value is changed by user entry
extern const wxEventType MATH_TEXT_CONTROL_UPDATE;
extern const wxEventTypeTag<wxCommandEvent> EVT_MATH_TEXT_CONTROL_UPDATE;

const wxEventType MATH_TEXT_CONTROL_UPDATE = wxNewEventType();
const wxEventTypeTag<wxCommandEvent> EVT_MATH_TEXT_CONTROL_UPDATE(
  MATH_TEXT_CONTROL_UPDATE);

}

namespace faint::events{
void on_value_change(MathTextCtrl* c, const coord_func& f){
  bind_fwd(c->AsWindow(), EVT_MATH_TEXT_CONTROL_UPDATE,
    [f, c](const wxCommandEvent&){
      f(c->GetValue());
    });
}

}

namespace faint{

static std::string format_inactive(coord value, coord originalValue){
  std::stringstream ss;
  ss << value << " (" << rounded(value / originalValue * 100) << "%)";
  return ss.str();
}

std::string format_active(coord value){
  std::stringstream ss;
  ss << value;
  return ss.str();
}

class MathTextCtrl::MathTextCtrlImpl : public wxTextCtrl {
  // Using an impl-class avoids showing all public functions from
  // wxTextCtrl in the public interface of MathTextCtrl.
public:
  MathTextCtrlImpl(wxWindow* parent, coord value) :
    wxTextCtrl(parent, wxID_ANY, "", wxPoint(1,1))
  {
    m_originalValue = value;
    SetCoordValue(value, false);

    events::on_set_focus(this, [this](){
      // When focus is gained, switch to entry-mode formatted value
      SetValue(format_active(m_value));
      SelectAll();
    });

    events::on_kill_focus(this, [this](){
      // When focus is lost, display the value with a percentage relation
      // and update the current value

      coord lastValue = UpdateValue();
      SetValue(format_inactive(m_value, m_originalValue));

      if (m_value != lastValue){
        wxCommandEvent updateEvent(EVT_MATH_TEXT_CONTROL_UPDATE, GetId());
        // Clients don't know about this class, so use the
        // parent (MathTextCtrl) as the event object.
        updateEvent.SetEventObject(GetParent());
        GetEventHandler()->ProcessEvent(updateEvent);
      }
    });
  }

  void SetCoordValue(coord value, bool hasFocus){
    m_value = value;
    SetValue(hasFocus ? format_active(m_value) :
      format_inactive(m_value, m_originalValue));
  }
  coord GetCoordValue(){
    UpdateValue();
    return m_value;
  }

  coord GetOldCoordValue(){
    return m_originalValue;
  }

private:
  coord m_value;
  coord m_originalValue;

  coord UpdateValue(){
    coord lastValue = m_value;
    auto result = parse_math_string((std::string)GetValue(), m_originalValue);
    result.IfSet(
      [&](coord value){
        if (value > 0){
          m_value = value;
        }
      });
    return lastValue;
  }
};

MathTextCtrl::MathTextCtrl(wxWindow* parent, coord value){
  m_textCtrl = make_wx<MathTextCtrlImpl>(parent, value);
  SetValue(value);
}

wxWindow* MathTextCtrl::AsWindow(){
  return m_textCtrl;
}

MathTextCtrl::MathTextCtrl(wxWindow* parent,
  coord value,
  const std::function<void(coord)>& f)
  : MathTextCtrl(parent, value)
{
  events::on_value_change(this, f);
}

void MathTextCtrl::SetValue(coord value){
  m_textCtrl->SetCoordValue(value, m_textCtrl->HasFocus());
}

coord MathTextCtrl::GetValue() const{
  return m_textCtrl->GetCoordValue();
}

coord MathTextCtrl::GetOldValue() const{
  return m_textCtrl->GetOldCoordValue();
}

bool MathTextCtrl::HasFocus() const{
  return m_textCtrl->HasFocus();
}

void MathTextCtrl::FitSizeTo(const utf8_string& str){
  fit_size_to(m_textCtrl, str);
}

wxWindow* as_window(MathTextCtrl* c){
  return c->AsWindow();
}

} // namespace


text:
<?php

namespace Chamilo\Core\User\Service\UserPropertiesExtension;

use Chamilo\Core\User\Storage\DataClass\User;

/**
 * Class UserPropertyExtensionManager
 * @package Chamilo\Core\User\Service\UserPropertiesExtension
 *
 * @author - Sven Vanpoucke - Hogeschool Gent
 */
class UserPropertiesExtensionManager
{
    /**
     * @var UserPropertiesExtensionInterface[]
     */
    protected $userPropertiesExtensions;

    /**
     * UserPropertyExtensionManager constructor.
     */
    public function __construct()
    {
        $this->userPropertiesExtensions = [];
    }

    /**
     * @param UserPropertiesExtensionInterface $userPropertiesExtension
     */
    public function addUserPropertiesExtension(UserPropertiesExtensionInterface $userPropertiesExtension)
    {
        $this->userPropertiesExtensions[] = $userPropertiesExtension;
    }

    /**
     * @param User $user
     *
     * @return array
     */
    public function getExtendedUserProperties(User $user)
    {
        $extendedUserProperties = [];

        foreach ($this->userPropertiesExtensions as $userPropertiesExtension)
        {
            $extendedUserProperties =
                array_merge($extendedUserProperties, $userPropertiesExtension->getExtendedUserProperties($user));
        }

        return $extendedUserProperties;
    }

}


text:
/**
 * Created by chirag on 14/07/15.
 */
'use strict';

// Config the app

angular.module("app", [
  /* Angular modules */
  "ngRoute",
  "ngAnimate",
  "ngSanitize",
  "ngAria",
  "ngMaterial",

  /* 3rd party modules */
  "oc.lazyLoad",
  "ui.bootstrap",
  "angular-loading-bar",
  "FBAngular",

  /* custom modules */
  "app.ctrls",
  "app.directives",
  "app.ui.ctrls",
  "app.ui.directives",
  "app.form.ctrls",
  "app.table.ctrls",
  "app.email.ctrls",
  "app.todo"

])
  // disable spinner in loading-bar
    .config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
      cfpLoadingBarProvider.includeSpinner = false;
      cfpLoadingBarProvider.latencyThreshold = 500;
    }])

  // lazy loading scripts refernces of angular modules only
    .config(["$ocLazyLoadProvider", function($oc) {
      $oc.config({
        debug: true,
        event: false,
        modules: [{
          name: "angularBootstrapNavTree",
          files: ["/modules/app/controllers/lazyload/abn_tree_directive.js", "/modules/app/styles/lazyload/abn_tree.css"]
        },
          {
            name: "ui.calendar",
            serie: true,	// load files in series
            files: [
              "/modules/app/controllers/lazyload/moment.min.js",
              "/modules/app/controllers/lazyload/fullcalendar.min.js",
              "/modules/app/styles/lazyload/fullcalendar.css",
              "/modules/app/controllers/lazyload/calendar.js"
            ]
          },
          {
            name: "ui.select",
            files: ["/modules/app/controllers/lazyload/select.min.js", "/modules/app/styles/lazyload/select.css"]
          },
          {
            name: "ngTagsInput",
            files: ["/modules/app/controllers/lazyload/ng-tags-input.min.js", "/modules/app/styles/lazyload/ng-tags-input.css"]
          },
          {
            name: "colorpicker.module",
            files: ["/modules/app/controllers/lazyload/bootstrap-colorpicker-module.min.js", "/modules/app/styles/lazyload/colorpicker.css"]
          },
          {
            name: "ui.slider",
            serie: true,
            files: ["/modules/app/controllers/lazyload/bootstrap-slider.min.js", "/modules/app/controllers/lazyload/directives/bootstrap-slider.directive.js", "/modules/app/styles/lazyload/bootstrap-slider.css"]
          },
          {
            name: "textAngular",
            serie: true,
            files: ["/modules/app/controllers/lazyload/textAngular-rangy.min.js",  "/modules/app/controllers/lazyload/textAngular.min.js", "/modules/app/controllers/lazyload/textAngularSetup.js", "/modules/app/styles/lazyload/textAngular.css"]
          },
          {
            name: "flow",
            files: ["/modules/app/controllers/lazyload/ng-flow-standalone.min.js"]
          },
          {
            name: "ngImgCrop",
            files: ["/modules/app/controllers/lazyload/ng-img-crop.js", "/modules/app/styles/lazyload/ng-img-crop.css"]
          },
          {
            name: "ngMask",
            files: ["/modules/app/controllers/lazyload/ngMask.min.js"]
          },
          {
            name: "angular-c3",
            files: ["/modules/app/controllers/lazyload/directives/c3.directive.js"]
          },
          {
            name: "easypiechart",
            files: ["/modules/app/controllers/lazyload/angular.easypiechart.min.js"]
          },
          {
            name: "ngMap",
            files: ["/modules/app/controllers/lazyload/ng-map.min.js"]
          }
        ]
      })
    }])

  // jquery/javascript and css for plugins via lazy load
    .constant("JQ_LOAD", {
      fullcalendar: [],
      moment: ["/modules/app/controllers/lazyload/moment.min.js"],
      sparkline: ["/modules/app/controllers/lazyload/jquery.sparkline.min.js"],
      c3: ["/modules/app/controllers/lazyload/d3.min.js", "/modules/app/controllers/lazyload/c3.min.js", "/modules/app/styles/lazyload/c3.css"],
      gmaps: ["https://maps.google.com/maps/api/js"]
    })

  // route provider

//.config(['$stateProvider','JQ_LOAD',
//  function($stateProvider,jqload) {
//    // Users state routing
//    $stateProvider.
//        state('app', {
//          url: '/app',
//          templateUrl: 'modules/app/views/base.html'
//        }).
//        state('calendar', {
//          url: '/calendar',
//          templateUrl: 'modules/app/views/calendar.html',
//          controller: "CalendarDemoCtrl",
//          resolve: {
//            deps: ["$ocLazyLoad", function(a) {
//              return a.load("ui.calendar")
//                  .then(function() {
//                    return a.load({
//                      name: "app.ctrls",
//                      files: ["/modules/app/controllers/lazyload/controllers/calendarCtrl.js"]
//                    })
//                  });
//            }]
//          }
//        }).
//        state('dashboard', {
//          url: '/dashboard',
//          templateUrl: 'modules/app/views/dashboard.html',
//          resolve: {
//            deps: ["$ocLazyLoad", function(a) {
//              return a.load([jqload.c3, jqload.sparkline])
//                  .then(function() {
//                    return a.load({
//                      name: "app.directives",
//                      files: ["/modules/app/controllers/lazyload/directives/sparkline.directive.js"]
//                    })
//                  })
//                  .then(function() {
//                    return a.load("angular-c3");
//                  })
//                  .then(function() {
//                    return a.load("easypiechart");
//                  })
//            }]
//          }
//
//        });
//
//  }
//    ])

      .config(["$routeProvider", "$locationProvider", "JQ_LOAD", function($routeProvider, $locationProvider, jqload) {

      var routes = [
        "ui/buttons", "ui/typography", "ui/grids", "ui/panels", "ui/tabs", "ui/modals", "ui/progress-bars", "ui/extras",
        "icons/font-awesome", "icons/ionicons",
        "forms/wizard",
        "tables/tables",
        "pages/signin", "pages/signup", "pages/404", "pages/forget-pass", "pages/lock-screen", "pages/invoice", "pages/search", "pages/timeline"
      ];

      function setRoutes(route) {
        var url = '/' + route,
            config = {
              templateUrl: "views/" + route + ".html"
            };

        $routeProvider.when(url, config);
        return $routeProvider;
      }

      routes.forEach(function(route) {
        setRoutes(route);
      });

      $routeProvider
          .when("/", {redirectTo: "/dashboard"})
          .when("/404", {templateUrl: "views/pages/404.html"})
          .otherwise({redirectTo: "/404"});

      $routeProvider.when("/dashboard", {
        templateUrl: "views/dashboard.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load([jqload.c3, jqload.sparkline])
                .then(function() {
                  return a.load({
                    name: "app.directives",
                    files: ["/modules/app/controllers/lazyload/directives/sparkline.directive.js"]
                  })
                })
                .then(function() {
                  return a.load("angular-c3");
                })
                .then(function() {
                  return a.load("easypiechart");
                })

          }]
        }
      });

      // text angular loaded in email/inbox
      $routeProvider.when("/email/inbox", {
        templateUrl: "views/email/inbox.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("textAngular");
          }]
        }
      });

      // calendar plugin
      // "/modules/app/controllers/lazyload/apps/calendarDemo.js"
      $routeProvider.when("/calendar", {
        templateUrl: "views/calendar.html",
        controller: "CalendarDemoCtrl",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("ui.calendar")
                .then(function() {
                  return a.load({
                    name: "app.ctrls",
                    files: ["/modules/app/controllers/lazyload/controllers/calendarCtrl.js"]
                  })
                });
          }]
        }
      });

      // Material Controller (For demo)
      $routeProvider.when("/material", {
        templateUrl: "views/material.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load({
              name: "app.ctrls",
              files: ["/modules/app/controllers/lazyload/controllers/materialCtrl.js"]
            })
          }]
        }
      });

      // tree view plugin
      $routeProvider.when("/ui/treeview", {
        templateUrl: "views/ui/treeview.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("angularBootstrapNavTree")
                .then(function() {
                  return a.load({
                    name: "app.ctrls",
                    files: ["/modules/app/controllers/lazyload/controllers/treeviewCtrl.js"]
                  })
                })
          }]
        }
      });

      // load ui-select when notification page load.
      $routeProvider.when("/ui/notifications", {
        templateUrl: "views/ui/notifications.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("ui.select");
          }]
        }
      });

      // load ui-select in form-elements
      $routeProvider.when("/forms/elements", {
        templateUrl: "views/forms/elements.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load(["ui.select", "ngTagsInput", "colorpicker.module", "ui.slider"])
                .then(function() {
                  return a.load({
                    name: "app.ctrls",
                    files: ["/modules/app/controllers/lazyload/controllers/selectCtrl.js", "/modules/app/controllers/lazyload/controllers/tagsInputCtrl.js"]
                  })
                })
                .then(function() {
                  return a.load("textAngular");
                })

          }]
        }
      });

      // file uploader in form-elements
      $routeProvider.when("/forms/uploader", {
        templateUrl: "views/forms/uploader.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("flow");
          }]
        }
      });

      // Image Crop in form-elements
      $routeProvider.when("/forms/imagecrop", {
        templateUrl: "views/forms/imagecrop.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("ngImgCrop")
                .then(function() {
                  return a.load({
                    name: "app.ctrls",
                    files: ["/modules/app/controllers/lazyload/controllers/imageCropCtrl.js"]
                  })
                })
          }]
        }
      });

      // Form validation
      $routeProvider.when("/forms/validation", {
        templateUrl: "views/forms/validation.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("ngMask");
          }]
        }
      });

      /// charts - sparklines
      $routeProvider.when("/charts/sparklines", {
        templateUrl: "views/charts/sparklines.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load(jqload.sparkline)
                .then(function() {
                  return a.load({
                    name: "app.directives",
                    files: ["/modules/app/controllers/lazyload/directives/sparkline.directive.js"]
                  })
                })
          }]
        }
      });

      /// charts - c3
      $routeProvider.when("/charts/c3", {
        templateUrl: "views/charts/c3.html",
        resolve: {
          deps: ["$ocLazyLoad", "$rootScope", "$timeout", function(a, $rootScope, $timeout) {
            return a.load(jqload.c3)
                .then(function() {
                  return a.load("angular-c3");
                })
                .then(function() {
                  return a.load({
                    name: "app.ctrls",
                    files: ["/modules/app/controllers/lazyload/controllers/c3ChartCtrl.js"]
                  })
                })
                .then(function() {
                  return a.load("easypiechart");
                })
                .then(function() {
                  $timeout(function() {
                    $rootScope.$broadcast("c3.resize");
                  }, 100);
                })

          }]
        }
      });

      /// Google Map
      $routeProvider.when("/maps/google-map", {
        templateUrl: "views/maps/google-map.html",
        resolve: {
          deps: ["$ocLazyLoad", function(a) {
            return a.load("ngMap");

          }]
        }
      });

    }])
.controller('maleBody', function($scope) {
      $scope.fileCount=0;
      $scope.$on('$destroy', function() {
        window.onbeforeunload = undefined;
      });
      $scope.$on('$locationChangeStart', function(event, next, current) {
        console.log($('body').find('div.dg.ac'));
        $('body').find('div.dg.ac').remove();
        console.log($('body').find('div.dg.ac'));
       });
    });


text:
/* eslint-disable */

module.exports = function(config) {
  config.set({
    // base path used to resolve all patterns
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files/patterns to load in the browser
    files: [{
      pattern: 'spec.bundle.js',
      watched: false
    }],

    // files to exclude
    exclude: [],

    plugins: [
      require("karma-chai"),
      require("karma-chrome-launcher"),
      require("karma-mocha"),
      require("karma-mocha-reporter"),
      require("karma-sourcemap-loader"),
      require("karma-webpack")
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'spec.bundle.js': ['webpack', 'sourcemap']
    },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [{
          test: /\.js$/,
          exclude: [/app\/lib/, /node_modules/],
          loader: 'ng-annotate!babel'
        }, {
          test: /\.html$/,
          loader: 'raw'
        }, {
          test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
          loader: "file"
        }, {
          test: /\.(woff|woff2)$/,
          loader: "url?prefix=font/&limit=5000"
        }, {
          test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url?limit=10000&mimetype=application/octet-stream"
        }, {
          test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
          loader: "url?limit=10000&mimetype=image/svg+xml"
        }, {
          test: /\.scss$/,
          loader: "style!css!sass"
        }, {
          test: /\.css$/,
          loader: "style!css"
        }, {
          test: /\.(jpe?g|png|gif|svg)$/i,
          loaders: [
            'file?hash=sha512&digest=hex&name=[name]_[hash].[ext]',
            'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
          ]
        }]
      }
    },

    webpackServer: {
      noInfo: true // prevent console spamming when running in Karma!
    },

    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable colors in the output
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // toggle whether to watch files and rerun tests upon incurring changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // if true, Karma runs tests once and exits
    singleRun: true
  });
};


text:
using System;
using System.Threading.Tasks;
using Depot.Messages.Commands;
using Microsoft.AspNetCore.Mvc;
using RawRabbit;

namespace Depot.Api.Controllers
{
    [Route("[controller]")]
    public class EntriesController : Controller
    {
        private readonly IBusClient _busClient;

        public EntriesController(IBusClient busClient)
        {
            _busClient = busClient;
        }

        [HttpPost]
        public async Task<IActionResult> Post([FromBody]CreateEntry command)
        {
            if(string.IsNullOrWhiteSpace(command.Key))
            {
               throw new ArgumentException("Entry key can not be empty.", nameof(command.Key));
            }
            await _busClient.PublishAsync(command);

            return Accepted();
        }
    }
}


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_InstanceGroups_SetNamedPorts_sync_flattened]
    using Google.Cloud.Compute.V1;
    using lro = Google.LongRunning;

    public sealed partial class GeneratedInstanceGroupsClientSnippets
    {
        /// <summary>Snippet for SetNamedPorts</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void SetNamedPorts()
        {
            // Create client
            InstanceGroupsClient instanceGroupsClient = InstanceGroupsClient.Create();
            // Initialize request argument(s)
            string project = "";
            string zone = "";
            string instanceGroup = "";
            InstanceGroupsSetNamedPortsRequest instanceGroupsSetNamedPortsRequestResource = new InstanceGroupsSetNamedPortsRequest();
            // Make the request
            lro::Operation<Operation, Operation> response = instanceGroupsClient.SetNamedPorts(project, zone, instanceGroup, instanceGroupsSetNamedPortsRequestResource);

            // Poll until the returned long-running operation is complete
            lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            Operation result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            lro::Operation<Operation, Operation> retrievedResponse = instanceGroupsClient.PollOnceSetNamedPorts(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Operation retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END compute_v1_generated_InstanceGroups_SetNamedPorts_sync_flattened]
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<EngineConfig xmlns="http://tempuri.org/EngineConfig.xsd">
	<FilePath type="Folder" src="..\..\..\..\Media\GpuPrograms"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Textures"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Interface"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Icons"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Meshes"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Skeletons"/>
	<FilePath type="Folder" src="..\..\..\..\Media\Materials"/>
     <!--
	<FilePath type="Folder" src="Media\Sounds"/>
	<FilePath type="Folder" src="Media\Fonts"/>
	<FilePath type="Folder" src="Media\Overlays"/>
	<FilePath type="ZipFile" src="Media\Archives\Fresnel.zip"/>
	<FilePath type="ZipFile" src="Media\Archives\Water.zip"/>
	<FilePath type="ZipFile" src="Media\Textures\SkyBoxes.zip"/>
    -->
</EngineConfig>


text:
using UnityEngine;
using System.Collections;

public class Rocket2D : Projectile2D {

    public GameObject explosion;
    public RocketExplosion2D explosionCollider;
    bool exploded = false;
    Animator anim;

	// Use this for initialization
	void Start () {
        base.Start();
        anim = GetComponent<Animator>();
        anim.SetBool("isFlying", true);
	}

	// Update is called once per frame
	void Update () {
        base.Update();
	}

    void FixedUpdate(){
        base.FixedUpdate();
    }

    public void Explode()
    {
        if (!exploded)
        {
            explosionCollider.ExplodeCollider();
            PlayExplosionAnim();
            exploded = true;
        }
    }

    void PlayExplosionAnim()
    {
        GameObject explosionAnim = Instantiate(explosion, this.transform.position, new Quaternion(0,0,0,1)) as GameObject;
        Animator explAnim = explosionAnim.GetComponent<Animator>();
        explAnim.SetTrigger("Explode");
        Destroy(explosionAnim, 3f);
    }

	void OnTriggerEnter2D(Collider2D other)
	{
        if (LayerMask.LayerToName(other.gameObject.layer) == "Ground" || LayerMask.LayerToName(other.gameObject.layer) == "Sandbag")
			Explode ();
	}
}