text:
#pragma once
#include <aws/codestar-connections/CodeStarconnections_EXPORTS.h>
#include <aws/codestar-connections/CodeStarconnectionsRequest.h>
#include <aws/codestar-connections/model/ProviderType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CodeStarconnections
{
namespace Model
{

  /**
   */
  class AWS_CODESTARCONNECTIONS_API ListConnectionsRequest : public CodeStarconnectionsRequest
  {
  public:
    ListConnectionsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListConnections"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline const ProviderType& GetProviderTypeFilter() const{ return m_providerTypeFilter; }

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline bool ProviderTypeFilterHasBeenSet() const { return m_providerTypeFilterHasBeenSet; }

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline void SetProviderTypeFilter(const ProviderType& value) { m_providerTypeFilterHasBeenSet = true; m_providerTypeFilter = value; }

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline void SetProviderTypeFilter(ProviderType&& value) { m_providerTypeFilterHasBeenSet = true; m_providerTypeFilter = std::move(value); }

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline ListConnectionsRequest& WithProviderTypeFilter(const ProviderType& value) { SetProviderTypeFilter(value); return *this;}

    /**
     *
Filters the list of connections to those associated with a specified
     * provider, such as Bitbucket.

     */
    inline ListConnectionsRequest& WithProviderTypeFilter(ProviderType&& value) { SetProviderTypeFilter(std::move(value)); return *this;}

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline const Aws::String& GetHostArnFilter() const{ return m_hostArnFilter; }

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline bool HostArnFilterHasBeenSet() const { return m_hostArnFilterHasBeenSet; }

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline void SetHostArnFilter(const Aws::String& value) { m_hostArnFilterHasBeenSet = true; m_hostArnFilter = value; }

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline void SetHostArnFilter(Aws::String&& value) { m_hostArnFilterHasBeenSet = true; m_hostArnFilter = std::move(value); }

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline void SetHostArnFilter(const char* value) { m_hostArnFilterHasBeenSet = true; m_hostArnFilter.assign(value); }

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline ListConnectionsRequest& WithHostArnFilter(const Aws::String& value) { SetHostArnFilter(value); return *this;}

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline ListConnectionsRequest& WithHostArnFilter(Aws::String&& value) { SetHostArnFilter(std::move(value)); return *this;}

    /**
     *
Filters the list of connections to those associated with a specified
     * host.

     */
    inline ListConnectionsRequest& WithHostArnFilter(const char* value) { SetHostArnFilter(value); return *this;}

    /**
     *
The maximum number of results to return in a single call. To retrieve the
     * remaining results, make another call with the returned nextToken
     * value.

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
The maximum number of results to return in a single call. To retrieve the
     * remaining results, make another call with the returned nextToken
     * value.

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
The maximum number of results to return in a single call. To retrieve the
     * remaining results, make another call with the returned nextToken
     * value.

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
The maximum number of results to return in a single call. To retrieve the
     * remaining results, make another call with the returned nextToken
     * value.

     */
    inline ListConnectionsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline ListConnectionsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline ListConnectionsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The token that was returned from the previous ListConnections
     * call, which can be used to return the next set of connections in the list.

     */
    inline ListConnectionsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    ProviderType m_providerTypeFilter;
    bool m_providerTypeFilterHasBeenSet;

    Aws::String m_hostArnFilter;
    bool m_hostArnFilterHasBeenSet;

    int m_maxResults;
    bool m_maxResultsHasBeenSet;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet;
  };

} // namespace Model
} // namespace CodeStarconnections
} // namespace Aws


text:
"""

Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Constraints:

0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed is a permutation of popped.
pushed and popped have distinct values.

"""

class Solution:
    def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
        start = 0
        stk = []
        for a in popped:
            if stk and stk[-1] == a:
                stk.pop()
                continue
            idx = pushed.index(a)
            if idx < start:
                return False
            for i in range(start, idx):
                stk.append(pushed[i])
            start = idx + 1
        return len(stk) == 0

redpajama_set_name: RedPajamaGithub


text:
django-sepa
===========

Django Sepa


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb162.project.geometry;

/**
 * @author xvalchar
 */
public class GeneralRegularPolygon implements RegularPolygon, Colored {

    private final Vertex2D center;
    private final int numEdges;
    private final double edgeLength;
    private Color color;

    /**
     * Constructor
     *
     * @param center center of polygon
     * @param numEdges number of edges
     * @param edgeLength length of edge
     */
    public GeneralRegularPolygon(Vertex2D center, int numEdges, double edgeLength) {
        this.center = center;
        this.numEdges = numEdges;
        this.edgeLength = edgeLength;
        setColor(Color.BLACK);
    }

    @Override
    public int getNumEdges() {
        return numEdges ;
    }

    @Override
    public double getEdgeLength() {
        return edgeLength;
    }

    @Override
    public Vertex2D getCenter() {
        return center;
    }

    @Override
    public double getRadius() {
        return(getEdgeLength() / (2 * Math.sin(Math.PI / getNumEdges())) );
    }

    @Override
    public double getArea() {
        return(((getNumEdges() * Math.pow(getRadius(),2) * Math.sin(2*Math.PI / getNumEdges()) ) / 2));
    }

    @Override
    public double getWidth() {
        return(2 * getRadius());
    }

    @Override
    public double getHeight() {
       return(2 * getRadius());
    }

    @Override
    public double getLength() {
        return(getNumEdges() * getEdgeLength());
    }

    @Override
    public Color getColor() {
        return color;
    }

    @Override
    public final void setColor(Color color) {
        this.color = color;
    }

    /**
     * Method print number of edges, center, length of edges and color
     * of polygon.
     *
     * @return String location of point
     */
    public String toString() {
        return(getNumEdges() + "-gon: center=" + getCenter() + ", " + "edge "
                + "length=" + getEdgeLength() + ", color=" + getColor());
    }

    @Override
    public Vertex2D getVertex(int index) throws IllegalArgumentException {
        double x = getCenter().getX() - getRadius() * Math.cos((index * 2 * Math.PI) / getNumEdges());
        double y = getCenter().getY() - getRadius() * Math.sin((index * 2 * Math.PI) / getNumEdges());
        return new Vertex2D(x,y);
    }

    @Override
    public int getNumVertices() {
        return numEdges;
    }

    /**
     * Triangulate divide polygon on triangles
     *
     * @return array of triangles that divide regular polygon
     */
    public Triangle[] triangulate() {
        Triangle[] triangles = new Triangle[getNumEdges()];

        for(int i = 0; i < getNumEdges(); i++) {
            triangles[i] = new Triangle(getCenter(), getVertex(i), getVertex(i + 1));
        }

        return triangles;
    }

}


text:
package io.github.meln1k.vkApi.services

import io.github.meln1k.vkApi.utils.AccessToken

import scala.concurrent.Future
import play.api.libs.json._

trait HttpLayerService {
  def apiRequest(methodName: String, params: Seq[(String,String)])(implicit accessToken: AccessToken): Future[JsValue]
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<localizationDictionary culture="fr">
  <texts>
    <text name="InvalidTenancyName" value="Ce nom de client (Tenant) n'est pas valide !" />
    <text name="TenancyNameIsAlreadyTaken" value="Le nom de client (Tenant) {0} est déjà connu et réservé." />
    <text name="RoleNameIsAlreadyTaken" value="Le nom du profil {0} est déjà connu et réservé." />
    <text name="RoleDisplayNameIsAlreadyTaken" value="Le nom affiché du profil est déjà connu et réservé." />
    <text name="CanNotDeleteStaticRole" value="Impossible d'effacer le profil statique : {0}" />
    <text name="CanNotRenameAdminUser" value="Impossible de renommer le nom d'utilisateur : {0} car il s'agit de l'utilisateur administrateur par défaut !" />
    <text name="CanNotDeleteAdminUser" value="Impossible d'effacer le nom d'utilisateur : {0} car il s'agit de l'utilisateur administrateur par défaut !" />
    <text name="OrganizationUnitDuplicateDisplayNameWarning" value="Il existe déjà une unité organisationnelle portant le nom {0}. Deux unités avec la même appelation ne peuvent être créées au même niveau." />
  </texts>
</localizationDictionary>


text:
// Use defaults to test ES2018 object spread
const defaults = {
	'drinking-age': 21,
};

// This config is used to decide if a person is allowed to drink.
// We use 'separate-lines' for multiline comments
// Read more at https://eslint.org/docs/rules/multiline-comment-style
const config = {
	...defaults,
	drinks: [
		'beer',
		'gin',
		'tequila',
	],
};

// The following comments are in JSDoc format
// which are always allowed. See http://usejsdoc.org/

/** Class representing a person. */
class Person {
	/**
	 * Create a person.
	 * @param {string} name - The name of the person.
	 * @param {int} age - The age of the person.
	 */
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}

	get name() {
		return this._name;
	}

	set name(value) {
		this._name = value;
	}

	party() {
		if (this.isAllowedToDrink) {
			return Person.cheer();
		}

		return Person.bummer();
	}

	static cheer() {
		return `Whooohoo, where's the ${config.drinks[0]}?!?!`;
	}

	static bummer() {
		return 'Bummer, dude!';
	}

	get isAllowedToDrink() {
		const { age } = this;
		const { 'drinking-age': legalAge } = config;

		return age >= legalAge;
	}
}

export default Person;


text:
package galaxyspace.systems.SolarSystem.planets.overworld.inventory.schematics;

import micdoodle8.mods.galacticraft.core.inventory.InventorySchematic;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;

public class InventorySchematicEngine extends InventorySchematic
{
	private final int size = 30;

    public InventorySchematicEngine(Container container)
    {
    	super(container);
        this.stacks = NonNullList.withSize(size, ItemStack.EMPTY);

    }

}


text:
package ArchiChaT.Rest;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;

/**
 * Created by SMITHE on 14-Jun-17.
 */
public interface IRest< T > {

	public T getOne( int id ) throws RemoteException, NotBoundException;

	public ArrayList<T> getAll() throws RemoteException, NotBoundException;
	public T put( int id, T resource ) throws RemoteException, NotBoundException;
	public T post( T resource ) throws RemoteException, NotBoundException;
	public void delete( int id ) throws RemoteException, NotBoundException;
	public Object lookupService(String serviceName) throws RemoteException, NotBoundException;
}


text:
package jenkins.xml;

import jenkins.util.xml.XMLUtils;

