text:
id: ios
title: iOS Variant
---

 The following step-by-step guide gives you an introduction on how to use the AeroGear UnifiedPush Server for sending
 Push Notifications to your own iOS Apps. The guide assumes you have an Apple developer account already setup, and uses tools available in macOS.

 To be able to send _push notifications_ to iOS, an _iOS variant_ must be created. That variant can be an _iOS (Certificate) Variant_ or an _iOS (APNS Token) Variant,
 depending on the way we are going to authenticate to the APNs:

 * with an APNs Certificate
 * with an APNs Token

 The first one is the legacy one: with this method you will be required to have one certificate for each application and, furthermore,
 you need two distinct certificates for the production and the development environments.

 The second one is the new token based authentication, which makes authentication much simpler:

 * The same key can be used for both development and production environments
 * The same key can be used for all the apps registered into your developer account
 * The key does not expire

 In this manual we will describe how to use both the approaches.

## APNs Certificate authentication
 A couple of configuration steps needs to be performed on the _Apple developer site_ before we can create the actual variant in the _Unified Push Server_:
 * Create a **CSR** _(Certificate Signing Request)_: this will be used to ask apple to generate a _development_ and/or _production_ certificate
 * Create an **App ID and its SSL certificate**: this will be used to authenticate the application to the APNs

#### Certificate Signing Request
 First you need to submit a request for a new digital certificate, which is based on a public/private key. The
 Certificate itself is acting as the public key, and when you request it, a private key is added to your **KeyChain**
 tool. The Cerficate will be used later on, to request an SSL certificate for the Apple Push Network service, which
 will allow the _AeroGear Push Server_ to send notification messages to it. Now the actual CSR (Certificate Signing
 Request) is done using **KeyChain Access** found in the **Applications > Utilities** folder on your Mac. Once opened, in
 the **KeyChain Access** menu, choose **Certificate Assistant > Request a Certificate** from a **Certificate Authority**:

 > ![Creating a CSR](assets/ios/CreateCert.png "Creating a CSR")

 Make sure that you have chosen "Saved to disk" to save the CSR locally; we will upload it later in the provisioning portal when
 requesting the actual SSL cert. Going back to **KeyChain Access** you now see a new private key:

 > ![Store CSR into KeyChain](assets/ios/KeyChain-keys.png)

