text:
The **spring-security-pac4j** library is a web multi-protocols client for [Spring Security](http://static.springsource.org/spring-security/site/index.html).

It supports these 6 authentication mechanisms on client side :

1. OAuth (1.0 & 2.0)
2. CAS (1.0, 2.0, SAML, logout & proxy)
3. HTTP (form & basic auth authentications)
4. OpenID
5. SAML (2.0)
6. Google App Engine UserService.

It's available under the Apache 2 license and based on my [pac4j](https://github.com/pac4j/pac4j) library.

## Providers supported

Provider	Protocol	Maven dependency	Client class	Profile class

CAS server	CAS	pac4j-cas	CasClient & CasProxyReceptor	CasProfile

CAS server using OAuth Wrapper	OAuth 2.0	pac4j-oauth	CasOAuthWrapperClient	CasOAuthWrapperProfile

DropBox	OAuth 1.0	pac4j-oauth	DropBoxClient	DropBoxProfile

Facebook	OAuth 2.0	pac4j-oauth	FacebookClient	FacebookProfile

GitHub	OAuth 2.0	pac4j-oauth	GitHubClient	GitHubProfile

Google	OAuth 2.0	pac4j-oauth	Google2Client	Google2Profile

LinkedIn	OAuth 1.0 & 2.0	pac4j-oauth	LinkedInClient & LinkedIn2Client	LinkedInProfile & LinkedIn2Profile

Twitter	OAuth 1.0	pac4j-oauth	TwitterClient	TwitterProfile

Windows Live	OAuth 2.0	pac4j-oauth	WindowsLiveClient	WindowsLiveProfile

WordPress	OAuth 2.0	pac4j-oauth	WordPressClient	WordPressProfile

Yahoo	OAuth 1.0	pac4j-oauth	YahooClient	YahooProfile

PayPal	OAuth 2.0	pac4j-oauth	PayPalClient	PayPalProfile

Vk	OAuth 2.0	pac4j-oauth	VkClient	VkProfile

Foursquare	OAuth 2.0	pac4j-oauth	FoursquareClient	FoursquareProfile

Bitbucket	OAuth 1.0	pac4j-oauth	BitbucketClient	BitbucketProfile

ORCiD	OAuth 2.0	pac4j-oauth	OrcidClient	OrcidProfile

Web sites with basic auth authentication	HTTP	pac4j-http	BasicAuthClient	HttpProfile

Web sites with form authentication	HTTP	pac4j-http	FormClient	HttpProfile

Google - Deprecated	OpenID	pac4j-openid	GoogleOpenIdClient	GoogleOpenIdProfile

Yahoo	OpenID	pac4j-openid	YahooOpenIdClient	YahooOpenIdProfile

SAML Identity Provider	SAML 2.0	pac4j-saml	Saml2Client	Saml2Profile

Google App Engine User Service	Gae User Service Mechanism	pac4j-gae	GaeUserServiceClient	GaeUserServiceProfile

## Technical description

This library has **only 4 classes** :

1. the **ClientAuthenticationFilter** class is called after authentication at the provider (on the /j_spring_pac4j_security_check url by default) : it creates the ClientAuthenticationToken token and calls the authentication manager to finish the authentication
2. the **ClientAuthenticationToken** class is the token for an authentication (= provider's credentials + the user profile)
3. the **ClientAuthenticationProvider** class is the provider responsible for authenticating ClientAuthenticationToken tokens : it calls the provider to get the access token and the user profile and computes the authorities
4. the **ClientAuthenticationEntryPoint** class redirects the user to the provider for authentication.

and is based on the pac4j-* libraries.

Learn more by browsing the [spring-security-pac4j Javadoc](http://www.pac4j.org/apidocs/spring-security-pac4j/index.html) and the [pac4j Javadoc](http://www.pac4j.org/apidocs/pac4j/index.html).

## How to use it ?

### Add the required dependencies

If you want to use a specific client support, you need to add the appropriate Maven dependency in the *pom.xml* file :

* for OAuth support, the *pac4j-oauth* dependency is required
* for CAS support, the *pac4j-cas* dependency is required
* for HTTP support, the *pac4j-http* dependency is required
* for OpenID support, the *pac4j-openid* dependency is required
* for SAML support, the *pac4j-saml* dependency is required
* for Google App Engine, the *pac4j-gae* dependency is required.

For example, to add OAuth support, add the following XML snippet :

    <dependency>
      <groupId>org.pac4j</groupId>
      <artifactId>pac4j-oauth</artifactId>
      <version>1.6.0</version>
    </dependency>

As these snapshot dependencies are only available in the [Sonatype snapshots repository](https://oss.sonatype.org/content/repositories/snapshots/org/pac4j/), the appropriate repository must be added in the *pom.xml* file also :

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

### Define the clients

All the clients used to communicate with various providers (Facebook, Twitter, a CAS server...) must be defined in your Spring security context file. For example :

    <bean id="facebookClient" class="org.pac4j.oauth.client.FacebookClient">
        <property name="key" value="fbkey" />
        <property name="secret" value="fbsecret" />
    </bean>
    <bean id="twitterClient" class="org.pac4j.oauth.client.TwitterClient">
        <property name="key" value="twkey" />
        <property name="secret" value="twsecret" />
    </bean>
	<bean id="usernamePasswordAuthenticator" class="org.pac4j.http.credentials.SimpleTestUsernamePasswordAuthenticator" />
    <bean id="formClient" class="org.pac4j.http.client.FormClient">
        <property name="loginUrl" value="http://localhost:8080/theForm.jsp" />
        <property name="usernamePasswordAuthenticator" ref="usernamePasswordAuthenticator" />
    </bean>
    <bean id="basicAuthClient" class="org.pac4j.http.client.BasicAuthClient">
        <property name="usernamePasswordAuthenticator" ref="usernamePasswordAuthenticator" />
    </bean>
    <bean id="casClient" class="org.pac4j.cas.client.CasClient">
        <property name="casLoginUrl" value="http://localhost:8888/cas/login" />
    </bean>
    <bean id="clients" class="org.pac4j.core.client.Clients">
        <property name="callbackUrl" value="http://localhost:8080/callback" />
        <property name="clients">
        	<list>
        		<ref bean="facebookClient" />
        		<ref bean="twitterClient" />
        		<ref bean="formClient" />
        		<ref bean="basicAuthClient" />
        		<ref bean="casClient" />
        	</list>
        </property>
    </bean>

### Define the appropriate filter and provider

To authenticate/get the profile of the users in your application after they have been successfully authenticated at the providers, you need to define a filter to receive callbacks (with credentials from the providers) and a provider to finish the authentication process :

    <bean id="clientFilter" class="org.pac4j.springframework.security.web.ClientAuthenticationFilter">
    	<constructor-arg value="/callback"/>
        <property name="clients" ref="clients" />
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>
    <bean id="clientProvider" class="org.pac4j.springframework.security.authentication.ClientAuthenticationProvider">
        <property name="clients" ref="clients" />
    </bean>

### Protect the urls

You can protect your urls and force the user to be authenticated by a client by using the defining the appropriate security configuration with entry points. For example :

    <security:http pattern="/facebook/**" entry-point-ref="facebookEntryPoint">
        <security:custom-filter after="CAS_FILTER" ref="clientFilter" />
        <security:intercept-url pattern="/facebook/**" access="IS_AUTHENTICATED_FULLY" />
    </security:http>
    <security:http pattern="/twitter/**" entry-point-ref="twitterEntryPoint">
        <security:custom-filter after="CAS_FILTER" ref="clientFilter" />
        <security:intercept-url pattern="/twitter/**" access="IS_AUTHENTICATED_FULLY" />
    </security:http>
    ...
    <security:http pattern="/**" entry-point-ref="casEntryPoint">
        <security:custom-filter after="CAS_FILTER" ref="clientFilter" />
        <security:intercept-url pattern="/cas/**" access="IS_AUTHENTICATED_FULLY" />
        <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <security:logout />
    </security:http>
	<bean id="facebookEntryPoint" class="org.pac4j.springframework.security.web.ClientAuthenticationEntryPoint">
        <property name="client" ref="facebookClient" />
    </bean>
    <bean id="twitterEntryPoint" class="org.pac4j.springframework.security.web.ClientAuthenticationEntryPoint">
        <property name="client" ref="twitterClient" />
    </bean>
    ...
    <bean id="casEntryPoint" class="org.pac4j.springframework.security.web.ClientAuthenticationEntryPoint">
        <property name="client" ref="casClient" />
    </bean>

### Get redirection urls

You can also explicitely compute a redirection url to a provider for authentication by using the *getRedirectionUrl* method of the client. For example with Facebook :

    <%
    	WebContext context = new J2EContext(request, response);
	    FacebookClient fbClient = (FacebookClient) application.getAttribute("FacebookClient");
	    String redirectionUrl = fbClient.getRedirectionUrl(context, false, false);
	%>

### Get the user profile

After successful authentication, you can get the authentication of the user using the well-known *SecurityContextHolder* class :

    ClientAuthenticationToken token = (ClientAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
    // user profile
    UserProfile userProfile = token.getUserProfile();
    CommonProfile commonProfile = (CommonProfile) userProfile;

The profile returned is a *CommonProfile*, from which you can retrieve the most common properties that all profiles share.
But you can also cast the user profile to the appropriate profile according to the provider used for authentication.
For example, after a Facebook authentication :

    // facebook profile
    FacebookProfile facebookProfile = (FacebookProfile) commonProfile;

Or for all the OAuth 1.0/2.0 profiles, to get the access token :

    OAuth10Profile oauthProfile = (OAuth10Profile) commonProfile
    String accessToken = oauthProfile.getAccessToken();
    // or
    String accessToken = facebookProfile.getAccessToken();

### Java config sample

    @Configuration
    public class Pac4jConfiguration {

      @Value("${google.key}")
      private String key;

      @Value("${google.secret}")
      private String secret;

      @Value("${callbackUrl}")
      private String callbackUrl;

      @Bean(initMethod = "init")
      public Clients clients() {
        return new Clients(callbackUrl, googleClient());
      }

      @Bean
      public Google2Client googleClient() {
        return new Google2Client(key, secret);
      }
    }

    @Configuration
    @EnableWebMvcSecurity
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

      @Autowired
      private Clients clients;

      @Autowired
      private Google2Client googleClient;

      @Override
      protected void configure(final HttpSecurity http) throws Exception {
        final ClientAuthenticationFilter clientFilter = new ClientAuthenticationFilter("/callback");
        clientFilter.setClients(clients);
        clientFilter.setAuthenticationManager(authenticationManager());
        final ClientAuthenticationEntryPoint googleEntryPoint = new ClientAuthenticationEntryPoint();
        googleEntryPoint.setClient(googleClient);
        http.authorizeRequests().antMatchers("/google").hasRole("USER").and()
          .addFilterBefore(clientFilter, AnonymousAuthenticationFilter.class).exceptionHandling()
          .authenticationEntryPoint(googleEntryPoint).and();
      }

      @Override
      protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        final ClientAuthenticationProvider clientProvider = new ClientAuthenticationProvider();
        clientProvider.setClients(clients);
        auth.authenticationProvider(clientProvider);
      }
    }

### Demo

A demo with Facebook, Twitter, CAS, form authentication and basic auth authentication providers is available at [spring-security-pac4j-demo](https://github.com/pac4j/spring-security-pac4j-demo).

## Versions

The current version **1.2.5-SNAPSHOT** is under development. It's available on the [Sonatype snapshots repository](https://oss.sonatype.org/content/repositories/snapshots/org/pac4j) as a Maven dependency :

The last released version is the **1.2.4** :

    <dependency>
        <groupId>org.pac4j</groupId>
        <artifactId>spring-security-pac4j</artifactId>
        <version>1.2.4</version>
    </dependency>

See the [release notes](https://github.com/pac4j/spring-security-pac4j/wiki/Release-Notes).

## Contact

If you have any question, please use the following mailing lists :
- [pac4j users](https://groups.google.com/forum/?hl=en#!forum/pac4j-users)
- [pac4j developers](https://groups.google.com/forum/?hl=en#!forum/pac4j-dev)


text:
package omx.hdf5;

import ncsa.hdf.hdf5lib.H5;
import ncsa.hdf.hdf5lib.HDF5Constants;
import ncsa.hdf.hdf5lib.exceptions.HDF5Exception;
import ncsa.hdf.hdf5lib.exceptions.HDF5LibraryException;

import java.lang.reflect.Array;
import java.util.*;

/**
 * The {@code OmxHdf5Dataset} ...
 *
 * @author crf
 *         Started 8/18/13 9:34 AM
 */
public class OmxHdf5Dataset implements OmxDataset {
    private final int fileId;
    private final String name;
    private final int[] shape;
    private final OmxHdf5Datatype datatype;
    private final Map<String,Object> attributes;
    private final OmxMutableDataset mutableDataset;

    OmxHdf5Dataset(int fileId, String datasetName, String parentName) {
        this.fileId = fileId;
        name = parentName + (parentName.endsWith("/") ? "" : "/") + datasetName;
        int datasetId = -1;
        try {
            datasetId = H5.H5Dopen(fileId,name,HDF5Constants.H5P_DEFAULT);

            //get datatype
            datatype = new OmxHdf5Datatype(H5.H5Dget_type(datasetId));

            //get shape
            int dataspaceId = H5.H5Dget_space(datasetId);
            long nDims = H5.H5Sget_simple_extent_ndims(dataspaceId);
            long[] dimSize = new long[(int) nDims];
            long[] maxDimSize =  new long[(int) nDims];
            H5.H5Sget_simple_extent_dims(dataspaceId,dimSize,maxDimSize);
            shape = new int[dimSize.length];
            for (int i = 0; i < dimSize.length; i++)
                shape[i] = (int) dimSize[i];

            //get attributes
            attributes = Hdf5Util.getAttributes(datasetId);

        } catch (HDF5Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (datasetId > -1) {
                try {
                    H5.H5Dclose(datasetId);
                } catch (HDF5LibraryException e) {
                    throw new RuntimeException(e); //should this be logged & swallowed instead? todo
                }
            }
        }
        mutableDataset = new OmxModifiableDataset(this);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public int[] getShape() {
        return Arrays.copyOf(shape,shape.length);
    }

    @Override
    public OmxHdf5Datatype getDatatype() {
        return datatype;
    }

    @Override
    public Map<String,Object> getAttributes() { //note: values will not be immutable, so be careful... todo
        return Collections.unmodifiableMap(attributes);
    }

    private void copyData(Object arrayForData) {
        int datasetId = -1;
        try {
            datasetId = H5.H5Dopen(fileId,name,HDF5Constants.H5P_DEFAULT);
            H5.H5Dread(datasetId,getDatatype().getOmxJavaType().getHdf5NativeId(),HDF5Constants.H5S_ALL, HDF5Constants.H5S_ALL,HDF5Constants.H5P_DEFAULT,arrayForData);
        } catch (HDF5Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (datasetId > -1) {
                try {
                    H5.H5Dclose(datasetId);
                } catch (HDF5LibraryException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public Object getData() {
        Object arrayForData = Array.newInstance(getDatatype().getOmxJavaType().getJavaClass(),getShape());
        copyData(arrayForData);
        return arrayForData;
    }

    @Override
    public OmxMutableDataset getMutableDataset() {
        return mutableDataset;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">App</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="title_activity_claimant_add_destination">Claim detail</string>
    <string name="title_activity_claimant_approver_info">ClaimantApproverInfoActivity</string>
    <string name="title_activity_claimant_destination_reason">ClaimantDestinationReasonActivity</string>
    <string name="title_activity_claimant_recipt">ClaimantReciptActivity</string>
    <string name="title_activity_claimant_tag_list">ClaimantTagListActivity</string>
    <string name="title_activity_approver_claim_list">ApproverClaimListActivity</string>
    <string name="title_activity_approver_item_list">ApproverItemListActivity</string>
    <string name="title_activity_approver_claim_detail_list">ApproverClaimDetailList</string>
    <string name="title_activity_approver_recipt">Approver_recipt_activity</string>
    <string name="title_activity_claimant_claim_list">Claimant Claim List</string>
    <string name="add_new_claim">Add a New Claim</string>
    <string name="title_activity_claimant_add_claim">add a new claim</string>
    <string name="title_claim_dialog">Choose what you want to do</string>
    <string name="title_item_dialog">Choose what you want to do</string>

    <string-array name="claim_dialog_array">
        <item>Detail and Destinations</item>
        <item>Expense Items</item>
        <item>Add Comment</item>
        <item>Return this claim</item>
        <item>Approve this claim</item>
    </string-array>
    <string-array name="item_dialog_array">
        <item>Flag/Deflag for Incompleteness</item>
        <item>Photo Recipt</item>
        <item>Details</item>
        <item>Attach a geolocation</item>
        <item>View the geolocation</item>
    </string-array>
    <string-array name="approver_item_dialog_array">
        <item>Photo Recipt</item>
        <item>View the geolocation</item>
    </string-array>
    <string-array name="dest_dialog_array">
        <item>Attach a geolocation</item>
        <item>View the geolocation</item>
    </string-array>
    <string-array name="tag_dialog_array">
        <item>Edit</item>
        <item>Delete</item>
    </string-array>
    <string-array name="currency">
        <item>CAD</item>
        <item>USD</item>
        <item>EUR</item>
        <item>GBP</item>
        <item>CHF</item>
        <item>JPY</item>
        <item>CNY</item>
    </string-array>
    <string-array name="category">
        <item>air fare</item>
        <item>ground transport</item>
        <item>vehicle rental</item>
        <item>private automobile</item>
        <item>fuel</item>
        <item>parking</item>
        <item>registration</item>
        <item>accommodation</item>
        <item>meal</item>
        <item>supplies</item>
    </string-array>

    <string name="title_activity_claimant_item_list">Item List</string>
    <string name="title_activity_claimant_add_item">Add an Item</string>
    <string name="title_activity_claimant_item_detail">Item Detail</string>
    <string name="title_activity_claimant_edit_item">Edit this Item</string>
    <string name="title_activity_claimant_edit_claim">Edit Claim</string>
    <string name="title_activity_claimant_receipt">Photo Receipt</string>
    <string name="push_online">Push Online</string>
    <string name="add_photo">Add a Photographic Receipt</string>
    <string name="delete_photo">Delete this Photographic Receipt</string>
    <string name="manage_tag">Manage Tag</string>
    <string name="title_activity_map">MapActivity</string>
    <string name="title_activity_get_location_by_map">GetLocationByMapActivity</string>
    <string name="title_activity_show_location">ShowLocationActivity</string>

</resources>


text:
package com.hazelcast.internal.jmx;

import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.nio.ConnectionManager;

import java.util.Hashtable;

import static com.hazelcast.internal.jmx.ManagementService.quote;

/**
 * Management bean for {@link com.hazelcast.nio.ConnectionManager}
 */
@ManagedDescription("HazelcastInstance.ConnectionManager")
public class ConnectionManagerMBean extends HazelcastMBean<ConnectionManager> {

    public ConnectionManagerMBean(HazelcastInstance hazelcastInstance, ConnectionManager connectionManager,
                                  ManagementService service) {
        super(connectionManager, service);

        Hashtable<String, String> properties = new Hashtable<String, String>(3);
        properties.put("type", quote("HazelcastInstance.ConnectionManager"));
        properties.put("instance", quote(hazelcastInstance.getName()));
        properties.put("name", quote(hazelcastInstance.getName()));
        setObjectName(properties);
    }

    public ConnectionManager getConnectionManager() {
        return managedObject;
    }

    @ManagedAnnotation("clientConnectionCount")
    @ManagedDescription("Current number of client connections")
    public int getCurrentClientConnections() {
        return getConnectionManager().getCurrentClientConnections();
    }

    @ManagedAnnotation("activeConnectionCount")
    @ManagedDescription("Current number of active connections")
    public int getActiveConnectionCount() {
        return getConnectionManager().getActiveConnectionCount();
    }

    @ManagedAnnotation("connectionCount")
    @ManagedDescription("Current number of connections")
    public int getConnectionCount() {
        return getConnectionManager().getConnectionCount();
    }
}


text:
from nltk import word_tokenize

class AlliterationFinder:

    def __init__(self):
        self.f = ""
        self.counter = 0

    #Path is inputted from AIPController
    #Returns alliteration counter

    def sendFile(self, path):
        self.f = open(path)
        for line in self.f:
            try: self.counter += self.get_all_allits(line)
            except: continue
        c = self.counter
        self.counter = 0
        return c

    #Returns the length of an array which contains all
    #instances of alliteration

    def get_all_allits(self, line):
        allits = []
        try:
            first_word = word_tokenize(line)[0].lower()
        except:
            pass
        for w in word_tokenize(line)[1:]:
            if w[0].lower() == first_word[0]:
                allits.append([first_word, w])
            else:
                first_word = w.lower()
        return len(allits)


text:
<?php global $building; ?>
<?php

	$builds_args = array(
		'hide_empty' => true
	);
	$the_buildings = get_terms('object', $builds_args );
?>

	Prisliste

    <?php foreach ($the_buildings as $building) { ?>
      <?php get_template_part('templates/building-apdetails'); ?>
    <?php } ?>


text:
from django import forms
from django.contrib.admin.widgets import RelatedFieldWidgetWrapper
from django.db.models import ManyToManyRel
from django.utils.translation import ugettext_lazy as _

from zinnia.models import Entry, Category
from zinnia.admin.widgets import MPTTFilteredSelectMultiple
from zinnia.admin.fields import MPTTModelMultipleChoiceField

class EntryForm(forms.ModelForm):
    categories = MPTTModelMultipleChoiceField(
        label=_('Categories'), required=False,
        queryset=Category.objects.all(),
        widget=MPTTFilteredSelectMultiple(_('categories'), False,
                                          attrs={'rows': '10'}))

    def __init__(self, *args, **kwargs):
        from django.contrib import admin
        super(EntryForm, self).__init__(*args, **kwargs)
        rel = ManyToManyRel(Category, 'id')
        self.fields['categories'].widget = RelatedFieldWidgetWrapper(
            self.fields['categories'].widget, rel, admin.site)
        self.fields['tags'].help_text = u"Kommagetrennt"
        #self.fields['image'].help_text = u"764px breit, 300px hoch;"\
        #    u" falls größer, wird zentral geschnitten"

    class Meta:
        model = Entry
        fields = ['title', 'slug', 'resized_image', 'status', 'categories',
                  'tags', 'comment_enabled']


text:
package org.jboss.migration.wfly10.config.management;

import java.util.Collections;
import java.util.HashSet;

/**
 * @author emmartins
 */
public interface ManageableResourceSelectors {

    static <T extends ManageableServerConfiguration> ManageableResourceSelector<T> selectServerConfiguration() {
        return resource -> Collections.singleton((T) resource.getServerConfiguration());
    }

    static ManageableResourceSelector<ManageableResource> toParent() {
        return resource -> {
            final ManageableResource parent = resource.getParentResource();
            return parent != null ? Collections.singleton(parent) : Collections.emptySet();
        };
    }

    static <T extends ManageableResource> ManageableResourceSelector<T> selectResources(Class<T> resourceType) {
        return resource -> resource.findResources(resourceType);
    }

    static <T extends ManageableResource> ManageableResourceSelector<T> selectResources(Class<T> resourceType, String resourceName) {
        return resource -> resource.findResources(resourceType, resourceName);
    }

    static <T extends ManageableResource> ManageableResourceSelector<T> toChildren(Class<T> resourceType) {
        return resource -> new HashSet<>(resource.getChildResources(resourceType));
    }

    static <T extends ManageableResource> ManageableResourceSelector<T> toChild(ManageableResourceType resourceType, String resourceName) {
        return resource -> {
            final T child = resource.getChildResource(resourceType, resourceName);
            return child != null ? Collections.singleton(child) : Collections.emptySet();
        };
    }
}


text:
package Google::Ads::GoogleAds::V12::Services::KeywordPlanIdeaService::GenerateAdGroupThemesResponse;

use strict;
use warnings;
use base qw(Google::Ads::GoogleAds::BaseEntity);

use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;

sub new {
  my ($class, $args) = @_;
  my $self = {
    adGroupKeywordSuggestions => $args->{adGroupKeywordSuggestions},
    unusableAdGroups          => $args->{unusableAdGroups}};

  # Delete the unassigned fields in this object for a more concise JSON payload
  remove_unassigned_fields($self, $args);

  bless $self, $class;
  return $self;
}

1;


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150603_103510_pyramid_create extends Migration
{
    public function up()
    {
        $this->createTable('{{%pyramid}}',[
            'id'=>Schema::TYPE_PK,
            'title'=>Schema::TYPE_STRING,
            'parentId'=>Schema::TYPE_INTEGER,
        ]);
        $this->createIndex('ixParentId','{{%pyramid}}','parentId');
    }

    public function down()
    {
        return $this->dropTable('{{%pyramid}}');
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}


text:
package org.neo4j.cypher.internal.compiler.v2_3.pipes

import org.neo4j.cypher.internal.compiler.v2_3._
import org.neo4j.cypher.internal.compiler.v2_3.commands._
import org.neo4j.cypher.internal.compiler.v2_3.commands.expressions.ShortestPathExpression
import org.neo4j.cypher.internal.compiler.v2_3.commands.predicates.Predicate
import org.neo4j.cypher.internal.compiler.v2_3.executionplan.{ReadsAllNodes, Effects, ReadsRelationships}
import org.neo4j.cypher.internal.compiler.v2_3.helpers.{CastSupport, CollectionSupport}
import org.neo4j.cypher.internal.compiler.v2_3.planDescription.InternalPlanDescription.Arguments.LegacyExpression
import org.neo4j.cypher.internal.frontend.v2_3.symbols._
import org.neo4j.graphdb.Path

import scala.collection.JavaConverters._
/**
 * Shortest pipe inserts a single shortest path between two already found nodes
 */
case class ShortestPathPipe(source: Pipe, shortestPathCommand: ShortestPath, predicates: Seq[Predicate] = Seq.empty)
                           (val estimatedCardinality: Option[Double] = None)(implicit pipeMonitor: PipeMonitor)
  extends PipeWithSource(source, pipeMonitor) with CollectionSupport with RonjaPipe {
  private def pathName = shortestPathCommand.pathName
  private val shortestPathExpression = ShortestPathExpression(shortestPathCommand, predicates)

  protected def internalCreateResults(input: Iterator[ExecutionContext], state: QueryState) = input.flatMap(ctx => {
    val result: Stream[Path] = shortestPathExpression(ctx)(state) match {
      case in: Stream[_] => CastSupport.castOrFail[Stream[Path]](in)
      case null => Stream()
      case path: Path => Stream(path)
      case in: Iterator[_] => CastSupport.castOrFail[Stream[Path]](in.toStream)
    }

    shortestPathCommand.relIterator match {
      case Some(relName) =>
        result.map { (path: Path) => ctx.newWith2(pathName, path, relName, path.relationships().asScala.toSeq) }
      case None =>
        result.map { (path: Path) => ctx.newWith1(pathName, path) }
    }
  })

  val symbols = {
    val withPath = source.symbols.add(pathName, CTPath)
    shortestPathCommand.relIterator match {
      case None    => withPath
      case Some(x) => withPath.add(x, CTCollection(CTRelationship))
    }
  }

  override def planDescriptionWithoutCardinality = {
    val args = predicates.map { p =>
      LegacyExpression(p)
    }
    source.planDescription.andThen(this.id, "ShortestPath", identifiers, args:_*)
  }

  def dup(sources: List[Pipe]): Pipe = {
    val (head :: Nil) = sources
    copy(source = head)(estimatedCardinality)
  }

  override def localEffects = Effects(ReadsAllNodes, ReadsRelationships)

  def withEstimatedCardinality(estimated: Double) = copy()(Some(estimated))
}


text:
#ifndef Theme_h
#define Theme_h

#include "platform/LengthBox.h"
#include "platform/LengthSize.h"
#include "platform/PlatformExport.h"
#include "platform/ThemeTypes.h"
#include "platform/fonts/FontDescription.h"
#include "platform/geometry/IntRect.h"
#include "platform/graphics/Color.h"
#include "wtf/Allocator.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"

namespace blink {

class GraphicsContext;
class ScrollableArea;

// Unlike other platform classes, Theme does extensively use virtual functions.  This design allows a platform to switch between multiple themes at runtime.
class PLATFORM_EXPORT Theme {
    USING_FAST_MALLOC(Theme);
    WTF_MAKE_NONCOPYABLE(Theme);
public:
    Theme() { }
    virtual ~Theme() { }

    // A method to obtain the baseline position adjustment for a "leaf" control.  This will only be used if a baseline
    // position cannot be determined by examining child content. Checkboxes and radio buttons are examples of
    // controls that need to do this.  The adjustment is an offset that adds to the baseline, e.g., marginTop() + height() + |offset|.
    // The offset is not zoomed.
    virtual int baselinePositionAdjustment(ControlPart) const { return 0; }

    // A method asking if the control changes its appearance when the window is inactive.
    virtual bool controlHasInactiveAppearance(ControlPart) const { return false; }

    // General methods for whether or not any of the controls in the theme change appearance when the window is inactive or
    // when hovered over.
    virtual bool controlsCanHaveInactiveAppearance() const { return false; }
    virtual bool controlsCanHaveHoveredAppearance() const { return false; }

    // Used by LayoutTheme::isControlStyled to figure out if the native look and feel should be turned off.
    virtual bool controlDrawsBorder(ControlPart) const { return true; }
    virtual bool controlDrawsBackground(ControlPart) const { return true; }
    virtual bool controlDrawsFocusOutline(ControlPart) const { return true; }

    // Methods for obtaining platform-specific colors.
    virtual Color selectionColor(ControlPart, ControlState, SelectionPart) const { return Color(); }
    virtual Color textSearchHighlightColor() const { return Color(); }

    // CSS system colors and fonts
    virtual Color systemColor(ThemeColor) const { return Color(); }

    // How fast the caret blinks in text fields.
    virtual double caretBlinkInterval() const { return 0.5; }

    // Methods used to adjust the ComputedStyles of controls.

    // The font description result should have a zoomed font size.
    virtual FontDescription controlFont(ControlPart, const FontDescription& fontDescription, float /*zoomFactor*/) const { return fontDescription; }

    // The size here is in zoomed coordinates already.  If a new size is returned, it also needs to be in zoomed coordinates.
    virtual LengthSize controlSize(ControlPart, const FontDescription&, const LengthSize& zoomedSize, float /*zoomFactor*/) const { return zoomedSize; }

    // Returns the minimum size for a control in zoomed coordinates.
    virtual LengthSize minimumControlSize(ControlPart, const FontDescription&, float /*zoomFactor*/) const { return LengthSize(Length(0, Fixed), Length(0, Fixed)); }

    // Allows the theme to modify the existing padding/border.
    virtual LengthBox controlPadding(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;
    virtual LengthBox controlBorder(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;

    // Whether or not whitespace: pre should be forced on always.
    virtual bool controlRequiresPreWhiteSpace(ControlPart) const { return false; }

    // Method for painting a control. The rect is in zoomed coordinates.
    virtual void paint(ControlPart, ControlStates, GraphicsContext&, const IntRect& /*zoomedRect*/, float /*zoomFactor*/, ScrollableArea*) const { }

    // Add visual overflow (e.g., the check on an OS X checkbox). The rect passed in is in zoomed coordinates so
    // the inflation should take that into account and make sure the inflation amount is also scaled by the zoomFactor.
    virtual void addVisualOverflow(ControlPart, ControlStates, float zoomFactor, IntRect& borderBox) const { }

private:
    mutable Color m_activeSelectionColor;
    mutable Color m_inactiveSelectionColor;
};

PLATFORM_EXPORT Theme* platformTheme();

} // namespace blink

#endif // Theme_h


text:
<!DOCTYPE html>

    <title>"Rock-A-By Baby" | Buttercup Gold and Other Stories | Ellen Robena Field | Lit2Go ETC</title>
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8">

          Lit2Go

<form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form>

Authors

Books

Genres

Collections

Readability

      Buttercup Gold and Other Stories

      by Ellen Robena Field

      "Rock-A-By Baby"

        Additional Information

            Year Published:
            1894

            Language:
            English

            Country of Origin:
            United States of America

            Source:
            Field, E.R. (1894)  Buttercup Gold and Other Stories  Bangor: C. H. Glass

            Readability:

                Flesch–Kincaid Level:
                9.5

            Word Count:
            304

            Genre:
            Fairy Tale/Folk Tale

            Keywords:
            19th century literature, children's literature, short stories

            ✎ Cite This

  Share
  |

Downloads

          Audio

          Passage PDF

Student Activity

            APA

            MLA

            Chicago

            Field, E. (1894). "Rock-A-By Baby". Buttercup Gold and Other Stories (Lit2Go Edition). Retrieved February 15, 2016, from http://etc.usf.edu/lit2go/165/buttercup-gold-and-other-stories/2897/rock-a-by-baby/

            Field, Ellen Robena. ""Rock-A-By Baby"." Buttercup Gold and Other Stories. Lit2Go Edition. 1894. Web. <http://etc.usf.edu/lit2go/165/buttercup-gold-and-other-stories/2897/rock-a-by-baby/>. February 15, 2016.

            Ellen Robena Field, ""Rock-A-By Baby"," Buttercup Gold and Other Stories, Lit2Go Edition, (1894), accessed February 15, 2016, http://etc.usf.edu/lit2go/165/buttercup-gold-and-other-stories/2897/rock-a-by-baby/.

Back

Next

                  <audio controls style="width:99%;">
            <source src="http://etc.usf.edu/lit2go/audio/mp3/buttercup-gold-and-other-stories-006-rock-a-by-baby.2897.mp3" type="audio/mpeg" />
                          <source src="http://etc.usf.edu/lit2go/audio/ogg/buttercup-gold-and-other-stories-006-rock-a-by-baby.2897.ogg" type="audio/ogg" />
                        The embedded audio player requires a modern internet browser. You should visit Browse Happy and update your internet browser today!
          </audio>

	”Rock-a-by baby in the treetop,

	    When the wind blows the cradle will rock.”

	FoliageHelena was playing with her dolls under the Maple tree in the garden. It was the first warm day of spring, and the little girl was glad to be out of doors again, and to rock her babies to sleep on one of the low branches.

	But she was not the only one singing a lullaby that bright sunny morning, for Mother Nature was singing one, too, and a soft breeze was gently tucking some little brown cradles to and fro in the tree tops. Some were very, very small, and others were larger, but each held a wee leaf baby, fast asleep. The next time Helena came out to play, the babies in the treetop were waking up, and she could see them in their dainty green nightdresses, peeping out at the world. During the next week they grew a great deal, and one of them crept out of their cradles which fell down to the ground, leaving the babies still up in the treetop.

	By the time Spring went away, the babies had grown large and strong, and spread beautiful green parasols to give shade to their friends through the hot, dusty days of summer. When Autumn came, Mother Nature gave them a holiday, and how pretty they looked in their gay gowns as they frolicked with the wind!

	Then they said goodbye to the Maple tree, and went dancing and whirling over the fields to meet King Winter. When Helena looked into their old homes on the tree, she found some more tiny brown cradles, and knew that in them were new leaf babies that sleep safely til Spring comes again to visit Earthdom, and wakes each “baby in the treetop.”

Back

Next

            This collection of children's literature is a part of the Educational Technology Clearinghouse and is funded by various grants.

            Copyright © 2006—2016 by the Florida Center for Instructional Technology, College of Education, University of South Florida.

License

Credits

FAQ

Giving

This document was downloaded from Lit2Go, a free online collection of stories and poems in Mp3 (audiobook) format published by the Florida Center for Instructional Technology. For more information, including classroom activities, readability data, and original sources, please visit http://etc.usf.edu/lit2go/165/buttercup-gold-and-other-stories/2897/rock-a-by-baby/.

Lit2Go: Buttercup Gold and Other Stories

"Rock-A-By Baby"


text:
#ifndef OMG_DDS_CORE_POLICY_DETAIL_QOS_POLICY_COUNT_HPP_
#define OMG_DDS_CORE_POLICY_DETAIL_QOS_POLICY_COUNT_HPP_

#include <dds/core/policy/detail/TQosPolicyCountImpl.hpp>
#include <org/opensplice/core/policy/QosPolicyCountDelegate.hpp>

/**
 * @cond
 * Ignore this file in the API
 */

namespace dds { namespace core { namespace policy { namespace detail {
	typedef dds::core::policy::TQosPolicyCount<org::opensplice::core::policy::QosPolicyCountDelegate> QosPolicyCount;
} } } }

/** @endcond */

#endif /* !defined(OMG_DDS_CORE_POLICY_DETAIL_QOS_POLICY_COUNT_HPP_) */


text:
To build in 8.4pl1-6, 8.5, 8.5pl1, 8.5pl2, or v8.6, run
```
make
```

In
[`src/Specific/X86/Exponent25519.v`](./src/Specific/X86/Exponent25519.v),
there is an execution of an Ltac reification procedure that can run
for over 90 hours without finishing.


text:
:: Purpose:       Installs a package
:: Requirements:  Run this script with Administrator rights
:: Author:        vocatus on reddit.com/r/sysadmin ( vocatus.gate@gmail.com ) // PGP key ID: 0x07d1490f82a211a2
:: History:       1.0.1 + Add proper console and logfile logging
::                1.0.0 + Initial write

::::::::::
:: Prep :: -- Don't change anything in this section
::::::::::
@echo off
set SCRIPT_VERSION=1.0.1
set SCRIPT_UPDATED=2020-02-05
:: Get the date into ISO 8601 standard date format (yyyy-mm-dd) so we can use it
FOR /f %%a in ('WMIC OS GET LocalDateTime ^| find "."') DO set DTS=%%a
set CUR_DATE=%DTS:~0,4%-%DTS:~4,2%-%DTS:~6,2%

:: This is useful if we start from a network share; converts CWD to a drive letter
pushd "%~dp0"
cls

:::::::::::::::
:: Variables :: -- Set these to your desired values
:::::::::::::::
:: Log location and name. Do not use trailing slashes (\)
set LOGPATH=%SystemDrive%\logs
set LOGFILE=jre10_x64_install.log

:: Package to install. Do not use trailing slashes (\)
set BINARY=jre-10.0.2-x64.msi
set FLAGS=ALLUSERS=1 /qn /norestart /l %LOGPATH%\%LOGFILE% JU=0 JAVAUPDATE=0 AUTOUPDATECHECK=0 RebootYesNo=No WEB_JAVA_SECURITY_LEVEL=M

:: Create the log directory if it doesn't exist
if not exist %LOGPATH% mkdir %LOGPATH%

::::::::::::::::::
:: INSTALLATION ::
::::::::::::::::::
:: This first removes previous versions of the JRE
echo %CUR_DATE% %TIME% Removing previous versions, please wait...
echo %CUR_DATE% %TIME% Removing previous versions, please wait...>> "%LOGPATH%\%LOGFILE%" 2>NUL
WMIC product where "IdentifyingNumber like '{DA69628A-2608-5BA9-8749-1EE90CB29D95}'" call uninstall /nointeractive >> "%LOGPATH%\%LOGFILE%"
WMIC product where "IdentifyingNumber like '{2590B9D6-4310-52BC-808E-1A585861A836}'" call uninstall /nointeractive >> "%LOGPATH%\%LOGFILE%"
WMIC product where "name like 'Java 10%%'" uninstall /nointeractive
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Install the package from a local directory (if all files are in the same directory)
:: Nothing below this line will log correctly, because MSI logs in a different format than the standard "echo >> %logfile%" commands. Haven't had time to find a workaround.
echo %CUR_DATE% %TIME% Installing package...
echo %CUR_DATE% %TIME% Installing package...>> "%LOGPATH%\%LOGFILE%" 2>NUL
msiexec /i "%BINARY%" %FLAGS%
echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

echo %CUR_DATE% %TIME% Disabling telemetry and cleaning up...
echo %CUR_DATE% %TIME% Disabling telemetry and cleaning up...>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: This line kills the Java Update scheduler if it's running
%SystemRoot%\System32\taskkill.exe /f /im jusched.exe>>%LOGPATH%\%LOGFILE% 2>NUL

:: Uninstall the Java Auto Updater from Add/Remove Programs because it sometimes sneaks through
wmic product where "name like 'Java Auto Updater'" call uninstall /nointeractive 2>NUL
wmic product where "IdentifyingNumber like '{4A03706F-666A-4037-7777-5F2748764D10}'" call uninstall /nointeractive >> "%LOGPATH%\%LOGFILE%"

:: These lines disable the Java Auto-Updater keys in the registry
%SystemRoot%\System32\reg.exe DELETE HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v SunJavaUpdateSched /f>> "%LOGPATH%\%LOGFILE%" 2>NUL
%SystemRoot%\System32\reg.exe DELETE "HKLM\SOFTWARE\JavaSoft\Java Update" /f>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Stop the Java Quickstarter service
net stop JavaQuickStarterService>> "%LOGPATH%\%LOGFILE%" 2>NUL
sc delete JavaQuickStarterService>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Stop the Java update service
net stop SunJavaUpdateSched>> "%LOGPATH%\%LOGFILE%" 2>NUL
sc delete SunJavaUpdateSched>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete the Java Update directory (normally contains jaureg.exe, jucheck.exe, and jusched.exe)
rmdir /S /Q "%CommonProgramFiles%\Java\Java Update\">> "%LOGPATH%\%LOGFILE%" 2>NUL
rmdir /S /Q "%CommonProgramFiles(x86)%\Java\Java Update\">> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Delete a bunch of pointless shortcuts Java installs in the All Users Start Menu (sigh...)
if exist "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Java Development Kit" rmdir /s /q "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Java Development Kit">> "%LOGPATH%\%LOGFILE%"
if exist "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Java" rmdir /s /q "%ProgramData%\Microsoft\Windows\Start Menu\Programs\Java">> "%LOGPATH%\%LOGFILE%"

:: This installs the customization files to set the Java Web Security level to MEDIUM (default in all versions prior to JRE8)
XCOPY deployment.* %WINDIR%\Sun\Java\Deployment /I /Y
XCOPY *.sites %WINDIR%\Sun\Java\Deployment /I /Y

echo %CUR_DATE% %TIME% Done.
echo %CUR_DATE% %TIME% Done.>> "%LOGPATH%\%LOGFILE%" 2>NUL

:: Pop back to original directory. This isn't necessary in stand-alone runs of the script, but is needed when being called from another script
popd

:: Return exit code to SCCM/PDQ Deploy/etc
exit /B %EXIT_CODE%


text:
FOUNDATION_EXPORT double KronosVersionNumber;

//! Project version string for Kronos.
FOUNDATION_EXPORT const unsigned char KronosVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Kronos/PublicHeader.h>


text:
<?php

include_once 'vendor/autoload.php';

use Tracy\Debugger;
Debugger::enable();

/**
 * INIT
 * - get token from https://api.slack.com/methods/im.history/test
 * - get channel name from https://api.slack.com/methods/im.list/test
 */
$channelName = '<CHANNEL-NAME>';
$token = '<GENERATED-TOKEN>';
$deletedCountInOneCall = 1000;

// slack can get only 100 last messages in one call
for($i = 1; $i <= ($deletedCountInOneCall / 100); $i++)
{
	// delete messages from channel
	$messagesUrl = "https://slack.com/api/channels.history?token=$token&channel=$channelName&count=$messagesCount&pretty=1";

	// delete messages from chats
	// $messagesUrl = "https://slack.com/api/im.history?token=$token&channel=$channelName&count=$messagesCount&pretty=1";

    // get messages
    $messagesCount = 100;
    $messagesJson = file_get_contents($messagesUrl);
    $messages = json_decode($messagesJson);

    // get message timestamps
    $ts = [];
    if (isset($messages->messages)) {
        foreach($messages->messages as $m) {
            $ts[] = $m->ts;
        }
    }

    // delete URL
    $deleteUrl = "https://slack.com/api/chat.delete?token=$token&channel=$channelName&pretty=1&ts=";

    // delete all messages
    foreach ($ts as $t) {
        $r = file_get_contents($deleteUrl . $t);
    }

    echo "deleted" . sizeof($ts) . " messages" . "\n";
}

exit("end");


text:
package com.blazebit.persistence.view.impl.metamodel;

import com.blazebit.persistence.view.CTEProvider;
import com.blazebit.persistence.view.LockMode;
import com.blazebit.persistence.view.ViewFilterProvider;
import com.blazebit.persistence.view.metamodel.ViewRoot;
import com.blazebit.persistence.view.spi.EntityViewMapping;
import com.blazebit.persistence.view.spi.EntityViewRootMapping;

import javax.persistence.metamodel.ManagedType;
import javax.persistence.metamodel.Type;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Christian Beikov
 * @since 1.2.0
 */
public interface ViewMapping extends Comparable<ViewMapping>, EntityViewMapping {

    InheritanceViewMapping getDefaultInheritanceViewMapping();

    Integer getDefaultBatchSize();

    void setDefaultBatchSize(Integer defaultBatchSize);

    Set<String> getExcludedAttributes();

    void setIdAttributeMapping(MethodAttributeMapping idAttribute);

    void setVersionAttributeMapping(MethodAttributeMapping versionAttribute);

    LockMode getResolvedLockMode();

    Map<String, MethodAttributeMapping> getMethodAttributes();

    void addConstructor(ConstructorMapping constructorMapping);

    Map<ParametersKey, ConstructorMapping> getConstructorMappings();

    String determineInheritanceMapping(MetamodelBuildingContext context);

    void setInheritanceMapping(String inheritanceMapping);

    boolean isInheritanceSubtypesResolved();

    void setInheritanceSubtypesResolved(boolean inheritanceSubtypesResolved);

    Set<Class<?>> getInheritanceSubtypeClasses();

    Set<ViewMapping> getInheritanceSubtypes();

    Set<ViewMapping> getInheritanceSupertypes();

    Set<InheritanceViewMapping> getInheritanceViewMappings();

    void onInitializeViewMappingsFinished(Runnable finishListener);

    boolean isCreatable(MetamodelBuildingContext context);

    void initializeViewMappings(MetamodelBuildingContext context, Runnable finishListener);

    ManagedType<?> getManagedType(MetamodelBuildingContext context);

    ManagedViewTypeImplementor<?> getManagedViewType(MetamodelBuildingContext context, EmbeddableOwner embeddableMapping);

    MethodAttributeMapping getIdAttribute();

    MethodAttributeMapping getVersionAttribute();

    boolean validateDependencies(MetamodelBuildingContext context, Set<Class<?>> dependencies, AttributeMapping originatingAttributeMapping, Class<?> excludeEntityViewClass, boolean reportError);

    List<Method> getSpecialMethods();

    void setSpecialMethods(List<Method> specialMethods);

    Set<Class<? extends CTEProvider>> getCteProviders();

    void setCteProviders(Set<Class<? extends CTEProvider>> cteProviders);

    Map<String, Class<? extends ViewFilterProvider>> getViewFilterProviders();

    void setViewFilterProviders(Map<String, Class<? extends ViewFilterProvider>> viewFilterProviders);

    Set<EntityViewRootMapping> getEntityViewRoots();

    void setEntityViewRoots(Set<EntityViewRootMapping> entityViewRoots);

    Set<ViewRoot> getViewRoots(MetamodelBuildingContext context);

    Map<String, Type<?>> getViewRootTypes(MetamodelBuildingContext context);
}


text:
package com.dianping.cat.report.graph.svg;

public abstract class AbstractGraphPayload implements GraphPayload {
	private String m_axisXLabel;

	private String m_axisYLabel;

	private String m_title;

	private double[] m_values;

	public AbstractGraphPayload(String title, String axisXLabel, String axisYLabel) {
		m_title = title;
		m_axisXLabel = axisXLabel;
		m_axisYLabel = axisYLabel;
	}

	@Override
	public String getAxisXLabel(int index) {
		return String.valueOf(index);
	}

	@Override
	public String getAxisXTitle() {
		return m_axisXLabel;
	}

	@Override
	public String getAxisYTitle() {
		return m_axisYLabel;
	}

	@Override
	public int getColumns() {
		return getValues().length;
	}

	@Override
	public String getDescription() {
		return null;
	}

	@Override
	public int getDisplayHeight() {
		return getHeight();
	}

	@Override
	public int getDisplayWidth() {
		return getWidth();
	}

	@Override
	public int getHeight() {
		return 250;
	}

	@Override
	public String getIdPrefix() {
		Class<?> clazz = getClass();

		if (clazz.isAnonymousClass()) {
			return "a";
		} else {
			return clazz.getSimpleName().substring(0, 1);
		}
	}

	@Override
	public int getMarginBottom() {
		return 60;
	}

	@Override
	public int getMarginLeft() {
		return 90;
	}

	@Override
	public int getMarginRight() {
		return 10;
	}

	@Override
	public int getMarginTop() {
		return 40;
	}

	@Override
	public int getOffsetX() {
		return 0;
	}

	@Override
	public int getOffsetY() {
		return 0;
	}

	@Override
	public int getRows() {
		return 5;
	}

	@Override
	public String getTitle() {
		return m_title;
	}

	@Override
	public final double[] getValues() {
		if (m_values == null) {
			m_values = loadValues();
		}

		return m_values;
	}

	@Override
	public int getWidth() {
		return 580;
	}

	@Override
	public boolean isAxisXLabelRotated() {
		return false;
	}

	@Override
	public boolean isAxisXLabelSkipped() {
		return getValues().length >= 16;
	}

	@Override
	public boolean isStandalone() {
		return true;
	}

	protected abstract double[] loadValues();
}


text:
ActionController::Routing::Routes.draw do |map|
  # theme stuffs
  map.connect 'stylesheets/theme/:filename*extension', :controller => 'theme', :action => 'stylesheets'
  map.connect 'javascripts/theme/:filename*extension', :controller => 'theme', :action => 'javascripts'
  map.connect 'images/theme/:filename*extension', :controller => 'theme', :action => 'images'

  # pretty-fy the feed urls
  map.connect 'feed/atom.xml', :controller => 'feed', :action => 'atom'
  map.connect 'feed/rss.xml', :controller => 'feed', :action => 'rss'

  # pagination
  map.connect 'page/:page', :controller => 'tumble', :action => 'list'

  # our admin stuffs
  map.connect 'admin', :controller => 'admin', :action => 'list'
  map.connect 'admin/:action', :controller => 'admin'

  # show posts by date
  map.connect ':year/:month/:day', :controller => 'tumble',
    :action => 'list_by_date', :year => /\d{4}/, :month => /\d{1,2}/,
    :day => /\d{1,2}/

  # show posts by month
  map.connect ':year/:month', :controller => 'tumble', :action => 'list_by_date',
                              :year => /\d{4}/, :month => /\d{1,2}/

  # show posts by type
  map.connect 'type/:type', :controller => 'tumble', :action => 'list_by_post_type'

  # default
  map.connect '', :controller => 'tumble', :action => 'list'

  # show a single post
  map.connect ':id', :controller => 'tumble', :action => 'show', :id => /\d+/

  # show a tag
  map.connect ':tag', :controller => 'tumble', :action => 'tag',
                      :tag => /[A-Za-z0-9+ ]+/

  # Install the default route as the lowest priority.
  map.connect ':controller/:action/:id'

end


text:
##=============================================================================##
#
# 32 Or 64 Bit Compiler ?
IF( CMAKE_SIZEOF_VOID_P EQUAL 8 )
        SET( HAVE_64_BIT 1 )
	ADD_DEFINITIONS(-DHAVE_64_BIT)
ELSE( CMAKE_SIZEOF_VOID_P EQUAL 8 )
        SET( HAVE_64_BIT 0 )
ENDIF( CMAKE_SIZEOF_VOID_P EQUAL 8 )

# Sets some variables depending on which compiler you are using
#
# USING_GCC  : gcc is being used for C compiler
# USING_GPP  : g++ is being used for C++ compiler
# USING_ICC  : icc is being used for C compiler
# USING_ICPC : icpc is being used for C++ compiler
# USING_WINDOWS_MSVC : MSVC Visual Studio's compiler
# USING_WINDOWS_ICL : Intel's Windows compiler
# USING_LLVM_CLANG : Clang = LLVM Clang (clang.llvm.org)
#  Absoft = Absoft Fortran (absoft.com)
#  ADSP = Analog VisualDSP++ (analog.com)
#  Cray = Cray Compiler (cray.com)
#  Embarcadero, Borland = Embarcadero (embarcadero.com)
#  G95 = G95 Fortran (g95.org)
# GNU = GNU Compiler Collection (gcc.gnu.org)
# HP = Hewlett-Packard Compiler (hp.com)
#  Intel = Intel Compiler (intel.com)
#  MIPSpro = SGI MIPSpro (sgi.com)
#  PGI = The Portland Group (pgroup.com)
#  PathScale = PathScale (pathscale.com)
#  SDCC = Small Device C Compiler (sdcc.sourceforge.net)
# SunPro = Oracle Solaris Studio (oracle.com)
#  TI_DSP = Texas Instruments (ti.com)
#  TinyCC = Tiny C Compiler (tinycc.org)
# Watcom = Open Watcom (openwatcom.org)
# XL, VisualAge, zOS = IBM XL (ibm.com)

# Have to set this variable outside of the top level IF statement,
# since CMake will break if you use it in an IF statement.

SET(NATIVE_COMPILER_NAME_REGEXPR "icc.*$")

#GCC/ICC
IF(NOT CMAKE_COMPILER_IS_GNUCC)
  # This regular expression also matches things like icc-9.1
  IF(CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
    SET(USING_ICC TRUE)
    SET(USING_KNOWN_C_COMPILER TRUE)

	MESSAGE("Using USING_ICC  : icc is being used for C compiler")

  ENDIF(CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
ELSE(NOT CMAKE_COMPILER_IS_GNUCC)
  SET(USING_GCC TRUE)
  SET(USING_KNOWN_C_COMPILER TRUE)

  MESSAGE("Using USING_GCC  : gcc is being used for C compiler")

ENDIF(NOT CMAKE_COMPILER_IS_GNUCC)

SET(NATIVE_COMPILER_NAME_REGEXPR "icpc.*$")
IF(NOT CMAKE_COMPILER_IS_GNUCXX)
  IF   (CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
    SET(USING_ICPC TRUE)
    SET(USING_KNOWN_CXX_COMPILER TRUE)

    EXEC_PROGRAM(${CMAKE_CXX_COMPILER}
      ARGS --version
      OUTPUT_VARIABLE TEMP)

    STRING(REGEX MATCH "([0-9\\.]+)"
      INTEL_COMPILER_VERSION
      ${TEMP})

	MESSAGE("Using USING_ICPC : icpc is being used for C++ compiler, version ${INTEL_COMPILER_VERSION}")

    MARK_AS_ADVANCED(INTEL_COMPILER_VERSION)
  ENDIF(CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
ELSE(NOT CMAKE_COMPILER_IS_GNUCXX)
  SET(USING_GPP TRUE)
  SET(USING_KNOWN_C_COMPILER TRUE)
  SET(USING_KNOWN_CXX_COMPILER TRUE)
  MESSAGE("Using USING_GPP  : g++ is being used for C++ compiler")
ENDIF(NOT CMAKE_COMPILER_IS_GNUCXX)

# The idea is to match a string that ends with cl but doesn't have icl in it.
SET(NATIVE_COMPILER_NAME_REGEXPR "([^i]|^)cl.*$")
IF( ${CMAKE_C_COMPILER_ID} STREQUAL MSVC AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
  SET(USING_WINDOWS_MSVC TRUE)
  SET(USING_KNOWN_C_COMPILER TRUE)
  SET(USING_KNOWN_CXX_COMPILER TRUE)
  # We should set this macro as well to get our nice trig functions
  ADD_DEFINITIONS(-D_USE_MATH_DEFINES)
  # Microsoft does some stupid things like #define min and max.
  ADD_DEFINITIONS(-DNOMINMAX)

  MESSAGE("Using USING_WINDOWS_MSVC : Visual Studio's compiler")

ENDIF( ${CMAKE_C_COMPILER_ID} STREQUAL MSVC AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})

IF( ${CMAKE_C_COMPILER_ID} STREQUAL Clang  AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL Clang  AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
  SET(USING_LLVM_CLANG TRUE)
  SET(USING_KNOWN_C_COMPILER TRUE)
  SET(USING_KNOWN_CXX_COMPILER TRUE)

  MESSAGE("Using USING_LLVM_CLANG : LLVM Clang compiler")

ENDIF( ${CMAKE_C_COMPILER_ID} STREQUAL Clang AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL Clang AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})

# Intel compiler on windows.  Make sure this goes after the cl one.
SET(NATIVE_COMPILER_NAME_REGEXPR "icl.exe$")
IF( ${CMAKE_C_COMPILER_ID} STREQUAL Intel AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL Intel  AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
  SET(USING_WINDOWS_ICL TRUE)
  SET(USING_WINDOWS_MSVC FALSE) # Turn off the other compiler just in case
  SET(USING_KNOWN_C_COMPILER TRUE)
  SET(USING_KNOWN_CXX_COMPILER TRUE)
  # We should set this macro as well to get our nice trig functions
  ADD_DEFINITIONS(-D_USE_MATH_DEFINES)
  # Microsoft does some stupid things like #define min and max.
  ADD_DEFINITIONS(-DNOMINMAX)

  MESSAGE("Using USING_WINDOWS_ICL : Intel's Windows compiler")

ENDIF( ${CMAKE_C_COMPILER_ID} STREQUAL Intel AND CMAKE_C_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR} AND
    ${CMAKE_CXX_COMPILER_ID} STREQUAL Intel  AND CMAKE_CXX_COMPILER MATCHES ${NATIVE_COMPILER_NAME_REGEXPR})
# Do some error checking

# Mixing compilers
IF   (USING_ICC AND USING_GPP)
  FIRST_TIME_MESSAGE("Using icc combined with g++.  Good luck with that.")
ENDIF(USING_ICC AND USING_GPP)

IF   (USING_GCC AND USING_ICPC)
  FIRST_TIME_MESSAGE("Using gcc combined with icpc.  Good luck with that.")
ENDIF(USING_GCC AND USING_ICPC)

IF   (USING_ICC AND USING_GPP)
  FIRST_TIME_MESSAGE("Using icc combined with g++.  Good luck with that")
ENDIF(USING_ICC AND USING_GPP)

# Using unknown compilers
IF   (NOT USING_KNOWN_C_COMPILER)
  FIRST_TIME_MESSAGE("Specified C compiler ${CMAKE_C_COMPILER} is not recognized (gcc, icc).  Using CMake defaults.")
ENDIF(NOT USING_KNOWN_C_COMPILER)

IF   (NOT USING_KNOWN_CXX_COMPILER)
  FIRST_TIME_MESSAGE("Specified CXX compiler ${CMAKE_CXX_COMPILER} is not recognized (g++, icpc).  Using CMake defaults.")
ENDIF(NOT USING_KNOWN_CXX_COMPILER)

# Warn if the compiler is not icc on SGI_LINUX systems
IF   (CMAKE_SYSTEM_PROCESSOR MATCHES "ia64")
  IF(NOT USING_ICC)
	  FIRST_TIME_MESSAGE("Intel Compilers recommended on ia64. setenv CC icc before running cmake.")
  ENDIF(NOT USING_ICC)

  IF(NOT USING_ICPC)
	  FIRST_TIME_MESSAGE("Intel Compilers recommended on ia64. setenv CXX icpc before running cmake.")
  ENDIF(NOT USING_ICPC)
ENDIF(CMAKE_SYSTEM_PROCESSOR MATCHES "ia64")


text:
// flow-typed signature: 0533cf4c3dd8abb74d7bfc21895ecbf1
// flow-typed version: <<STUB>>/react-frame-component_v^4.0.2/flow_v0.100.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'react-frame-component'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'react-frame-component' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'react-frame-component/dist/appbundle' {
  declare module.exports: any;
}

declare module 'react-frame-component/lib/Content' {
  declare module.exports: any;
}

declare module 'react-frame-component/lib/Context' {
  declare module.exports: any;
}

declare module 'react-frame-component/lib/Frame' {
  declare module.exports: any;
}

declare module 'react-frame-component/lib/index' {
  declare module.exports: any;
}

declare module 'react-frame-component/src/Content' {
  declare module.exports: any;
}

declare module 'react-frame-component/src/Context' {
  declare module.exports: any;
}

declare module 'react-frame-component/src/Frame' {
  declare module.exports: any;
}

declare module 'react-frame-component/src/index' {
  declare module.exports: any;
}

declare module 'react-frame-component/test/Content.spec' {
  declare module.exports: any;
}

declare module 'react-frame-component/test/Context.spec' {
  declare module.exports: any;
}

declare module 'react-frame-component/test/Frame.spec' {
  declare module.exports: any;
}

declare module 'react-frame-component/webpack.config' {
  declare module.exports: any;
}

// Filename aliases
declare module 'react-frame-component/dist/appbundle.js' {
  declare module.exports: $Exports<'react-frame-component/dist/appbundle'>;
}
declare module 'react-frame-component/lib/Content.js' {
  declare module.exports: $Exports<'react-frame-component/lib/Content'>;
}
declare module 'react-frame-component/lib/Context.js' {
  declare module.exports: $Exports<'react-frame-component/lib/Context'>;
}
declare module 'react-frame-component/lib/Frame.js' {
  declare module.exports: $Exports<'react-frame-component/lib/Frame'>;
}
declare module 'react-frame-component/lib/index.js' {
  declare module.exports: $Exports<'react-frame-component/lib/index'>;
}
declare module 'react-frame-component/src/Content.jsx' {
  declare module.exports: $Exports<'react-frame-component/src/Content'>;
}
declare module 'react-frame-component/src/Context.jsx' {
  declare module.exports: $Exports<'react-frame-component/src/Context'>;
}
declare module 'react-frame-component/src/Frame.jsx' {
  declare module.exports: $Exports<'react-frame-component/src/Frame'>;
}
declare module 'react-frame-component/src/index.js' {
  declare module.exports: $Exports<'react-frame-component/src/index'>;
}
declare module 'react-frame-component/test/Content.spec.jsx' {
  declare module.exports: $Exports<'react-frame-component/test/Content.spec'>;
}
declare module 'react-frame-component/test/Context.spec.jsx' {
  declare module.exports: $Exports<'react-frame-component/test/Context.spec'>;
}
declare module 'react-frame-component/test/Frame.spec.jsx' {
  declare module.exports: $Exports<'react-frame-component/test/Frame.spec'>;
}
declare module 'react-frame-component/webpack.config.js' {
  declare module.exports: $Exports<'react-frame-component/webpack.config'>;
}


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

import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.OrcDecompressor;
import com.facebook.presto.orc.checkpoint.ByteStreamCheckpoint;
import io.airlift.slice.Slice;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.facebook.presto.memory.context.AggregatedMemoryContext.newSimpleAggregatedMemoryContext;
import static com.facebook.presto.orc.OrcDecompressor.createOrcDecompressor;
import static com.facebook.presto.orc.metadata.CompressionKind.SNAPPY;

public class TestByteStream
        extends AbstractTestValueStream<Byte, ByteStreamCheckpoint, ByteOutputStream, ByteInputStream>
{
    @Test
    public void testLiteral()
            throws IOException
    {
        List<List<Byte>> groups = new ArrayList<>();
        for (int groupIndex = 0; groupIndex < 3; groupIndex++) {
            List<Byte> group = new ArrayList<>();
            for (int i = 0; i < 1000; i++) {
                group.add((byte) (groupIndex * 10_000 + i));
            }
            groups.add(group);
        }
        testWriteValue(groups);
    }

    @Test
    public void testRleLong()
            throws IOException
    {
        List<List<Byte>> groups = new ArrayList<>();
        for (int groupIndex = 0; groupIndex < 3; groupIndex++) {
            List<Byte> group = new ArrayList<>();
            for (int i = 0; i < 1000; i++) {
                group.add((byte) 77);
            }
            groups.add(group);
        }
        testWriteValue(groups);
    }

    @Test
    public void testRleShort()
            throws IOException
    {
        List<List<Byte>> groups = new ArrayList<>();
        for (int groupIndex = 0; groupIndex < 3; groupIndex++) {
            List<Byte> group = new ArrayList<>();
            for (int i = 0; i < 1000; i++) {
                group.add((byte) ((groupIndex * 10_000 + i) / 13));
            }
            groups.add(group);
        }
        testWriteValue(groups);
    }

    @Override
    protected ByteOutputStream createValueOutputStream()
    {
        return new ByteOutputStream(SNAPPY, COMPRESSION_BLOCK_SIZE);
    }

    @Override
    protected void writeValue(ByteOutputStream outputStream, Byte value)
    {
        outputStream.writeByte(value);
    }

    @Override
    protected ByteInputStream createValueStream(Slice slice)
            throws OrcCorruptionException
    {
        Optional<OrcDecompressor> orcDecompressor = createOrcDecompressor(ORC_DATA_SOURCE_ID, SNAPPY, COMPRESSION_BLOCK_SIZE);
        return new ByteInputStream(new OrcInputStream(ORC_DATA_SOURCE_ID, slice.getInput(), orcDecompressor, newSimpleAggregatedMemoryContext(), slice.getRetainedSize()));
    }

    @Override
    protected Byte readValue(ByteInputStream valueStream)
            throws IOException
    {
        return valueStream.next();
    }
}


text:
package mesosphere.marathon.upgrade

import akka.testkit.{ TestProbe, TestActorRef }
import com.codahale.metrics.MetricRegistry
import mesosphere.marathon.core.launcher.impl.LaunchQueueTestHelper
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.core.leadership.AlwaysElectedLeadershipModule
import mesosphere.marathon.core.readiness.ReadinessCheckExecutor
import mesosphere.marathon.core.task.{ TaskStateOp, Task }
import mesosphere.marathon.core.task.tracker.{ TaskCreationHandler, TaskTracker }
import mesosphere.marathon.event.{ DeploymentStatus, HealthStatusChanged, MesosStatusUpdateEvent }
import mesosphere.marathon.health.HealthCheck
import mesosphere.marathon.metrics.Metrics
import mesosphere.marathon.state.PathId._
import mesosphere.marathon.state.{ AppDefinition, Timestamp }
import mesosphere.marathon.test.MarathonActorSupport
import mesosphere.marathon.{ MarathonTestHelper, SchedulerActions, TaskUpgradeCanceledException }
import mesosphere.util.state.memory.InMemoryStore
import org.apache.mesos.SchedulerDriver
import org.mockito.Mockito
import org.mockito.Mockito.{ spy, verify, when }
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{ BeforeAndAfter, FunSuiteLike, Matchers }

import scala.concurrent.duration._
import scala.concurrent.{ Await, Promise }

class TaskStartActorTest
    extends MarathonActorSupport
    with FunSuiteLike
    with Matchers
    with MockitoSugar
    with ScalaFutures
    with BeforeAndAfter {

  for (
    (counts, description) <- Seq(
      None -> "with no item in queue",
      Some(LaunchQueueTestHelper.zeroCounts) -> "with zero count queue item"
    )
  ) {
    test(s"Start success $description") {
      val f = new Fixture
      val promise = Promise[Unit]()
      val app = AppDefinition("/myApp".toPath, instances = 5)

      when(f.launchQueue.get(app.id)).thenReturn(counts)
      val ref = f.startActor(app, app.instances, promise)
      watch(ref)

      verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances)

      for (i <- 0 until app.instances)
        system.eventStream.publish(MesosStatusUpdateEvent("", Task.Id(s"task-$i"), "TASK_RUNNING", "", app.id, "", None, Nil, app.version.toString))

      Await.result(promise.future, 3.seconds) should be(())

      expectTerminated(ref)
    }
  }

  test("Start success with one task left to launch") {
    val f = new Fixture
    val counts = Some(LaunchQueueTestHelper.zeroCounts.copy(tasksLeftToLaunch = 1, finalTaskCount = 1))
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 5)

    when(f.launchQueue.get(app.id)).thenReturn(counts)

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances - 1)

    for (i <- 0 until (app.instances - 1))
      system
        .eventStream
        .publish(MesosStatusUpdateEvent("", Task.Id(s"task-$i"), "TASK_RUNNING", "", app.id, "", None, Nil, app.version.toString))

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Start success with existing task in launch queue") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 5)

    when(f.launchQueue.get(app.id)).thenReturn(None)
    val task =
      MarathonTestHelper.startingTaskForApp(app.id, appVersion = Timestamp(1024))
    f.taskCreationHandler.created(TaskStateOp.LaunchEphemeral(task)).futureValue

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances - 1)

    for (i <- 0 until (app.instances - 1))
      system.eventStream.publish(MesosStatusUpdateEvent("", Task.Id(s"task-$i"), "TASK_RUNNING", "", app.id, "", None, Nil, app.version.toString))

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Start success with no instances to start") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 0)
    when(f.launchQueue.get(app.id)).thenReturn(None)

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Start with health checks") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition(
      "/myApp".toPath,
      instances = 5,
      healthChecks = Set(HealthCheck())
    )
    when(f.launchQueue.get(app.id)).thenReturn(None)

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances)

    for (i <- 0 until app.instances)
      system.eventStream.publish(HealthStatusChanged(app.id, Task.Id(s"task_$i"), app.version, alive = true))

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Start with health checks with no instances to start") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition(
      "/myApp".toPath,
      instances = 0,
      healthChecks = Set(HealthCheck())
    )
    when(f.launchQueue.get(app.id)).thenReturn(None)

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Cancelled") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 5)
    when(f.launchQueue.get(app.id)).thenReturn(None)

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    system.stop(ref)

    intercept[TaskUpgradeCanceledException] {
      Await.result(promise.future, 5.seconds)
    }.getMessage should equal("The task upgrade has been cancelled")

    expectTerminated(ref)
  }

  test("Task fails to start") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 1)

    when(f.launchQueue.get(app.id)).thenReturn(None)
    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances)

    system.eventStream.publish(MesosStatusUpdateEvent("", Task.Id.forRunSpec(app.id), "TASK_FAILED", "", app.id, "", None, Nil, app.version.toString))

    verify(f.launchQueue, Mockito.timeout(3000)).add(app, 1)

    for (i <- 0 until app.instances)
      system.eventStream.publish(MesosStatusUpdateEvent("", Task.Id.forRunSpec(app.id), "TASK_RUNNING", "", app.id, "", None, Nil, app.version.toString))

    Await.result(promise.future, 3.seconds) should be(())

    expectTerminated(ref)
  }

  test("Start success with dying existing task, reschedules, but finishes early") {
    val f = new Fixture
    val promise = Promise[Unit]()
    val app = AppDefinition("/myApp".toPath, instances = 5)
    when(f.launchQueue.get(app.id)).thenReturn(None)

    val outdatedTask = MarathonTestHelper.stagedTaskForApp(app.id, appVersion = Timestamp(1024))
    val taskId = outdatedTask.taskId
    f.taskCreationHandler.created(TaskStateOp.LaunchEphemeral(outdatedTask)).futureValue

    val ref = f.startActor(app, app.instances, promise)
    watch(ref)

    // wait for initial sync
    verify(f.launchQueue, Mockito.timeout(3000)).get(app.id)
    verify(f.launchQueue, Mockito.timeout(3000)).add(app, app.instances - 1)

    Mockito.verifyNoMoreInteractions(f.launchQueue)
    Mockito.reset(f.launchQueue)

    // let existing task die
    when(f.taskTracker.countLaunchedAppTasksSync(app.id)).thenReturn(0)
    when(f.launchQueue.get(app.id)).thenReturn(Some(LaunchQueueTestHelper.zeroCounts.copy(tasksLeftToLaunch = 4, finalTaskCount = 4)))
    system.eventStream.publish(MesosStatusUpdateEvent(
      slaveId = "", taskId = taskId, taskStatus = "TASK_ERROR", message = "", appId = app.id, host = "",
      ipAddresses = None, ports = Nil,
      // The version does not match the app.version so that it is filtered in StartingBehavior.
      // does that make sense?
      version = outdatedTask.launched.get.runSpecVersion.toString
    ))

    // sync will reschedule task
    ref ! StartingBehavior.Sync
    verify(f.launchQueue, Mockito.timeout(3000)).get(app.id)
    verify(f.launchQueue, Mockito.timeout(3000)).add(app, 1)

    Mockito.verifyNoMoreInteractions(f.launchQueue)
    Mockito.reset(f.launchQueue)

    // launch 4 of the tasks
    when(f.launchQueue.get(app.id)).thenReturn(Some(LaunchQueueTestHelper.zeroCounts.copy(tasksLeftToLaunch = app.instances, finalTaskCount = 4)))
    when(f.taskTracker.countLaunchedAppTasksSync(app.id)).thenReturn(4)
    List(0, 1, 2, 3) foreach { i =>
      system.eventStream.publish(MesosStatusUpdateEvent("", Task.Id(s"task-$i"), "TASK_RUNNING", "", app.id, "", None, Nil, app.version.toString))
    }

    // it finished early
    Await.result(promise.future, 3.seconds) should be(())

    Mockito.verifyNoMoreInteractions(f.launchQueue)

    expectTerminated(ref)
  }

  class Fixture {

    val driver: SchedulerDriver = mock[SchedulerDriver]
    val scheduler: SchedulerActions = mock[SchedulerActions]
    val launchQueue: LaunchQueue = mock[LaunchQueue]
    val metrics: Metrics = new Metrics(new MetricRegistry)
    val leadershipModule = AlwaysElectedLeadershipModule.forActorSystem(system)
    val taskTrackerModule = MarathonTestHelper.createTaskTrackerModule(
      leadershipModule, store = new InMemoryStore, metrics = metrics)
    val taskTracker: TaskTracker = spy(taskTrackerModule.taskTracker)
    val taskCreationHandler: TaskCreationHandler = taskTrackerModule.taskCreationHandler
    val deploymentManager = TestProbe()
    val status: DeploymentStatus = mock[DeploymentStatus]
    val readinessCheckExecutor: ReadinessCheckExecutor = mock[ReadinessCheckExecutor]

    def startActor(app: AppDefinition, scaleTo: Int, promise: Promise[Unit]): TestActorRef[TaskStartActor] = TestActorRef(TaskStartActor.props(
      deploymentManager.ref, status, driver, scheduler, launchQueue, taskTracker, system.eventStream, readinessCheckExecutor, app, scaleTo, promise
    ))
  }
}


text:
package org.wso2.siddhi.parser.core;

import org.wso2.siddhi.parser.core.appcreator.DeployableSiddhiQueryGroup;
import org.wso2.siddhi.parser.core.topology.SiddhiTopology;
import org.wso2.siddhi.parser.service.model.MessagingSystem;

import java.util.List;

/**
 * This interface is utilized by  which will be implemented by different
 * distributed deployment implementations. Implementor can either choose to
 * implement from scratch using this interface or use.
 */
public interface SiddhiAppCreator {
    /**
     * Create valid concrete Siddhi Apps for each Query Group in the given {@link SiddhiTopology}.
     *
     * @param topology Input topology to create Siddhi Apps
     * @return List of {@link DeployableSiddhiQueryGroup}s. Length of the list should be equal to no. of groups user
     * has defined. Length of the list should be greater than zero always.
     */
    List<DeployableSiddhiQueryGroup> createApps(SiddhiTopology topology, MessagingSystem messagingSystem);
}


text:
'''

 All components of this library are licensed under the BSD 3-Clause
 License.

 Copyright (c) 2015-, Algorithmic Robotics and Control Group @Rutgers
 (http://arc.cs.rutgers.edu). All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:

 Redistributions of source code must retain the above copyright notice,
 this list of conditions and the following disclaimer.  Redistributions
 in binary form must reproduce the above copyright notice, this list of
 conditions and the following disclaimer in the documentation and/or
 other materials provided with the distribution. Neither the name of
 Rutgers University nor the names of the contributors may be used to
 endorse or promote products derived from this software without specific
 prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'''
"""
microMVP useful functions.

"""

# The arduino ID and the respect tag of car (ID, tag), max 10
carInfo = [(2, 2), (3, 3), (4, 4), (5, 0), (6, 11),(7, 7),(8, 8),(9, 9),(10, 10)]
# IP address of the computer running position_.exe (local: zmqPublisherIP = "localhost")
zmqPublisherIP = "localhost"
# Port of xBee sender, can be found in Device Manager, Ports
xBeeSocket = 'COM3'
# Simulation Speed, lower value gives a more precise simulation
simSpeed = 5.0
# Sidelength of tag / Vehicle wheelbase
tagRatio = 0.90

"""
-------------------------------------------------------
Dont make changes under this line
-------------------------------------------------------
"""
# Part 0: configs
zmqPublisherPort = "5556"
wheelBase = 30.0
tagRatio = 0.90
container_width = 1420
container_height = 780
painter_width = 1280
painter_height = 720
spacer = 8
gridCopy = []

# Part 1: Colors
RGB_WHITE = (255, 255, 255)
RGB_BLACK = (0, 0, 0)
RGB_RED = (255, 0, 0)
RGB_GREEN = (0, 255, 0)
RGB_BLUE = (0, 0, 255)
RGB_PINK = (255, 0, 255)
RGB_YELLOW = (255, 255, 0)
RGB_GREY = (128, 128, 128)
RGB_DEEPBLUE = (0, 0, 255)
RGB_PURPLE = (127, 0, 255)

# High contrast colors, from http://godsnotwheregodsnot.blogspot.ru/2012/09/color-distribution-methodology.html
RGB_PATH_COLORS = [(0, 0, 0),(1, 0, 103),(213, 255, 0),(255, 0, 86),(158, 0, 142),(14, 76, 161),\
(255, 229, 2),(0, 95, 57),(0, 255, 0),(149, 0, 58),(255, 147, 126),(164, 36, 0),\
(0, 21, 68),(145, 208, 203),(98, 14, 0),(107, 104, 130),(0, 0, 255),(0, 125, 181),\
(106, 130, 108),(0, 174, 126),(194, 140, 159),(190, 153, 112),(0, 143, 156),(95, 173, 78),\
(255, 0, 0),(255, 0, 246),(255, 2, 157),(104, 61, 59),(255, 116, 163),(150, 138, 232),\
(152, 255, 82),(167, 87, 64),(1, 255, 254),(255, 238, 232),(254, 137, 0),(189, 198, 255),\
(1, 208, 255),(187, 136, 0),(117, 68, 177),(165, 255, 210),(255, 166, 254),(119, 77, 0),\
(122, 71, 130),(38, 52, 0),(0, 71, 84),(67, 0, 44),(181, 0, 255),(255, 177, 103),\
(255, 219, 102),(144, 251, 146),(126, 45, 210),(189, 211, 147),(229, 111, 254),(222, 255, 116),\
(0, 255, 120),(0, 155, 255),(0, 100, 1),(0, 118, 255),(133, 169, 0),(0, 185, 23),\
(120, 130, 49),(0, 255, 198),(255, 110, 65),(232, 94, 190)]

# Part n: Class for a car
class UnitCar:
    def __init__(self, tag = "0", ID = "0"):
        self.tag = tag
        self.ID = ID
        self.x = 0.0
        self.y = 0.0
        self.theta = 0.0
        self.lSpeed = 0.0
        self.rSpeed = 0.0
        self.path = list()

class Boundary:
    def __init__(self):
        self.u = 2 * wheelBase
        self.d = painter_height - 2 * wheelBase
        self.l = 2 * wheelBase
        self.r = painter_width - 2 * wheelBase
        self.width = self.r - self.l
        self.height = self.d - self.u

# Part 1: Dialogs in GUI
from pgu import gui

class AboutDialog(gui.Dialog):
    def __init__(self, **params):
        title = gui.Label("About microMVP")

        width = 400
        height = 200
        doc = gui.Document(width = width)

        space = title.style.font.size(" ")

        doc.block(align=0)
        for word in """microMVP v2.0""".split(" "):
            doc.add(gui.Label(word))
            doc.space(space)
        doc.br(space[1])

        doc.block(align=-1)
        for word in """microMVP v2.0""".split(" "):
            doc.add(gui.Label(word))
            doc.space(space)
        doc.br(space[1])

        gui.Dialog.__init__(self,title,gui.ScrollArea(doc,width,height))

class HelpDialog(gui.Dialog):
    def __init__(self, **params):
        title = gui.Label("Help")

        doc = gui.Document(width=400)

        space = title.style.font.size(" ")

        doc.br(space[1])

        doc.block(align=-1)
        for word in """Please refer to http://arc.cs.rutgers.edu/mvp/""".split(" "):
            doc.add(gui.Label(word))
            doc.space(space)

        gui.Dialog.__init__(self,title,doc)

class QuitDialog(gui.Dialog):
    def __init__(self, **params):
        title = gui.Label("Quit")

        t = gui.Table()

        t.tr()
        t.add(gui.Label("Are you sure you want to quit?"),colspan=2)

        t.tr()
        e = gui.Button("Okay")
        e.connect(gui.CLICK,self.send,gui.QUIT)
        t.td(e)

        e = gui.Button("Cancel")
        e.connect(gui.CLICK,self.close,None)
        t.td(e)

        gui.Dialog.__init__(self,title,t)

import math

def CheckCollosion(thresh, x1, y1, x2, y2):
        if math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) <= thresh:
            return True
        return False


text:
package org.piraso.ui.base.views;

import org.piraso.api.entry.MethodCallEntry;
import org.piraso.api.entry.ObjectEntry;
import org.piraso.api.entry.ObjectEntryUtils;
import org.piraso.ui.api.views.BaseEntryViewTopComponent;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;

import javax.swing.*;

import static org.piraso.ui.api.util.JTextPaneUtils.*;

/**
 * Method call view component
 */
@ActionID(category = "Window", id = "org.piraso.ui.base.MethodCallViewTopComponent")
@ActionReference(path = "Menu/Window", position = 333)
@ConvertAsProperties(dtd = "-//org.piraso.ui.base//MethodCallView//EN", autostore = false)
@TopComponent.Description(preferredID = "MethodCallViewTopComponent", iconBase= "org/piraso/ui/base/icons/method.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "output", openAtStartup = true)
@TopComponent.OpenActionRegistration(displayName = "#CTL_MethodViewAction", preferredID = "MethodCallViewTopComponent")
public class MethodCallViewTopComponent extends BaseEntryViewTopComponent<MethodCallEntry> {

    public MethodCallViewTopComponent() {
        super(MethodCallEntry.class, "Method");

        setName(NbBundle.getMessage(MethodCallViewTopComponent.class, "CTL_MethodViewTopComponent"));
        setToolTipText(NbBundle.getMessage(MethodCallViewTopComponent.class, "HINT_MethodViewTopComponent"));
    }

    @Override
    protected void populateMessage(JTextPane txtMessage, MethodCallEntry entry) throws Exception {
        insertHeaderCode(txtMessage, currentEntry.getGenericString());
        insertCode(txtMessage, "\n");

        if(currentEntry.getArguments() != null && currentEntry.getArguments().length > 0) {
            for(int i = 0; i < currentEntry.getArguments().length; i++) {
                ObjectEntry argument = currentEntry.getArguments()[i];
                insertKeyword(txtMessage, String.format("\nArgument[%d]: ", i));
                insertCode(txtMessage, ObjectEntryUtils.toString(argument));
            }
        }

        if(!currentEntry.getReturnClassName().equals("void")) {
            insertKeyword(txtMessage, "\nReturn: ");
            insertCode(txtMessage, ObjectEntryUtils.toString(currentEntry.getReturnedValue()));
        }
    }

    void writeProperties(java.util.Properties p) {
        p.setProperty("version", "1.0");
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
    }
}


text:
<?php

namespace Oro\Bundle\EmailBundle\Tests\Unit\EventListener;

use Doctrine\Common\Util\ClassUtils;

use JMS\JobQueueBundle\Entity\Job;

use Oro\Component\TestUtils\Mocks\ServiceLink;
use Oro\Component\TestUtils\ORM\Mocks\UnitOfWork;
use Oro\Bundle\EmailBundle\EventListener\EntityListener;
use Oro\Bundle\UserBundle\Entity\User;
use Oro\Bundle\EmailBundle\Entity\Email;
use Oro\Bundle\EmailBundle\Entity\Provider\EmailOwnerProviderStorage;
use Oro\Bundle\EmailBundle\Tests\Unit\Entity\TestFixtures\EmailAddress;

class EntityListenerTest extends \PHPUnit_Framework_TestCase
{
    /** @var EntityListener */
    private $listener;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $emailOwnerManager;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $emailActivityManager;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $emailThreadManager;

    /** @var EmailOwnerProviderStorage */
    private $emailOwnerStorage;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $registry;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $userEmailOwnerProvider;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    private $emailActivityUpdates;

    /** @var ActivityListChainProvider */
    private $chainProvider;

    protected function setUp()
    {
        $this->emailOwnerManager    =
            $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Manager\EmailOwnerManager')
                ->disableOriginalConstructor()
                ->getMock();
        $this->emailActivityManager =
            $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Manager\EmailActivityManager')
                ->disableOriginalConstructor()
                ->getMock();
        $this->emailThreadManager =
            $this->getMockBuilder('Oro\Bundle\EmailBundle\Entity\Manager\EmailThreadManager')
                ->disableOriginalConstructor()
                ->getMock();
        $this->registry = $this->getMockBuilder('Doctrine\Bundle\DoctrineBundle\Registry')
                ->setMethods(['getRepository', 'getEmailsByOwnerEntity'])
                ->disableOriginalConstructor()
                ->getMock();
        $this->userEmailOwnerProvider = $this
            ->getMockBuilder('Oro\Bundle\UserBundle\Entity\Provider\EmailOwnerProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $this->chainProvider =
            $this->getMockBuilder('Oro\Bundle\ActivityListBundle\Provider\ActivityListChainProvider')
                ->disableOriginalConstructor()->getMock();

        $this->emailOwnerStorage = new EmailOwnerProviderStorage();
        $this->emailOwnerStorage->addProvider($this->userEmailOwnerProvider);

        $this->emailActivityUpdates = $this->getMockBuilder('Oro\Bundle\EmailBundle\Model\EmailActivityUpdates')
            ->disableOriginalConstructor()
            ->getMock();

        $this->listener = new EntityListener(
            $this->emailOwnerManager,
            new ServiceLink($this->emailActivityManager),
            new ServiceLink($this->emailThreadManager),
            $this->emailActivityUpdates
        );
    }

    public function testOnFlush()
    {
        $contactsArray = [new User(), new User(), new User()];
        $updatedEmailAddresses = [new EmailAddress(1), new EmailAddress(2)];

        $uow = $this->getMockBuilder('Oro\Component\TestUtils\ORM\Mocks\UnitOfWork')
            ->disableOriginalConstructor()
            ->setMethods(['computeChangeSet'])
            ->getMock();

        array_map([$uow, 'addInsertion'], $contactsArray);

        $metadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')
            ->disableOriginalConstructor()
            ->getMock();
        $em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();
        $em->expects($this->any())
            ->method('getClassMetadata')
            ->will($this->returnValue($metadata));
        $em->expects($this->any())
            ->method('getUnitOfWork')
            ->will($this->returnValue($uow));
        $em
            ->expects($this->once())
            ->method('flush');
        $uow->expects($this->exactly(2))
            ->method('computeChangeSet')
            ->withConsecutive(
                [$metadata, $updatedEmailAddresses[0]],
                [$metadata, $updatedEmailAddresses[1]]
            );
        $onFlushEventArgs = $this->getMockBuilder('Doctrine\ORM\Event\OnFlushEventArgs')
            ->disableOriginalConstructor()
            ->getMock();
        $onFlushEventArgs
            ->expects($this->once())
            ->method('getEntityManager')
            ->will($this->returnValue($em));

        $this->emailOwnerManager->expects($this->once())
            ->method('createEmailAddressData')
            ->with($this->identicalTo($uow))
            ->will($this->returnValue([]));
        $this->emailOwnerManager->expects($this->once())
            ->method('handleChangedAddresses')
            ->with([])
            ->will($this->returnValue($updatedEmailAddresses));

        $postFlushEventArgs = $this->getMockBuilder('Doctrine\ORM\Event\PostFlushEventArgs')
            ->disableOriginalConstructor()
            ->getMock();
        $postFlushEventArgs
            ->expects($this->any())
            ->method('getEntityManager')
            ->will($this->returnValue($em));

        $this->emailActivityUpdates
            ->expects($this->once())
            ->method('createJobs')
            ->will($this->returnValue([new Job('command')]));

        $this->listener->onFlush($onFlushEventArgs);
        $this->listener->postFlush($postFlushEventArgs);
    }

    public function testOnFlushNotSupported()
    {
        $contactsArray = [new User(), new User(), new User()];
        $createdEmailsArray = [new Email(), new Email(), new Email()];
        $updatedEmailsArray = [new Email()];
        $createdEmails = [
            spl_object_hash($createdEmailsArray[0]) => $createdEmailsArray[0],
            spl_object_hash($createdEmailsArray[1]) => $createdEmailsArray[1],
            spl_object_hash($createdEmailsArray[2]) => $createdEmailsArray[2],
        ];
        $updatedEmails = [
            spl_object_hash($updatedEmailsArray[0]) => $updatedEmailsArray[0],
        ];

        $uow = new UnitOfWork();
        array_map([$uow, 'addInsertion'], array_merge($contactsArray, $createdEmailsArray));
        array_map([$uow, 'addUpdate'], $updatedEmailsArray);

        $metadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadataInfo')
            ->disableOriginalConstructor()
            ->getMock();
        $em = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();
        $em->expects($this->any())
            ->method('getClassMetadata')
            ->will($this->returnValue($metadata));
        $em->expects($this->any())
            ->method('getUnitOfWork')
            ->will($this->returnValue($uow));
        $onFlushEventArgs = $this->getMockBuilder('Doctrine\ORM\Event\OnFlushEventArgs')
            ->disableOriginalConstructor()
            ->getMock();
        $onFlushEventArgs
            ->expects($this->any())
            ->method('getEntityManager')
            ->will($this->returnValue($em));

        $this->emailOwnerManager->expects($this->once())
            ->method('createEmailAddressData')
            ->will($this->returnValue([]));
        $this->emailOwnerManager->expects($this->once())
            ->method('handleChangedAddresses')
            ->will($this->returnValue([]));
        $this->emailActivityManager->expects($this->once())
            ->method('updateActivities')
            ->with($createdEmails);
        $this->emailThreadManager->expects($this->once())
            ->method('updateThreads')
            ->with($createdEmails);
        $this->emailThreadManager->expects($this->once())
            ->method('updateHeads')
            ->with($updatedEmails);
        $this->emailActivityManager->expects($this->once())
            ->method('updateActivities')
            ->with($createdEmails);

        $postFlushEventArgs = $this->getMockBuilder('Doctrine\ORM\Event\PostFlushEventArgs')
            ->disableOriginalConstructor()
            ->getMock();
        $postFlushEventArgs
            ->expects($this->any())
            ->method('getEntityManager')
            ->will($this->returnValue($em));

        $this->registry
            ->expects($this->never())
            ->method('getRepository')
            ->will($this->returnValue($this->registry));
        $this->registry
            ->expects($this->never())
            ->method('getEmailsByOwnerEntity')
            ->will($this->returnValue($createdEmailsArray));
        $this->emailActivityUpdates
                ->expects($this->once())
                ->method('processUpdatedEmailAddresses')
                ->with([]);
        $this->emailActivityUpdates->expects($this->once())
            ->method('createJobs')
            ->will($this->returnValue([new Job('command')]));
        $this->userEmailOwnerProvider
            ->expects($this->never())
            ->method('getEmailOwnerClass')
            ->will($this->returnValue(ClassUtils::getClass(new User)));

        $this->emailActivityManager
            ->expects($this->never())
            ->method('addAssociation');

        $this->listener->onFlush($onFlushEventArgs);
        $this->listener->postFlush($postFlushEventArgs);
    }
}