import org.junit.Assert;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPathExpressionException;

import static org.hamcrest.core.StringContains.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;

import org.jvnet.hudson.test.Issue;
import org.xml.sax.SAXException;

public class XMLUtilsTest {

    @Issue("SECURITY-167")
    @Test
    public void testSafeTransformDoesNotProcessForeignResources() throws Exception {
        final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" +
                "<!DOCTYPE project[\n" +
                "  <!ENTITY foo SYSTEM \"file:///\">\n" +
                "]>\n" +
                "<project>\n" +
                "  <actions/>\n" +
                "  <description>&foo;</description>\n" +
                "  <keepDependencies>false</keepDependencies>\n" +
                "  <properties/>\n" +
                "  <scm class=\"hudson.scm.NullSCM\"/>\n" +
                "  <canRoam>true</canRoam>\n" +
                "  <triggers/>\n" +
                "  <builders/>\n" +
                "  <publishers/>\n" +
                "  <buildWrappers/>\n" +
                "</project>";

        StringWriter stringWriter = new StringWriter();
        try {
            XMLUtils.safeTransform(new StreamSource(new StringReader(xml)), new StreamResult(stringWriter));
            // if no exception then JAXP is swallowing these - so there should be no entity in the description.
            assertThat(stringWriter.toString(), containsString("<description/>"));
        } catch (TransformerException ex) {
            assertThat(ex.getMessage(), containsString("Refusing to resolve entity"));
        }

    }

    @Issue("SECURITY-167")
    @Test
    public void testUpdateByXmlIDoesNotFail() throws Exception {
        final String xml = "<?xml version='1.0' encoding='UTF-8'?>\n" +
                "<project>\n" +
                "  <actions/>\n" +
                "  <description>&</description>\n" +
                "  <keepDependencies>false</keepDependencies>\n" +
                "  <properties/>\n" +
                "  <scm class=\"hudson.scm.NullSCM\"/>\n" +
                "  <canRoam>true</canRoam>\n" +
                "  <triggers/>\n" +
                "  <builders/>\n" +
                "  <publishers/>\n" +
                "  <buildWrappers/>\n" +
                "</project>";

        StringWriter stringWriter = new StringWriter();

        XMLUtils.safeTransform(new StreamSource(new StringReader(xml)), new StreamResult(stringWriter));
        // make sure that normal entities are retained.
        assertThat(stringWriter.toString(), containsString("<description>&</description>"));
    }

    /**
     * Tests getValue() directly. Tests the parse methods too (indirectly - yeah, a purest would have
     * tests for each).
     */
    @Test
    public void testGetValue() throws XPathExpressionException, SAXException, IOException {
        URL configUrl = getClass().getResource("/jenkins/xml/config.xml");
        File configFile = new File(configUrl.getFile());

        Assert.assertEquals("1.480.1", XMLUtils.getValue("/hudson/version", configFile));
        Assert.assertEquals("", XMLUtils.getValue("/hudson/unknown-element", configFile));
    }

    @Test
    public void testParse_with_XXE() {
        final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<!DOCTYPE foo [\n" +
                "   <!ELEMENT foo ANY >\n" +
                "   <!ENTITY xxe SYSTEM \"http://abc.com/temp/test.jsp\" >]> " +
                "<foo>&xxe;</foo>";

        StringReader stringReader = new StringReader(xml);
        final SAXException e = assertThrows(SAXException.class, () -> XMLUtils.parse(stringReader));
        assertThat(e.getMessage(), containsString("\"http://apache.org/xml/features/disallow-doctype-decl\""));
    }
}


text:
namespace ui::test {

namespace {

DEFINE_LOCAL_ELEMENT_IDENTIFIER_VALUE(kTestElementIdentifier);
const ElementContext kTestElementContext(1);

class MockInteractionSimulator : public InteractionTestUtil::Simulator {
 public:
  MockInteractionSimulator() = default;
  ~MockInteractionSimulator() override = default;

  MOCK_METHOD2(PressButton,
               bool(TrackedElement* element, InputType input_type));
  MOCK_METHOD2(SelectMenuItem,
               bool(TrackedElement* element, InputType input_type));
};

}  // namespace

TEST(InteractionTestUtilTest, PressButton) {
  TestElement element(kTestElementIdentifier, kTestElementContext);
  InteractionTestUtil util;
  auto* const mock = util.AddSimulator(
      std::make_unique<testing::NiceMock<MockInteractionSimulator>>());
  EXPECT_CALL(*mock,
              PressButton(&element, InteractionTestUtil::InputType::kDontCare))
      .WillOnce(testing::Return(true));
  util.PressButton(&element);
}

TEST(InteractionTestUtilTest, SelectMenuItem) {
  TestElement element(kTestElementIdentifier, kTestElementContext);
  InteractionTestUtil util;
  auto* const mock = util.AddSimulator(
      std::make_unique<testing::NiceMock<MockInteractionSimulator>>());
  EXPECT_CALL(*mock, SelectMenuItem(&element,
                                    InteractionTestUtil::InputType::kDontCare))
      .WillOnce(testing::Return(true));
  util.SelectMenuItem(&element);
}

}  // namespace ui::test


text:
require 'spec_helper'

feature 'Validating an email address', :vcr do
  background do
    PostcodeAnywhere::EmailValidation.key = ENV['POSTCODE_ANYWHERE_KEY']
  end

  scenario 'With valid format and valid DNS record' do
    expect(PostcodeAnywhere::EmailValidation.valid?('info@google.com')).to be_truthy
  end

  scenario 'With invalid format' do
    expect(PostcodeAnywhere::EmailValidation.valid?('@google.com')).to be_falsey
  end

  scenario 'With invalid DNS record' do
    expect(PostcodeAnywhere::EmailValidation.valid?('info@google.google')).to be_falsey
  end

  scenario 'Without API key' do
    PostcodeAnywhere::EmailValidation.key = 'AA11-AA11-AA11-AA11'

    expect { PostcodeAnywhere::EmailValidation.valid?('info@google.com') }.to raise_error(PostcodeAnywhere::EmailValidation::ValidationError)
  end
end


text:
/**
 * @fileoverview Representation of a message.
 */

/**
 * @class
 * Base interface for all message collection objects.
 *
 *

 *
 * @name opensocial.MessageCollection
 */

/**
 * Base interface for all message collection objects.
 *
 * @param {Object.<opensocial.MessageCollection.Field, Object>=} opt_params Any other
 *    fields that should be set on the message object. All of the defined
 *    Fields are supported.
 * @private
 * @constructor
 * @deprecated since 1.0 see http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-Gadget.xml#rfc.section.A.39.
 */
opensocial.MessageCollection = function(opt_params) {
  this.fields_ = opt_params || {};
};

/**
 * @static
 * @class
 * All of the fields that message collections can have.
 *
 *

 * See also:
 * opensocial.MessageCollection.getField()
 *

 *
 * @name opensocial.MessageCollection.Field
 * @deprecated since 1.0 see http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-Gadget.xml#rfc.section.A.40.
 */
opensocial.MessageCollection.Field = {
  /**
   * The Unique ID of this message collection.
   * @member opensocial.MessageCollection.Field
   */
  ID: 'id',

  /**
   * The title of the message collection.
   * @member opensocial.MessageCollection.Field
   */
  TITLE: 'title',

  /**
   * The total number of messages in this collection.
   * @member opensocial.MessageCollection.Field
   */
  TOTAL: 'total',

  /**
   * The total number of unread messages in this collection
   * @member opensocial.MessageCollection.Field
   */
  UNREAD: 'unread',

  /**
   * The updated timestamp for this collection
   * @member opensocial.MessageCollection.Field
   */
  UPDATED: 'updated',

  /**
   * Urls associated with this collection
   * @member opensocial.MessageCollection.Field
   */
  URLS: 'urls'
};

/**
 * Gets the message data that's associated with the specified key.
 *
 * @param {string} key The key to get data for;
 *   see the Field class
 * for possible values.
 * @param {Object.<opensocial.DataRequest.DataRequestFields, Object>}
 *  opt_params Additional
 *    params
 *    to pass to the request.
 * @return {string} The data.
 * @member opensocial.MessageCollection
 * @deprecated since 1.0 see http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-Gadget.xml#rfc.section.A.39.1.1.
 */
opensocial.MessageCollection.prototype.getField = function(key, opt_params) {
  return opensocial.Container.getField(this.fields_, key, opt_params);
};

/**
 * Sets data for this message associated with the given key.
 *
 * @param {string} key The key to set data for.
 * @param {string} data The data to set.
 * @deprecated since 1.0 see http://opensocial-resources.googlecode.com/svn/spec/1.0/Social-Gadget.xml#rfc.section.A.39.1.2.
 */
opensocial.MessageCollection.prototype.setField = function(key, data) {
  return this.fields_[key] = data;
};


text:
import isIndexed from './isIndexed'
import isKeyed from './isKeyed'

export default function isAssociative(data) {
  return isKeyed(data) || isIndexed(data)
}


text:
"""Test DistributionStrategy, TowerContext, and supporting APIs."""

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

from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import test
from tensorflow.python.training import distribute

class _TestTowerContext(distribute.TowerContext):

  def merge_call(self, fn, *args, **kwargs):
    return kwargs["test_arg"]

class _TestStrategy(distribute.DistributionStrategy):

  def _call_for_each_tower(self, fn, *args, **kwargs):
    with _TestTowerContext(self, tower_id=0):
      return fn(*args, **kwargs)

  def _create_variable(self, next_creator, *args, **kwargs):
    return kwargs["name"]

def _assert_in_default_state(t):
  t.assertIs(distribute._default_tower_context,
             distribute.get_tower_context())
  t.assertIs(None, distribute.get_cross_tower_context())
  t.assertIs(distribute._default_distribution_strategy,
             distribute.get_distribution_strategy())
  t.assertFalse(distribute.has_distribution_strategy())

class TestStrategyTest(test.TestCase):

  def testCallForEachTower(self):
    _assert_in_default_state(self)
    dist = _TestStrategy()

    def run_fn():
      tower_context = distribute.get_tower_context()
      self.assertTrue(tower_context is not None)
      self.assertIs(None, distribute.get_cross_tower_context())
      self.assertTrue(distribute.has_distribution_strategy())
      self.assertIs(dist, distribute.get_distribution_strategy())
      self.assertEqual("foo", tower_context.merge_call(None, test_arg="foo"))
      self.assertEqual("bar", variable_scope.variable(1.0, name="bar"))