#### Apple App ID and SSL certificate for APNs
 Now that the CSR is generated, go to the [Provisioning Portal](https://developer.apple.com/account/overview.action)
 and log in with your Apple developer account. Now, click on the **Identifiers** link in order to create a new App ID
 (use the **PLUS** Icon on the right).
 In the window that will appear, select **App IDs**

 > ![Store CSR into KeyChain](assets/ios/ChooseAppIDs.png)

 Click on _continue_. In the form that will appear:
  * select _iOS, tvOS, watchOS_, give the **App ID** a _descriptive_ name, like **My first AeroGear Push App**
  * select **Bundle ID Explicit** (generic **Wildcard App ID** does not work with Push)
  * In the _Bundle ID_ field enter **YOUR** bundle ID. This is similar to Java packages. In this example we choose
    _org.aerogear.PushHelloWorld_, however you must use your own ID
  * Double check that the **Push Notifications** checkbox is selected in the list of _Capabilities_:

:::note
The _Bundle ID_ has to match the one from the actual iOS application that you are building later in this guide.
:::

 > ![Set App ID](assets/ios/SetAppId.png)

In the next screen confirm your new App ID, and double check that the _Push Notifications_ option is enabled.
Afterwards click the _Register_ button! Then, click on on the newly created App ID, and ensure that the _Push Notifications_ capability
is enable and click on the _Configure_ button close to that.
The following screen will appear:

 > ![Configure Push](assets/ios/ConfigurePush.png)

Here we are asked to generate a _Development_ and a _Production_ certificate that will be used by the UnifiedPush server
when contacting the Apple Push Notification service to send messages. If you plan to distribute your app in the
App Store, you are required to generate a Production certificate. In this guide we will generate both
Certificates and register them with the UnifiedPush server.

Let's start first by generating the _Development Certificate_. Click the _Create Certificate_ button on the
_Development SSL Certificate_ section:

 > ![Upload CSR](assets/ios/UploadCSR.png)

Choose the _Certificate Signing Request_ you generate before and click on _Continue_: that will sign your certificate
request and will give you the chance to download your newly generated certificate.

By following the same steps as before, you can now generate a production certificate too.

Now, if you go to your identifier, the _Push Notifications_ capability will appear as below:

 > ![Push Notifications Capability with cert](assets/ios/PushNotificationsWithCerts.png)

Click on _Edit_:

 > ![Download Push Certificates](assets/ios/DownloadPushCertificates.png)

Download and install the certificate (double click on it and choose `login` as keychain)
Open the KeyChain an select the `login` keychain and the `My Certificates` category:

 > ![KeyChain](assets/ios/KeyChain.png)

Now you have to export this certificate/private key pair as **Personal Information Exchange (.p12)**. This file will
be uploaded later on to the AeroGear Push Server enabling it to authorize itself for your development application on
Apple Push Network Service and send messages to it.

 > ![Download P12](assets/ios/DownloadP12.png)

When exporting the file you need to assign a passphrase that will protect the private key. Make note of the passphrase, because later
when uploading the private key to the _AeroGear Push Server_ you will need both the exported file and the passphrase.

Follow the same steps to download the _Production SSL Certificate_, the file is being downloaded as aps_production.cer.
This file will be uploaded later on to the AeroGear Push Server enabling it to authorize itself for your production
application on Apple Push Network Service and send messages to it.

### Creating the variant in the UnifiedPush Server
APNs is now configured and we are now ready to setup the _UnifiedPush Server_ to connect to APNs and send push messages.

In the Wizard after you create a PushApplication, click the **Add Variant** button and fill out the iOS option.
You will want to use the certificate and passphrase you create earlier:

 > ![Add Variant](assets/ios/AddVariant.png)

Afterwards you will see some code snippets containing the **Variant ID** and **Secret** that you can use in your iOS
application for registering the device when running your app:

 > ![Add Variant](assets/ios/Snippets.png)

:::note
Clicking on the appropriate tab, you can choose between Objective-C, Swift and Cordova snippet |
:::

## APNs Token Authentication
 To be able to authentication using _token authentication_ you will need to collect the following informations:
 * your **bundle id**: This is similar to Java packages. In this example we choose _org.aerogear.PushHelloWorld_, however you must use your own ID
 * your **team ID**
 * your **private key**
 * your **key id**

### The TEAM ID
 Your _Team ID_ can be obtained very easily form your _developer account_:
 * Enter your development account
 * Click on _Certificates, IDs & Profiles_

 > ![Team ID](assets/ios/team-id.png)

 Your _team id_ will be on the upper right corner, right below your name, next to your team name.

### Generating the private key and the Key ID

As for the [team id](#the-team-id), go to the _Certificates, IDs & Profiles_ page.
Once there click _Keys_ to go the _keys management page_ and click on the _plus sign_ at the right of the _keys_ header:

 > ![Team ID](assets/ios/keys.png)

That will lead to a form where you will be able to set a name for the _key_ and select the feature to enable.

:::important
Double check that **Apple Push Notifications service (APNs)** is enabled here!
:::

 > ![Team ID](assets/ios/apns-key.png)

We are almost done: click on _Continue_ and then on _Register_. That will bring you to a screen similar to the one below.

 > ![Team ID](assets/ios/key-details.png)

 Take note of the _Key ID_ and click on _Download_ to save the key somewhere, since we will need it to create the variant.

 :::warning
 Please, take care of the downloaded key, since, after you click on _download_ you won't be able to download it again!
 :::

### Creating the variant in the UnifiedPush Server
APNs is now configured and we are now ready to setup the _UnifiedPush Server_ to connect to APNs and send push messages.

In the Wizard after you create a PushApplication, click the **Add Variant** button and select **iOS (APNS Token)**.
You will need the private key you just downloaded, its **key id**, your **team id** and your **bundle id**

 ![Add Variant](assets/ios/apns-token-variant.png)

Afterwards you will see some code snippets containing the **Variant ID** and **Secret** that you can use in your iOS
application for registering the device when running your app:

 > ![Add Variant](assets/ios/apns-token-variant-details.png)

:::note
Clicking on the appropriate tab, you can choose between Objective-C, Swift and Cordova snippet |
:::


text:
package io.kaif.model.zone;

import static java.util.Arrays.asList;

import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import io.kaif.model.account.Account;
import io.kaif.model.account.Authority;
import io.kaif.model.account.Authorization;
import io.kaif.web.v1.dto.V1ZoneDto;

/**
 * Although authorities has lots of combination, but valid cases are:
 *

 * 1) default --  CITIZEN allow: upVote, write, debate
 *

 * 2) kaif    --  CITIZEN allow: upVote, debate, zoneAdmin allow write
 *

 * 3) kVoting --  CITIZEN allow: debate, SUFFRAGE allow upVote, zoneAdmins allow write
 *

 * 4) vote    --  CITIZEN allow: upVote, debate, zoneAdmins allow write
 *

 * CITIZEN allow up/down vote on PEOPLE, regardless ZoneInfo settings
 */
public class ZoneInfo {

  public static final int ALIAS_NAME_MAX = 20;

  public static final String THEME_DEFAULT = "z-theme-default";

  // theme used in site related zone, like Blog or FAQ
  public static final String THEME_KAIF = "z-theme-kaif";

  public static final String THEME_NORMAL_VOTING = "z-theme-normal-voting";

  public static final String THEME_K_VOTING = "z-theme-k-voting";

  public static final String RESERVED_WORD = "kaif";

  public static ZoneInfo createKVoting(String zoneValue,
      String aliasName,
      Account creator,
      Instant now) {
    checkDefault(zoneValue);
    checkAliasName(aliasName);
    boolean hideFromTopRanking = false;
    Authority voteAuth = Authority.SUFFRAGE;
    Authority debateAuth = Authority.CITIZEN;
    Authority writeAuth = Authority.FORBIDDEN;
    return new ZoneInfo(Zone.valueOf(zoneValue),
        aliasName,
        THEME_K_VOTING,
        voteAuth,
        debateAuth,
        writeAuth,
        asList(creator.getAccountId()),
        hideFromTopRanking,
        now);
  }

  public static ZoneInfo createNormalVoting(String zoneValue,
      String aliasName,
      Account creator,
      Instant now) {
    checkDefault(zoneValue);
    checkAliasName(aliasName);
    boolean hideFromTopRanking = false;
    Authority voteAuth = Authority.CITIZEN;
    Authority debateAuth = Authority.CITIZEN;
    Authority writeAuth = Authority.FORBIDDEN;
    return new ZoneInfo(Zone.valueOf(zoneValue),
        aliasName,
        THEME_NORMAL_VOTING,
        voteAuth,
        debateAuth,
        writeAuth,
        asList(creator.getAccountId()),
        hideFromTopRanking,
        now);
  }

  /**
   * zone allow tourist to vote/debate/write ...etc, this should be test zone
   */
  public static ZoneInfo createTourist(String zoneValue, String aliasName, Instant now) {
    checkAliasName(aliasName);
    boolean hideFromTopRanking = true;
    Authority voteAuth = Authority.TOURIST;
    Authority debateAuth = Authority.TOURIST;
    Authority writeAuth = Authority.TOURIST;
    return new ZoneInfo(Zone.valueOf(zoneValue),
        aliasName,
        THEME_DEFAULT,
        voteAuth,
        debateAuth,
        writeAuth,
        Collections.emptyList(),
        hideFromTopRanking,
        now);
  }

  public static ZoneInfo createKaif(String zoneValue, String aliasName, Instant now) {
    checkAliasName(aliasName);
    boolean hideFromTopRanking = true;
    Authority voteAuth = Authority.CITIZEN;
    Authority debateAuth = Authority.CITIZEN;
    Authority writeAuth = Authority.FORBIDDEN;
    return new ZoneInfo(Zone.valueOf(zoneValue),
        aliasName,
        THEME_KAIF,
        voteAuth,
        debateAuth,
        writeAuth,
        Collections.emptyList(),
        hideFromTopRanking,
        now);
  }

  public static ZoneInfo createDefault(String zoneValue, String aliasName, Instant now) {
    checkDefault(zoneValue);
    checkAliasName(aliasName);
    boolean hideFromTopRanking = false;
    Authority voteAuth = Authority.CITIZEN;
    Authority debateAuth = Authority.CITIZEN;
    Authority writeAuth = Authority.CITIZEN;
    return new ZoneInfo(Zone.valueOf(zoneValue),
        aliasName,
        THEME_DEFAULT,
        voteAuth,
        debateAuth,
        writeAuth,
        Collections.emptyList(),
        hideFromTopRanking,
        now);
  }

  private static void checkAliasName(String aliasName) {
    Preconditions.checkArgument(aliasName.length() <= ALIAS_NAME_MAX);
  }

  private static void checkDefault(String zoneValue) {
    Preconditions.checkArgument(isValidDefault(zoneValue));
  }

  public static boolean isValidDefault(String zoneValue) {
    return !zoneValue.contains(RESERVED_WORD);
  }

  /**
   * zone are always lowercase and URL friendly
   */
  private final Zone zone;

  /**
   * display name of zone, may include Upper case or even Chinese
   */
  private final String aliasName;

  /**
   * css theme class name
   */
  private final String theme;

  /**
   * which authority can vote on this zone
   */
  private final Authority voteAuthority;

  /**
   * which authority can debate on this zone
   */
  private final Authority debateAuthority;

  /**
   * which authority can write article in this zone
   */
  private final Authority writeAuthority;

  /**
   * accountId can do everything about this zone, he ignore all authority check
   */
  private final List<UUID> adminAccountIds;

  /**
   * hide this zone in home page top ranking
   */
  private final boolean hideFromTop;

  private final Instant createTime;

  ZoneInfo(Zone zone,
      String aliasName,
      String theme,
      Authority voteAuthority,
      Authority debateAuthority,
      Authority writeAuthority,
      List<UUID> adminAccountIds,
      boolean hideFromTop,
      Instant createTime) {
    this.zone = zone;
    this.aliasName = aliasName;
    this.theme = theme;
    this.voteAuthority = voteAuthority;
    this.debateAuthority = debateAuthority;
    this.writeAuthority = writeAuthority;
    this.adminAccountIds = adminAccountIds;
    this.hideFromTop = hideFromTop;
    this.createTime = createTime;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ZoneInfo zoneInfo = (ZoneInfo) o;

    if (zone != null ? !zone.equals(zoneInfo.zone) : zoneInfo.zone != null) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return zone != null ? zone.hashCode() : 0;
  }

  public Zone getZone() {
    return zone;
  }

  public String getAliasName() {
    return aliasName;
  }

  public Authority getVoteAuthority() {
    return voteAuthority;
  }

  public String getTheme() {
    return theme;
  }

  public Authority getWriteAuthority() {
    return writeAuthority;
  }

  public List<UUID> getAdminAccountIds() {
    return adminAccountIds;
  }

  public Instant getCreateTime() {
    return createTime;
  }

  public Authority getDebateAuthority() {
    return debateAuthority;
  }

  public boolean canUpVote(Authorization auth) {
    if (auth.belongToAccounts(adminAccountIds)) {
      return true;
    }
    return auth.containsAuthority(voteAuthority);
  }

  public boolean canDebate(Authorization auth) {
    if (auth.belongToAccounts(adminAccountIds)) {
      return true;
    }
    return auth.containsAuthority(debateAuthority);
  }

  public boolean canWriteArticle(Authorization auth) {
    if (auth.belongToAccounts(adminAccountIds)) {
      return true;
    }
    return auth.containsAuthority(writeAuthority);
  }

  public boolean canContributeVoteStats() {
    return voteAuthority == Authority.CITIZEN;
  }

  public boolean isHideFromTop() {
    return hideFromTop;
  }

  public ZoneInfo withAdmins(List<UUID> accountIds) {
    return new ZoneInfo(zone,
        aliasName,
        theme,
        voteAuthority,
        debateAuthority,
        writeAuthority,
        ImmutableList.copyOf(accountIds),
        hideFromTop,
        createTime);
  }

  /**
   * shortcut to zone.value()
   */
  public String getName() {
    return zone.value();
  }

  @Override
  public String toString() {
    return "/z/" + zone;
  }

  public V1ZoneDto toV1Dto() {
    return new V1ZoneDto(getName(), getAliasName());
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace PXPAgent {
namespace Util {
    bool isValidUTF8(std::string &s) {
        rapidjson::StringStream source(s.data());
        rapidjson::InsituStringStream target(&s[0]);

        target.PutBegin();
        while (source.Tell() < s.size()) {
            if (!rapidjson::UTF8<char>::Validate(source, target)) {
                return false;
            }
        }

        // rapidjson::UTF8<char>::Validate accepts null bytes as valid UTF-8.
        // They technically are valid since they're the null character. But
        // null characters aren't valid in a string, so we want to disallow
        // them regardless.
        bool has_null = std::any_of(s.begin(), s.end(), [](char c) {
                            return c == 0;
                        });
        return !has_null;
    }
}  // namespace Util
}  // namespace PXPAgent


text:
schema: opendataschema
title: Scuole
organization: MIUR
notes: 'Tutte le scuole di Prato. Aggiornati da Scuola in Chiaro http://cercalatuascuola.istruzione.it/cercalatuascuola/opendata/ anno 2015/2016.'
resources:
  - name: Scuole Statali del Comune di Prato
    url: 'https://github.com/iltempe/opendataprato/blob/master/scuole_statali.csv'
    format: csv
  - name: Scuole Paritarie della Provincia di Prato
    url: 'https://github.com/iltempe/opendataprato/blob/master/scuole_paritarie.csv'
    format: csv
category:
  - Cultura
  - Educazione
maintainer: Matteo Tempestini
maintainer_email: mtempestini@gmail.com
license: 'https://creativecommons.org/licenses/by/4.0/'
pubdate: 28/04/2016
---


text:
#include <boost/test/unit_test.hpp>
#include <mpack.h>

BOOST_AUTO_TEST_CASE(test_encode_init_empty)
{
  mpack::encoder encoder;

  BOOST_CHECK(encoder.begin == nullptr);
  BOOST_CHECK(encoder.end == nullptr);
  BOOST_CHECK(encoder.pos == nullptr);
}

BOOST_AUTO_TEST_CASE(test_encode_init_from_buffer)
{
  char buffer[32] = { 0 };
  mpack::encoder encoder { buffer, sizeof(buffer) };

  BOOST_CHECK(encoder.begin == buffer);
  BOOST_CHECK(encoder.end == (buffer + sizeof(buffer)));
  BOOST_CHECK(encoder.pos == buffer);
}


text:
package pl.themolka.arcade.dominator;

import com.google.common.collect.ImmutableMap;

import java.util.Map;

/**
 * All object(s) dominates.
 */
public class Everybody<T> extends AbstractDominator<T> {
    @Override
    public Map<T, Integer> getDominators(Map<T, Integer> input) {
        return ImmutableMap.copyOf(input);
    }
}


text:
package io.buoyant.linkerd
package protocol

import com.twitter.conversions.time._
import com.twitter.finagle.buoyant.linkerd.Headers
import com.twitter.finagle.http.{Method, Request, Response}
import com.twitter.finagle.stats.{InMemoryStatsReceiver, NullStatsReceiver}
import com.twitter.finagle._
import com.twitter.io.Buf
import com.twitter.util.{Future, MockTimer, Time, Var}
import com.twitter.finagle.tracing.NullTracer
import io.buoyant.test.FunSuite
import java.net.InetSocketAddress

class RetriesEndToEndTest extends FunSuite {

  case class Downstream(name: String, service: Service[Request, Response]) {
    val stack = Http.server.stack.remove(Headers.Ctx.serverModule.role)
    val server = Http.server.withStack(stack)
      .configured(param.Label(name))
      .configured(param.Tracer(NullTracer))
      .serve(":*", service)
    val address = server.boundAddress.asInstanceOf[InetSocketAddress]
    val port = address.getPort
  }

  def upstream(server: ListeningServer) = {
    val address = Address(server.boundAddress.asInstanceOf[InetSocketAddress])
    val name = Name.Bound(Var.value(Addr.Bound(address)), address)
    val stack = Http.client.stack.remove(Headers.Ctx.clientModule.role)
    Http.client.withStack(stack)
      .configured(param.Stats(NullStatsReceiver))
      .configured(param.Tracer(NullTracer))
      .newClient(name, "upstream").toService
  }

  val writeException = new WriteException {}

  test("requeues") {
    var i = 0
    val downstream = Downstream("ds", Service.mk { req =>
      val rsp = i match {
        case 0 => Future.value(Response()) // first request
        case 1 => Future.exception(writeException)  // second request
        case 2 => Future.value(Response()) // second request (requeue)
        case 3 => Future.exception(writeException) // third request (budget exceeded)
      }
      i += 1
      rsp
    })

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: /svc/* => /$$/inet/127.1/${downstream.port}
          |  service:
          |    retries:
          |      budget:
          |        minRetriesPerSec: 0
          |        percentCanRetry: 0.0
          |  client:
          |    failFast: false
          |    failureAccrual:
          |      kind: none
          |    requeueBudget:
          |      minRetriesPerSec: 0
          |      # each request may generate 0.5 retries, on average
          |      percentCanRetry: 0.5
          |      ttlSecs: 10
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def budget = stats.gauges(Seq("rt", "http", "client", s"$$/inet/127.1/${downstream.port}", "retries", "budget"))
        def requeues = stats.counters.getOrElse(
          Seq("rt", "http", "client", s"$$/inet/127.1/${downstream.port}", "retries", "requeues"),
          0
        )
        def requestLimit = stats.counters.getOrElse(
          Seq("rt", "http", "client", s"$$/inet/127.1/${downstream.port}", "retries", "request_limit"),
          0
        )

        val req = Request()
        req.host = "foo"

        assert(await(client(req)).statusCode == 200) // first request (success)
        assert(budget() == 0) // (0.5).toInt
        assert(requeues == 0)
        assert(requestLimit == 0)

        assert(await(client(req)).statusCode == 200) // second request (success after a requeue)
        assert(budget() == 0)
        assert(requeues == 1)
        assert(requestLimit == 0)

        assert(await(client(req)).statusCode == 502) // third request (failed, no budget available for requeue)
        assert(budget() == 0) // (0.5).toInt
        assert(requeues == 1)
        assert(requestLimit == 1)

        // close the downstream
        await(downstream.server.close())
        assert(await(client(req)).statusCode == 502) // service acquisition failed
        assert(requeues == 26) // tried 25  times for service acquisition
      }
    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("per-client requeue policy") {

    class FailEveryN(n: Int) extends Service[Request, Response] {
      private[this] var i = 0
      def apply(req: Request): Future[Response] = {
        if (i%n == 0) {
          i += 1
          Future.exception(writeException)
        } else {
          i += 1
          Future.value(Response())
        }
      }
    }

    val downstreamA = Downstream("a", new FailEveryN(2))
    val downstreamB = Downstream("b", new FailEveryN(2))

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: |
          |    /svc/a => /$$/inet/127.1/${downstreamA.port} ;
          |    /svc/b => /$$/inet/127.1/${downstreamB.port} ;
          |  client:
          |    kind: io.l5d.static
          |    configs:
          |    - prefix: /
          |      failFast: false
          |      failureAccrual:
          |        kind: none
          |    - prefix: /$$/inet/127.1/${downstreamA.port}
          |      requeueBudget:
          |        minRetriesPerSec: 0
          |        # each request may generate 1.0 requeue, on average
          |        percentCanRetry: 1.0
          |        ttlSecs: 10
          |    - prefix: /$$/inet/127.1/${downstreamB.port}
          |      requeueBudget:
          |        minRetriesPerSec: 0
          |        # each request may generate 0.5 requeues, on average
          |        percentCanRetry: 0.5
          |        ttlSecs: 10
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def budget(ds: Downstream) =
          stats.gauges(Seq("rt", "http", "client", s"$$/inet/127.1/${ds.port}", "retries", "budget"))

        def requeues(ds: Downstream) = stats.counters.getOrElse(
          Seq("rt", "http", "client", s"$$/inet/127.1/${ds.port}", "retries", "requeues"),
          0
        )
        def requestLimit(ds: Downstream) = stats.counters.getOrElse(
          Seq("rt", "http", "client", s"$$/inet/127.1/${ds.port}", "retries", "request_limit"),
          0
        )

        val req = Request()
        req.host = "a"

        for (i <- 1 to 10) {
          // each request initially fails and then succeeds after 1 requeue
          assert(await(client(req)).statusCode == 200)
          assert(budget(downstreamA)() == 0)
          assert(requeues(downstreamA) == i)
          assert(requestLimit(downstreamA) == 0)
        }

        req.host = "b"
        // budget == 0
        assert(await(client(req)).statusCode == 502) // failure, no budget to requeue
        assert(budget(downstreamB)() == 0)
        assert(requeues(downstreamB) == 0)
        assert(requestLimit(downstreamB) == 1)

        // budget == 0.5
        assert(await(client(req)).statusCode == 200) // success on first try
        assert(budget(downstreamB)() == 1)
        assert(requeues(downstreamB) == 0)
        assert(requestLimit(downstreamB) == 1)

        // budget == 1
        assert(await(client(req)).statusCode == 200) // success after a requeue
        assert(budget(downstreamB)() == 0)
        assert(requeues(downstreamB) == 1)
        assert(requestLimit(downstreamB) == 1)

        // budget == 0.5
        assert(await(client(req)).statusCode == 200) // success after a requeue
        assert(budget(downstreamB)() == 0)
        assert(requeues(downstreamB) == 2)
        assert(requestLimit(downstreamB) == 1)

        // budget == 0
        assert(await(client(req)).statusCode == 502) // failure, no budget to requeue
        assert(budget(downstreamB)() == 0)
        assert(requeues(downstreamB) == 2)
        assert(requestLimit(downstreamB) == 2)
      }
    } finally {
      await(client.close())
      await(downstreamA.server.close())
      await(downstreamB.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("retries") {
    val success = Future.value(Response())
    val failure = Future.value {
      val rsp = Response()
      rsp.statusCode = 500
      rsp
    }
    var i = 0
    val downstream = Downstream("ds", Service.mk { req =>
      val rsp = i match {
        case 0 => success // first request
        case 1 => failure  // second request
        case 2 => success // second request (retry)
        case 3 => failure // third request (budget exceeded)
      }
      i += 1
      rsp
    })

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: /svc/* => /$$/inet/127.1/${downstream.port}
          |  client:
          |    failFast: false
          |    failureAccrual:
          |      kind: none
          |  service:
          |    responseClassifier:
          |      kind: io.l5d.http.retryableRead5XX
          |    retries:
          |      budget:
          |        minRetriesPerSec: 0
          |        # each request may generate 0.5 retries, on average
          |        percentCanRetry: 0.5
          |        ttlSecs: 10
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def budget = stats.gauges(Seq("rt", "http", "service", "svc/foo", "retries", "budget"))
        def retries = stats.counters.getOrElse(
          Seq("rt", "http", "service", "svc/foo", "retries", "total"),
          0
        )
        def budgetExhausted = stats.counters.getOrElse(
          Seq("rt", "http", "service", "svc/foo", "retries", "budget_exhausted"),
          0
        )

        val req = Request()
        req.host = "foo"

        assert(await(client(req)).statusCode == 200) // first request (success)
        assert(budget() == 0) // (0.5).toInt
        assert(retries == 0)
        assert(budgetExhausted == 0)

        assert(await(client(req)).statusCode == 200) // second request (success after a retry)
        assert(budget() == 0)
        assert(retries == 1)
        assert(budgetExhausted == 0)

        assert(await(client(req)).statusCode == 500) // third request (failed, no budget available for retry)
        assert(budget() == 0) // (0.5).toInt
        assert(retries == 1)
        assert(budgetExhausted == 1)
      }
    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("per-service retry policy") {

    class FailEveryN(n: Int) extends Service[Request, Response] {
      private[this] var i = 0
      def apply(req: Request): Future[Response] = {
        if (i%n == 0) {
          i += 1
          val rsp = Response()
          rsp.statusCode = 500
          Future.value(rsp)
        } else {
          i += 1
          Future.value(Response())
        }
      }
    }

    val downstreamA = Downstream("a", new FailEveryN(2))
    val downstreamB = Downstream("b", new FailEveryN(2))

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: |
          |    /svc/a => /$$/inet/127.1/${downstreamA.port} ;
          |    /svc/b => /$$/inet/127.1/${downstreamB.port} ;
          |  client:
          |    failFast: false
          |    failureAccrual:
          |      kind: none
          |  service:
          |    kind: io.l5d.static
          |    configs:
          |    - prefix: /svc/a
          |      retries:
          |        budget:
          |          minRetriesPerSec: 0
          |          # each request may generate 1.0 requeue, on average
          |          percentCanRetry: 1.0
          |          ttlSecs: 10
          |    - prefix: /svc/b
          |      retries:
          |        budget:
          |          minRetriesPerSec: 0
          |          # each request may generate 0.5 requeues, on average
          |          percentCanRetry: 0.5
          |          ttlSecs: 10
          |    - prefix: /
          |      responseClassifier:
          |        kind: io.l5d.http.retryableRead5XX
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def budget(ds: Downstream) =
          stats.gauges(Seq("rt", "http", "service", s"svc/${ds.name}", "retries", "budget"))

        def retries(ds: Downstream) = stats.counters.getOrElse(
          Seq("rt", "http", "service", s"svc/${ds.name}", "retries", "total"),
          0
        )
        def budgetExhausted(ds: Downstream) = stats.counters.getOrElse(
          Seq("rt", "http", "service", s"svc/${ds.name}", "retries", "budget_exhausted"),
          0
        )

        val req = Request()
        req.host = "a"

        for (i <- 1 to 10) {
          // each request initially fails and then succeeds after 1 retry
          assert(await(client(req)).statusCode == 200)
          assert(budget(downstreamA)() == 0)
          assert(retries(downstreamA) == i)
          assert(budgetExhausted(downstreamA) == 0)
        }

        req.host = "b"
        // budget == 0
        assert(await(client(req)).statusCode == 500) // failure, no budget to retry
        assert(budget(downstreamB)() == 0)
        assert(retries(downstreamB) == 0)
        assert(budgetExhausted(downstreamB) == 1)

        // budget == 0.5
        assert(await(client(req)).statusCode == 200) // success on first try
        assert(budget(downstreamB)() == 1)
        assert(retries(downstreamB) == 0)
        assert(budgetExhausted(downstreamB) == 1)

        // budget == 1
        assert(await(client(req)).statusCode == 200) // success after a retry
        assert(budget(downstreamB)() == 0)
        assert(retries(downstreamB) == 1)
        assert(budgetExhausted(downstreamB) == 1)

        // budget == 0.5
        assert(await(client(req)).statusCode == 200) // success after a retry
        assert(budget(downstreamB)() == 0)
        assert(retries(downstreamB) == 2)
        assert(budgetExhausted(downstreamB) == 1)

        // budget == 0
        assert(await(client(req)).statusCode == 500) // failure, no budget to retry
        assert(budget(downstreamB)() == 0)
        assert(retries(downstreamB) == 2)
        assert(budgetExhausted(downstreamB) == 2)
      }
    } finally {
      await(client.close())
      await(downstreamA.server.close())
      await(downstreamB.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("budgets for each service and client are independent") {

    val downstreamA = Downstream("a", Service.mk { req => Future.value(Response()) })
    val downstreamB = Downstream("b", Service.mk { req => Future.value(Response()) })

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: |
          |    /svc/a => /$$/inet/127.1/${downstreamA.port} ;
          |    /svc/b => /$$/inet/127.1/${downstreamB.port} ;
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>
        val req = Request()
        req.host = "a"
        for (i <- 1 to 10) {
          await(client(req))
        }

        // Each budget starts with a balance of 100 from minRetriesPerSec
        // we subtract that off to see just the deposits
        def retryBudget(svc: String): Int =
          stats.gauges.get(Seq("rt", "http", "service", svc, "retries", "budget")).map(_() - 100).getOrElse(0.0f).toInt
        def requeueBudget(clnt: String): Int =
          stats.gauges.get(Seq("rt", "http", "client", clnt, "retries", "budget")).map(_() - 100).getOrElse(0.0f).toInt

        // 20% budget
        assert(retryBudget("svc/a") == 2)
        assert(retryBudget("svc/b") == 0)
        assert(requeueBudget(s"$$/inet/127.1/${downstreamA.port}") == 2)
        assert(requeueBudget(s"$$/inet/127.1/${downstreamB.port}") == 0)
        req.host = "b"
        for (i <- 1 to 10) {
          await(client(req))
        }

        assert(retryBudget("svc/a") == 2)
        assert(retryBudget("svc/b") == 2)
        assert(requeueBudget(s"$$/inet/127.1/${downstreamA.port}") == 2)
        assert(requeueBudget(s"$$/inet/127.1/${downstreamB.port}") == 2)
      }
    } finally {
      await(client.close())
      await(downstreamA.server.close())
      await(downstreamB.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("l5d-retryable header is respected by default") {
    var i = 0
    val downstream = Downstream("ds", Service.mk { req =>
      val rsp = i match {
        case 0 => Future.value {
          val rsp = Response()
          rsp.statusCode = 500
          Headers.Retryable.set(rsp.headerMap, retryable = true)
          rsp
        }
        case 1 => Future.value(Response())
      }
      i += 1
      rsp
    })

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: /svc/* => /$$/inet/127.1/${downstream.port}
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def retries = stats.counters.getOrElse(
          Seq("rt", "http", "service", "svc/foo", "retries", "total"),
          0
        )

        val req = Request()
        req.host = "foo"

        assert(await(client(req)).statusCode == 200)
        assert(retries == 1)
      }
    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("l5d-retryable header takes precedence over repsonse classifier") {
    var i = 0
    val downstream = Downstream("ds", Service.mk { req =>
      val rsp = i match {
        case 0 => Future.value {
          val rsp = Response()
          rsp.statusCode = 500
          Headers.Retryable.set(rsp.headerMap, retryable = true)
          rsp
        }
        case 1 => Future.value(Response())
      }
      i += 1
      rsp
    })

    val config =
      s"""|routers:
          |- protocol: http
          |  dtab: /svc/* => /$$/inet/127.1/${downstream.port}
          |  service:
          |    responseClassifier:
          |      kind: io.l5d.http.retryableRead5XX
          |  servers:
          |  - port: 0
          |""".stripMargin

    val stats = new InMemoryStatsReceiver
    val linker = Linker.load(config).configured(param.Stats(stats))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {
      Time.withCurrentTimeFrozen { tc =>

        def retries = stats.counters.getOrElse(
          Seq("rt", "http", "service", "svc/foo", "retries", "total"),
          0
        )

        val req = Request()
        req.method = Method.Post
        req.host = "foo"

        // POST should not usually be retryable, but l5d-retryable indicates
        // the request can be retried anyway
        assert(await(client(req)).statusCode == 200)
        assert(retries == 1)
      }
    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }
  }

  test("chunked error responses should not leak connections on retries") {
    val stats = new InMemoryStatsReceiver
    val tracer = NullTracer

    val downstream = Downstream("dog", Service.mk { req =>
      val rsp = Response()
      rsp.statusCode = 500
      rsp.setChunked(true)
      rsp.close()
      Future.value(rsp)
    })

    val label = s"$$/inet/127.1/${downstream.port}"
    val dtab = Dtab.read(s"/svc/dog => /$label;")
    val yaml =
      s"""|routers:
          |- protocol: http
          |  dtab: ${dtab.show}
          |  service:
          |    responseClassifier:
          |      kind: io.l5d.http.retryableRead5XX
          |  servers:
          |  - port: 0
          |""".stripMargin
    val linker = Linker.load(yaml)
      .configured(param.Stats(stats))
      .configured(param.Tracer(tracer))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {

      val req = Request()
      req.host = "dog"
      val errrsp = await(client(req))
      assert(errrsp.statusCode == 500)
      assert(stats.counters.get(Seq("rt", "http", "server", "127.0.0.1/0", "requests")) == Some(1))
      assert(stats.counters.get(Seq("rt", "http", "client", label, "requests")) == Some(101))
      assert(stats.gauges.get(Seq("rt", "http", "client", label, "connections")).map(_.apply.toInt) == Some(1))

    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }

  }

  test("individual request timeouts should be retried") {
    val stats = new InMemoryStatsReceiver
    val tracer = NullTracer
    val timer = new MockTimer

    @volatile var i = 0

    val downstream = Downstream("dog", Service.mk { req =>
      if (i == 0) {
        i += 1
        Future.sleep(2.seconds)(timer).map(_ => Response())
      } else {
        val rsp = Response()
        Future.value(rsp)
      }
    })

    val label = s"$$/inet/127.1/${downstream.port}"
    val dtab = Dtab.read(s"/svc/dog => /$label;")
    val yaml =
      s"""|routers:
          |- protocol: http
          |  dtab: ${dtab.show}
          |  service:
          |    responseClassifier:
          |      kind: io.l5d.http.retryableRead5XX
          |  client:
          |    requestAttemptTimeoutMs: 1000
          |  servers:
          |  - port: 0
          |""".stripMargin
    val linker = Linker.load(yaml)
      .configured(param.Stats(stats))
      .configured(param.Tracer(tracer))
    val router = linker.routers.head.initialize()
    val server = router.servers.head.serve()
    val client = upstream(server)

    try {

      val req = Request()
      req.host = "dog"
      Time.withCurrentTimeFrozen { tc =>
        val rspF = client(req)
        tc.advance(3.seconds)
        timer.tick()
        val rsp = await(rspF)
        assert(rsp.statusCode == 200)
        assert(stats.counters.get(Seq("rt", "http", "server", "127.0.0.1/0", "requests")) == Some(1))
        assert(stats.counters.get(Seq("rt", "http", "client", label, "requests")) == Some(2))
        assert(stats.counters.get(Seq("rt", "http", "service", s"svc/dog", "retries", "total")) == Some(1))
      }
    } finally {
      await(client.close())
      await(downstream.server.close())
      await(server.close())
      await(router.close())
    }

  }
}


text:
namespace CalculatorUI
{
    partial class LicenseForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.SuspendLayout();
            //
            // richTextBox1
            //
            this.richTextBox1.BackColor = System.Drawing.SystemColors.ControlDark;
            this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.richTextBox1.Font = new System.Drawing.Font("Consolas", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.richTextBox1.Location = new System.Drawing.Point(0, 0);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.ReadOnly = true;
            this.richTextBox1.Size = new System.Drawing.Size(990, 412);
            this.richTextBox1.TabIndex = 0;
            this.richTextBox1.Text = "";
            this.richTextBox1.WordWrap = false;
            //
            // LicenseForm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(990, 412);
            this.Controls.Add(this.richTextBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.MaximizeBox = false;
            this.Name = "LicenseForm";
            this.Text = "License";
            this.TopMost = true;
            this.Load += new System.EventHandler(this.LicenseForm_Load);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.RichTextBox richTextBox1;
    }
}


text:
#define PY_SSIZE_T_CLEAN
#include <Python.h>

#define NPY_NO_DEPRECATED_API NPY_API_VERSION
#define _MULTIARRAYMODULE
#include <numpy/ndarraytypes.h>

#include "npy_config.h"
#include "npy_pycompat.h"

#include "convert_datatype.h"
#include "methods.h"
#include "shape.h"
#include "lowlevel_strided_loops.h"

#include "array_assign.h"

/*
 * Assigns the array from 'src' to 'dst'. The strides must already have
 * been broadcast.
 *
 * Returns 0 on success, -1 on failure.
 */
NPY_NO_EXPORT int
raw_array_assign_array(int ndim, npy_intp *shape,
        PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides,
        PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides)
{
    int idim;
    npy_intp shape_it[NPY_MAXDIMS];
    npy_intp dst_strides_it[NPY_MAXDIMS];
    npy_intp src_strides_it[NPY_MAXDIMS];
    npy_intp coord[NPY_MAXDIMS];

    PyArray_StridedUnaryOp *stransfer = NULL;
    NpyAuxData *transferdata = NULL;
    int aligned, needs_api = 0;
    npy_intp src_itemsize = src_dtype->elsize;

    NPY_BEGIN_THREADS_DEF;

    /* Check alignment */
    aligned = raw_array_is_aligned(ndim,
                        dst_data, dst_strides, dst_dtype->alignment) &&
              raw_array_is_aligned(ndim,
                        src_data, src_strides, src_dtype->alignment);

    /* Use raw iteration with no heap allocation */
    if (PyArray_PrepareTwoRawArrayIter(
                    ndim, shape,
                    dst_data, dst_strides,
                    src_data, src_strides,
                    &ndim, shape_it,
                    &dst_data, dst_strides_it,
                    &src_data, src_strides_it) < 0) {
        return -1;
    }

    /*
     * Overlap check for the 1D case. Higher dimensional arrays and
     * opposite strides cause a temporary copy before getting here.
     */
    if (ndim == 1 && src_data < dst_data &&
                src_data + shape_it[0] * src_strides_it[0] > dst_data) {
        src_data += (shape_it[0] - 1) * src_strides_it[0];
        dst_data += (shape_it[0] - 1) * dst_strides_it[0];
        src_strides_it[0] = -src_strides_it[0];
        dst_strides_it[0] = -dst_strides_it[0];
    }

    /* Get the function to do the casting */
    if (PyArray_GetDTypeTransferFunction(aligned,
                        src_strides_it[0], dst_strides_it[0],
                        src_dtype, dst_dtype,
                        0,
                        &stransfer, &transferdata,
                        &needs_api) != NPY_SUCCEED) {
        return -1;
    }

    if (!needs_api) {
        NPY_BEGIN_THREADS;
    }

    NPY_RAW_ITER_START(idim, ndim, coord, shape_it) {
        /* Process the innermost dimension */
        stransfer(dst_data, dst_strides_it[0], src_data, src_strides_it[0],
                    shape_it[0], src_itemsize, transferdata);
    } NPY_RAW_ITER_TWO_NEXT(idim, ndim, coord, shape_it,
                            dst_data, dst_strides_it,
                            src_data, src_strides_it);

    if (!needs_api) {
        NPY_END_THREADS;
    }

    NPY_AUXDATA_FREE(transferdata);

    return (needs_api && PyErr_Occurred()) ? -1 : 0;
}

/*
 * Assigns the array from 'src' to 'dst, whereever the 'wheremask'
 * value is True. The strides must already have been broadcast.
 *
 * Returns 0 on success, -1 on failure.
 */
NPY_NO_EXPORT int
raw_array_wheremasked_assign_array(int ndim, npy_intp *shape,
        PyArray_Descr *dst_dtype, char *dst_data, npy_intp *dst_strides,
        PyArray_Descr *src_dtype, char *src_data, npy_intp *src_strides,
        PyArray_Descr *wheremask_dtype, char *wheremask_data,
        npy_intp *wheremask_strides)
{
    int idim;
    npy_intp shape_it[NPY_MAXDIMS];
    npy_intp dst_strides_it[NPY_MAXDIMS];
    npy_intp src_strides_it[NPY_MAXDIMS];
    npy_intp wheremask_strides_it[NPY_MAXDIMS];
    npy_intp coord[NPY_MAXDIMS];

    PyArray_MaskedStridedUnaryOp *stransfer = NULL;
    NpyAuxData *transferdata = NULL;
    int aligned, needs_api = 0;
    npy_intp src_itemsize = src_dtype->elsize;

    NPY_BEGIN_THREADS_DEF;

    /* Check alignment */
    aligned = raw_array_is_aligned(ndim,
                        dst_data, dst_strides, dst_dtype->alignment) &&
              raw_array_is_aligned(ndim,
                        src_data, src_strides, src_dtype->alignment);

    /* Use raw iteration with no heap allocation */
    if (PyArray_PrepareThreeRawArrayIter(
                    ndim, shape,
                    dst_data, dst_strides,
                    src_data, src_strides,
                    wheremask_data, wheremask_strides,
                    &ndim, shape_it,
                    &dst_data, dst_strides_it,
                    &src_data, src_strides_it,
                    &wheremask_data, wheremask_strides_it) < 0) {
        return -1;
    }

    /*
     * Overlap check for the 1D case. Higher dimensional arrays cause
     * a temporary copy before getting here.
     */
    if (ndim == 1 && src_data < dst_data &&
                src_data + shape_it[0] * src_strides_it[0] > dst_data) {
        src_data += (shape_it[0] - 1) * src_strides_it[0];
        dst_data += (shape_it[0] - 1) * dst_strides_it[0];
        wheremask_data += (shape_it[0] - 1) * wheremask_strides_it[0];
        src_strides_it[0] = -src_strides_it[0];
        dst_strides_it[0] = -dst_strides_it[0];
        wheremask_strides_it[0] = -wheremask_strides_it[0];
    }

    /* Get the function to do the casting */
    if (PyArray_GetMaskedDTypeTransferFunction(aligned,
                        src_strides_it[0],
                        dst_strides_it[0],
                        wheremask_strides_it[0],
                        src_dtype, dst_dtype, wheremask_dtype,
                        0,
                        &stransfer, &transferdata,
                        &needs_api) != NPY_SUCCEED) {
        return -1;
    }

    if (!needs_api) {
        NPY_BEGIN_THREADS;
    }

    NPY_RAW_ITER_START(idim, ndim, coord, shape_it) {
        /* Process the innermost dimension */
        stransfer(dst_data, dst_strides_it[0], src_data, src_strides_it[0],
                    (npy_bool *)wheremask_data, wheremask_strides_it[0],
                    shape_it[0], src_itemsize, transferdata);
    } NPY_RAW_ITER_THREE_NEXT(idim, ndim, coord, shape_it,
                            dst_data, dst_strides_it,
                            src_data, src_strides_it,
                            wheremask_data, wheremask_strides_it);

    if (!needs_api) {
        NPY_END_THREADS;
    }

    NPY_AUXDATA_FREE(transferdata);

    return (needs_api && PyErr_Occurred()) ? -1 : 0;
}

/*
 * An array assignment function for copying arrays, broadcasting 'src' into
 * 'dst'. This function makes a temporary copy of 'src' if 'src' and
 * 'dst' overlap, to be able to handle views of the same data with
 * different strides.
 *
 * dst: The destination array.
 * src: The source array.
 * wheremask: If non-NULL, a boolean mask specifying where to copy.
 * casting: An exception is raised if the copy violates this
 *          casting rule.
 *
 * Returns 0 on success, -1 on failure.
 */
NPY_NO_EXPORT int
PyArray_AssignArray(PyArrayObject *dst, PyArrayObject *src,
                    PyArrayObject *wheremask,
                    NPY_CASTING casting)
{
    int copied_src = 0;

    npy_intp src_strides[NPY_MAXDIMS];

    /* Use array_assign_scalar if 'src' NDIM is 0 */
    if (PyArray_NDIM(src) == 0) {
        return PyArray_AssignRawScalar(
                            dst, PyArray_DESCR(src), PyArray_DATA(src),
                            wheremask, casting);
    }

    /*
     * Performance fix for expresions like "a[1000:6000] += x".  In this
     * case, first an in-place add is done, followed by an assignment,
     * equivalently expressed like this:
     *
     *   tmp = a[1000:6000]   # Calls array_subscript_nice in mapping.c
     *   np.add(tmp, x, tmp)
     *   a[1000:6000] = tmp   # Calls array_ass_sub in mapping.c
     *
     * In the assignment the underlying data type, shape, strides, and
     * data pointers are identical, but src != dst because they are separately
     * generated slices.  By detecting this and skipping the redundant
     * copy of values to themselves, we potentially give a big speed boost.
     *
     * Note that we don't call EquivTypes, because usually the exact same
     * dtype object will appear, and we don't want to slow things down
     * with a complicated comparison.  The comparisons are ordered to
     * try and reject this with as little work as possible.
     */
    if (PyArray_DATA(src) == PyArray_DATA(dst) &&
                        PyArray_DESCR(src) == PyArray_DESCR(dst) &&
                        PyArray_NDIM(src) == PyArray_NDIM(dst) &&
                        PyArray_CompareLists(PyArray_DIMS(src),
                                             PyArray_DIMS(dst),
                                             PyArray_NDIM(src)) &&
                        PyArray_CompareLists(PyArray_STRIDES(src),
                                             PyArray_STRIDES(dst),
                                             PyArray_NDIM(src))) {
        /*printf("Redundant copy operation detected\n");*/
        return 0;
    }

    if (PyArray_FailUnlessWriteable(dst, "assignment destination") < 0) {
        goto fail;
    }

    /* Check the casting rule */
    if (!PyArray_CanCastTypeTo(PyArray_DESCR(src),
                                PyArray_DESCR(dst), casting)) {
        PyObject *errmsg;
        errmsg = PyUString_FromString("Cannot cast scalar from ");
        PyUString_ConcatAndDel(&errmsg,
                PyObject_Repr((PyObject *)PyArray_DESCR(src)));
        PyUString_ConcatAndDel(&errmsg,
                PyUString_FromString(" to "));
        PyUString_ConcatAndDel(&errmsg,
                PyObject_Repr((PyObject *)PyArray_DESCR(dst)));
        PyUString_ConcatAndDel(&errmsg,
                PyUString_FromFormat(" according to the rule %s",
                        npy_casting_to_string(casting)));
        PyErr_SetObject(PyExc_TypeError, errmsg);
        Py_DECREF(errmsg);
        goto fail;
    }

    /*
     * When ndim is 1 and the strides point in the same direction,
     * the lower-level inner loop handles copying
     * of overlapping data. For bigger ndim and opposite-strided 1D
     * data, we make a temporary copy of 'src' if 'src' and 'dst' overlap.'
     */
    if (((PyArray_NDIM(dst) == 1 && PyArray_NDIM(src) >= 1 &&
                    PyArray_STRIDES(dst)[0] *
                            PyArray_STRIDES(src)[PyArray_NDIM(src) - 1] < 0) ||
                    PyArray_NDIM(dst) > 1) && arrays_overlap(src, dst)) {
        PyArrayObject *tmp;

        /*
         * Allocate a temporary copy array.
         */
        tmp = (PyArrayObject *)PyArray_NewLikeArray(dst,
                                        NPY_KEEPORDER, NULL, 0);
        if (tmp == NULL) {
            goto fail;
        }

        if (PyArray_AssignArray(tmp, src, NULL, NPY_UNSAFE_CASTING) < 0) {
            Py_DECREF(tmp);
            goto fail;
        }

        src = tmp;
        copied_src = 1;
    }

    /* Broadcast 'src' to 'dst' for raw iteration */
    if (PyArray_NDIM(src) > PyArray_NDIM(dst)) {
        int ndim_tmp = PyArray_NDIM(src);
        npy_intp *src_shape_tmp = PyArray_DIMS(src);
        npy_intp *src_strides_tmp = PyArray_STRIDES(src);
        /*
         * As a special case for backwards compatibility, strip
         * away unit dimensions from the left of 'src'
         */
        while (ndim_tmp > PyArray_NDIM(dst) && src_shape_tmp[0] == 1) {
            --ndim_tmp;
            ++src_shape_tmp;
            ++src_strides_tmp;
        }

        if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst),
                    ndim_tmp, src_shape_tmp,
                    src_strides_tmp, "input array",
                    src_strides) < 0) {
            goto fail;
        }
    }
    else {
        if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst),
                    PyArray_NDIM(src), PyArray_DIMS(src),
                    PyArray_STRIDES(src), "input array",
                    src_strides) < 0) {
            goto fail;
        }
    }

    if (wheremask == NULL) {
        /* A straightforward value assignment */
        /* Do the assignment with raw array iteration */
        if (raw_array_assign_array(PyArray_NDIM(dst), PyArray_DIMS(dst),
                PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst),
                PyArray_DESCR(src), PyArray_DATA(src), src_strides) < 0) {
            goto fail;
        }
    }
    else {
        npy_intp wheremask_strides[NPY_MAXDIMS];

        /* Broadcast the wheremask to 'dst' for raw iteration */
        if (broadcast_strides(PyArray_NDIM(dst), PyArray_DIMS(dst),
                    PyArray_NDIM(wheremask), PyArray_DIMS(wheremask),
                    PyArray_STRIDES(wheremask), "where mask",
                    wheremask_strides) < 0) {
            goto fail;
        }

        /* A straightforward where-masked assignment */
         /* Do the masked assignment with raw array iteration */
         if (raw_array_wheremasked_assign_array(
                 PyArray_NDIM(dst), PyArray_DIMS(dst),
                 PyArray_DESCR(dst), PyArray_DATA(dst), PyArray_STRIDES(dst),
                 PyArray_DESCR(src), PyArray_DATA(src), src_strides,
                 PyArray_DESCR(wheremask), PyArray_DATA(wheremask),
                         wheremask_strides) < 0) {
             goto fail;
         }
    }

    if (copied_src) {
        Py_DECREF(src);
    }
    return 0;

