text:
layout: post
id: 2022-02-18-exposing-kafka-cluster
title: Exposing a Kafka Cluster via a VPC Endpoint Service
date: 2022-02-18 00:20:00
authors: [fabrice-harbulot]
categories: [Engineering]
tags: [Engineering, Cloud, Kafka]
comments: true
cover_photo: /img/exposing-kafka-cluster/cover.jpg
excerpt: "Establishing communications between cloud resources that are hosted on different Virtual Private Clouds (VPC) can be complex and costly. Find out how the Coban team used a VPC Endpoint Service to expose an Apache Kafka cluster across multiple Availability Zones to a different VPC."
---
In large organisations, it is a common practice to isolate the cloud resources of different verticals. Amazon Web Services (AWS) Virtual Private Cloud (VPC) is a convenient way of doing so. At Grab, while our core AWS services reside in a main VPC, a number of Grab Tech Families (TFs) have their own dedicated VPC. One such example is [GrabKios](https://www.grab.com/id/kios/). Previously known as "Kudo", GrabKios was acquired by Grab in 2017 and has always been residing in its own AWS account and dedicated VPC.

In this article, we explore how we exposed an Apache Kafka cluster across multiple Availability Zones (AZs) in Grab's main VPC, to producers and consumers residing in the GrabKios VPC, via a [VPC Endpoint Service](https://docs.aws.amazon.com/vpc/latest/privatelink/endpoint-service.html). This design is part of Coban unified stream processing platform at Grab.

There are several ways of enabling communication between applications across distinct VPCs; VPC peering is the most straightforward and affordable option. However, it potentially exposes the entire VPC networks to each other, needlessly increasing the attack surface.

Security has always been one of Grab's top concerns and with Grab's increasing growth, there is a need to deprecate VPC peering and shift to a method of only exposing services that require remote access. The AWS VPC Endpoint Service allows us to do exactly that for TCP/IPv4 communications within a single [AWS region](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/).

Setting up a VPC Endpoint Service compared to VPC peering is already relatively complex. On top of that, we need to expose an Apache Kafka cluster via such an endpoint, which comes with an extra challenge. Apache Kafka requires clients, called producers and consumers, to be able to deterministically establish a TCP connection to all [brokers](https://jaceklaskowski.gitbooks.io/apache-kafka/content/kafka-brokers.html) forming the cluster, not just any one of them.

Last but not least, we need a design that optimises performance and cost by limiting data transfer across AZs.

*Note: **All** variable names, port numbers and other details used in this article are only used as examples.*

## Architecture overview

As shown in this diagram, the Kafka cluster resides in the service provider VPC (Grab's main VPC) while local Kafka producers and consumers reside in the service consumer VPC (GrabKios VPC).

In Grab's main VPC, we created a Network Load Balancer (NLB) and set it up across all three AZs, enabling cross-zone load balancing. We then created a VPC Endpoint Service associated with that NLB.

Next, we created a VPC Endpoint Network Interface in the GrabKios VPC, also set up across all three AZs, and attached it to the remote VPC endpoint service in Grab's main VPC. Apart from this, we also created a Route 53 Private Hosted Zone `.grab` and a CNAME record `kafka.grab` that points to the VPC Endpoint Network Interface hostname.

Lastly, we configured producers and consumers to use `kafka.grab:10000` as their Kafka bootstrap server endpoint, `10000/tcp` being an arbitrary port of our choosing. We will explain the significance of these in later sections.

## Network Load Balancer setup

On the NLB in Grab's main VPC, we set up the corresponding bootstrap listener on port `10000/tcp`, associated with a target group containing all of the Kafka brokers forming the cluster. But this listener alone is not enough.

As mentioned earlier, Apache Kafka requires producers and consumers to be able to deterministically establish a TCP connection to all brokers. That's why we created one listener for every broker in the cluster, incrementing the TCP port number for each new listener, so each broker endpoint would have the same name but with different port numbers, e.g. `kafka.grab:10001` and `kafka.grab:10002`.

We then associated each listener with a dedicated target group containing only the targeted Kafka broker, so that remote producers and consumers could differentiate between the brokers by their TCP port number.

The following listeners and associated target groups were set up on the NLB:

*   `10000/tcp` (bootstrap) -> `9094/tcp` @ [broker 101, broker 201, broker 301]
*   `10001/tcp` -> `9094/tcp` @ [broker 101]
*   `10002/tcp` -> `9094/tcp` @ [broker 201]
*   `10003/tcp` -> `9094/tcp` @ [broker 301]

## Security Group rules

In the Kafka brokers' Security Group (SG), we added an ingress SG rule allowing `9094/tcp` traffic from each of the three private IP addresses of the NLB. As mentioned earlier, the NLB was set up across all three AZs, with each having its own private IP address.

On the GrabKios VPC (consumer side), we created a new SG and attached it to the VPC Endpoint Network Interface. We also added ingress rules to allow all producers and consumers to connect to `tcp/10000-10003`.

## Kafka setup

Kafka brokers typically come with a listener on port `9092/tcp`, advertising the brokers by their private IP addresses. We kept that default listener so that local producers and consumers in Grab's main VPC could still connect directly.

```
$ kcat -L -b 10.0.0.1:9092
 3 brokers:
 broker 101 at 10.0.0.1:9092 (controller)
 broker 201 at 10.0.0.2:9092
 broker 301 at 10.0.0.3:9092
... truncated output ...
```

We also configured all brokers with an additional listener on port `9094/tcp` that advertises the brokers by:

*   Their shared private name `kafka.grab`.
*   Their distinct TCP ports previously set up on the NLB's dedicated listeners.

```
$ kcat -L -b 10.0.0.1:9094
 3 brokers:
 broker 101 at kafka.grab:10001 (controller)
 broker 201 at kafka.grab:10002
 broker 301 at kafka.grab:10003
... truncated output ...
```

Note that there is a difference in how the broker's endpoints are advertised in the two outputs above. The latter enables connection to any particular broker from the GrabKios VPC via the VPC Endpoint Service.

It would definitely be possible to advertise the brokers directly with the remote VPC Endpoint Interface hostname instead of `kafka.grab`, but relying on such a private name presents at least two advantages.

First, it decouples the Kafka deployment in the service provider VPC from the infrastructure deployment in the service consumer VPC. Second, it makes the Kafka cluster easier to expose to other remote VPCs, should we need it in the future.

## Limiting data transfer across Availability Zones

At this stage of the setup, our Kafka cluster is **fully reachable** from producers and consumers in the GrabKios VPC. Yet, the design is not optimal.

When a producer or a consumer in the GrabKios VPC needs to connect to a particular broker, it uses its individual endpoint made up of the shared name `kafka.grab` and the broker's dedicated TCP port.

The shared name arbitrarily resolves into one of the three IP addresses of the VPC Endpoint Network Interface, one for each AZ.

Hence, there is a fair chance that the obtained IP address is neither in the client's AZ nor in that of the target Kafka broker. The probability of this happening can be as high as 2/3 when both client and broker reside in the same AZ and 1/3 when they do not.

While that is of little concern for the initial bootstrap connection, it becomes a serious drawback for actual data transfer, impacting the performance and incurring unnecessary data transfer cost.

For this reason, we created **three additional** CNAME records in the Private Hosted Zone in the GrabKios VPC, one for each AZ, with each pointing to the VPC Endpoint Network Interface zonal hostname in the corresponding AZ:

*   `kafka-az1.grab`
*   `kafka-az2.grab`
*   `kafka-az3.grab`

Note that we used az1, az2, az3 instead of the typical AWS 1a, 1b, 1c suffixes, because the latter's mapping is not consistent across AWS accounts.

We also reconfigured each Kafka broker in Grab's main VPC by setting their `9094/tcp` listener to advertise brokers by their new zonal private names.

```
$ kcat -L -b 10.0.0.1:9094
 3 brokers:
 broker 101 at kafka-az1.grab:10001 (controller)
 broker 201 at kafka-az2.grab:10002
 broker 301 at kafka-az3.grab:10003
... truncated output ...
```

Our private zonal names are shared by all brokers in the same AZ while TCP ports remain distinct for each broker. However, this is not clearly shown in the output above because our cluster only counts three brokers, one in each AZ.

The previous common name `kafka.grab` remains in the GrabKios VPC's Private Hosted Zone and allows connections to any broker via an arbitrary, likely non-optimal route. GrabKios VPC producers and consumers still use that highly-available endpoint to initiate bootstrap connections to the cluster.

## Future improvements

For this setup, scalability is our main challenge. If we add a new broker to this Kafka cluster, we would need to:

*   Assign a new TCP port number to it.
*   Set up a new dedicated listener on that TCP port on the NLB.
*   Configure the newly spun up Kafka broker to advertise its service with the same TCP port number and the private zonal name corresponding to its AZ.
*   Add the new broker to the target group of the bootstrap listener on the NLB.
*   Update the network SG rules on the service consumer side to allow connections to the newly allocated TCP port.

We rely on Terraform to dynamically deploy all AWS infrastructure and on Jenkins and Ansible to deploy and configure Apache Kafka. There is limited overhead but there are still a few manual actions due to a lack of integration. These include transferring newly allocated TCP ports and their corresponding EC2 instances' IP addresses to our Ansible inventory, commit them to our codebase and trigger a Jenkins job deploying the new Kafka broker.

Another concern of this setup is that it is only applicable for AWS. As we are aiming to be multi-cloud, we may need to port it to Microsoft Azure and leverage the [Azure Private Link service](https://docs.microsoft.com/en-us/azure/private-link/private-link-service-overview).

In both cases, running Kafka on Kubernetes with the Strimzi operator would be helpful in addressing the scalability challenge and reducing our adherence to one particular cloud provider. We will explain how this solution has helped us address these challenges in a future article.

---

Special thanks to David Virgil Naranjo whose [blog post](https://dvirgiln.github.io/exposing-kafka-throw-different-aws-vpcs/) inspired this work.

---

## Join us

Grab is a leading superapp in Southeast Asia, providing everyday services that matter to consumers. More than just a ride-hailing and food delivery app, Grab offers a wide range of on-demand services in the region, including mobility, food, package and grocery delivery services, mobile payments, and financial services across over 400 cities in eight countries.

Powered by technology and driven by heart, our mission is to drive Southeast Asia forward by creating economic empowerment for everyone. If this mission speaks to you, [join our team](https://grab.careers/) today!


text:
static ABAddressBookRef shared = NULL;

@implementation ABStandin
// Return the current shared address book,
// Creating if needed
+ (ABAddressBookRef) addressBook
{
    @synchronized (self) {
        if (!shared) {
            if (ABAddressBookCreateWithOptions == NULL) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
                shared = ABAddressBookCreate();
#pragma clang diagnostic pop
            } else {
                shared = ABAddressBookCreateWithOptions(NULL, NULL);
            }
            if (![self hasAddressBookAccess:shared]) {
                //TODO: show beautiful alert
                shared = NULL;
            }
        }
    }
    return shared;
}

// Load the current address book
+ (ABAddressBookRef) currentAddressBook
{
    if (shared)
    {
        CFRelease(shared);
        shared = nil;
    }

    return [self addressBook];
}

// Thanks Frederic Bronner
// Save the address book out
+ (BOOL) save: (NSError **) error
{
    CFErrorRef cfError;
    if (shared)
    {
        BOOL success = ABAddressBookSave(shared, &cfError);
        if (!success)
        {
            if (error)
                *error = (__bridge_transfer NSError *)cfError;
            return NO;
        }
        return YES;
    }
    return NO;
}

+ (BOOL)hasAddressBookAccess:(ABAddressBookRef)addressBook {
    if (ABAddressBookRequestAccessWithCompletion == NULL) {
        // before iOS 6
        return YES;
    }
    // iOS 6 and more
    __block BOOL accessGranted = NO;

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        accessGranted = granted;
        if(semaphore) {
            dispatch_semaphore_signal(semaphore);
        }
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_release(semaphore);
    semaphore = NULL;

    return accessGranted;
}
@end

redpajama_set_name: RedPajamaGithub


text:
[assembly: Microsoft.Owin.OwinStartupAttribute(typeof(GiveawayApp.Startup))]

namespace GiveawayApp
{
    using Microsoft.AspNet.SignalR;
    using Microsoft.AspNet.SignalR.Infrastructure;
    using Owin;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Specify that UserId should be pull from the IIdentity.Name
            GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new PrincipalUserIdProvider());
            app.MapSignalR();
        }
    }
}


text:
advisory: swarm-standalone
hide_from_sitemap: true
description: Provision with Machine
keywords: docker, Swarm, clustering, provision, Machine
title: Provision a Swarm cluster with Docker Machine
---

You can use Docker Machine to provision a Docker Swarm cluster. Machine is the
Docker provisioning tool. Machine provisions the hosts, installs Docker Engine
on them, and then configures the Docker CLI client. With Machine's Swarm
options, you can also quickly configure a Swarm cluster as part of this
provisioning.

This page explains the commands you need to provision a basic Swarm cluster on a
local Mac or Windows computer using Machine. Once you understand the process,
you can use it to setup a Swarm cluster on a cloud provider, or inside your
company's data center.

If this is the first time you are creating a Swarm cluster, you should first
learn about Swarm and its requirements by
[installing a Swarm for evaluation](install-w-machine.md) or
[installing a Swarm for production](install-manual.md). If this is the first
time you have used Machine, you should take some time to
[understand Machine before continuing](/machine).

## What you need

If you are using macOS or Windows and have installed with Docker Toolbox, you
should already have Machine installed. If you need to install, see the
instructions for [macOS](/docker-for-mac/) or
[Windows](/docker-for-windows/).

Machine supports installing on AWS, Digital Ocean, Google Cloud Platform, IBM
Softlayer, Microsoft Azure and Hyper-V, OpenStack, Rackspace, VirtualBox, VMware
Fusion®, vCloud® AirTM and vSphere®.  In this example,
you'll use VirtualBox to run several VMs based on the `boot2docker.iso` image.
This image is a small-footprint Linux distribution for running Engine.

The Toolbox installation gives you VirtualBox and the `boot2docker.iso` image
you need. It also gives you the ability provision on all the systems Machine
supports.

**Note**:These examples assume you are using macOS or Windows, if you like you can also
[install Docker Machine directly on a Linux system](/machine/install-machine).

## Provision a host to generate a Swarm token

Before you can configure a Swarm, you start by provisioning a host with Engine.
Open a terminal on the host where you installed Machine. Then, to provision a
host called `local`, do the following:

```
docker-machine create -d virtualbox local
```

This examples uses VirtualBox but it could easily be DigitalOcean or a host on
your data center. The `local` value is the host name. Once you create it,
configure your terminal's shell environment to interact with the `local` host.

```
eval "$(docker-machine env local)"
```

Each Swarm host has a token installed into its Engine configuration. The token
allows the Swarm discovery backend to recognize a node as belonging to a
particular Swarm cluster. Create the token for your cluster by running the
`swarm` image:

```
docker run swarm create
Unable to find image 'swarm' locally
1.1.0-rc2: Pulling from library/swarm
892cb307750a: Pull complete
fe3c9860e6d5: Pull complete
cc01ef3f1fbc: Pull complete
b7e14a9c9c72: Pull complete
3ec746117013: Pull complete
703cb7acfce6: Pull complete
d4f6bb678158: Pull complete
2ad500e1bf96: Pull complete
Digest: sha256:f02993cd1afd86b399f35dc7ca0240969e971c92b0232a8839cf17a37d6e7009
Status: Downloaded newer image for swarm
0de84fa62a1d9e9cc2156111f63ac31f
```

The output of the `swarm create` command is a cluster token. Copy the token to a
safe place you will remember. Once you have the token, you can provision the
Swarm nodes and join them to the cluster_id.  The rest of this documentation,
refers to this token as the `SWARM_CLUSTER_TOKEN`.

## Provision Swarm nodes

All Swarm nodes in a cluster must have Engine installed. With Machine and the
`SWARM_CLUSTER_TOKEN` you can provision a host with Engine and configure it as a
Swarm node with one Machine command. To create a Swarm manager node on a new VM
called `swarm-manager`, you do the following:

```
docker-machine create \
    -d virtualbox \
    --swarm \
    --swarm-master \
    --swarm-discovery token://SWARM_CLUSTER_TOKEN \
    swarm-manager
```

Then, provision an additional node. You must supply the
`SWARM_CLUSTER_TOKEN` and a unique name for each host node, `HOST_NODE_NAME`.

```
docker-machine create \
    -d virtualbox \
    --swarm \
    --swarm-discovery token://SWARM_CLUSTER_TOKEN \
    HOST_NODE_NAME
```

For example, you might use `node-01` as the `HOST_NODE_NAME` in the previous
example.

>**Note**: These command rely on Docker Swarm's hosted discovery service, Docker
Hub. If Docker Hub or your network is having issues, these commands may fail.
Check the [Docker Hub status page](http://status.docker.com/) for service
availability. If the problem Docker Hub, you can wait for it to recover or
configure other types of discovery backends.

## Connect node environments with Machine

If you are connecting to typical host environment with Machine, you use the
`env` subcommand, like this:

```
eval "$(docker-machine env local)"
```

Docker Machine provides a special `--swarm` flag with its `env` command to
connect to Swarm nodes.

```bash
docker-machine env --swarm HOST_NODE_NAME
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.101:3376"
export DOCKER_CERT_PATH="/Users/mary/.docker/machine/machines/swarm-manager"
export DOCKER_MACHINE_NAME="swarm-manager"
# Run this command to configure your shell:
# eval $(docker-machine env --swarm HOST_NODE_NAME)
```

To set your SHELL connect to a Swarm node called `swarm-manager`, you would do
this:

```
eval "$(docker-machine env --swarm swarm-manager)"
```

Now, you can use the Docker CLI to query and interact with your cluster.

```bash
docker info
Containers: 2
Images: 1
Role: primary
Strategy: spread
Filters: health, port, dependency, affinity, constraint
Nodes: 1
 swarm-manager: 192.168.99.101:2376
  └ Status: Healthy
  └ Containers: 2
  └ Reserved CPUs: 0 / 1
  └ Reserved Memory: 0 B / 1.021 GiB
  └ Labels: executiondriver=native-0.2, kernelversion=4.1.13-boot2docker, operatingsystem=Boot2Docker 1.9.1 (TCL 6.4.1); master : cef800b - Fri Nov 20 19:33:59 UTC 2015, provider=virtualbox, storagedriver=aufs
CPUs: 1
Total Memory: 1.021 GiB
Name: swarm-manager
```

## Related information

* [Evaluate Swarm in a sandbox](install-w-machine.md)
* [Build a Swarm cluster for production](install-manual.md)
* [Swarm Discovery](discovery.md)
* [Docker Machine](/machine/index.md) documentation


text:
require 'ppds/class_factory'
require 'rest_client'
require 'xml'

module Ppds
  class Photo < ClassFactory
    attr_accessor :id, :secret, :server, :farm, :title, :owner, :username,
                  :ispublic, :isfriend, :isfamily, :dateupload, :iconserver,
                  :iconfarm, :license
  end

  class Flickr
    API_URL = 'http://api.flickr.com/services/rest'
    API_KEY = '0282f93eb6da0425310bd5791f4c2fc0'

    attr_accessor :photos

    def initialize
    end

    def query(action, data)
      data.update({
        :api_key => API_KEY,
        :method  => action
      })
      RestClient.post(API_URL, data)
    rescue RestClient::RequestFailed
      raise 'Query failed: %s' % $!
    rescue RestClient::RequestTimeout
      raise 'Timeout occured'
    rescue Exception
      raise $!
    end

    def update(qty)
      data = {
        :extras       => 'date_upload,icon_server,license',
        :count        => qty,
        :user_id      => $cfg.get(:nsid).to_s,
        :single_photo => $cfg.get(:one_per_contact) ? 1 : 0,
        :just_friends => $cfg.get(:only_from_friends) ? 1 : 0,
        :include_self => $cfg.get(:include_self) ? 1 : 0
      }
      xml = query('flickr.photos.getContactsPublicPhotos', data)
      @xml = XML::Parser.string(xml).parse
      self.photos = @xml.find('//photos/photo').map do |node|
        Photo.new(node.attributes)
      end
    end
  end
end


text:
var User       = require('../models/user')
var Group      = require('../models/group')
var Membership = require('../models/membership')
var School     = require('../models/school')
var Jobs       = require('../models/jobs')
var Companies  = require('../models/companies')
var Utils      = require('./utils')

exports.mount = function (app) {

	app.get('/API/jobs', function(req, res){
		Jobs.retrieveAll(function(x){res.send({Jobs: x})
    })
  });

	app.post('/API/jobs', function(req, res){
		console.log(req.body, "jobsAPI")
		if (!req.body) return res.sendStatus(400)
			var newValues = Jobs.updateOrCreate(req.body)
		res.send(req.body)
	});

}


text:
package products

import (
	"github.com/apigee/apigeecli/apiclient"
	"github.com/apigee/apigeecli/client/products"
	"github.com/spf13/cobra"
)

//ExpCmd to export products
var ExpCmd = &cobra.Command{
	Use:   "export",
	Short: "Export API products to a file",
	Long:  "Export API products to a file",
	Args: func(cmd *cobra.Command, args []string) (err error) {
		return apiclient.SetApigeeOrg(org)
	},
	RunE: func(cmd *cobra.Command, args []string) (err error) {
		const exportFileName = "products.json"
		payload, err := products.Export(conn)
		if err != nil {
			return
		}
		return apiclient.WriteArrayByteArrayToFile(exportFileName, false, payload)
	},
}

func init() {

	ExpCmd.Flags().IntVarP(&conn, "conn", "c",
		4, "Number of connections")
}


text:
package com.google.cloud.bigtable.data.v2.it;

import static com.google.common.truth.Truth.assertThat;

import com.google.api.gax.batching.Batcher;
import com.google.api.gax.rpc.ServerStream;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.Query;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowCell;
import com.google.cloud.bigtable.data.v2.models.RowMutationEntry;
import com.google.cloud.bigtable.test_helpers.env.TestEnvRule;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.ByteString;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class RowMutationEntryBatcherIT {

  @ClassRule public static TestEnvRule testEnvRule = new TestEnvRule();

  @Test
  public void testNewBatcher() throws Exception {
    BigtableDataClient client = testEnvRule.env().getDataClient();
    String tableId = testEnvRule.env().getTableId();
    String family = testEnvRule.env().getFamilyId();
    String rowPrefix = UUID.randomUUID().toString();

    try (Batcher<RowMutationEntry, Void> batcher = client.newBulkMutationBatcher(tableId)) {
      for (int i = 0; i < 10; i++) {
        batcher.add(
            RowMutationEntry.create(rowPrefix + "-" + i)
                .setCell(family, "qualifier", 10_000L, "value-" + i));
      }
    }

    List<Row> expectedRows = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      expectedRows.add(
          Row.create(
              ByteString.copyFromUtf8(rowPrefix + "-" + i),
              ImmutableList.of(
                  RowCell.create(
                      family,
                      ByteString.copyFromUtf8("qualifier"),
                      10_000L,
                      ImmutableList.<String>of(),
                      ByteString.copyFromUtf8("value-" + i)))));
    }
    ServerStream<Row> actualRows = client.readRows(Query.create(tableId).prefix(rowPrefix));

    assertThat(actualRows).containsExactlyElementsIn(expectedRows);
  }
}


text:
package com.sfl.pms.services.payment.customer.method.exception;

import com.sfl.pms.services.common.exception.ServicesRuntimeException;
import com.sfl.pms.services.payment.customer.method.model.CustomerPaymentMethodType;

/**
 * User: Ruben Dilanyan
 * Company: SFL LLC
 * Date: 1/15/15
 * Time: 5:15 PM
 */
public class UnknownCustomerPaymentMethodException extends ServicesRuntimeException {
    private static final long serialVersionUID = -1758959561331372821L;

    /* Properties */
    private final CustomerPaymentMethodType customerPaymentMethodType;

    /* Constructors */
    public UnknownCustomerPaymentMethodException(final CustomerPaymentMethodType customerPaymentMethodType) {
        super("Unknown customer payment method type - " + customerPaymentMethodType);
        this.customerPaymentMethodType = customerPaymentMethodType;
    }

    /* Properties getters and setters */
    public CustomerPaymentMethodType getCustomerPaymentMethodType() {
        return customerPaymentMethodType;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:ignore="MissingPrefix"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/relative"
        android:layout_width="match_parent"
        android:layout_height="310dp"
        android:gravity="center">

        <ImageView
            android:id="@+id/blurredBackGroundImage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:weightSum="1"
>

            <ImageView
                android:id="@+id/backGroundImage"
                android:src="@drawable/abc_btn_radio_material"
                android:layout_width="190dp"
                android:layout_height="0dp"
                android:layout_weight="0.85"
                android:layout_gravity="center_horizontal"
                />

            <TextView
                android:id="@+id/item_title"
                android:layout_width="fill_parent"
                android:layout_height="0dp"
                android:layout_weight="0.15"
                android:layout_alignBottom="@+id/relative"
                android:gravity="center"
                android:background="#CF222222"
                android:text="Unfinished symphaty"
                android:textColor="#DEDEDE"
                android:textSize="17dp"
                />

        </LinearLayout>

    </RelativeLayout>

</RelativeLayout>


text:
#import "AppDelegate.h"

extern NSString* const UIApplicationRegisterUserNotificationSettings;

@interface AppDelegate (APPAppEvent)

@end


text:
package org.apereo.openlrs.services.caliper;

import org.apache.log4j.Logger;
import org.apereo.openlrs.model.caliper.CaliperEvent;
import org.apereo.openlrs.services.EventService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

/**
 * @author ggilbert
 *
 */
@Service
@Profile({"redis","mongo"})
public class CaliperService extends EventService {

	private Logger log = Logger.getLogger(CaliperService.class);

	public void post(String organizationId, CaliperEvent caliperEvent) {
    	if (log.isDebugEnabled()) {
    		log.debug(String.format("Caliper event: %s",caliperEvent));
    	}

        getTierOneStorage().save(caliperEvent);
	}

}


text:
"""Service details and instances for the Contacts service.

Some use cases:
Add contacts:
  contacts add "Bob Smith, bob@smith.com" "Jim Raynor, jimmy@noreaster.com"

List contacts:
  contacts list title,email

"""
from __future__ import with_statement

__author__ = 'tom.h.miller@gmail.com (Tom Miller)'
import logging
import os.path
import googlecl.contacts

LOG = logging.getLogger(googlecl.contacts.LOGGER_NAME + '.base')

class ContactsBaseCL(object):
  """Class inherited by either ContactsServiceCL or ContactsClientCL. """

  def add_contacts(self, contacts):
    """Add contact(s).

    Args:
      contacts: Contact(s) to add. This is either a path to a CSV with
          contact information, or a list of comma separated contact data.
    """
    successes = []
    for contact in contacts:
      if os.path.exists(contact):
        with open(contact, 'r') as contacts_csv_file:
          for line in contacts_csv_file:
            entry = self.add_single_contact(line)
            if entry:
              successes.append(entry)
      else:
        entry = self.add_single_contact(contact)
        if entry:
          successes.append(entry)
    return successes

  AddContacts = add_contacts

  def add_single_contact(self, contact_string, delimiter=',',
                         fields=('name', 'email')):
    """Add contact.

    Args:
      contact_string: String representing fields of a contact to add.
      delimiter: Delimiter for fields in the contact string. Default ','
      fields: Fields contained in the contact string. Default ('name', 'email')

    Returns:
      ContactEntry with fields filled in, or None if the contact string did not
      contain the data described by fields.
    """
    num_fields = len(fields)
    values = contact_string.split(delimiter, num_fields)
    if num_fields != len(values):
      LOG.error('String did not have correct number of fields!')
      LOG.debug('Expected fields %s', fields)
      LOG.debug('Got string %s', contact_string)
      return None
    new_contact = self._get_contact_entry()
    for i in range(num_fields):
      if fields[i] == 'name':
        self._add_name(values[i].strip(), new_contact)
      elif fields[i] == 'email':
        self._add_email(values[i].strip(), new_contact)
    return self.CreateContact(new_contact)

  AddSingleContact = add_single_contact


text:
Comments = new Mongo.Collection('comments');

Meteor.methods({
  commentInsert: function(commentAttributes) {
    check(this.userId, String);
    check(commentAttributes, {
      postId: String,
      body: String
    });
    var user = Meteor.user();
    var post = Posts.findOne(commentAttributes.postId);
    if(!post)
      throw new Meteor.Error('invalid-comment', 'You must comment on a post');
    comment = _.extend(commentAttributes, {
      userId: user._id,
      author: user.username,
      submitted: new Date()
    });

    Posts.update(comment.postId, {$inc: {commentsCount: 1}})

    comment._id = Comments.insert(comment);

    createCommentNotification(comment);
    return comment._id;
  }
})


text:
void OSCBundle()
{
    auto consumer1 = MessageConsumer("/C1");
    auto consumer2 = MessageConsumer("/C2");

    auto OSC = OSC::Arduino<2, 0>();
    OSC.addConsumer(&consumer1);
    OSC.addConsumer(&consumer2);

    auto Udp = UDP();

    std::string testString = "#bundle_\x1\x2\x3\x4\x5\x6\x7\x8___\x20/C1_,iiiii_____\x1___\x2___\x3___\x4___\x5___\x20/C2_,iiiii_____\x6___\x7___\x8___\x9___\xa";
    int length = testString.length();

    Udp.write(testString.c_str(), length);
    Udp.normalizeBuffer();

    OSC.bindUDP(&Udp, 0, 0);

    OSC.loop();

    TEST_ASSERT_TRUE(consumer1.callbackCalled);
    TEST_ASSERT_TRUE(consumer2.callbackCalled);

    TEST_ASSERT_EQUAL_INT32(1, consumer1._message.messageStruct.int1);
    TEST_ASSERT_EQUAL_INT32(2, consumer1._message.messageStruct.int2);
    TEST_ASSERT_EQUAL_INT32(3, consumer1._message.messageStruct.int3);
    TEST_ASSERT_EQUAL_INT32(4, consumer1._message.messageStruct.int4);
    TEST_ASSERT_EQUAL_INT32(5, consumer1._message.messageStruct.int5);

    TEST_ASSERT_EQUAL_INT32(6, consumer2._message.messageStruct.int1);
    TEST_ASSERT_EQUAL_INT32(7, consumer2._message.messageStruct.int2);
    TEST_ASSERT_EQUAL_INT32(8, consumer2._message.messageStruct.int3);
    TEST_ASSERT_EQUAL_INT32(9, consumer2._message.messageStruct.int4);
    TEST_ASSERT_EQUAL_INT32(10, consumer2._message.messageStruct.int5);
}

void OSCSingleBundle()
{
    auto consumer1 = MessageConsumer("/C1");
    auto consumer2 = MessageConsumer("/C2");

    auto OSC = OSC::Arduino<2, 0>();
    OSC.addConsumer(&consumer1);
    OSC.addConsumer(&consumer2);

    auto Udp = UDP();

    std::string testString = "#bundle_\x1\x2\x3\x4\x5\x6\x7\x8___\x20/C1_,iiiii_____\x1___\x2___\x3___\x4___\x5";
    int length = testString.length();

    Udp.write(testString.c_str(), length);
    Udp.normalizeBuffer();

    OSC.bindUDP(&Udp, 0, 0);

    OSC.loop();

    TEST_ASSERT_TRUE(consumer1.callbackCalled);
    TEST_ASSERT_FALSE(consumer2.callbackCalled);

    TEST_ASSERT_EQUAL_INT32(1, consumer1._message.messageStruct.int1);
    TEST_ASSERT_EQUAL_INT32(2, consumer1._message.messageStruct.int2);
    TEST_ASSERT_EQUAL_INT32(3, consumer1._message.messageStruct.int3);
    TEST_ASSERT_EQUAL_INT32(4, consumer1._message.messageStruct.int4);
    TEST_ASSERT_EQUAL_INT32(5, consumer1._message.messageStruct.int5);
}

void OSCEmptyBundle()
{
    auto consumer1 = MessageConsumer("/C1");
    auto consumer2 = MessageConsumer("/C2");

    auto OSC = OSC::Arduino<2, 0>();
    OSC.addConsumer(&consumer1);
    OSC.addConsumer(&consumer2);

    auto Udp = UDP();

    std::string testString = "#bundle_\x1\x2\x3\x4\x5\x6\x7\x8___\x0";
    int length = testString.length();

    Udp.write(testString.c_str(), length);
    Udp.normalizeBuffer();

    OSC.bindUDP(&Udp, 0, 0);

    OSC.loop();

    TEST_ASSERT_FALSE(consumer1.callbackCalled);
    TEST_ASSERT_FALSE(consumer2.callbackCalled);
}

void OSCErrorBundle()
{
    auto consumer1 = MessageConsumer("/C1");
    auto consumer2 = MessageConsumer("/C2");

    auto OSC = OSC::Arduino<2, 0>();
    OSC.addConsumer(&consumer1);
    OSC.addConsumer(&consumer2);

    auto Udp = UDP();

    std::string testString = "#bundle_\x1\x2\x3\x4\x5\x6\x7\x8___\x20/C1_,iiiii_____\x1___\x2___\x3___\x4___\x5___\x20";
    int length = testString.length();

    Udp.write(testString.c_str(), length);
    Udp.normalizeBuffer();

    OSC.bindUDP(&Udp, 0, 0);

    OSC.loop();

    TEST_ASSERT_TRUE(consumer1.callbackCalled);
    TEST_ASSERT_FALSE(consumer2.callbackCalled);

    TEST_ASSERT_EQUAL_INT32(1, consumer1._message.messageStruct.int1);
    TEST_ASSERT_EQUAL_INT32(2, consumer1._message.messageStruct.int2);
    TEST_ASSERT_EQUAL_INT32(3, consumer1._message.messageStruct.int3);
    TEST_ASSERT_EQUAL_INT32(4, consumer1._message.messageStruct.int4);
    TEST_ASSERT_EQUAL_INT32(5, consumer1._message.messageStruct.int5);
}

void process()
{
    UNITY_BEGIN();

    RUN_TEST(OSCBundle);
    RUN_TEST(OSCSingleBundle);
    RUN_TEST(OSCEmptyBundle);
    RUN_TEST(OSCErrorBundle);

    UNITY_END();
}

int main(int argc, char **argv)
{
    process();
    return 0;
}


text:
package us.kbase.expressionservices;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: GseObject

 *

 * GSE OBJECT
 *

 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "gse_id",
    "gse_title",
    "gse_summary",
    "gse_design",
    "gse_submission_date",
    "pub_med_id",
    "gse_samples",
    "gse_warnings",
    "gse_errors"
})
public class GseObject {

    @JsonProperty("gse_id")
    private java.lang.String gseId;
    @JsonProperty("gse_title")
    private java.lang.String gseTitle;
    @JsonProperty("gse_summary")
    private java.lang.String gseSummary;
    @JsonProperty("gse_design")
    private java.lang.String gseDesign;
    @JsonProperty("gse_submission_date")
    private java.lang.String gseSubmissionDate;
    @JsonProperty("pub_med_id")
    private java.lang.String pubMedId;
    @JsonProperty("gse_samples")
    private Map<String, GsmObject> gseSamples;
    @JsonProperty("gse_warnings")
    private List<String> gseWarnings;
    @JsonProperty("gse_errors")
    private List<String> gseErrors;
    private Map<java.lang.String, Object> additionalProperties = new HashMap<java.lang.String, Object>();

    @JsonProperty("gse_id")
    public java.lang.String getGseId() {
        return gseId;
    }

    @JsonProperty("gse_id")
    public void setGseId(java.lang.String gseId) {
        this.gseId = gseId;
    }

    public GseObject withGseId(java.lang.String gseId) {
        this.gseId = gseId;
        return this;
    }

    @JsonProperty("gse_title")
    public java.lang.String getGseTitle() {
        return gseTitle;
    }

    @JsonProperty("gse_title")
    public void setGseTitle(java.lang.String gseTitle) {
        this.gseTitle = gseTitle;
    }

    public GseObject withGseTitle(java.lang.String gseTitle) {
        this.gseTitle = gseTitle;
        return this;
    }

    @JsonProperty("gse_summary")
    public java.lang.String getGseSummary() {
        return gseSummary;
    }

    @JsonProperty("gse_summary")
    public void setGseSummary(java.lang.String gseSummary) {
        this.gseSummary = gseSummary;
    }

    public GseObject withGseSummary(java.lang.String gseSummary) {
        this.gseSummary = gseSummary;
        return this;
    }

    @JsonProperty("gse_design")
    public java.lang.String getGseDesign() {
        return gseDesign;
    }

    @JsonProperty("gse_design")
    public void setGseDesign(java.lang.String gseDesign) {
        this.gseDesign = gseDesign;
    }

    public GseObject withGseDesign(java.lang.String gseDesign) {
        this.gseDesign = gseDesign;
        return this;
    }

    @JsonProperty("gse_submission_date")
    public java.lang.String getGseSubmissionDate() {
        return gseSubmissionDate;
    }

    @JsonProperty("gse_submission_date")
    public void setGseSubmissionDate(java.lang.String gseSubmissionDate) {
        this.gseSubmissionDate = gseSubmissionDate;
    }

    public GseObject withGseSubmissionDate(java.lang.String gseSubmissionDate) {
        this.gseSubmissionDate = gseSubmissionDate;
        return this;
    }

    @JsonProperty("pub_med_id")
    public java.lang.String getPubMedId() {
        return pubMedId;
    }

    @JsonProperty("pub_med_id")
    public void setPubMedId(java.lang.String pubMedId) {
        this.pubMedId = pubMedId;
    }

    public GseObject withPubMedId(java.lang.String pubMedId) {
        this.pubMedId = pubMedId;
        return this;
    }

    @JsonProperty("gse_samples")
    public Map<String, GsmObject> getGseSamples() {
        return gseSamples;
    }

    @JsonProperty("gse_samples")
    public void setGseSamples(Map<String, GsmObject> gseSamples) {
        this.gseSamples = gseSamples;
    }

    public GseObject withGseSamples(Map<String, GsmObject> gseSamples) {
        this.gseSamples = gseSamples;
        return this;
    }

    @JsonProperty("gse_warnings")
    public List<String> getGseWarnings() {
        return gseWarnings;
    }

    @JsonProperty("gse_warnings")
    public void setGseWarnings(List<String> gseWarnings) {
        this.gseWarnings = gseWarnings;
    }

    public GseObject withGseWarnings(List<String> gseWarnings) {
        this.gseWarnings = gseWarnings;
        return this;
    }

    @JsonProperty("gse_errors")
    public List<String> getGseErrors() {
        return gseErrors;
    }

    @JsonProperty("gse_errors")
    public void setGseErrors(List<String> gseErrors) {
        this.gseErrors = gseErrors;
    }

    public GseObject withGseErrors(List<String> gseErrors) {
        this.gseErrors = gseErrors;
        return this;
    }

    @JsonAnyGetter
    public Map<java.lang.String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(java.lang.String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public java.lang.String toString() {
        return ((((((((((((((((((((("GseObject"+" [gseId=")+ gseId)+", gseTitle=")+ gseTitle)+", gseSummary=")+ gseSummary)+", gseDesign=")+ gseDesign)+", gseSubmissionDate=")+ gseSubmissionDate)+", pubMedId=")+ pubMedId)+", gseSamples=")+ gseSamples)+", gseWarnings=")+ gseWarnings)+", gseErrors=")+ gseErrors)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text:
package net.fehmicansaglam.bson.reader

import java.nio.ByteBuffer

import net.fehmicansaglam.bson.element.BsonInteger

case class BsonIntegerReader(buffer: ByteBuffer) extends Reader[BsonInteger] {

  def read: Option[BsonInteger] = {
    val name = readCString()
    val value = buffer.getInt()
    Some(BsonInteger(name, value))
  }
}


text:
using SharpKit.JavaScript;
namespace Ext.layout.component
{
    #region Auto
    /// <inheritdocs />
    ///
    ///
The class is the default component layout for <see cref="Ext.Component">Ext.Component</see> when no explicit
    /// <c><see cref="Ext.ComponentConfig.componentLayout">componentLayout</see></c> is configured.

    ///
This class uses template methods to perform the individual aspects of measurement,
    /// calculation and publication of results. The methods called depend on the component's
    /// <see cref="Ext.AbstractComponent.getSizeModel">size model</see>.

    ///
configured / calculated

    ///
In either of these size models, the dimension of the outer element is of a known size.
    /// The size is found in the <c>ownerContext</c> (the <see cref="Ext.layout.ContextItem">Ext.layout.ContextItem</see> for the owner
    /// component) as either "width" or "height". This value, if available, is passed to the
    /// <c>publishInnerWidth</c> or <c>publishInnerHeight</c> method, respectively.

    ///
shrinkWrap

    ///
When a dimension uses the <c>shrinkWrap</c> size model, that means the content is measured,
    /// then the outer (owner) size is calculated and published.

    ///
For example, for a shrinkWrap width, the following sequence of calls are made:

    ///

    ///
<c>Ext.layout.component.Component#measureContentWidth</c>

    ///
<c>publishOwnerWidth</c>
    ///

    ///
<c>calculateOwnerWidthFromContentWidth</c>

    ///
<c>publishInnerWidth</c> (in the event of hitting a min/maxWidth constraint)

    ///

    ///

    ///

    ///
natural

    ///
When a dimension uses the <c>natural</c> size model, the measurement is made on the outer
    /// (owner) element. This size is then used to determine the content area in much the same
    /// way as if the outer element had a <c>configured</c> or <c>calculated</c> size model.

    ///

    ///
<c>Ext.layout.component.Component#measureOwnerWidth</c>

    ///
<c>publishInnerWidth</c>

    ///

    ///
    [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
    public partial class Auto : Ext.layout.component.Component
    {
        ///
        /// When publishing height of an auto Component, it is usually not written to the DOM.
        /// Setting this to true overrides this behaviour.
        /// Defaults to: <c>false</c>
        ///
        public bool setHeightInDom;
        ///
        /// When publishing width of an auto Component, it is usually not written to the DOM.
        /// Setting this to true overrides this behaviour.
        /// Defaults to: <c>false</c>
        ///
        public bool setWidthInDom;
        public Auto(Ext.layout.component.AutoConfig config){}
        public Auto(){}
        public Auto(params object[] args){}
    }
    #endregion
    #region AutoConfig
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class AutoConfig : Ext.layout.component.ComponentConfig
    {
        ///
        /// When publishing height of an auto Component, it is usually not written to the DOM.
        /// Setting this to true overrides this behaviour.
        /// Defaults to: <c>false</c>
        ///
        public bool setHeightInDom;
        ///
        /// When publishing width of an auto Component, it is usually not written to the DOM.
        /// Setting this to true overrides this behaviour.
        /// Defaults to: <c>false</c>
        ///
        public bool setWidthInDom;
        public AutoConfig(params object[] args){}
    }
    #endregion
    #region AutoEvents
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class AutoEvents : Ext.layout.component.ComponentEvents
    {
        public AutoEvents(params object[] args){}
    }
    #endregion
}


text:
<!doctype html>

    <title>Send Page Options</title>

Mail Client Type

      What type of mail client do you use?

      If you are using a web mail client the tab will be kept open for the web mail client.

      If you are using a local mail client, which is registered to handle mailto links, a new tab will quickly appear
      and disappear again after having opened the mail client.

        <select id="mailClientType">

          <option value="web">Web Mail Client</option>

          <option value="local">Local Mail Client</option>
        </select>

Message Body Template

      By default the generated Mail will only contain the page title as subject and the url to send as text.
      But if you want you may define text that will appear before and after the URL.

        Text before URL:

        <textarea rows="4" cols="80" id="bodyPrefix"></textarea>

        Text after URL:

        <textarea rows="4" cols="80" id="bodyPostfix"></textarea>

      <button id="save">Save</button>


text:
function [S,f,R,varS,zerosp,C,Serr]=mtspectrumsegpt(data,win,params,segave,fscorr)
% Multi-taper segmented spectrum for a univariate binned point process
%
% Usage:
%
% [S,f,R,varS,zerosp,C,Serr]=mtspectrumsegpt(data,win,params,segave,fscorr)
% Input:
% Note units have to be consistent. See chronux.m for more information.
%       data (structure array of one channel of spike times;
%            also accepts 1d vector of spike times) -- required
%       win  (duration of the segments) - required.
%       params: structure with fields tapers, pad, Fs, fpass, err
%       - optional
%           tapers : precalculated tapers from dpss or in the one of the following
%                    forms:
%                   (1) A numeric vector [TW K] where TW is the
%                       time-bandwidth product and K is the number of
%                       tapers to be used (less than or equal to
%                       2TW-1).
%                   (2) A numeric vector [W T p] where W is the
%                       bandwidth, T is the duration of the data and p
%                       is an integer such that 2TW-p tapers are used. In
%                       this form there is no default i.e. to specify
%                       the bandwidth, you have to specify T and p as
%                       well. Note that the units of W and T have to be
%                       consistent: if W is in Hz, T must be in seconds
%                       and vice versa. Note that these units must also
%                       be consistent with the units of params.Fs: W can
%                       be in Hz if and only if params.Fs is in Hz.
%                       The default is to use form 1 with TW=3 and K=5
%
%	        pad		    (padding factor for the FFT) - optional (can take values -1,0,1,2...).
%                    -1 corresponds to no padding, 0 corresponds to padding
%                    to the next highest power of 2 etc.
%			      	 e.g. For N = 500, if PAD = -1, we do not pad; if PAD = 0, we pad the FFT
%			      	 to 512 points, if pad=1, we pad to 1024 points etc.
%			      	 Defaults to 0.
%           Fs   (sampling frequency) - optional. Default 1.
%           fpass    (frequency band to be used in the calculation in the form
%                                   [fmin fmax])- optional.
%                                   Default all frequencies between 0 and Fs/2
%           err  (error calculation [1 p] - Theoretical error bars; [2 p] - Jackknife error bars
%                                   [0 p] or 0 - no error bars) - optional. Default 0.
%       segave - (0 for don't average over segments, 1 for average) - optional - default  1
%       fscorr   (finite size corrections, 0 (don't use finite size corrections) or
%                1 (use finite size corrections) - optional
%                (available only for spikes). Defaults 0.
% Output:
%       S       (spectrum in form frequency x segments if segave=0; function of frequency if segave=1)
%       f       (frequencies)
%       R       (spike rate)
%       varS    (variance of the spectrum as a function of frequency)
%       zerosp  (0 for segments in which spikes were found, 1 for segments
%       C       (covariance matrix of the log spectrum - frequency x
%       frequency matrix)
%       Serr    (error bars) - only if err(1)>=1

if nargin < 2; error('Need data and segment information'); end;
if nargin < 3; params=[]; end;
if nargin < 4 || isempty(segave); segave=1; end;
[tapers,pad,Fs,fpass,err,trialave,params]=getparams(params);
clear params trialave
if nargin < 5 || isempty(fscorr); fscorr=0;end;

if nargout > 4 && err(1)==0; error('cannot compute error bars with err(1)=0; change params and run again'); end;

dtmp=change_row_to_column(data);
T=max(dtmp); % total length of data
minT=min(dtmp);
E=minT:win:T-win; % fictitious event triggers
win=[0 win]; % use window length to define left and right limits of windows around triggers
dtmp=createdatamatpt(dtmp,E,win); % create segmented data set
[mintime,maxtime]=minmaxsptimes(dtmp);
dt=1/Fs; % sampling time
t=mintime-dt:dt:maxtime+dt; % time grid for prolates
N=length(t); % number of points in grid for dpss
nfft=max(2^(nextpow2(N)+pad),N); % number of points in fft of prolates
[f,findx]=getfgrid(Fs,nfft,fpass); % get frequency grid for evaluation
tapers=dpsschk(tapers,N,Fs); % check tapers
[J,Msp,Nsp]=mtfftpt(dtmp,tapers,nfft,t,f,findx);% mt fft for point process times
R=Msp*Fs;
S=squeeze(mean(conj(J).*J,2)); % spectra of non-overlapping segments (averaged over tapers)
if segave==1; SS=squeeze(mean(S,2));R=mean(R);else;SS=S;end;% mean of the spectrum averaged across segments
if nargout > 3
    lS=log(SS); % log spectrum for nonoverlapping segments
%     varS=var(lS,1,2); % variance of log spectrum
    varS=var(lS',1)';% variance of the log spectrum R13
    if nargout > 4
       zerosp=zeros(1,size(data,2));
       zerosp(Nsp==0)=1;
       if nargout > 5
          C=cov(lS'); % covariance matrix of the log spectrum
          if nargout==7;
             if fscorr==1;
                Serr=specerr(SS,J,err,segave,Nsp);
             else
                Serr=specerr(SS,J,err,segave);
             end;
          end;
       end;
    end;
end;
S=SS;


text:
module Lab42
  class NHash
    module LookupChains
      def push_prefix_lookup *prefixes
        prefixes.reverse.each do | prefix |
          push_fallback do
            with_prefix prefix do
              again
            end
          end
        end
      end

      def push_suffix_lookup *suffixes
        suffixes.reverse.each do | suffix |
          push_fallback do
            with_suffix suffix do
              again
            end
          end
        end
      end

      def push_affix_lookup( prefixes: required, suffixes: required, suffixes_first: false )
        if suffixes_first
          suffixes.product( prefixes ).reverse.each do | suff, pref |
            push_fallback do
              with_suffix suff do
                with_prefix pref do
                  again
                end
              end
            end
          end
        else
          prefixes.product( suffixes ).reverse.each do | pref, suff |
            push_fallback do
              with_suffix suff do
                with_prefix pref do
                  again
                end
              end
            end
          end
        end
      end
    end # module LookupChains
    include LookupChains
  end # class NHash
end # module Lab42


text:
@implementation LQSAttentionOnePictureView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        // 内容模式
        self.contentMode = UIViewContentModeScaleAspectFill;
        // 超出边框的内容都剪掉
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)setPictureURL:(NSString *)pictureURL
{
    _pictureURL = pictureURL;

    // 设置图片
    [self sd_setImageWithURL:[NSURL URLWithString:pictureURL] placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]];

}

@end


text:
        Add a
        Edit
        Page

    <mat-toolbar class="highlight small" *ngIf="awaitingApproval" routerLink="/admin/approvals">
        This product has a change awaiting moderation

            View Approvals

    </mat-toolbar>

    <mat-form-field class="block">
        <input matInput placeholder="Page URL (no slashes, spaces or special characters)" type="text" [(ngModel)]="newURL">
    </mat-form-field>

    <mat-form-field class="block">
        <input matInput placeholder="Title" [(ngModel)]="newTitle">
    </mat-form-field>

    <ckeditor
        [(ngModel)]="newBody"
        [config]="{uiColor: '#FFFFFF', extraPlugins: 'divarea'}"
        [readonly]="false">
    </ckeditor>

    <mat-slide-toggle ngDefaultControl [(ngModel)]="newPublished">
        Publish
        Un-Publish
    </mat-slide-toggle>

    <button
        mat-raised-button
        (click)="approveItem(newURL, newTitle, newBody, newPublished)"
        class="submit"
        *ngIf="router.url.includes('approval') && (currentAdmin.role === 'super-admin' || currentAdmin.role === 'admin')">
        Approve
    </button>

    <button
        mat-raised-button
        (click)="submitForModeration(newURL, newTitle, newBody, newPublished)"
        class="submit"
        *ngIf="router.url.includes('approval') && entityObject && ((currentAdmin.role === 'super-admin' || currentAdmin.role === 'admin') || currentAdmin.uid === entityObject.updatedBy)">
        Save Draft
    </button>

    <button
        mat-raised-button
        (click)="deleteItem($event)"
        class="submit"
        *ngIf="router.url.includes('approval') && entityObject && ((currentAdmin.role === 'super-admin' || currentAdmin.role === 'admin') || currentAdmin.uid === entityObject.updatedBy)">
        Delete Draft
    </button>

    <button
        mat-raised-button
        (click)="submitForModeration(newURL, newTitle, newBody, newPublished)"
        class="submit"
        *ngIf="!router.url.includes('approval')">
        Submit for Moderation
    </button>

    <button
        mat-raised-button
        (click)="addPage(newURL, newTitle, newBody, newPublished)"
        class="submit"
        *ngIf="!router.url.includes('approval') && (currentAdmin.role === 'super-admin' || currentAdmin.role === 'admin')">
        Add
        Save
        Page
    </button>


text:
<!DOCTYPE html>

	<link rel="stylesheet" href="<?php echo base_url()?>asset/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
	<title>Category group management</title>

Edit Category Groups

		 	<?php $id = $_GET['id'];?>

        <form class="forms" action="<?php echo base_url()?>category/edit_category_group?id=<?php echo $id ?>" method="post" style="width : 250px; height : 400px">

                Group Name

                <?php foreach ( $aCategory_group as $group ):?>
					<?php if($group->id == $id): ?>
						<?php echo $group->title ?>
					<?php endif ?>
				<?php endforeach; ?>

                Group Title *
                <input type       ="text"
                       class      ="form-control"
                       placeholder=""
                       name       ="group_title"
                       value      ="">

    			Status
    			<select class="form-control" name="category_group_status">

    				<?php foreach ( $aStatus as $data ):
    					echo "<option value=".$data->id.">".$data->title."</option>";
    				 endforeach;?>

    			</select>

            <button type="submit" class="btn btn-primary">Update / Back</button>
        </form>


text:
<?xml version="1.0" encoding="utf-8" ?>
<gadget>
<name>AutoSMS</name>
<namespace>org.cuuldesign.autosms</namespace>
<version>1.0.0.0</version>
<author name="David Luu">
<info url="watacrackaz.com/autosms" text="WataCrackaz AutoSMS" />
</author>
<copyright>© 2010</copyright>
<description>Send SMS without any registration.</description>
<icons>
<icon height="64" width="64" src="AutoSMS_icon_64.png" />
</icons>
<hosts>
<host name="sidebar">
<base type="HTML" apiVersion="1.0.0" src="asms.html" />
<permissions>full</permissions>
<platform minPlatformVersion="0.3" />
</host>
</hosts>
</gadget>


text:
local ScrollViewCell = import("..ui.ScrollViewCell")
local ProductCell = class("ProductCell", ScrollViewCell)

function ProductCell:ctor(size, sprite, rect)
	local start_pos_x 	= sprite:getContentSize().width/2 + rect.origin.x;
	local start_pos_y 	= rect.origin.y + sprite:getContentSize().height/2;

	sprite:setPosition(start_pos_x, start_pos_y)
	sprite:addTo(self)
end

return ProductCell


text:
package ru.job4j.utils;

import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
//import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
/**
 * Класс HibernateSessionFactoryTest тестирует класс HibernateSessionFactory.
 *
 * @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
 * @version 2019-03-18
 * @since 2018-08-04
 */
public class HibernateSessionFactoryTest {
    /**
     * Локальное имя файла конфигурации Hibernate.
     */
    private static String cfgLocalFileName;
    /**
     * Название субд.
     */
    private static String dbmsName;
    /**
     * Действия перед тестом.
     * @throws Exception исключение.
     */
    @BeforeClass
    public static void beforeAllTests() throws Exception {
        String path = HibernateSessionFactoryTest.class.getClassLoader().getResource(".").getPath();
        path = path.replaceFirst("^/(.:/)", "$1");
        dbmsName = new PropertyLoader(String.format("%s%s", path, "activeDBMS.properties")).getPropValue("name");
        cfgLocalFileName = "hibernate.cfg.xml";
        if (!dbmsName.equals("PostgreSQL")) {
            cfgLocalFileName = String.format("hibernate.%s.cfg.xml", dbmsName);
        }
    }
    /**
     * Тестирует public static SessionFactory get(String localFileName).
     * @throws Exception исключение.
     */
    @Test
    public  void testGetPassCfgNameSessionFactoryAllreadyExists() throws Exception {
        HibernateSessionFactory.get(cfgLocalFileName);
        SessionFactory sf = HibernateSessionFactory.get(cfgLocalFileName);
        assertNotNull(sf);
    }
    /**
     * Тестирует public static SessionFactory get(String localFileName).
     * Получает новый SessionFactory.
     * @throws Exception исключение.
     */
    @Test
    public  void testGetPassCfgNameSessionFactoryNotExistsYet() throws Exception {
        SessionFactory sf = HibernateSessionFactory.get(cfgLocalFileName);
        assertNotNull(sf);
    }
    /**
     * Тестирует public static SessionFactory get(String localFileName).
     * Возвращает существующий SessionFactory по-умолчанию.
     * @throws Exception исключение.
     */
    @Test
    public  void testGetSessionFactoryAllreadyExists() throws Exception {
        SessionFactory sf = HibernateSessionFactory.get();
        assertNotNull(sf);
    }
}


text:
{% extends "base.html" %}
{% block title %}TwittBack - View single tweet{% endblock %}
{% block content %}

{% include "tweet.html" %}

{% endblock %}


text:
import { Plugin, Cordova } from './plugin';

/**
 * @name baidu login
 * @description
 * Cordova / Phonegap plugin for baidu login
 */
@Plugin({
  pluginName: 'Login',
  plugin: 'cordova-plugin-login',
  pluginRef: 'Login',
  repo: ''
})
export class Login {

  @Cordova()
  static getCookie(url: string): Promise<any> { return; }

  @Cordova()
  static getCookieValue(url: string, cookieKey: string): Promise<any> { return; }

  @Cordova()
  static showPASSQRCodeScanViewController(): Promise<any> { return; }

  @Cordova()
  static showPASSAccountRealNameViewController(): Promise<any> { return; }

  @Cordova()
  static showLoginView(): Promise<any> { return; }

  @Cordova()
  static showPassLoginView(): Promise<any> { return; }

  @Cordova()
  static showUCLoginView(): Promise<any> { return; }

  @Cordova()
  static showUCRegisterView(): Promise<any> { return; }

  @Cordova()
  static ucLoginSuccess(url: Object): Promise<any> { return; }

  @Cordova()
  static popView(): void { }

  @Cordova()
  static logout(): Promise<any> { return; }

}


text:
<!DOCTYPE html>

    <meta charset='utf-8'>
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% include head-meta.html %}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

    <link href='http://fonts.googleapis.com/css?family=Oswald|Lato|Open+Sans'
          rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="../stylesheets/newindex.css">

    <title>Eric Su</title>

                        Back

Eric Su

                Full-Stack Software Engineer

Boston MA

                        AboutAbout

Work

Skills

Blog

Contact

    {% include footer.html %}


text:
PRAPinnedListView  enables you to use Sticky Headers feature with header click, use this list view to make your app look awesome. You don't need to write lot's of code to use this just few simple steps and you can add it to your app. this contains a generic adapter also that means you also don't need to make a separate list adapter to bind list, just pass your item collection and your list will be bind prestty well. **:)**

![PRA List Preview](https://raw.githubusercontent.com/rzee7/PRAPinnedListview/master/Preview/PinnedList.gif)

# Features #
- Sticky Headers
- Inbuilt Adapter
- Header Click

## PRAListView ##

Ready to use!! Follow me >

- Add PRAPinnedListView reference to app.
- Add PRAListView to your Xaml file (e.g. Main.xaml)

	     <prapinnedlistview.PRAListView
		    android:id="@+id/list"
		    android:layout_width="match_parent"
		    android:layout_height="match_parent" />

- Access in your activity (e.g. MainActivity.cs).

			#region Pinned List View

            PRAService.Register<IListItemView<ItemHolder>>(this);
            listView = FindViewById<PRAListView>(Resource.Id.list);
            listView.SetItemSource<ItemHolder>(DataHandler.GetData());
            listView.PRAItemClick += listView_PRAItemClick;
            #endregion

> PRAListItem Click Cvent

		void listView_PRAItemClick(object sender, PRAListItemClickEventArg<object> e)
        {
            Toast.MakeText(this, string.Format("Hey! you clicked {0}", ((ItemHolder)e.Item).Title), ToastLength.Short).Show();
        }

- Implement **IListItemView** interface with your modal into your activity where you accessing PRAListView.

    	public class MainActivity : Activity, IListItemView<ItemHolder>

- Initialized both views method **GetItemHeaderView()** and **GetItemView()**.

		#region Get Header Item View

        public View GetItemHeaderView(int position, View convertView, ViewGroup parent, ItemHolder headerItem)
        {
            View view = convertView;
            view = view ?? LayoutInflater.Inflate(Resource.Layout.HeaderView, parent, false); //Header view
            view.FindViewById<TextView>(Resource.Id.txtTitle).Text = headerItem.Title;
            return view;
        }

        #endregion

		#region Get Item View

        public View GetItemView(int position, View convertView, ViewGroup parent, ItemHolder item)
        {
            View view = convertView;
            view = view ?? LayoutInflater.Inflate(Resource.Layout.ItemView, parent, false); //Item view
            view.FindViewById<TextView>(Resource.Id.txtItemTitle).Text = item.Title;
            return view;
        }

        #endregion

Yo!

You have done your most time taken part here :) Now we just need to pass **Item Header View** and **Item View** these view will be customized as per your need :) Yeppeeeee!! we have done

This lib ported from [Pinned Section](https://github.com/beworker/pinned-section-listview "Sergej Shafarenka") Thanks! [Sergej Shafarenka](https://github.com/beworker)


text:
package com.googlecode.jsonrpc4j.spring.rest;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.Assert;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * JSON-RPC Message converter for Spring RestTemplate
 */
@SuppressWarnings({ "WeakerAccess", "unused" })
class MappingJacksonRPC2HttpMessageConverter extends AbstractHttpMessageConverter<Object> {

	private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	private static final MediaType APPLICATION_JSON_RPC = new MediaType("application", "json-rpc", DEFAULT_CHARSET);

	private ObjectMapper objectMapper;

	private boolean prefixJson = false;

	/**
	 * Construct a new {@code BindingJacksonHttpMessageConverter}.
	 */
	public MappingJacksonRPC2HttpMessageConverter() {
		super(APPLICATION_JSON_RPC);
		objectMapper = new ObjectMapper();
	}

	/**
	 * Construct a new {@code BindingJacksonHttpMessageConverter}.
	 *
	 * @param objectMapper the object mapper for this view
	 */
	public MappingJacksonRPC2HttpMessageConverter(ObjectMapper objectMapper) {
		super(APPLICATION_JSON_RPC);
		Assert.notNull(objectMapper, "ObjectMapper must not be null");
		this.objectMapper = objectMapper;
	}

	/**
	 * Return the underlying {@code ObjectMapper} for this view.
	 *
	 * @return the object mapper for this view
	 */
	public ObjectMapper getObjectMapper() {
		return this.objectMapper;
	}

	/**
	 * Set the {@code ObjectMapper} for this view. If not set, a default
	 * {@link ObjectMapper#ObjectMapper() ObjectMapper} is used.
	 *

	 * Setting a custom-configured {@code ObjectMapper} is one way to take further control of the JSON serialization
	 * process. For example, an extended {@code org.codehaus.jackson.map.SerializerFactory} can be configured that
	 * provides custom serializers for specific types. The other option for refining the serialization process is to use
	 * Jackson's provided annotations on the types to be serialized, in which case a custom-configured ObjectMapper is
	 * unnecessary.
	 *
	 * @param objectMapper the object mapper for this view
	 */
	public void setObjectMapper(ObjectMapper objectMapper) {
		Assert.notNull(objectMapper, "ObjectMapper must not be null");
		this.objectMapper = objectMapper;
	}

	/**
	 * Indicate whether the JSON output by this view should be prefixed with "{} &&". Default is false.
	 *

	 * Prefixing the JSON string in this manner is used to help prevent JSON Hijacking. The prefix renders the string
	 * syntactically invalid as a script so that it cannot be hijacked. This prefix does not affect the evaluation of
	 * JSON, but if JSON validation is performed on the string, the prefix would need to be ignored.
	 *
	 * @param prefixJson whether the JSON should be prefixed
	 */
	public void setPrefixJson(boolean prefixJson) {
		this.prefixJson = prefixJson;
	}

	@Override
	public boolean canRead(Class<?> clazz, MediaType mediaType) {

		if (!ObjectNode.class.isAssignableFrom(clazz)) { return false; }

		if (mediaType == null) { return true; }

		for (MediaType supportedMediaType : getSupportedMediaTypes()) {
			// we can't read multipart
			if (supportedMediaType.includes(mediaType)) { return true; }
		}
		return false;

	}

	@Override
	public boolean canWrite(Class<?> clazz, MediaType mediaType) {

		if (!ObjectNode.class.isAssignableFrom(clazz)) { return false; }

		if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; }

		for (MediaType supportedMediaType : getSupportedMediaTypes()) {
			if (supportedMediaType.isCompatibleWith(mediaType)) { return true; }
		}

		return false;
	}

	@Override
	protected boolean supports(Class<?> clazz) {
		// should not be called, since we override canRead/Write instead
		throw new UnsupportedOperationException();
	}

	@Override
	protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {

		JavaType javaType = getJavaType(clazz);
		try {
			return this.objectMapper.readValue(inputMessage.getBody(), javaType);
		} catch (IOException ex) {
			throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex);
		}
	}

	@Override
	protected void writeInternal(Object object, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {

		JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());

		JsonGenerator jsonGenerator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
		try {
			if (this.prefixJson) {
				jsonGenerator.writeRaw("{} && ");
			}
			this.objectMapper.writeValue(jsonGenerator, object);
		} catch (IOException ex) {
			throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
		}
	}

	/**
	 * Determine the JSON encoding to use for the given content type.
	 *
	 * @param contentType the media type as requested by the caller
	 * @return the JSON encoding to use (never null)
	 */
	private JsonEncoding getJsonEncoding(MediaType contentType) {
		if (contentType != null && contentType.getCharSet() != null) {
			Charset charset = contentType.getCharSet();
			for (JsonEncoding encoding : JsonEncoding.values()) {
				if (charset.name().equals(encoding.getJavaName())) { return encoding; }
			}
		}
		return JsonEncoding.UTF8;
	}

	/**
	 * Return the Jackson {@link JavaType} for the specified class.
	 *

	 * The default implementation returns {@link ObjectMapper#constructType(java.lang.reflect.Type)}, but this can be
	 * overridden in subclasses, to allow for custom generic collection handling. For instance:
	 *

	 * protected JavaType getJavaType(Class<?> clazz) { if (List.class.isAssignableFrom(clazz)) { return
	 * objectMapper.getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class); } else { return
	 * super.getJavaType(clazz); } }
	 *

	 *
	 * @param javaClass the class to return the java type for
	 * @return the java type
	 */
	private JavaType getJavaType(Class<?> javaClass) {
		return objectMapper.constructType(javaClass);
	}

}


text:
FactoryGirl.define do
  factory :site do
    url Faker::Internet.url
  end
end


text:
import test from 'ava';
import yajob from '..';
import {QueueDb} from './_utils';

test('putUnique should add only unique jobs to queue', async t => {
	const queueDb = await new QueueDb();
	const queue = yajob(queueDb.uri);

	try {
		await queue.putUnique({a: 'b', c: {d: 'e'}});
		await queue.putUnique({test: 'message2'});
		const nInserted = await queue.putUnique({a: 'b', c: {d: 'e'}});
		const job = await queueDb.db.collection('default').find().toArray();

		t.same(nInserted, {result: {ok: 0, n: 0}});
		t.same(job.length, 2);
	} finally {
		await queueDb.close();
	}
});


text:
package de.geeksfactory.opacclient.apis;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class BaseHtmlTest {
    /**
     * Reads content from an InputStream into a string
     *
     * @param is InputStream to read from
     * @return String content of the InputStream
     */
    private static String convertStreamToString(InputStream is) throws IOException {
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            reader = new BufferedReader(new InputStreamReader(is));
        }
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    protected String readResource(String filename) {
        InputStream is = getClass().getResourceAsStream(filename);
        if (is == null) return null;
        try {
            return convertStreamToString(is);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected List<String> getResourceFiles(String path) throws IOException {
        List<String> filenames = new ArrayList<>();
        InputStream in = getClass().getResourceAsStream(path);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String resource;
        while ((resource = br.readLine()) != null) {
            filenames.add(resource);
        }
        return filenames;
    }

    protected static void assertContainsData(Map<String, String> item, String key) {
        assertTrue(item.containsKey(key));
        assertNotNull(item.get(key));
        assertNotEquals(item.get(key).trim(), "");
    }

    protected static void assertContainsData(String text) {
        assertNotNull(text);
        assertNotEquals(text, "");
    }

    protected static void assertNullOrNotEmpty(String text) {
        if (text != null) {
            assertNotEquals(text, "");
        }
    }
}


text:
package com.mvp4g.client.history;

import com.mvp4g.client.event.EventBus;

/**
 * Interface that defines methods to convert a token from/to an event.

 *
 * @param <E>
 *   type of the event bus where the event is defined.
 *
 * @author plcoirier
 */
public interface HistoryConverter<E extends EventBus> {

  /**
   * Convert a token to event's object and trigger the event bus.

   *

   * Specific information can also be retrieved (from a cookie or server for example).
   *
   * @param historyName
   *   event's name
   * @param param
   *   string that was stored in the token, used to retrieve event's object (can be null
   *   if no information was stored in the URI)
   * @param eventBus
   *   event bus of the application
   */
  public void convertFromToken(String historyName,
                               String param,
                               E eventBus);

  /**
   * Return true if the token generated should be crawlable
   *
   * @return true if crawlable
   */
  public boolean isCrawlable();

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class LooksJSON_model extends MY_Model {
    function __construct() {
        parent::__construct();
    }
    public function getJSON($data) {
        $JSONData = [];
		//$this->db->order_by('gender','DESC');
		$this->db->select('id,imagePath');
		$this->db->from('carousel_data');
		$this->db->where('type',$data['type']);
		$this->db->where('gender',$data['gender']);
        $query = $this->db->get();
        // $this->output->enable_profiler(TRUE);
        foreach ($query->result() as $row) {
			$asset_path = "http://".$_SERVER['HTTP_HOST']."/myntra/upload/carousel/";
			$row->imagePath = $asset_path.$row->imagePath;
            $JSONData[] = $row;
        }
		return $JSONData;
    }
	public function getStyles($carousel_id)
	{

		$StyleData = [];
		$this->db->select('style_id');
		$this->db->from('styles_data');
		$this->db->where('carousel_id',$carousel_id);
		$query = $this->db->get();
		foreach ($query->result() as $row) {
            $StyleData[] = $row;
        }
		return $StyleData;
	}
}


text:
class LimitedAlgorithm:
    """
    Handles the direct running of algorithms as generators and saving
    their intermediate results and setup.
    """
    def __init__(self, module, problem, setup, params):
        """
        :param module: the module of the algorithm to run
        :type module: module
        :param problem: the problem to run with the algorithm
        :type problem: object
        :param setup: the pre-setup objects useful for running
            any algorithm
        :type setup: one of {Evaluation, TestRun}
        :param params: the parameters to the algorithm
        :type params: map<str, object>
        """
        self.setup = setup
        self.problem = problem
        self.module = module

        self.params = self.module.params.copy()
        self.params.update(params)

        self.runner = module.run(self.problem, self.setup, self.params)

        self.output_history = []

    def set_limit(self, limit):
        self.setup.counter.limit = limit

    def next_output(self):
        """
        Get the next intermediate output from the algorithm, or its
        final output if it is done.
        """
        try:
            output = self.runner.next()
        except StopIteration:
            output = None

        self.output_history.append(output)
        return output


text:
{{{
  "title": "ctl.io Outbound Email Communication Protocol",
  "date": "4-11-2016",
  "author": "Rich DuBose",
  "attachments": [],
  "contentIsHTML": false
}}}

The CenturyLink Platform Enablement Team produces the following Digital Magazines ('eZines') that are designed to inspire users, developers and partners to engage and solve problems with our platform. They are:

  * **Ramp** - Targeted at *new* users of the platform
  * **View** - Targeted at seasoned users of the platform
  * **Code** - Targeted at developers of the platform
  * **Link** - Targeted to internal CTL audiences only to highlight platform success

Also, a few other products leverage Platform Enablement to produce product-specific newsletters for their technical audiences

  * **Orchestrate** produces a monthly newsletter
  * **Managed Services** delivers a periodic newsletter (Internal Only)

The ctl.io Outbound Email Program following the principles of **Permission Based Marketing**. Individuals only received the eZines once **Explicit Consent** is obtained. Explicit Consent is obtained in the following ways:

  * Establishment of a new account on ctl.io thru the online activation mechanism.
  * The opt-into one of the *signup* widgets on ctl.io.
  * Being an existing customer of ctl.io at the time the Outbound Email Program was established.
    * The ctl.io Outbound Email Program is fully compliant with US Anti-Spam Law, Canadian Anti-Spam Law (CASL) & European Union Regulations governing electronic communications (Privacy and Electronic Communications Directive). As such, all emails:
      * Clearly indicate the email is being sent by CenturyLink Cloud.
      * Contain a Unsubscrible Link.
      * A link to CenturyLink Cloud's Privacy Policy.

In addition to the ctl.io Outbound Email Communications, our Customer Support Team will periodically send out *Specical Announcments* with respect to the status of our platform or data centers.  For instance, our Customer Care Team will proactively send email communications to customers affected by planned maintainence or an incident ongoing in one of our data centers.

* Explicit Consent is also obtained for *Special Announcements*.  Consent is collected via the following vehicles for *Special Announcements*:
  * A user account is created on [Platform CenturyLink](https://control.ctl.io).
  * A user opts-in to receiving Customer Care *Special Announcements* via the ctl.io [Status Page](https://status.ctl.io).
* Consent to Digital Magazines is not assumed to infer consent to *Special Announcements*.

The final type of email communication sent by the ctl.io team surrounds Service End Of Life (EOL) messaging. We are legally bound to provide customer notification when a product(s) or service(s) they may be using is being terminated. In these cases, the responsible Product Owner(s) provide list of affected customers.

**NOTE:** As CenturyLink offers a platform that has many built-in reseller features, many of our customers are channel partners or internal corporate development groups who may not even know CenturyLink Cloud is powering their infrastructure. As a result, we make every effort NOT to send communications to downstream customers of resellers.  However, if one of those customers adds an account directly on the platform, or purposefully opts-in via one of the methods mentioned above, CenturyLink has no way of reactively excluding them unless the reseller informs us.


text:
using FluentAssertions;
using emd.cs.Nodes;
using pegleg.cs.Parsing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace emd.cs.Grammar
{
  public class EmphasisTests : GrammarTestFixture {
    [Fact] public void Emphasis_matches_base_case() {
      var expected = new EmphasisNode(
        new IInlineNode[] { new TextNode("text", new SourceRange(1, 4, 1, 1)) },
        new SourceRange(0, 6, 1, 0)
      );

      var match = EmdGrammar.RichEmphasis.ShouldMatchAllOf("*text*");

      match.Succeeded.Should().BeTrue();
      match.Product.ShouldBeEquivalentTo(expected);
    }

    [Fact] public void Emphasis_should_not_match_with_missing_end_delimiter() {
      var match = EmdGrammar.RichEmphasis.ShouldNotMatch("*foo");
    }

    [Fact] public void Emphasis_should_not_match_when_empty() {
      EmdGrammar.RichEmphasis.ShouldNotMatch("**");
    }
  }
}


text:
package org.olat.admin.sysinfo;

import org.olat.core.commons.persistence.DBFactory;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.link.LinkFactory;
import org.olat.core.gui.components.velocity.VelocityContainer;
import org.olat.core.gui.control.Event;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.control.controller.BasicController;

/**
 *
 * Initial date: 16.11.2012<br>
 * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
 */
public class HibernateStatisticsController extends BasicController {

	private Link enableLink;
	private Link disableLink;
	private Link clearLink;
	private VelocityContainer mainVC;

	public HibernateStatisticsController(UserRequest ureq, WindowControl wControl) {
		super(ureq, wControl);

		mainVC = createVelocityContainer("hibernateinfo");
		enableLink = LinkFactory.createButton("enable.hibernate.statistics", mainVC, this);
		disableLink = LinkFactory.createButton("disable.hibernate.statistics", mainVC, this);
		clearLink = LinkFactory.createButton("clear.hibernate.statistics", mainVC, this);

		loadModel();
		putInitialPanel(mainVC);
	}

	public void loadModel() {
		mainVC.contextPut("isStatisticsEnabled", DBFactory.getInstance(false).getStatistics().isStatisticsEnabled());
		mainVC.contextPut("hibernateStatistics", DBFactory.getInstance(false).getStatistics());
	}

	@Override
	protected void doDispose() {
		//
	}

	@Override
	protected void event(UserRequest ureq, Component source, Event event) {
		if (source == enableLink){
			DBFactory.getInstance(false).getStatistics().setStatisticsEnabled(true);
			mainVC.contextPut("isStatisticsEnabled", DBFactory.getInstance(false).getStatistics().isStatisticsEnabled());
			getWindowControl().setInfo("Hibernate statistics enabled.");
			loadModel();
		} else if (source == disableLink){
			DBFactory.getInstance(false).getStatistics().setStatisticsEnabled(false);
			mainVC.contextPut("isStatisticsEnabled", DBFactory.getInstance(false).getStatistics().isStatisticsEnabled());
			getWindowControl().setInfo("Hibernate statistics disabled.");
			loadModel();
		} else if (source == clearLink){
			DBFactory.getInstance(false).getStatistics().clear();
			getWindowControl().setInfo("Hibernate statistics clear done.");
			loadModel();
		}
	}

}


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee1815689bc">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States District Court Northern District of Ohio</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2012-01-03</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2010-01-28</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-5_04-cr-00545</identifier>
<identifier type="local">P0b002ee1815689bc</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2012-01-03</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2012-01-03</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ohnd-5_04-cr-00545</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ohnd-5_04-cr-00545</accessId>
 <courtType>District</courtType>
 <courtCode>ohnd</courtCode>
 <courtCircuit>6th</courtCircuit>
 <courtState>Ohio</courtState>
 <courtSortOrder>2392</courtSortOrder>
 <caseNumber>5:04-cr-00545</caseNumber>
 <caseOffice>Akron</caseOffice>
 <caseType>criminal</caseType>
 <party firstName="Michael" fullName="Michael Johnson" lastName="Johnson" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
</extension>
<titleInfo>
 <title>United States of America v. Johnson</title>
 <partNumber>5:04-cr-00545</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-5_04-cr-00545/content-detail.html</url>
</location>
<classification authority="sudocs">JU 4.15</classification>
<identifier type="preferred citation">5:04-cr-00545;04-545</identifier>
<name type="corporate">
 <namePart>United States District Court Northern District of Ohio</namePart>
 <namePart>6th Circuit</namePart>
 <namePart>Akron</namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>Michael Johnson</displayForm>
 <namePart type="family">Johnson</namePart>
 <namePart type="given">Michael</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Defendant</description>
</name>
<name type="personal">
 <displayForm>United States of America</displayForm>
 <namePart type="family">United States of America</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Plaintiff</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ohnd-5_04-cr-00545</accessId>
 <courtType>District</courtType>
 <courtCode>ohnd</courtCode>
 <courtCircuit>6th</courtCircuit>
 <courtState>Ohio</courtState>
 <courtSortOrder>2392</courtSortOrder>
 <caseNumber>5:04-cr-00545</caseNumber>
 <caseOffice>Akron</caseOffice>
 <caseType>criminal</caseType>
 <party firstName="Michael" fullName="Michael Johnson" lastName="Johnson" role="Defendant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Plaintiff"></party>
 <state>Ohio</state>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ohnd-5_04-cr-00545-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-5_04-cr-00545/USCOURTS-ohnd-5_04-cr-00545-0/mods.xml">
 <titleInfo>
  <title>United States of America v. Johnson</title>
  <subTitle>Order Adopting Magistrate Judge George J. Limbert's Report and Recommendation as to Defendant, Michael Johnson. Defendant's supervised release is revoked and Defendant is sentenced to 9 months imprisonment. Defendant's remaining term of supervised release is terminated. (Related document 27). Judge Peter C. Economus on 1/27/10. (BR,S)</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2010-01-28</dateIssued>
</originInfo>
 <relatedItem xlink:href="http://www.gpo.gov/fdsys/pkg/pdf/USCOURTS-ohnd-5_04-cr-00545-0.pdf" type="otherFormat">
  <identifier type="FDsys Unique ID">D09002ee18165adcc</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-5_04-cr-00545/USCOURTS-ohnd-5_04-cr-00545-0</identifier>
 <identifier type="former granule identifier">ohnd-5_04-cr-00545_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ohnd-5_04-cr-00545/USCOURTS-ohnd-5_04-cr-00545-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ohnd-5_04-cr-00545/pdf/USCOURTS-ohnd-5_04-cr-00545-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 5:04-cr-00545; United States of America v. Johnson; </searchTitle>
  <courtName>United States District Court Northern District of Ohio</courtName>
  <state>Ohio</state>
  <accessId>USCOURTS-ohnd-5_04-cr-00545-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2010-01-28</dateIssued>
  <docketText>Order Adopting Magistrate Judge George J. Limbert's Report and Recommendation as to Defendant, Michael Johnson. Defendant's supervised release is revoked and Defendant is sentenced to 9 months imprisonment. Defendant's remaining term of supervised release is terminated. (Related document 27). Judge Peter C. Economus on 1/27/10. (BR,S)</docketText>
</extension>
</relatedItem>
</mods>


text:
This repo is divided into multiple packages using Yarn workspaces:

- `ember-css-transitions` is the actual `ember-css-transitions` addon
- `docs` documentation app for `ember-css-transitions` Ember.js addon
- `test-app` contains `ember-css-transitions` test suite

## Installation

* `git clone https://github.com/miguelcobain/ember-css-transitions.git`
* `cd ember-css-transitions`
* `yarn install`

## Linting

* `yarn lint`
* `yarn lint:fix`

## Running tests

* `cd ember-css-transitions && yarn start` – Builds the addon in "watch mode" so changes picked up by test app.
* `cd test-app && ember test` – Runs the test suite on the current Ember version
* `cd test-app && ember test --server` – Runs the test suite in "watch mode"
* `cd test-app && ember try:each` – Runs the test suite against multiple Ember versions

During development, if you'd like test app to pick up changes in the addon, make sure to run both
`cd ember-css-transitions && yarn start` and `cd test-app && ember test --server` in different terminals.

## Running the test application

* `cd test-app && ember serve`
* Visit the test application at [http://localhost:4200](http://localhost:4200).

For more information on using ember-cli, visit [https://cli.emberjs.com/release/](https://cli.emberjs.com/release/).