    with self.assertRaises(RuntimeError):
      dist.call_for_each_tower(run_fn)
    with dist.scope():
      dist.call_for_each_tower(run_fn)
    _assert_in_default_state(self)

  def testScope(self):
    _assert_in_default_state(self)
    dist = _TestStrategy()
    with dist.scope():
      self.assertIs(None, distribute.get_tower_context())
      self.assertIs(dist, distribute.get_cross_tower_context())
      self.assertTrue(distribute.has_distribution_strategy())
      self.assertIs(dist, distribute.get_distribution_strategy())
      self.assertEqual("baz", variable_scope.variable(1.0, name="baz"))
    _assert_in_default_state(self)

class DefaultDistributionStrategyTest(test.TestCase):

  def testMergeCall(self):
    _assert_in_default_state(self)

    def merge_fn(dist, s):
      self.assertIs(distribute._default_distribution_strategy, dist)
      self.assertIs(None, distribute.get_tower_context())
      self.assertIs(dist, distribute.get_cross_tower_context())
      self.assertIs(dist, distribute.get_distribution_strategy())
      self.assertFalse(distribute.has_distribution_strategy())
      return "foo_" + s

    tower_ctx = distribute.get_tower_context()
    self.assertIs(distribute._default_tower_context, tower_ctx)
    self.assertEqual("foo_bar", tower_ctx.merge_call(merge_fn, "bar"))
    _assert_in_default_state(self)

if __name__ == "__main__":
  test.main()


text:
<md-content layout-padding>

        <md-card>
            <md-card-header>
                <md-card-header-text>
                    On The Spot
                </md-card-header-text>
            </md-card-header>
            <md-card-title>
                <md-card-title-text>
                    Bill Wiley
                    Owner/Operator
                </md-card-title-text>
            </md-card-title>
            <md-card-content>

                    On the Spot is a privately owned and listed company that focuses on on providing the most accurate and secure courier and delivery experience.

                    Originally founded by Bill Wiley, On the Spot has become the product of Bills years of experience from working in large international courier and shipping service companies.

                    What sets us apart from our competitors is our utilisation of technology to provide quality customer experiences and transparency in our company in regards to your deliveries.

                    Through the use of state of the art technology, On the Spot provides its services to locations all around Australia.

                    With technology such as GPS tracking and specifically designed internal information systems, On the Spot is able to provide a secure and accurate delivery service.
                    Our GPS tracking system enables us to provide you with live updates on the location and status of your packages.
                    In addition to this our tailor made information system allows our company to run more efficiently and productively than our competitors resulting in a highly accurate service.

                    Our aim is to provide accuracy and an exception customer experience in relation to domestic courier services.

            </md-card-content>
        </md-card>

</md-content>


text:
package com.groupdocs.viewer.examples.basic_usage.render_document_to_image;

import org.testng.annotations.Test;

public class RenderForDisplayWithTextTests {

    /**
     * This example demonstrates how to render document so extracted text may be
     * placed as top layer over the image.
     */
    @Test
    public void run() {
        RenderForDisplayWithText.run();
    }
}


text:
package org.wso2.carbon.apimgt.rest.api.publisher.v1.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import javax.validation.constraints.*;

import io.swagger.annotations.*;
import java.util.Objects;

import javax.xml.bind.annotation.*;

public class CertificateValidityDTO   {

    private String from = null;
    private String to = null;

  /**
   **/
  public CertificateValidityDTO from(String from) {
    this.from = from;
    return this;
  }

  @ApiModelProperty(example = "12-12-2017", value = "")
  @JsonProperty("from")
  public String getFrom() {
    return from;
  }
  public void setFrom(String from) {
    this.from = from;
  }

  /**
   **/
  public CertificateValidityDTO to(String to) {
    this.to = to;
    return this;
  }

  @ApiModelProperty(example = "01-01-2019", value = "")
  @JsonProperty("to")
  public String getTo() {
    return to;
  }
  public void setTo(String to) {
    this.to = to;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CertificateValidityDTO certificateValidity = (CertificateValidityDTO) o;
    return Objects.equals(from, certificateValidity.from) &&
        Objects.equals(to, certificateValidity.to);
  }