fail:
    if (copied_src) {
        Py_DECREF(src);
    }
    return -1;
}


text:
"""This module provides the main functionality of codeclimate-test-reporter.

Invocation flow:

  1. Read, validate and process the input (args, `stdin`).
  2. Create and send test coverage to codeclimate.com.
  3. Report back to `stdout`.
  4. Exit.

"""
from coverage.misc import CoverageException
import os
import platform
import sys
import requests.exceptions

from ..__init__ import __version__ as reporter_version
from ..components.argument_parser import ArgumentParser
from ..components.formatter import InvalidReportVersion
from ..components.payload_validator import InvalidPayload
from ..components.reporter import CoverageFileNotFound, Reporter

class Runner:
    def __init__(self, args=sys.argv[1:], out=sys.stdout, err=sys.stderr):
        self.parsed_args = ArgumentParser().parse_args(args)
        self.out = out
        self.err = err

    def run(self):
        """
        The main function.

        Pre-process args, handle some special types of invocations,
        and run the main program with error handling.

        Return exit status code.

        """

        if self.parsed_args.version:
            self.out.write(reporter_version)
            return 0

        if self.parsed_args.debug:
            self.out.write(self.__debug_info())

        try:
            reporter = Reporter(self.parsed_args)
            exit_status = reporter.run()
            return exit_status
        except CoverageFileNotFound as e:
            return self.__handle_error(
                str(e) + "\nUse --file <file> to specifiy an alternate location."
            )
        except CoverageException as e:
            return self.__handle_error(str(e), support=True)
        except InvalidPayload as e:
            return self.__handle_error("Invalid Payload: " + str(e), support=True)
        except InvalidReportVersion as e:
            return self.__handle_error(str(e))
        except requests.exceptions.HTTPError as e:
            return self.__handle_error(str(e), support=True)
        except requests.exceptions.Timeout:
            return self.__handle_error(
                "Client HTTP Timeout: No response in 5 seconds.",
                support=True
            )

    def __handle_error(self, message, support=False):
        self.err.write(message)

        if support:
            self.err.write(
                "\n\nContact support at https://codeclimate.com/help "
                "with the following debug info if error persists:"
                "\n" + message + "\n" + self.__debug_info()
            )

        return 1

    def __debug_info(self):
        from requests import __version__ as requests_version

        return "\n".join([
            "codeclimate-test-repoter %s" % reporter_version,
            "Requests %s" % requests_version,
            "Python %s\n%s" % (sys.version, sys.executable),
            "%s %s" % (platform.system(), platform.release()),
        ])


text:
module Azure::CognitiveServices::Customvisiontraining::V2_2
  module Models
    #
    # Represents settings associated with a project.
    #
    class ProjectSettings

      include MsRestAzure

      # @return Gets or sets the id of the Domain to use with this project.
      attr_accessor :domain_id

      # @return [Classifier] Gets or sets the classification type of the
      # project. Possible values include: 'Multiclass', 'Multilabel'
      attr_accessor :classification_type

      #
      # Mapper for ProjectSettings class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ProjectSettings',
          type: {
            name: 'Composite',
            class_name: 'ProjectSettings',
            model_properties: {
              domain_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'domainId',
                type: {
                  name: 'String'
                }
              },
              classification_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'classificationType',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
namespace H_Solution_3
{
    public abstract class AbstractCommand
    {
        protected Square square;

        public AbstractCommand(Square square)
        {
            this.square = square;
        }

        public Square getSquare()
        {
            return square;
        }

        public abstract void undo();
    }
}


text:
views:
    breadcrumb:
        region: breadcrumb
        template: default/breadcrumb
        data:
            meta:
                type: breadcrumb

    flash:
        region: flash
        template: default/image
        data:
            src: "img/header.jpg"

    byline:
        region: after-main
        template: default/content
        sort: 1
        data:
            meta:
                type: content
                route: block/byline
...


text:
//
//  ember-renderspeed
//
//  Include this script if you want to instrument your rendering speed in your Ember
//  applications.
//
//  https://github.com/eviltrout/ember-renderspeed
//
if ((typeof console !== 'undefined') && console.groupCollapsed && !window.QUnit) {

  (function () {

    /**
      Used for assembling a tree of render calls so they can be grouped and displayed
      nicely afterwards.

      @class ProfileNode
    **/
    var ProfileNode = function(start, payload) {
      this.start = start;
      this.payload = payload;
      this.children = [];
    };

    /**
      Adds a child node underneath this node.

      @method addChild
      @param {ProfileNode} node the node we want as a child
    **/
    ProfileNode.prototype.addChild = function(node) {
      this.children.push(node);
    };

    /**
      Logs this node and any children to the developer console, grouping appropriately
      for easy drilling down.

      @method log
    **/
    ProfileNode.prototype.log = function(type) {
      var description = "";
      if (this.payload) {
        if (this.payload.template) {
          description += "'" + this.payload.template + "' ";
        }

        if (this.payload.object) {
          description += this.payload.object.toString() + " ";
        }
      }
      description += (Math.round(this.time * 100) / 100).toString() + "ms";

      if (this.children.length === 0) {
        console.log(type + ": " + description);
      } else {
        // render a collapsed group when there are children
        console.groupCollapsed(type + ": " + description);
        this.children.forEach(function (c) {
          c.log(type);
        });
        console.groupEnd();
      }
    };

    // Set up our instrumentation of Ember below
    Ember.subscribe("render", {
      depth: null,

      before: function(name, timestamp, payload) {
        var node = new ProfileNode(timestamp, payload);
        if (this.depth) { node.parent = this.depth; }
        this.depth = node;

        return node;
      },

      after: function(name, timestamp, payload, profileNode) {

        if (payload.exception) {
          throw new Error(payload.exception);
        }

        profileNode.time = (timestamp - profileNode.start);
        this.depth = profileNode.parent;

        if (profileNode.time < 1) { return; }

        if (this.depth) {
          this.depth.addChild(profileNode);
        } else {
          profileNode.log("Render");
        }
      }
    });

  })();

}


text:
package com.microsoft.azure.management.datamigration.v2018_07_15_preview;

import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Database specific information for SQL to SQL migration task inputs.
 */
public class MigrateSqlServerSqlServerDatabaseInput {
    /**
     * Name of the database.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * Name of the database at destination.
     */
    @JsonProperty(value = "restoreDatabaseName")
    private String restoreDatabaseName;

    /**
     * The backup and restore folder.
     */
    @JsonProperty(value = "backupAndRestoreFolder")
    private String backupAndRestoreFolder;

    /**
     * The list of database files.
     */
    @JsonProperty(value = "databaseFiles")
    private List<DatabaseFileInput> databaseFiles;

    /**
     * Get name of the database.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set name of the database.
     *
     * @param name the name value to set
     * @return the MigrateSqlServerSqlServerDatabaseInput object itself.
     */
    public MigrateSqlServerSqlServerDatabaseInput withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get name of the database at destination.
     *
     * @return the restoreDatabaseName value
     */
    public String restoreDatabaseName() {
        return this.restoreDatabaseName;
    }

    /**
     * Set name of the database at destination.
     *
     * @param restoreDatabaseName the restoreDatabaseName value to set
     * @return the MigrateSqlServerSqlServerDatabaseInput object itself.
     */
    public MigrateSqlServerSqlServerDatabaseInput withRestoreDatabaseName(String restoreDatabaseName) {
        this.restoreDatabaseName = restoreDatabaseName;
        return this;
    }

    /**
     * Get the backup and restore folder.
     *
     * @return the backupAndRestoreFolder value
     */
    public String backupAndRestoreFolder() {
        return this.backupAndRestoreFolder;
    }

    /**
     * Set the backup and restore folder.
     *
     * @param backupAndRestoreFolder the backupAndRestoreFolder value to set
     * @return the MigrateSqlServerSqlServerDatabaseInput object itself.
     */
    public MigrateSqlServerSqlServerDatabaseInput withBackupAndRestoreFolder(String backupAndRestoreFolder) {
        this.backupAndRestoreFolder = backupAndRestoreFolder;
        return this;
    }

    /**
     * Get the list of database files.
     *
     * @return the databaseFiles value
     */
    public List<DatabaseFileInput> databaseFiles() {
        return this.databaseFiles;
    }

    /**
     * Set the list of database files.
     *
     * @param databaseFiles the databaseFiles value to set
     * @return the MigrateSqlServerSqlServerDatabaseInput object itself.
     */
    public MigrateSqlServerSqlServerDatabaseInput withDatabaseFiles(List<DatabaseFileInput> databaseFiles) {
        this.databaseFiles = databaseFiles;
        return this;
    }

}


text:
using System;

namespace Zombus.Configuration.Settings
{
    public class GlobalOutboundInterceptorTypesSetting : Setting<Type[]>
    {
        public override Type[] Default
        {
            get { return new Type[0]; }
        }
    }
}


text:
<?php namespace Anomaly\Streams\Platform\Ui\Grid\Command;

use Anomaly\Streams\Platform\Support\Evaluator;
use Anomaly\Streams\Platform\Support\Resolver;
use Anomaly\Streams\Platform\Ui\Grid\GridBuilder;

/**
 * Class SetGridOptions
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class SetGridOptions
{

    /**
     * The grid builder.
     *
     * @var GridBuilder
     */
    protected $builder;

    /**
     * Create a new SetGridOptions instance.
     *
     * @param GridBuilder $builder
     */
    public function __construct(GridBuilder $builder)
    {
        $this->builder = $builder;
    }

    /**
     * Handle the command.
     *
     * @param Resolver  $resolver
     * @param Evaluator $evaluator
     */
    public function handle(Resolver $resolver, Evaluator $evaluator)
    {
        $arguments = ['builder' => $this->builder];

        $grid = $this->builder->getGrid();

        $options = $this->builder->getOptions();

        $options = $resolver->resolve($options, $arguments);
        $options = $evaluator->evaluate($options, $arguments);

        foreach ($options as $key => $value) {
            $grid->setOption($key, $value);
        }
    }
}