  @Override
  public int hashCode() {
    return Objects.hash(from, to);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class CertificateValidityDTO {\n");

    sb.append("    from: ").append(toIndentedString(from)).append("\n");
    sb.append("    to: ").append(toIndentedString(to)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
/*
 * See example/counting.html
 */

Zone.countingZone = {

  // setTimeout
  '+enqueueTask': function () {
    this.data.count += 1;
  },

  // fires when...
  // - clearTimeout
  // - setTimeout finishes
  '-dequeueTask': function () {
    this.data.count -= 1;
  },

  '+afterTask': function () {
    if (this.data.count === 0 && !this.data.flushed) {
      this.data.flushed = true;
      this.run(this.onFlush);
    }
  },

  counter: function () {
    return this.data.count;
  },

  data: {
    count: 0,
    flushed: false
  },

  onFlush: function () {}
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05_CharRotation
	{
	class Rotate
		{
		static void Main(string[] args)
			{
			var letters = Console.ReadLine().ToCharArray();
			var nums = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
			var output = string.Empty;

			for (int i = 0; i < letters.Length; i++)
				{
				char currentChar;
				if (nums[i] % 2 == 0)
					{
					currentChar = (char)(letters[i] - nums[i]);
					output += currentChar;
					}
				else
					{
					currentChar = (char)(letters[i] + nums[i]);
					output += currentChar;
					}
				}
			Console.WriteLine(output);
			}
		}
	}


text:
"""This code example updates contact addresses.

To determine which contacts exist, run get_all_contacts.py.

The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.

"""

# Import appropriate modules from the client library.
from googleads import ad_manager

# Set the ID of the contact to update.
CONTACT_ID = 'INSERT_CONTACT_ID_HERE'

def main(client, contact_id):
  # Initialize appropriate service.
  contact_service = client.GetService('ContactService', version='v202205')

  # Create statement object to select the single contact by ID.
  statement = (ad_manager.StatementBuilder(version='v202205')
               .Where('id = :id')
               .WithBindVariable('id', int(contact_id))
               .Limit(1))

  # Get contacts by statement.
  response = contact_service.getContactsByStatement(
      statement.ToStatement())

  if 'results' in response and len(response['results']):
    updated_contacts = []
    for contact in response['results']:
      contact['address'] = '123 New Street, New York, NY, 10011'
      updated_contacts.append(contact)

    # Update the contact on the server.
    contacts = contact_service.updateContacts(updated_contacts)

    # Display results.
    for contact in contacts:
      print(('Contact with ID "%s", name "%s", and address "%s" '
             'was updated.')
            % (contact['id'], contact['name'], contact['address']))
  else:
    print('No contacts found to update.')

if __name__ == '__main__':
  # Initialize client object.
  ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
  main(ad_manager_client, CONTACT_ID)


text:
package chat.rocket.android.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SlidingPaneLayout;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import android.support.v7.widget.Toolbar;
import android.view.View;

import java.util.List;
import chat.rocket.android.LaunchUtil;
import chat.rocket.android.R;
import chat.rocket.android.api.MethodCallHelper;
import chat.rocket.android.fragment.chatroom.HomeFragment;
import chat.rocket.android.fragment.chatroom.RoomFragment;
import chat.rocket.android.fragment.sidebar.SidebarMainFragment;
import chat.rocket.android.helper.LogcatIfError;
import chat.rocket.android.helper.TextUtils;
import chat.rocket.android.model.ddp.RoomSubscription;
import chat.rocket.android.model.ddp.User;
import chat.rocket.android.model.internal.Session;
import chat.rocket.android.realm_helper.RealmHelper;
import chat.rocket.android.realm_helper.RealmListObserver;
import chat.rocket.android.realm_helper.RealmObjectObserver;
import chat.rocket.android.realm_helper.RealmStore;
import chat.rocket.android.service.ConnectivityManager;
import chat.rocket.android.widget.RoomToolbar;
import hugo.weaving.DebugLog;

/**
 * Entry-point for Rocket.Chat.Android application.
 */
public class MainActivity extends AbstractAuthedActivity {

  private RealmObjectObserver<Session> sessionObserver;
  private RealmListObserver<RoomSubscription> unreadRoomSubscriptionObserver;
  private boolean isForeground;
  private StatusTicker statusTicker;

  @Override
  protected int getLayoutContainerForFragment() {
    return R.id.activity_main_container;
  }

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    statusTicker = new StatusTicker();
    setupSidebar();
    if (roomId == null) {
      showFragment(new HomeFragment());
    }

    if (shouldLaunchAddServerActivity()) {
      LaunchUtil.showAddServerActivity(this);
    }
  }

  @Override
  protected void onStart() {
    super.onStart();

    setUserOnlineIfServerAvailable();
  }

  @Override
  protected void onResume() {
    isForeground = true;
    super.onResume();
  }

  @Override
  protected void onPause() {
    isForeground = false;
    super.onPause();
  }

  @Override
  protected void onStop() {
    setUserAwayIfServerAvailable();

    super.onStop();
  }

  private void setUserOnlineIfServerAvailable() {
    if (hostname != null) {
      new MethodCallHelper(this, hostname).setUserPresence(User.STATUS_ONLINE)
          .continueWith(new LogcatIfError());
    }
  }

  private void setUserAwayIfServerAvailable() {
    if (hostname != null) {
      new MethodCallHelper(this, hostname).setUserPresence(User.STATUS_AWAY)
          .continueWith(new LogcatIfError());
    }
  }

  private void setupSidebar() {
    SlidingPaneLayout pane = (SlidingPaneLayout) findViewById(R.id.sliding_pane);
    if (pane == null) {
      return;
    }

    final SlidingPaneLayout subPane = (SlidingPaneLayout) findViewById(R.id.sub_sliding_pane);
    pane.setPanelSlideListener(new SlidingPaneLayout.SimplePanelSlideListener() {
      @Override
      public void onPanelClosed(View panel) {
        super.onPanelClosed(panel);
        if (subPane != null) {
          subPane.closePane();
        }
      }
    });

    final DrawerArrowDrawable drawerArrowDrawable = new DrawerArrowDrawable(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.activity_main_toolbar);
    toolbar.setNavigationIcon(drawerArrowDrawable);
    toolbar.setNavigationOnClickListener(view -> {
      if (pane.isSlideable() && !pane.isOpen()) {
        pane.openPane();
      }
    });

    //ref: ActionBarDrawerToggle#setProgress
    pane.setPanelSlideListener(new SlidingPaneLayout.PanelSlideListener() {
      @Override
      public void onPanelSlide(View panel, float slideOffset) {
        drawerArrowDrawable.setProgress(slideOffset);
      }

      @Override
      public void onPanelOpened(View panel) {
        drawerArrowDrawable.setVerticalMirror(true);
      }

      @Override
      public void onPanelClosed(View panel) {
        drawerArrowDrawable.setVerticalMirror(false);
      }
    });
  }

  private boolean closeSidebarIfNeeded() {
    // REMARK: Tablet UI doesn't have SlidingPane!
    SlidingPaneLayout pane = (SlidingPaneLayout) findViewById(R.id.sliding_pane);
    if (pane != null && pane.isSlideable() && pane.isOpen()) {
      pane.closePane();
      return true;
    }
    return false;
  }

  private boolean shouldLaunchAddServerActivity() {
    return ConnectivityManager.getInstance(getApplicationContext()).getServerList().isEmpty();
  }

  @DebugLog
  @Override
  protected void onHostnameUpdated() {
    super.onHostnameUpdated();
    updateSessionObserver();
    updateUnreadRoomSubscriptionObserver();
    updateSidebarMainFragment();
  }

  private void updateSessionObserver() {
    if (sessionObserver != null) {
      sessionObserver.unsub();
      sessionObserver = null;
    }

    if (hostname == null) {
      return;
    }

    RealmHelper realmHelper = RealmStore.get(hostname);
    if (realmHelper == null) {
      return;
    }

    sessionObserver = realmHelper
        .createObjectObserver(realm ->
            Session.queryDefaultSession(realm)
                .isNotNull(Session.TOKEN))
        .setOnUpdateListener(this::onSessionChanged);
    sessionObserver.sub();
  }

  private void onSessionChanged(@Nullable Session session) {
    if (session == null) {
      if (isForeground) {
        LaunchUtil.showLoginActivity(this, hostname);
      }
      statusTicker.updateStatus(StatusTicker.STATUS_DISMISS, null);
    } else if (!TextUtils.isEmpty(session.getError())) {
      statusTicker.updateStatus(StatusTicker.STATUS_CONNECTION_ERROR,
          Snackbar.make(findViewById(getLayoutContainerForFragment()),
              R.string.fragment_retry_login_error_title, Snackbar.LENGTH_INDEFINITE)
              .setAction(R.string.fragment_retry_login_retry_title, view ->
                  Session.retryLogin(RealmStore.get(hostname))));
    } else if (!session.isTokenVerified()) {
      statusTicker.updateStatus(StatusTicker.STATUS_TOKEN_LOGIN,
          Snackbar.make(findViewById(getLayoutContainerForFragment()),
              R.string.server_config_activity_authenticating, Snackbar.LENGTH_INDEFINITE));
    } else {
      statusTicker.updateStatus(StatusTicker.STATUS_DISMISS, null);
    }
  }

  private void updateUnreadRoomSubscriptionObserver() {
    if (unreadRoomSubscriptionObserver != null) {
      unreadRoomSubscriptionObserver.unsub();
      unreadRoomSubscriptionObserver = null;
    }

    if (hostname == null) {
      return;
    }

    RealmHelper realmHelper = RealmStore.get(hostname);
    if (realmHelper == null) {
      return;
    }

    unreadRoomSubscriptionObserver = realmHelper
        .createListObserver(realm ->
            realm.where(RoomSubscription.class)
                .equalTo(RoomSubscription.ALERT, true)
                .equalTo(RoomSubscription.OPEN, true)
                .findAll())
        .setOnUpdateListener(this::updateRoomToolbarUnreadCount);
    unreadRoomSubscriptionObserver.sub();
  }

  private void updateRoomToolbarUnreadCount(List<RoomSubscription> unreadRooms) {
    RoomToolbar toolbar = (RoomToolbar) findViewById(R.id.activity_main_toolbar);
    if (toolbar != null) {
      //ref: Rocket.Chat:client/startup/unread.js
      final int numUnreadChannels = unreadRooms.size();
      int numMentionsSum = 0;
      for (RoomSubscription room : unreadRooms) {
        numMentionsSum += room.getUnread();
      }
      toolbar.setUnreadBudge(numUnreadChannels, numMentionsSum);
    }
  }

  private void updateSidebarMainFragment() {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.sidebar_fragment_container, SidebarMainFragment.create(hostname))
        .commit();
  }

  @Override
  protected void onRoomIdUpdated() {
    super.onRoomIdUpdated();

    if (roomId != null && RoomFragment.canCreate(RealmStore.get(hostname))) {
      showFragment(RoomFragment.create(hostname, roomId));
      closeSidebarIfNeeded();
    } else {
      showFragment(new HomeFragment());
    }
  }

  @Override
  protected void onDestroy() {
    if (sessionObserver != null) {
      sessionObserver.unsub();
      sessionObserver = null;
    }
    if (unreadRoomSubscriptionObserver != null) {
      unreadRoomSubscriptionObserver.unsub();
      unreadRoomSubscriptionObserver = null;
    }
    super.onDestroy();
  }

  @Override
  protected boolean onBackPress() {
    return closeSidebarIfNeeded() || super.onBackPress();
  }

  //TODO: consider this class to define in layouthelper for more complicated operation.
  private static class StatusTicker {
    public static final int STATUS_DISMISS = 0;
    public static final int STATUS_CONNECTION_ERROR = 1;
    public static final int STATUS_TOKEN_LOGIN = 2;

    private int status;
    private Snackbar snackbar;

    public StatusTicker() {
      status = STATUS_DISMISS;
    }

    public void updateStatus(int status, Snackbar snackbar) {
      if (status == this.status) {
        return;
      }
      this.status = status;
      if (this.snackbar != null) {
        this.snackbar.dismiss();
      }
      if (status != STATUS_DISMISS) {
        this.snackbar = snackbar;
        if (this.snackbar != null) {
          this.snackbar.show();
        }
      }
    }
  }
}


text:
/**
 * Injection Engine for Plug and Play widgets. This class is a phanton class for a
 * Bootstrap Engine (gallery-bootstrap-engine). It facilitates the instantiation
 * of a bootstrap object in an iframe sandbox and provides an easy way to set properties and
 * capture events from the bootstrap object.
 *
 * @module gallery-injection-engine
 * @requires node, base-base
 * @class Y.InjectionEngine
 * @param config {Object} Configuration object
 * @extends Y.Base
 * @constructor
 */

///////////////////////////////////////////////////////////////////////////
//
// Private shorthands, constants and variables
//
///////////////////////////////////////////////////////////////////////////

var config,
    documentElem = Y.config.doc.documentElement,
    script = 'script',
    regexUrlDetection = /^(http[s]?:\/\/|\/\/[\w\d]+)/; // supporting http://domain..., https://domain... and //domain...

///////////////////////////////////////////////////////////////////////////
//
// Class definition
//
///////////////////////////////////////////////////////////////////////////

function InjectionEngine () {
    Y.log ('Constructor', 'info', 'injection');
    InjectionEngine.superclass.constructor.apply(this, arguments);
}

Y.mix(InjectionEngine, {

    /**
     * The identity of the class.
     * @property NAME
     * @type string
     * @static
     * @final
     * @readOnly
     * @default 'injection'
     */
    NAME: 'injection',

    /**
     * Static property used to define the default attribute configuration of
     * the class.
     * @property InjectionEngine.ATTRS
     * @type Object
     * @protected
     * @static
     */
    ATTRS: {
        // other injection specific parameters.
        /**
         * @attribute bootstrap
         * @type {Object}
         * @writeOnce
         * @description A reference to the bootstrap engine. This attribute will be set after the
         * bootstrap engine execute the callback method to connect with the injection engine.
         */
        bootstrap: {
            readOnly: true
        },
        /**
         * @attribute html
         * @type {String}
         * @writeOnce
         * @description The HTML fragment that will be injected at the top of the Body element in the iframe.
         */
         // there is not need to have an actual "html" attribute explicitely here, let's use the config object instead.
        /**
         * @attribute css
         * @type {String|Array}
         * @writeOnce
         * @description One or more style blocks or urls. e.g., ['http://full/path/is/required/script.js', 'https://secure/path/also/works/script.js', 'function(){ return 1; }', {url: 'relative/path.js'}]
         */
        css: {
            getter: '_buildCSS'
        },
        /**
         * @attribute js
         * @type {String|Array}
         * @writeOnce
         * @description One or more js blocks or urls. e.g., ['http://full/path/is/required/style.css', 'https://secure/path/also/works/style.css', 'inline{css:property;}', {url: 'relative/path.css'}]
         */
        js: {
            getter: '_buildJS'
        },
        /**
         * @attribute dir
         * @type {String}
         * @writeOnce
         * @description The HTML DIR attribute specifies the base direction (LTR, RTL) of text in the tray.
         * @default document.documentElement.dir
         */
        dir: {
            value: documentElem.dir || 'ltr'
        },
        /**
         * @attribute lang
         * @type {String}
         * @default document.documentElement.lang
         * @writeOnce
         * @description The HTML lang attribute can be used to declare the language of the tray.
         */
        lang: {
            value: documentElem.lang || 'en'
        },
        /**
         * @attribute container
         * @type {String}
         * @writeOnce
         * @description selector for the container element
         */
        container: {
            setter: function (n) {
                return Y.one(n);
            }
        },
        /**
         * @attribute dynamicAttrs
         * @type {Array}
         * @writeOnce
         * @description Collection of attributes that will be in sycn between the phantom and the bootstrap object
         */
        dynamicAttrs: {
            value: []
        },
        /**
         * @attribute dynamicEvents
         * @type {Array}
         * @writeOnce
         * @description Collection of events that will be propagated from the bootstrap object into the
         * injection engine. Each element in the collection could be an string (event name), or an
         * liternal object like this: {name: 'abc', rename: 'xyz', fn: function (ev, name, o) {} }
         * to faciliate the event transformation if needed. In this defintion, "rename" will become
         * the name of the event fired on the injection engine, and fn will be used to analyze the event
         * and avoid firing it if needed (return false to avoid firing the event locally).
         */
        dynamicEvents: {
            value: []
        }
    }

});

Y.extend(InjectionEngine, Y.Base, {
    /**
     * Any basic configuration argument that should be propagated to the iframe YUI_config object
     * have to be defined as part of the initial config and the name of the property have to be
     * included in this property so it will be processed.
     * @property YCONFIG_MAP
     * @type Array
     * @default ['guid', 'lang']
     */
    YCONFIG_MAP: ['guid', 'lang'],

    /**
     * Construction logic executed during Injection Engine instantiation.
     *
     * @method initializer
     * @protected
     */
    initializer: function (cfg) {
        var instance = this;

        Y.log ('Initialization', 'info', 'injection');

        // storing the injection configuration. This will be passed into the bootstrap engine on ready
        config = Y.merge((cfg || {}), {
            lang: instance.get('lang'),
            guid: Y.guid() // instance stamp
        });

        // creating dynamic attributes for the sync up
        Y.each(instance.get('dynamicAttrs'), function(name) {
            // creating the new dynamic attribute
            instance.addAttr(name, {value: config[name]}, false);
            // removing them from config to avoid sending and initial data to bootstrap
            delete config[name];
        });

        // defining the pipeline to connect bootstrap with injection
        // once the bootstrap finishes the initialization. This is a way to
        // connect both objects.
        YUI.Env[config.guid] = Y.bind(instance._connect, instance);

        // finishing the initialization process async to facilitate
        // addons to hook into _init/_bind if needed.
        // YUI.Env.yui_3_3_0_1_130429815869015 will be a callback method
        Y.later(0, instance, function() {
            instance._init();
        });
    },

    /**
     * Preload any asset before the boot process. Good for performance. By default it will
     * preload the css and js files produced by those attributes.
     *
     * @method preload
     * @param files {string|array} custom files to preload. If specified, it will not load the default ones.
     * @return this for chaining
     */
    preload: function (files) {
        var instance = this,
            node = instance.get('container'),
            ie = Y.UA.ie,
            fn = function (f) {
                if ((f = instance._testFullURL(f)) && (f = f.url)) {
                    Y.log("Preloading asset: " + f, "info", "injection");
                    if (ie) {
                        (new Image()).src = f;
                    } else {
                        node.append('<object data="'+f+'" width="0" tabindex="-1" height="0" style="display:none;left:-9999px;position:absolute;"></object>');
                    }
                }
            };

        Y.log ('method: preload', 'info', 'injection');

        files = ( Y.Lang.isArray(files) ? files : Y.Array(arguments, 0, true));

        if (files.length > 0) {
            Y.log("Preloading custom assets (arguments):", "info", "injection");
            Y.each(files, fn);
        } else {
            Y.log("Preloading JS assets:", "info", "injection");
            Y.each(instance.get('js'), fn);
            Y.log("Preloading CSS assets:", "info", "injection");
            Y.each(instance.get('css'), fn);
        }
        return instance;
    },

    /**
     * Boot the system, creating the sandbox, injecting the css and the js into the iframe,
     * waiting for the bootstrap to gets ready, then continueing with the workflow.
     *
     * @method boot
     * @return this for chaining
     */
    boot: function () {
        var instance = this;
        Y.log ('Boot', 'info', 'injection');
        instance._createSandbox ( config );
        return instance; // chaining on public methods
    },

    /**
     * Connects the injection engine with the bootstrap running in the iframe. This method
     * defines the hand-shake process between them. This method is meant to be called by
     * the bootstrap engine in the sandbox to start the connection.
     *
     * @method _connect
     * @param bootstrap {Object} Reference to the bootstrap engine object.
     */
    _connect: function (bootstrap) {
        var instance = this;

        Y.log ('Connect', 'info', 'injection');
        // setting an internal attribute to keep a reference to the bootstrap engine (just in case)
        instance._set ('bootstrap', bootstrap);

        // storing a reference to the tray
        bootstrap.setAttrs(config);

        // syncing up attributes between injection and bootstrap now that the bootstrap is ready
        Y.each(instance.get('dynamicAttrs'), function(name) {
            var v = instance.get(name);
            Y.log ('Initializating dynamic attribute: '+name, 'info', 'injection');
            if (!Y.Lang.isUndefined(v)) {
                Y.log ('Initial attribute sync up: '+name+'='+v, 'info', 'injection');
                bootstrap.set(name, instance.get(name));
            }
            instance.on(name+'Change', function (e) {
                Y.log ('Setting new value for attribute: '+e.attrName+'='+e.newVal, 'info', 'injection');
                bootstrap.set(e.attrName, e.newVal);
            });
        });

        // syncing up attributes between injection and bootstrap now that the bootstrap is ready
        Y.each(instance.get('dynamicEvents'), function(ev) {
            ev = ( Y.Lang.isObject(ev) ? ev : { name: ev } );
            Y.log ('Initializating dynamic event: ' + ev.name, 'info', 'injection');
            if (ev.name) {
                bootstrap.on(ev.name, Y.bind( instance._onEvent, instance, ev ));
            }
        });

        // removing the preload placeholders if needed
        if (!Y.UA.ie) {
            Y.log('Removing pre-load placeholders: ' + instance.get('container').all('object'), 'info', 'ura-injection');
            instance.get('container').all('object').remove();
        }

        Y.log('Bootstrap is ready.', 'info', 'injection');
        return this._ready();
    },

    /**
     * Basic initialization routine, binding events.
     *
     * @method _bind
     * @protected
     */
    _init: function () {
        // binding some extra events
        Y.log ('Init', 'info', 'injection');
        this._bind();
    },

    /**
     * Defines the binding logic for the injection engine, listening for some attributes
     * that might change.
     *
     * @method _bind
     * @protected
     */
    _bind: function() {
        Y.log ('Bind', 'info', 'injection');
    },

    /**
     * Defines the moment when the bootstrap engine gets ready to be used.
     *
     * @method _ready
     * @protected
     * @return {boolean} use this to control the state of the initialization on the bootstrap engine since it might
     * take some time to load the stuff in the iframe, and the user might interact with the page
     * invalidating the initialization routine. If return true, the _ready method in the bootstrap will be called at
     * the end of the initialization.
     */
    _ready: function() {
        Y.log ('Ready', 'info', 'injection');
    },

    /**
     * Handler for any dynamic event from the bootstrap. By default, renames the event
     * if needed, calls a custom function if needed, and broadcasts the event if needed.
     *
     * @method _onEvent
     * @param o {Object} dynamic event object from the "dynamicEvents" collection.
     * @param e {Object} event object from the bootstrap engine.
     * @protected
     */
    _onEvent: function (o, e) {
        var instance = this,
            name = o.rename || o.name;
        Y.log ('Catching an event from the bootstrap engine: ' + o.name, 'info', 'injection');
        if ( ( o.fn ? o.fn.apply(instance, [e, name, o]) : true ) ) {
            Y.log ('Triggering the corresponding local event: ' + name, 'info', 'injection');
            instance.fire(name);
        }
    },

    /**
     * Getter method for the attribute called js.
     *
     * @method _buildJS
     * @param url {String|Array} One or more js blocks or urls.
     * @protected
     * @return {Array} Collection of urls or inline scripts to be inserted as script tags the body of the iframe.
     */
    _buildJS: function (url) {
        return Y.Array( (url || []) );
    },

    /**
     * Getter method for the attribute called css.
     *
     * @method _buildCSS
     * @param url {String|Array} One or more style blocks or urls.
     * @protected
     * @return {Array} Collection of urls or inline styles to be inserted as link or style tags the head of the iframe.
     */
    _buildCSS: function (url) {
        return Y.Array( (url || []) );
    },

    /**
     * Build the basic meta tags for the iframe document. By default, it adds the content-type as text/html and
     * charset as utf-8.
     *
     * @method _buildMeta
     * @param config {Object} Literal object with the initial configuration from the injection engine.
     * @protected
     * @return {string} HTML Fragment to be inserted at the top of the header.
     */
    _buildMeta: function (config) {
        return '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>';
    },

    /**
     * Build the basic YUI_config object that will injected in the iframe to boot based on those configs.
     * Keep in mind that all the other configs will be injected into the bootstrap once it boots.
     * At this point, only guid and lang are required.
     *
     * @method _buildCfg
     * @protected
     * @return {Object} Literal object with the basic YUI_config.
     */
    _buildCfg: function () {
        var ycfg = {};
        // mapping all the property names from YCONFIG_MAP with the final YUI_config object
        Y.each (this.YCONFIG_MAP, function(prop) {
            ycfg[prop] = config[prop];
        });
        // setting the timestamp 0 right before starting the injection process (just in case you want to do some perf)
        ycfg.t0 = new Date().getTime();
        // forcing debug mode if needed
        ycfg.debug = config.debug || false;
        return ycfg;
    },

    /**
     * Build the basic html content for the iframe's body. By default, it adds the required YUI_config structure.
     * If JSON is available, the custom yui config and the global yui config will be mixed and stringified.
     *
     * @method _buildBody
     * @param config {Object} Literal object with the initial configuration from the injection engine.
     * @protected
     * @return {Array} Collection of HTML Fragments to be inserted at the body of the iframe.
     */
    _buildBody: function (config) {
        var b = [(config.html ? config.html : '')],
            J = Y.JSON || (Y.config.win || {}).JSON,
            ycfg = this._buildCfg(),
            yui_config = [];

        // ycfg will be transformed into a custom YUI_config object as part of the iframe body, but
        // it requires JSON to stringify the configuration. Since this is usually a debug trick, we
        // decided not to have JSON as a dependency, but as an option.
        // Also, ycfg contains the basic configuration that is required by the bootstrap engine.
        if (J) {
            yui_config = J.stringify( ycfg );
        } else {
        // if JSON is not available, we will create a minimum required configuration using string only
            yui_config = [];
            Y.each (Y.Object.keys(ycfg), function (name) {
                var v = ycfg[name];
                if (!Y.Lang.isUndefined(v)) {
                    yui_config.push( name + ':' + ( Y.Lang.isBoolean(v) ? v : '"' + v + '"' ) );
                }
            });
            yui_config = '{' + yui_config.join(',') + '}';
        }
        Y.log ('Setting initial YUI_config=' + yui_config, 'info', 'injection');
        b.push('<', script, '>YUI_config=', yui_config, ';</', script, '>');

        return b;
    },

    /**
     * Creates an iframe using a custom configuration. It uses the [js] and [css] attributes
     * within the iframe scope.
     *
     * @method _createSandbox
     * @param config {Object} The configuration object
     * @protected
     */
    _createSandbox: function (config) {
        var instance = this,
            iframe = Y.Node.create(''),
            container = instance.get('container'),
            CSS = instance.get('css'),
            JS = instance.get('js'),
            META = instance._buildMeta(config),
            BODY = instance._buildBody(config),
            doc;

        // setting the bootstrap engine css (usually a full rollout)
        Y.each (CSS, function (value, indx) {
            value = instance._testFullURL(value);
            CSS[indx] = ( value && Y.Lang.isObject(value) ?
                            '<link rel="stylesheet" type="text/css" href="' + value.url + '"/>' :
                            ''
                        );
        });
        // setting the bootstrap engine js (usually a full rollout)
        Y.each (JS, function (value, indx) {
            value = instance._testFullURL(value);
            JS[indx] = ( value && Y.Lang.isObject(value) ?
                            '<' + script + ' src="' + value.url + '"></' + script + '>' :
                            '<' + script + '>' + value + '</' + script + '>'
                       );
        });

        // setting up the iframe src to avoid warnings
        iframe.set('src', 'javascript' + ((Y.UA.ie) ? ':false' : ':') + ';');
        // injecting the structure into the container
        container.append( iframe );
        // setting the content of the iframe
        doc = iframe._node.contentWindow.document;
        doc.open().write('<!doctype html>' + META + CSS.join('') + '' + BODY.join('') + JS.join('') + '');
        doc.close();
    },

    /**
     * Detect an url pattern on a string value to decide if the string is a full url.
     *
     * @method _testFullURL
     * @param value {String} string to be confirmed as a full url.
     * @protected
     * @return {String|Object} If the value is an url, returns an object {url: value}, if not, returns the value.
     */
    _testFullURL: function (value) {
        if (Y.Lang.isString(value)) {
            value =  ( regexUrlDetection.test(value) ? {url: value} : value );
        }
        return ( Y.Lang.isObject(value) && !value.url ? null: value );
    }

});

Y.InjectionEngine = InjectionEngine;


text:
using System;
using System.Runtime.InteropServices;

namespace Examples
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            RevisionManager.Application application = null;
            RevisionManager.PropertySets propertySets = null;
            RevisionManager.Properties properties = null;

            try
            {
                application = new RevisionManager.Application();
                propertySets = (RevisionManager.PropertySets)application.PropertySets;
                propertySets.Open(@"C:\Part1.par", false);
                properties = (RevisionManager.Properties)propertySets.Item["Custom"];
                var count = properties.Count;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}


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

/// <summary>
///  This script lets you render text\font in a form of Sprite to the World space
/// based on the input string. It is particularly useful when you need to display
/// text in the world space that changes during the runtime.
///
/// Each letter must have a representation array of sprites. One array represents
/// an ASCII group (Alphabetic, Numeric, Special Character...), where first element
/// is a an ASCII code of the letter group. E.g. Upper case Alphabet in ASCII are
/// values between 65 to 90 both inclusive. Thus, element 0 is (65-65 = 0 = A);
/// element 1 in the AlphabetU array is 66-65 = 1 = B and so on.
///
/// Get a Font sprite with all the letters and numbers; Using Sprite Editor with a
/// "Multiple" Sprite Mode, slice each character. NOTE: make sure they all sliced with
/// the same Width and Height to get consistant spacing. Then, add each sliced sprite
/// to the sprite array groups (Numeric, AlphabetU, SpecialChars...). Refer to the
/// ASCII table for the Dec codes (http://www.asciitable.com/).
/// NOTE: int decCode = 'A';  // this will return 65.
/// </summary>
public class TextToWorld: MonoBehaviour {

    protected Vector2 AlphabetUCaseRange = new Vector2(65, 90);
    protected Vector2 SpecialCharRange   = new Vector2(32, 47);
    protected Vector2 NumericCharRange   = new Vector2(48, 57);

    public GameObject NumericPool;
    public GameObject AlphabetPool;
    public GameObject SpecialCharPool;
    [Tooltip("Space between letters.")]
    public float    LetterSpacing = 0.1f;
    [Tooltip("SpriteRenderer 'Sorting layer'.")]
    public string   SortingLayerName;
    [Tooltip("SpriteRenderer 'Order in layer'.")]
    public int      OrderInLayer;
    [Tooltip("'Pixel Per Unit' value used on the sprite itself.")]
    public int      PixelPerUnit = 100;
    [Tooltip("Text to be rendered in the world space using Sprite arrays.")]
    public string   TextToRender = "Hello World";
    [Tooltip("Scale for each letter.")]
    public Vector3  Scale = Vector3.one;
    public List<SpriteRenderer> renderedSprites;

    [Tooltip("Element in the array represents the a number sprite.")]
    public List<Sprite> Numeric;
    [Tooltip("Upper Case alphabet. Hex range from 65 to 90. where 65 is element 0 of the array.")]
    protected List<Sprite> AlphabetU;
    [Tooltip("Special Characters sprites. Hex range from 32 to 47. where 32 is element 0 of the array.")]
    protected List<Sprite> SpecialChars;

    public void Start() {
        renderedSprites = new List<SpriteRenderer>();
        Numeric = AlphabetU = SpecialChars = new List<Sprite>();
        ReadPool(ref NumericPool, ref Numeric);
        ReadPool(ref AlphabetPool, ref AlphabetU);
        ReadPool(ref SpecialCharPool, ref SpecialChars);

        RenderText(TextToRender);
    }//Start

    public void ReadPool(ref GameObject goPool, ref List<Sprite> spritePool) {
        if (goPool == null)
            return;
        foreach (SpriteRenderer sr in goPool.GetComponentsInChildren<SpriteRenderer>())
            spritePool.Add(sr.sprite);
    }//ReadPool

    /// <summary>
    ///  Rendre string into a world space representing each character with sprites.
    /// </summary>
    public void RenderText(string toRender) {
        for (int i = 0; i < toRender.Length; i++) {
            if (i < renderedSprites.Count && renderedSprites.Count != 0) {
                this.Replace(toRender[i], i);
            } else {
                Add(toRender[i]);
            }
        }//for
    }//RenderText

    /// <summary>
    ///  Create a GameObject with a Sprite representation of the passed symbol.
    /// </summary>
    /// <param name="symbol">A character symbol to be rendered in world space.</param>
    /// <param name="atPosition">Where to add this symbol in the currently rendrered sentance. default = -1 -> add to the end of list.</param>
    /// <returns>Return created in the world SpriteRenderer object.</returns>
    public SpriteRenderer Add(char symbol, int atPosition=-1) {
        Sprite letterSprite      = CharToSprite(symbol);

        SpriteRenderer letterObj = this.createWorldObject();
        letterObj.sprite = letterSprite;
        letterObj.sortingLayerName = SortingLayerName;
        letterObj.sortingOrder = OrderInLayer;

        Vector2 letterNewPos = Vector2.zero;
        if (this.renderedSprites.Count > 0) {
            Vector2 prevLetterSize = this.renderedSprites[this.renderedSprites.Count - 1].sprite.rect.size / PixelPerUnit;
            Vector2 prevLetterPos = this.renderedSprites[this.renderedSprites.Count - 1].transform.localPosition;

            if (this.renderedSprites.Count > 0) {
                var offset = prevLetterPos.x + prevLetterSize.x + LetterSpacing;
                letterNewPos = new Vector2(offset, 0);
            }//if
        }//if

        letterObj.transform.localPosition = letterNewPos;

        renderedSprites.Add(letterObj);

        if (letterObj == null) //safety net
            return null;       //no need to render NULl object.

        if (atPosition < 0 || renderedSprites.Count <= atPosition)
            renderedSprites.Add(letterObj);
        else
            renderedSprites.Insert(atPosition, letterObj);

        letterObj.gameObject.name = symbol.ToString().ToUpper();
        letterObj.gameObject.SetActive(true);
        return letterObj;
    }//Add

    /// <summary>
    ///  Remove rendrered character from the world.
    /// </summary>
    /// <param name="letterPosition">
    ///  Default(-1) will remove from the top of the list (end of sentance).
    /// Otherwise - pass an index of the letter to remove. Passing invalid index will do nothing.
    /// </param>
    /// <returns>True - letter was removed. False - nothing happened.</returns>
    public bool Remove(int letterPosition = -1) {
        if (letterPosition == -1)
            letterPosition = renderedSprites.Count - 1;

        if (letterPosition >= renderedSprites.Count)
            return false;

        if (renderedSprites.Count == 0)
            return false;

        SpriteRenderer letter = renderedSprites[letterPosition];
        renderedSprites.RemoveAt(letterPosition);
        if (letter != null)
            Destroy(letter.gameObject);
        return true;
    }//RemoveLetter

    /// <summary>
    ///  Replace a letter with the new symbol at requested position.
    /// </summary>
    /// <param name="symbol">New symbol to create.</param>
    /// <param name="atPosition">Position in the rendrered sentance to replace.</param>
    /// <returns>SpriteRenderer of the newly created world character.</returns>
    public SpriteRenderer Replace(char symbol, int atPosition) {
        if (atPosition >= renderedSprites.Count || atPosition < 0)
            return null;
        this.renderedSprites[atPosition].sprite = CharToSprite(symbol);
        this.renderedSprites[atPosition].name   = symbol.ToString();
        return this.renderedSprites[atPosition];
    }//Replace

    /// <summary>
    ///  Remove all of the created characters from the world space.
    /// </summary>
    public void RemoveAll() {
        TextToRender = "";
        for(int i = 0; i < renderedSprites.Count; i++) {
            Remove(i);
        }//for
    }//RemoveAll

    /// <summary>
    ///  Get a sprite representing the symbol based of the Sprite arrays.
    /// This function will use a ASCII(Dec) value of the symbol to search
    /// for the representation.
    /// </summary>
    /// <param name="symbol">Symbol to find a Sprite representation for.</param>
    /// <returns>A Sprite representing the symbol. Null - no Sprite found.</returns>
    public Sprite CharToSprite(char symbol) {
        int decCode    = symbol;  //refer to ASCII table for the char codes.
        int arrayIndex  = -1;

        /* *** Parse Number character *** */
        if (this.IsNumber(symbol)) {
            arrayIndex = decCode - Mathf.FloorToInt(NumericCharRange.x);
            if (!validateArrayIndex(arrayIndex, ref Numeric))
                return null;
            return Numeric[arrayIndex];
        }//if number

        /* *** Parse Special character *** */
        if (IsSpecialChar(symbol)) {
            arrayIndex = decCode - Mathf.FloorToInt(SpecialCharRange.x);
            if (!validateArrayIndex(arrayIndex, ref SpecialChars))
                return null;
            return SpecialChars[arrayIndex];
        }//if special

        /* *** Parse Alphabetic character *** */
        char upperLetter = symbol.ToString().ToUpper()[0]; //make it upper, cause no lowercase support here.
        bool isLetter = IsUAlphabetic(upperLetter);
        if (isLetter) {
            arrayIndex = upperLetter - Mathf.FloorToInt(AlphabetUCaseRange.x);
            if (!validateArrayIndex(arrayIndex, ref AlphabetU))
                return null;
            return AlphabetU[arrayIndex];
        }//if alphabetic

        return null; //Unknown character was passed.
    }//BuildText

    /// <summary>
    ///  Create a GameObject instance with a SpriteRenderer component.
    /// Sorting Layer, Sorting Order, Parent, LocalScale, LocalPosition are
    /// set here.
    /// </summary>
    /// <returns>SpriteRenderer component of the created GameObject.</returns>
    protected SpriteRenderer createWorldObject() {
        GameObject numberGO = new GameObject();
        numberGO.AddComponent<SpriteRenderer>();

        SpriteRenderer spriteRenderer = numberGO.GetComponent<SpriteRenderer>();
        spriteRenderer.sortingLayerName = SortingLayerName;
        spriteRenderer.sortingOrder = OrderInLayer;

        numberGO.transform.parent = this.transform;
        numberGO.transform.localScale = Scale;
        numberGO.transform.localPosition = Vector3.zero;
        numberGO.SetActive(false);

        return spriteRenderer;
    }//CreateWorldFont

    /// <summary>
    ///  Check if symbol is between hex values of 32 and 47 (both inclusive).
    /// This is a special character range, based of: http://www.asciitable.com/
    /// </summary>
    public bool IsSpecialChar(char symbol) {
        int decCode = symbol;
        return decCode >= SpecialCharRange.x && decCode <= SpecialCharRange.y;
    }//IsSpecialChar

    /// <summary>
    ///  Check if between hex value of 65 and 90 (both inclusive) which
    ///  represent the Upper Case alphabetic characters: http://www.asciitable.com/
    /// </summary>
    public bool IsUAlphabetic(char symbol) {
        int decCode = symbol;
        return decCode >= AlphabetUCaseRange.x && decCode <= AlphabetUCaseRange.y;
    }//IsUpperLetter

    /// <summary>
    ///  Check if symbol is between
    /// </summary>
    public bool IsNumber(char symbol) {
        int decCode = symbol;
        return decCode >= NumericCharRange.x && decCode <= NumericCharRange.y;
    }//IsNumber

    /// <summary>
    ///  Validates array for out of bounds and for null sprite
    /// at the index's position. I just want a slightly more
    /// readable message to be displayed with less panic when
    /// things go wrong...
    /// </summary>
    /// <param name="index">Index of the array to validate.</param>
    /// <param name="target">Array to validate on.</param>
    /// <returns>True if everything is good.
    ///          False - something went wrong.
    /// </returns>
    protected bool validateArrayIndex(int index, ref List<Sprite> target) {
        if(target.Count == 0) {
            #if UNITY_EDITOR
                Debug.LogWarning("Array has no sprites set!");
            #endif
            return false;
        }
        if (index >= target.Count || index < 0) {
            #if UNITY_EDITOR
                Debug.LogWarning("Out Of range! Passed " + index + " for the array  " + target.Count);
            #endif
            return false;
        }//if length

        if (target[index] == null) {
            #if UNITY_EDITOR
                if (target[index] == null)
                    Debug.LogWarning("Array with index '" + index + "' has no sprite representation!");
            #endif
            return false;
        }//if null

        return true;
    }//validateArrayIndex

}//class


text:
import {Injectable} from '@angular/core';
import {Observable, Observer} from 'rxjs';

import {ResponseOptions} from '../base_response_options';
import {ReadyState, RequestMethod, ResponseType} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {Request} from '../static_request';
import {Response} from '../static_response';

import {BrowserJsonp} from './browser_jsonp';

const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';

/**
 * Base class for an in-flight JSONP request.
 *
 * @deprecated see https://angular.io/guide/http
 */
export class JSONPConnection implements Connection {
  // TODO(issue/24571): remove '!'.
  private _id !: string;
  // TODO(issue/24571): remove '!'.
  private _script !: Element;
  private _responseData: any;
  private _finished: boolean = false;

  /**
   * The {@link ReadyState} of this request.
   */
  // TODO(issue/24571): remove '!'.
  readyState !: ReadyState;

  /**
   * The outgoing HTTP request.
   */
  request: Request;

  /**
   * An observable that completes with the response, when the request is finished.
   */
  response: Observable<Response>;

  /** @internal */
  constructor(
      req: Request, private _dom: BrowserJsonp, private baseResponseOptions?: ResponseOptions) {
    if (req.method !== RequestMethod.Get) {
      throw new TypeError(JSONP_ERR_WRONG_METHOD);
    }
    this.request = req;
    this.response = new Observable<Response>((responseObserver: Observer<Response>) => {

      this.readyState = ReadyState.Loading;
      const id = this._id = _dom.nextRequestID();

      _dom.exposeConnection(id, this);

      // Workaround Dart
      // url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
      const callback = _dom.requestCallback(this._id);
      let url: string = req.url;
      if (url.indexOf('=JSONP_CALLBACK&') > -1) {
        url = url.replace('=JSONP_CALLBACK&', `=${callback}&`);
      } else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
        url = url.substring(0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
      }

      const script = this._script = _dom.build(url);

      const onLoad = (event: Event) => {
        if (this.readyState === ReadyState.Cancelled) return;
        this.readyState = ReadyState.Done;
        _dom.cleanup(script);
        if (!this._finished) {
          let responseOptions =
              new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseType.Error, url});
          if (baseResponseOptions) {
            responseOptions = baseResponseOptions.merge(responseOptions);
          }
          responseObserver.error(new Response(responseOptions));
          return;
        }

        let responseOptions = new ResponseOptions({body: this._responseData, url});
        if (this.baseResponseOptions) {
          responseOptions = this.baseResponseOptions.merge(responseOptions);
        }

        responseObserver.next(new Response(responseOptions));
        responseObserver.complete();
      };

      const onError = (error: Error) => {
        if (this.readyState === ReadyState.Cancelled) return;
        this.readyState = ReadyState.Done;
        _dom.cleanup(script);
        let responseOptions = new ResponseOptions({body: error.message, type: ResponseType.Error});
        if (baseResponseOptions) {
          responseOptions = baseResponseOptions.merge(responseOptions);
        }
        responseObserver.error(new Response(responseOptions));
      };

      script.addEventListener('load', onLoad);
      script.addEventListener('error', onError);

      _dom.send(script);

      return () => {
        this.readyState = ReadyState.Cancelled;
        script.removeEventListener('load', onLoad);
        script.removeEventListener('error', onError);
        this._dom.cleanup(script);
      };
    });
  }

  /**
   * Callback called when the JSONP request completes, to notify the application
   * of the new data.
   */
  finished(data?: any) {
    // Don't leak connections
    this._finished = true;
    this._dom.removeConnection(this._id);
    if (this.readyState === ReadyState.Cancelled) return;
    this._responseData = data;
  }
}

/**
 * A {@link ConnectionBackend} that uses the JSONP strategy of making requests.
 *
 * @deprecated see https://angular.io/guide/http
 */
@Injectable()
export class JSONPBackend extends ConnectionBackend {
  /** @internal */
  constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
    super();
  }