text:
using System.IO;

namespace Rhino.Licensing.Tests
{
    public class BaseLicenseTest
    {
        public readonly string public_and_private;
        public readonly string public_only;
		public readonly string floating_private;
		public readonly string floating_public;

        public BaseLicenseTest()
        {
            public_and_private = new StreamReader(typeof (Can_generate_and_validate_key)
                                                      .Assembly
                                                      .GetManifestResourceStream(
                                                      "Rhino.Licensing.Tests.public_and_private.xml"))
                .ReadToEnd();

            public_only = new StreamReader(typeof (Can_generate_and_validate_key)
                                               .Assembly
                                               .GetManifestResourceStream("Rhino.Licensing.Tests.public_only.xml"))
                .ReadToEnd();

			floating_private = new StreamReader(typeof(Can_generate_and_validate_key)
											  .Assembly
											  .GetManifestResourceStream("Rhino.Licensing.Tests.floating_private.xml"))
			   .ReadToEnd();

			floating_public = new StreamReader(typeof(Can_generate_and_validate_key)
											  .Assembly
											  .GetManifestResourceStream("Rhino.Licensing.Tests.floating_public.xml"))
			   .ReadToEnd();
        }

    }
}


text:
import {
  getViewportWidth,
  getViewportHeight,
  getViewportMin,
  getViewportMax,
  getRootFontSize,
  getRootLineHeight,
  getNodeFontSize,
  getNodeLineHeight,
  getNodeSize,
} from '../_defaults'

test('should return viewport width', () => {
  expect(getViewportWidth({ window: window })).toBe(1024)
})

test('should return viewport height', () => {
  expect(getViewportHeight({ window: window })).toBe(768)
})

test('should return viewport min', () => {
  expect(getViewportMin({ window: window })).toBe(768)
})

test('should return viewport max', () => {
  expect(getViewportMax({ window: window })).toBe(1024)
})

test('should return root font size', () => {
  document.documentElement.style.fontSize = '16px'

  expect(getRootFontSize({ document: { fontSize: 24 } })).toBe(24)
  expect(getRootFontSize({ document: document })).toBe(16)
})

test('should return root line height', () => {
  document.documentElement.style.lineHeight = '16px'

  expect(getRootLineHeight({ document: { lineHeight: 24 } })).toBe(24)
  expect(getRootLineHeight({ document: document })).toBe(16)
})

test('should return node size', () => {
  const div = document.createElement('div')
  div.style.width = '250px'

  expect(getNodeSize({ node: { width: 500 }, property: 'width' })).toBe(500)
  expect(getNodeSize({ node: div, property: 'width' })).toBe(250)
})

test('should throw when trying to get node size based on unspecified property', () => {
  expect(() =>
    getNodeSize({
      node: { width: 500 },
      property: 'height',
    }),
  ).toThrow()
})