  createConnection(request: Request): JSONPConnection {
    return new JSONPConnection(request, this._browserJSONP, this._baseResponseOptions);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CohesionAndCoupling
{
    public static class PointUtils
    {
        public static double CalcDistance2D(double x1, double y1, double x2, double y2)
        {
            double distance = Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
            return distance;
        }

        public static double CalcDistance3D(double x1, double y1, double z1, double x2, double y2, double z2)
        {
            double distance = Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) + (z2 - z1) * (z2 - z1));
            return distance;
        }
    }
}


text:
<?php
/**
     *
     *
     * @author Sam Schmidt
     * @date 2015-04-22
     * @company Linus Shops
     */

namespace LinusShops\Prophet;

class Module
{
    private $path;
    private $name;
    private $options;
    private $validationErrors = array();

    public function __construct($name, $path, $options = array())
    {
        $this->name = $name;
        $this->path = $path;

        $this->options = $options;
    }

    public function getOption($name)
    {
        if (!isset($this->options[$name])) {
            return null;
        }

        return $this->options[$name];
    }

    public function isIsolated()
    {
        return $this->getOption('isolate') === true;
    }

    /**
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Check if the module is valid for testing with prophet
     * @return boolean
     */
    public function validate($pathPrefix = '')
    {
        $valid = true;

        $path = empty($pathPrefix) ? $this->getPath() : $pathPrefix.'/'.$this->getPath();

        //Confirm path is valid
        if (!is_dir($path)) {
            $valid = $this->addValidationError(
                $this->getName().
                ': Path ['.$path.'] is not valid.'
            );
        }

        //Confirm existence of phpunit.xml in path
        if (!file_exists($path.'/phpunit.xml')) {
            $valid = $this->addValidationError(
                $this->getName().
                ': ['.$path.'] does not contain a phpunit.xml.'
            );
        }

        return $valid;
    }

    private function addValidationError($message)
    {
        $this->validationErrors[] = $message;
        return false;
    }

    /**
     * @return array
     */
    public function getValidationErrors()
    {
        return $this->validationErrors;
    }

    public function createTestStructure($pathPrefix = '.')
    {
        file_put_contents($this->getPhpUnitPath($pathPrefix), $this->getPhpunitStandardXml());
        file_put_contents($this->getBehatPath($pathPrefix), $this->getBehatStandardConfig());

        //Create tests directory
        if (!file_exists($pathPrefix.'/'.$this->getPath())) {
            mkdir($pathPrefix.'/'.$this->getPath().'/tests');
            mkdir($pathPrefix.'/'.$this->getPath().'/tests/phpunit');
            mkdir($pathPrefix.'/'.$this->getPath().'/tests/behat');
        }

    }

    public function getAvailableTestFrameworks()
    {
        $frameworks = array();

        if (is_file($this->getPhpUnitPath())) {
            $frameworks[] = 'phpunit';
        }

        if (is_file($this->getBehatPath())) {
            $frameworks[] = 'behat';
        }

        return $frameworks;
    }

    public function getPhpUnitPath($pathPrefix = '.')
    {
        return $pathPrefix.'/'.$this->getPath().'/phpunit.xml';
    }