test('should return node font size', () => {
  const div = document.createElement('div')
  div.style.fontSize = '28px'

  expect(getNodeFontSize({ node: { fontSize: 18 } })).toBe(18)
  expect(getNodeFontSize({ node: div })).toBe(28)
})

test('should return node line height', () => {
  const div = document.createElement('div')
  div.style.lineHeight = '28px'

  expect(getNodeLineHeight({ node: { lineHeight: 18 } })).toBe(18)
  expect(getNodeLineHeight({ node: div })).toBe(28)
})


text:
<#
The MIT License (MIT)

Copyright (c) 2015 Objectivity Bespoke Software Specialists

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>

Import-Module -Name "$PSScriptRoot\..\..\Objectivity.TeamcityMetarunners.psd1" -Force

Describe "Get-TeamcityArrayParameter" {
    InModuleScope Objectivity.TeamcityMetarunners {
        Context "when supplied a string with escaped commas" {
            It "should return one-element array with commas" {
               $result = Get-TeamcityArrayParameter -Param 'key=value1\,va\\lue2'

               $result | Should Not Be $null
               $result.Count | Should Be 1
               $result[0] | Should Be 'key=value1,va\lue2'
            }
        }

        Context "when supplied a string with unescaped ," {
            It "should return two-element array without \n" {
               $result = Get-TeamcityArrayParameter -Param "key1=value1,key2=value2\\,key3=value3"

               $result | Should Not Be $null
               $result.Count | Should Be 3
               $result[0] | Should Be 'key1=value1'
               $result[1] | Should Be 'key2=value2\'
               $result[2] | Should Be 'key3=value3'
            }
        }

        Context "when supplied a string with \n" {
            It "should return two-element array without \n" {
               $result = Get-TeamcityArrayParameter -Param "key1=value1`nkey2=value2"

               $result | Should Not Be $null
               $result.Count | Should Be 2
               $result[0] | Should Be 'key1=value1'
               $result[1] | Should Be 'key2=value2'
            }
        }

        Context "when supplied a string with \r\n" {
            It "should return two-element array without \r\n" {
               $result = Get-TeamcityArrayParameter -Param "key1=value1`r`nkey2=value2"

               $result | Should Not Be $null
               $result.Count | Should Be 2
               $result[0] | Should Be 'key1=value1'
               $result[1] | Should Be 'key2=value2'
            }
        }
    }
}


text:
+--------------------------------------------------------------------------------------------------------------+
| Note: Google Genomics is now Cloud Life Sciences.                                                            |
| The Google Genomics Cookbook on Read the Docs is not actively                                                |
| maintained and may contain incorrect or outdated information.                                                |
| The cookbook is only available for historical reference. For                                                 |
| the most up to date documentation, view the official Cloud                                                   |
| Life Sciences documentation at https://cloud.google.com/life-sciences.                                       |
|                                                                                |
| Also note that much of the Genomics v1 API surface has been                                                  |
| superseded by `Variant Transforms <https://cloud.google.com/life-sciences/docs/how-tos/variant-transforms>`_ |
| and `htsget <https://cloud.google.com/life-sciences/docs/how-tos/reading-data-htsget>`_.                     |
+--------------------------------------------------------------------------------------------------------------+

Analyze Linkage Disequilibrium Results
======================================

.. comment: begin: goto-read-the-docs

.. container:: visible-only-on-github

   +-----------------------------------------------------------------------------------+
   | **The properly rendered version of this document can be found at Read The Docs.** |
   |                                                                                |
   | **If you are reading this on github, you should instead click** `here`__.         |
   +-----------------------------------------------------------------------------------+

.. _RenderedVersion: http://googlegenomics.readthedocs.org/en/latest/use_cases/linkage_disequilibrium/analyze_ld_results.html

__ RenderedVersion_

.. comment: end: goto-read-the-docs

.. toctree::
   :maxdepth: 2