    public function getBehatPath($pathPrefix = '.')
    {
        return $pathPrefix.'/'.$this->getPath().'/behat.yml';
    }

    public function getPhpunitStandardXml()
    {
        return <<<XML
<?xml version="1.0" encoding="UTF-8"?>

<phpunit colors="true">
    <testsuites>
        <testsuite name="Prophet Test Suite">
            <directory suffix="Test.php">./tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./src</directory>
        </whitelist>
    </filter>
</phpunit>

XML;

    }

    public function getBehatStandardConfig()
    {
        return <<<YML
# behat.yml

default:
    autoload:
        '': %paths.base%/tests/behat/contexts
    suites:
        default:
          paths: [ %paths.base%/tests/behat ]
          contexts:
            - FeatureContext
            - Behat\MinkExtension\Context\MinkContext
    extensions:
        Behat\MinkExtension:
            base_url: https://develop.vagrant.dev
            sessions:
                headless:
                    selenium2:
                      wd_host: "http://localhost:8643/wd/hub"
                full:
                    selenium2: ~

YML;

    }
}


text:
namespace Utils {

    void getLocalDomains(const FieldLayout<DIM> & FLayout,
                         std::vector<NDIndex<DIM> > & vectorLocalDomains);

    void getNodeIndices(const FieldLayout<DIM> & cellCenteredLayout,
                        std::vector<int> & vectorNodeIndices);

    void increaseLocalDomainsLast(const FieldLayout<DIM> & cellCenteredLayout,
                                  std::vector<NDIndex<DIM> > & vectorLocalDomains);

    void decreaseLocalDomainsLast(const FieldLayout<DIM> & cellCenteredLayout,
                                  std::vector<NDIndex<DIM> > & vectorLocalDomains);

    void increaseLocalDomainsFirst(const FieldLayout<DIM> & cellCenteredLayout,
                                   std::vector<NDIndex<DIM> > & vectorLocalDomains);

    void decreaseLocalDomainsFirst(const FieldLayout<DIM> & cellCenteredLayout,
                                   std::vector<NDIndex<DIM> > & vectorLocalDomains);

    void addGostCellToLocalDomains(const FieldLayout<DIM> & cellCenteredLayout,
                                   std::vector<NDIndex<DIM> > & vectorLocalDomains);

    template<class M, class T>
    class CompanionDeleter {
    public:
        CompanionDeleter(T* t);
        void operator()(M* m);
    private:
        T* companion_;
    };

    template<class T>
    T ipow(T base, unsigned int exp);

    float Q_rsqrt( float x );

    class KahanAccumulation
    {
    private:
        long double total;
        long double correction;

    public:
        KahanAccumulation();
        KahanAccumulation& sum(const double & value);

        KahanAccumulation& operator+(const double & value)
        {
            return sum(value);
        }

        KahanAccumulation& operator-(const double & value)
        {
            return sum(-value);
        }
    };

    template <typename T> int sgn(T val) {
        return (T(0) <= val) - (val < T(0));
    }
}

template<class M, class T>
Utils::CompanionDeleter<M,T>::CompanionDeleter(T* t):
companion_(t)
{ }

template<class M, class T>
void
Utils::CompanionDeleter<M,T>::operator()(M* master)
{
    delete master;
    delete companion_;
}

template<class T>
T Utils::ipow(T base, unsigned int exp)
{
    T result = 1;
    while (exp)
        {
            if (exp & 1)
                result *= base;
            exp >>= 1;
            base *= base;
        }

    return result;
}

inline
void Utils::getLocalDomains(const FieldLayout<DIM> & FLayout,
                            std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    vectorLocalDomains.resize(Ippl::getNodes());
    vectorLocalDomains[Ippl::myNode()] = FLayout.getLocalNDIndex();
    for (FieldLayout<DIM>::const_iterator_dv domainMapIterator = FLayout.begin_rdv();
         domainMapIterator != FLayout.end_rdv();
         ++ domainMapIterator) {
        RefCountedP<Vnode<DIM> > virtualNode = (*domainMapIterator).second;
        vectorLocalDomains[virtualNode->getNode()] = virtualNode->getDomain();
    }
}

inline
void Utils::getNodeIndices(const FieldLayout<DIM> & cellCenteredLayout,
                           std::vector<int> & vectorNodeIndices)
{
    vectorNodeIndices.resize(Ippl::getNodes());
    vectorNodeIndices[Ippl::myNode()] = Ippl::myNode();
    for (FieldLayout<DIM>::const_iterator_dv domainMapIterator = cellCenteredLayout.begin_rdv();
         domainMapIterator != cellCenteredLayout.end_rdv();
         ++ domainMapIterator)
        {
            RefCountedP<Vnode<DIM> > virtualNode = (*domainMapIterator).second;
            vectorNodeIndices[virtualNode->getNode()] = virtualNode->getNode();
        }
}

inline
void Utils::increaseLocalDomainsLast(const FieldLayout<DIM> & cellCenteredLayout,
                                     std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    const NDIndex<DIM> & globalDomain = cellCenteredLayout.getDomain();

    for (std::vector<NDIndex<DIM> >::iterator NDIndexIterator = vectorLocalDomains.begin();
         NDIndexIterator != vectorLocalDomains.end();
         ++ NDIndexIterator) {
        NDIndex<DIM> & domain = *NDIndexIterator;
        if (domain[0].last() == globalDomain[0].last()) {
            domain[0] = Index(domain[0].first(), globalDomain[0].last() + 1);
        }

        if (domain[1].last() == globalDomain[1].last()) {
            domain[1] = Index(domain[1].first(), globalDomain[1].last() + 1);
        }
    }
}

inline
void Utils::decreaseLocalDomainsLast(const FieldLayout<DIM> & cellCenteredLayout,
                                     std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    const NDIndex<DIM> & globalDomain = cellCenteredLayout.getDomain();

    for (std::vector<NDIndex<DIM> >::iterator NDIndexIterator = vectorLocalDomains.begin();
         NDIndexIterator != vectorLocalDomains.end();
         ++ NDIndexIterator) {
        NDIndex<DIM> & domain = *NDIndexIterator;
        if (domain[0].last() == globalDomain[0].last()) {
            domain[0] = Index(domain[0].first(), globalDomain[0].last() - 1);
        }

        if (domain[1].last() == globalDomain[1].last()) {
            domain[1] = Index(domain[1].first(), globalDomain[1].last() - 1);
        }
    }
}

inline
void Utils::increaseLocalDomainsFirst(const FieldLayout<DIM> & cellCenteredLayout,
                                      std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    const NDIndex<DIM> & globalDomain = cellCenteredLayout.getDomain();

    for (std::vector<NDIndex<DIM> >::iterator NDIndexIterator = vectorLocalDomains.begin();
         NDIndexIterator != vectorLocalDomains.end();
         ++ NDIndexIterator) {
        NDIndex<DIM> & domain = *NDIndexIterator;
        if (domain[0].first() == globalDomain[0].first()) {
            domain[0] = Index(globalDomain[0].first() - 1, domain[0].last());
        }

        if (domain[1].first() == globalDomain[1].first()) {
            domain[1] = Index(globalDomain[1].first() - 1, domain[1].last());
        }
    }
}

inline
void Utils::decreaseLocalDomainsFirst(const FieldLayout<DIM> & cellCenteredLayout,
                                      std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    const NDIndex<DIM> & globalDomain = cellCenteredLayout.getDomain();

    for (std::vector<NDIndex<DIM> >::iterator NDIndexIterator = vectorLocalDomains.begin();
         NDIndexIterator != vectorLocalDomains.end();
         ++ NDIndexIterator) {
        NDIndex<DIM> & domain = *NDIndexIterator;
        if (domain[0].first() == globalDomain[0].first()) {
            domain[0] = Index(globalDomain[0].first() + 1, domain[0].last());
        }

        if (domain[1].first() == globalDomain[1].first()) {
            domain[1] = Index(globalDomain[1].first() + 1, domain[1].last());
        }
    }
}

inline
void Utils::addGostCellToLocalDomains(const FieldLayout<DIM> & cellCenteredLayout,
                                      std::vector<NDIndex<DIM> > & vectorLocalDomains)
{
    const NDIndex<DIM> & globalDomain = cellCenteredLayout.getDomain();

    for (std::vector<NDIndex<DIM> >::iterator NDIndexIterator = vectorLocalDomains.begin();
         NDIndexIterator != vectorLocalDomains.end();
         ++ NDIndexIterator) {
        NDIndex<DIM> & domain = *NDIndexIterator;

        if (domain[0].first() != globalDomain[0].first()) {
            domain[0] = Index(domain[0].first() - 1, domain[0].last());
        }

        if (domain[0].last() != globalDomain[0].last()) {
            domain[0] = Index(domain[0].first(), domain[0].last() + 1);
        }

        if (domain[1].first() != globalDomain[1].first()) {
            domain[1] = Index(domain[1].first() - 1, domain[1].last());
        }

        if (domain[1].last() != globalDomain[1].last()) {
            domain[1] = Index(domain[1].first(), domain[1].last() + 1);
        }
    }
}

inline
float Utils::Q_rsqrt( float x )
{
    float xhalf = 0.5f*x;
    float xqhalf = 0.5010936f*x;
    uint32_t i;
    assert(sizeof(x) == sizeof(i));
    std::memcpy(&i, &x, sizeof(i));
    i = 0x5f3759df - (i>>1);
    std::memcpy(&x, &i, sizeof(i));
    x = x*(1.5f - xhalf*x*x);        // result is less than correct result for all x since 1/sqrt(x) is convex
    x = x*(1.5010936f - xqhalf*x*x); // optimized slope (steeper slope pushes result to higher values)
    return x;
}
#endif