There are several examples of interacting with LD results stored in BigQuery using Datalab in GitHub. The examples are all part of the `linkage disequilibrium project <https://github.com/googlegenomics/linkage-disequilibrium/tree/master/datalab>`_.

* Exploring `summary statistics of LD data <https://github.com/googlegenomics/linkage-disequilibrium/blob/master/datalab/Exploring_Linkage_Disequilibrium_Data.ipynb>`_.
* `Visualizing LD patterns <https://github.com/googlegenomics/linkage-disequilibrium/blob/master/datalab/Visualizing_Regional_LD.ipynb>`_ in specific genomic regions.
* Examining the rate of `LD decay <https://github.com/googlegenomics/linkage-disequilibrium/blob/master/datalab/LD_decay.ipynb>`_ as a function of distance.
* Selecting "tag variants" and visualizing `tag variant distributions <https://github.com/googlegenomics/linkage-disequilibrium/blob/master/datalab/Tag_variant_identification.ipynb>`_.


text:
package org.springframework.cloud.consul.discovery;

import java.util.Map;

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.Service;

import static org.junit.Assert.assertNull;

/**
 * @author Spencer Gibb
 */
@RunWith(SpringJUnit4ClassRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@SpringApplicationConfiguration(classes = TestPropsConfig.class)
@WebIntegrationTest(value = { "spring.application.name=myTestNotRegisteredService",
		"spring.cloud.consul.discovery.register=false"}, randomPort = true)
public class ConsulLifecycleRegistrationDisabledTests {
	@Autowired
	private ConsulClient consul;

	@Test
	public void contextLoads() {
		Response<Map<String, Service>> response = consul.getAgentServices();
		Map<String, Service> services = response.getValue();
		Service service = services.get("myTestNotRegisteredService");
		assertNull("service was registered", service);
	}
}


text:
module Algorithms
  module GraphProcessing
    class DepthFirstOrder
      def initialize(graph)
        @graph = graph
        execute
      end

      def pre
        @pre.clone
      end

      def post
        @post.clone
      end

      private

      def execute
        @marked = Array.new(@graph.size_vertices) { false }
        @pre = []
        @post = []
        @marked.each_with_index do |was_visited, v|
          r_execute(v) unless was_visited
        end
      end

      def r_execute(from)
        @pre.push(from)

        @marked[from] = true
        @graph.adjacent(from).each do |to|
          r_execute(to) unless @marked[to]
        end

        @post.push(from)
      end
    end
  end
end


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

define(function(require) {
  var Locale = require('utils/locale');
  var TemplateUtils = require('utils/template-utils');
  var VNetsTable = require('tabs/vnets-tab/datatable');

  //==============================================================================
  // VM & Service user inputs
  //==============================================================================

  return {
    'vmTemplateInsert': _generateVMTemplateUserInputs,
    'serviceTemplateInsert': _generateServiceTemplateUserInputs
  }

  // It will replace the div's html with a row for each USER_INPUTS
  // opts.text_header: header text for the text & password inputs
  // opts.network_header: header text for the network inputs
  // returns true if at least one input was inserted
  function _generateVMTemplateUserInputs(div, template_json, opts) {
    return _generateInstantiateUserInputs(
        div, template_json.VMTEMPLATE.TEMPLATE.USER_INPUTS, opts);
  }

  // It will replace the div's html with a row for each USER_INPUTS
  // opts.text_header: header text for the text & password inputs
  // opts.network_header: header text for the network inputs
  // returns true if at least one input was inserted
  function _generateServiceTemplateUserInputs(div, template_json, opts) {
    return _generateInstantiateUserInputs(
        div, template_json.DOCUMENT.TEMPLATE.BODY.custom_attrs, opts);
  }

  // It will replace the div's html with a row for each USER_INPUTS
  // opts.text_header: header text for the text & password inputs
  // opts.network_header: header text for the network inputs
  // returns true if at least one input was inserted
  function _generateInstantiateUserInputs(div, user_inputs, opts) {
    div.empty();

    if (user_inputs == undefined) {
      return false;
    }

    if (opts == undefined) {
      opts = {};
    }

    if (opts.text_header == undefined) {
      opts.text_header = Locale.tr("Custom Attributes");
    }

    if (opts.network_header == undefined) {
      opts.network_header = Locale.tr("Network");
    }

    var network_attrs = [];
    var text_attrs = [];

    $.each(user_inputs, function(key, value) {
      var parts = value.split("|");
      // 0 mandatory; 1 type; 2 desc;
      var attrs = {
        "name": key,
        "mandatory": parts[0],
        "type": parts[1],
        "description": parts[2],
      }

      switch (parts[1]) {
        case "vnet_id":
          network_attrs.push(attrs)
          break;
        case "text":
        case "text64":
        case "password":
          text_attrs.push(attrs)
          break;
      }
    });

    if (network_attrs.length > 0) {
      if (opts.network_header.length > 0) {
        div.append(
        '
' +
        '
' +
          '
' +
            '
' +
              opts.network_header +
            '
' +
          '
' +
        '
');
      }

      div.append('
');

      var separator = "";

      var vnetsTable;
      $.each(network_attrs, function(index, vnet_attr) {
        var unique_id = "user_input_" + (vnet_attr.name.replace(/ /g, "_"));
        vnetsTable = new VNetsTable(unique_id, {'select': true});

        $(".instantiate_user_inputs", div).append(
          '
' +
            '
' +
              separator +
              '
' +
                TemplateUtils.htmlDecode(vnet_attr.description) +
              '
' +
              vnetsTable.dataTableHTML +
            '
' +
          '
');

        separator = "
";

        vnetsTable.initialize();

        $('#refresh_button_' + unique_id).click();

        vnetsTable.idInput().attr("wizard_field", vnet_attr.name).attr("required", "");
      });
    }

    if (text_attrs.length > 0) {
      if (opts.text_header.length > 0) {
        div.append(
        '
' +
        '
' +
          '
' +
            '
' +
              opts.text_header +
            '
' +
          '
' +
        '
');
      }

      div.append('
');

      $.each(text_attrs, function(index, custom_attr) {
        var input;

        switch (custom_attr.type) {
          case "text":
            input = '<textarea type="text" rows="1" wizard_field="' + custom_attr.name + '" required/>';
            break;
          case "text64":
            input = '<textarea type="text" rows="1" wizard_field_64="true" wizard_field="' + custom_attr.name + '" required/>';
            break;
          case "password":
            input = '<input type="password" wizard_field="' + custom_attr.name + '" required/>';
            break;
        }

        $(".instantiate_user_inputs", div).append(
          '
' +
            '
' +
              '' +
                TemplateUtils.htmlDecode(custom_attr.description) +
                input +
              '' +
            '
' +
          '
');
      });
    }

    return (network_attrs.length > 0 || text_attrs.length > 0);
  }
})


text:
package runner

import (
	"os"
	"syscall"
)

func MustMountTmpfs(destination string) {
	if _, err := os.Stat(destination); os.IsNotExist(err) {
		must(os.MkdirAll(destination, 0755))
		must(syscall.Mount("tmpfs", destination, "tmpfs", 0, ""))
	}
}

func must(err error) {
	if err != nil {
		panic(err)
	}
}


text:
function Z = jacobiansparsityfromnonlinear(model)

    m = length(model.lb);
    allA=[model.Anonlinineq; model.Anonlineq];
    jacobianstructure = spalloc(size(allA,1),m,0);
    depends = allA | allA;
    for i = 1:size(depends,1)
        vars = find(depends(i,:));
        [ii,vars] = find(model.deppattern(vars,:));
        vars = unique(vars);
        s = size(jacobianstructure,1);
        for j = 1:length(vars)
            jacobianstructure(i,find(vars(j) == model.linearindicies)) = 1;
        end
    end
    allA=[model.A; model.Aeq];
    depends = allA | allA;
    jacobianstructure = [jacobianstructure;depends];

    Z = sparse(jacobianstructure);


text:
<?php

namespace Magento\Framework\Model\Test\Unit\ResourceModel\Db\Relation;

use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;

class ActionPoolTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\Model\ResourceModel\Db\Relation\ActionPool
     */
    protected $model;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $objectManagerMock;

    protected function setUp()
    {
        $this->objectManagerMock = $this->getMockBuilder('Magento\Framework\ObjectManagerInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $objectManager = new ObjectManager($this);

        $entityType = 'Entity_Test';
        $actionName = ['Test_Read' => ['Test_Class']];

        $relationActions = [$entityType => $actionName];
        $this->model = $objectManager->getObject(
            'Magento\Framework\Model\ResourceModel\Db\Relation\ActionPool',
            [
                'objectManager' => $this->objectManagerMock,
                'relationActions' => $relationActions
            ]
        );
    }

    public function testGetActionsNoAction()
    {
        $this->assertEmpty($this->model->getActions('test', 'test'));
    }

    public function testGetActions()
    {
        $this->objectManagerMock->expects($this->once())
            ->method('get')
            ->with('Test_Class')
            ->willReturn(new \stdClass());
        $this->assertNotEmpty($this->model->getActions('Entity_Test', 'Test_Read'));
    }
}


text:
<?php

namespace PWE\Utils;

use PWE\Core\PWEURL;

require_once __DIR__ . '/../../PWEUnitTests.php';

class PWEUtilsTest extends \PHPUnit_Framework_TestCase
{

    public function testProtectAgainsRelativePaths_1()
    {
        $path = "somedir/./subdir/../test.php";
        $expected = "somedir/test.php";
        $res = FilesystemHelper::protectAgainsRelativePaths($path);
        $this->assertEquals($expected, $res);
    }

    public function testProtectAgainsRelativePaths_2()
    {
        $path = "somedir/./subdir/../../test.php";
        $expected = "test.php";
        $res = FilesystemHelper::protectAgainsRelativePaths($path);
        $this->assertEquals($expected, $res);
    }

    public function testProtectAgainsRelativePaths_3()
    {
        $path = "/somedir/./subdir/../test.php";
        $expected = "/somedir/test.php";
        $res = FilesystemHelper::protectAgainsRelativePaths($path);
        $this->assertEquals($expected, $res);
    }

}