text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Moq;
using NUnit.Framework;
using SFA.DAS.PAS.Account.Api.Orchestrator;
using SFA.DAS.PAS.Account.Api.Types;
using SFA.DAS.ProviderApprenticeshipsService.Application.Commands.SendNotification;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces;

namespace SFA.DAS.PAS.Account.Api.UnitTests.Orchestrator
{
    [TestFixture]
    public class WhenSendingEmailToAllProviderRecipients_AccountUsers
    {
        private EmailOrchestrator _sut;
        private Mock<IAccountOrchestrator> _accountOrchestrator;
        private Mock<IMediator> _mediator;
        private long _ukprn;
        private List<string> _emailAddresses;
        private ProviderEmailRequest _request;
        private string _templateId;
        private Dictionary<string, string> _tokens;

        [SetUp]
        public async Task Setup()
        {
            _ukprn = 228987165;
            _emailAddresses = new List<string>
            {
                "test1@example.com",
                "test2@example.com",
                "nobody@idams.com"
            };
            _templateId = Guid.NewGuid().ToString();
            _tokens = new Dictionary<string, string>();
            _tokens.Add("key1", "value1");
            _tokens.Add("key2", "value2");

            _accountOrchestrator = new Mock<IAccountOrchestrator>();
            _mediator = new Mock<IMediator>();

            _accountOrchestrator
                .Setup(x => x.GetAccountUsers(_ukprn))
                .ReturnsAsync(_emailAddresses.Select(x => new User { UserRef = $"ref-{x}", EmailAddress = x, ReceiveNotifications = true }));

            _request = new ProviderEmailRequest
            {
                TemplateId = _templateId,
                Tokens = _tokens
            };

            _sut = new EmailOrchestrator(_accountOrchestrator.Object, _mediator.Object, Mock.Of<IProviderCommitmentsLogger>());
            await _sut.SendEmailToAllProviderRecipients(_ukprn, _request);
        }

        [TestCase(0)]
        [TestCase(1)]
        public void ShouldSendNotificationToEachAddress(int index)
        {
            _mediator.Verify(x => x.Send(It.Is<SendNotificationCommand>(y
                => y.Email.RecipientsAddress == _emailAddresses[index]
                && y.Email.TemplateId == _templateId
                && y.Email.Tokens.SequenceEqual(_tokens)
                && y.Email.ReplyToAddress == "noreply@sfa.gov.uk"
                && y.Email.Subject == "x"
                && y.Email.SystemId == "x"
            ), It.IsAny<CancellationToken>()));
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.security.models;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;

/** Resource collection API of IotSecuritySolutions. */
public interface IotSecuritySolutions {
    /**
     * Use this method to get the list of IoT Security solutions by subscription.
     *
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solutions as paginated response with {@link PagedIterable}.
     */
    PagedIterable<IoTSecuritySolutionModel> list();

    /**
     * Use this method to get the list of IoT Security solutions by subscription.
     *
     * @param filter Filter the IoT Security solution with OData syntax. Supports filtering by iotHubs.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solutions as paginated response with {@link PagedIterable}.
     */
    PagedIterable<IoTSecuritySolutionModel> list(String filter, Context context);

    /**
     * Use this method to get the list IoT Security solutions organized by resource group.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solutions as paginated response with {@link PagedIterable}.
     */
    PagedIterable<IoTSecuritySolutionModel> listByResourceGroup(String resourceGroupName);

    /**
     * Use this method to get the list IoT Security solutions organized by resource group.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param filter Filter the IoT Security solution with OData syntax. Supports filtering by iotHubs.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return list of IoT Security solutions as paginated response with {@link PagedIterable}.
     */
    PagedIterable<IoTSecuritySolutionModel> listByResourceGroup(
        String resourceGroupName, String filter, Context context);

    /**
     * User this method to get details of a specific IoT Security solution based on solution name.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution configuration and resource information along with {@link Response}.
     */
    Response<IoTSecuritySolutionModel> getByResourceGroupWithResponse(
        String resourceGroupName, String solutionName, Context context);

    /**
     * User this method to get details of a specific IoT Security solution based on solution name.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution configuration and resource information.
     */
    IoTSecuritySolutionModel getByResourceGroup(String resourceGroupName, String solutionName);

    /**
     * Use this method to delete yours IoT Security solution.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> deleteByResourceGroupWithResponse(String resourceGroupName, String solutionName, Context context);

    /**
     * Use this method to delete yours IoT Security solution.
     *
     * @param resourceGroupName The name of the resource group within the user's subscription. The name is case
     *     insensitive.
     * @param solutionName The name of the IoT Security solution.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void deleteByResourceGroup(String resourceGroupName, String solutionName);

    /**
     * User this method to get details of a specific IoT Security solution based on solution name.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution configuration and resource information along with {@link Response}.
     */
    IoTSecuritySolutionModel getById(String id);

    /**
     * User this method to get details of a specific IoT Security solution based on solution name.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return ioT Security solution configuration and resource information along with {@link Response}.
     */
    Response<IoTSecuritySolutionModel> getByIdWithResponse(String id, Context context);

    /**
     * Use this method to delete yours IoT Security solution.
     *
     * @param id the resource ID.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     */
    void deleteById(String id);

    /**
     * Use this method to delete yours IoT Security solution.
     *
     * @param id the resource ID.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the {@link Response}.
     */
    Response<Void> deleteByIdWithResponse(String id, Context context);

    /**
     * Begins definition for a new IoTSecuritySolutionModel resource.
     *
     * @param name resource name.
     * @return the first stage of the new IoTSecuritySolutionModel definition.
     */
    IoTSecuritySolutionModel.DefinitionStages.Blank define(String name);
}

redpajama_set_name: RedPajamaGithub


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.main;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.main.AwsVaultConfigurationProperties;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class AwsVaultConfigurationPropertiesConfigurer extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        org.apache.camel.main.AwsVaultConfigurationProperties target = (org.apache.camel.main.AwsVaultConfigurationProperties) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "accesskey":
        case "AccessKey": target.setAccessKey(property(camelContext, java.lang.String.class, value)); return true;
        case "awsvaultconfiguration":
        case "AwsVaultConfiguration": target.setAwsVaultConfiguration(property(camelContext, org.apache.camel.vault.AwsVaultConfiguration.class, value)); return true;
        case "azurevaultconfiguration":
        case "AzureVaultConfiguration": target.setAzureVaultConfiguration(property(camelContext, org.apache.camel.vault.AzureVaultConfiguration.class, value)); return true;
        case "defaultcredentialsprovider":
        case "DefaultCredentialsProvider": target.setDefaultCredentialsProvider(property(camelContext, boolean.class, value)); return true;
        case "gcpvaultconfiguration":
        case "GcpVaultConfiguration": target.setGcpVaultConfiguration(property(camelContext, org.apache.camel.vault.GcpVaultConfiguration.class, value)); return true;
        case "region":
        case "Region": target.setRegion(property(camelContext, java.lang.String.class, value)); return true;
        case "secretkey":
        case "SecretKey": target.setSecretKey(property(camelContext, java.lang.String.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Class<?> getOptionType(String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "accesskey":
        case "AccessKey": return java.lang.String.class;
        case "awsvaultconfiguration":
        case "AwsVaultConfiguration": return org.apache.camel.vault.AwsVaultConfiguration.class;
        case "azurevaultconfiguration":
        case "AzureVaultConfiguration": return org.apache.camel.vault.AzureVaultConfiguration.class;
        case "defaultcredentialsprovider":
        case "DefaultCredentialsProvider": return boolean.class;
        case "gcpvaultconfiguration":
        case "GcpVaultConfiguration": return org.apache.camel.vault.GcpVaultConfiguration.class;
        case "region":
        case "Region": return java.lang.String.class;
        case "secretkey":
        case "SecretKey": return java.lang.String.class;
        default: return null;
        }
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        org.apache.camel.main.AwsVaultConfigurationProperties target = (org.apache.camel.main.AwsVaultConfigurationProperties) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "accesskey":
        case "AccessKey": return target.getAccessKey();
        case "awsvaultconfiguration":
        case "AwsVaultConfiguration": return target.getAwsVaultConfiguration();
        case "azurevaultconfiguration":
        case "AzureVaultConfiguration": return target.getAzureVaultConfiguration();
        case "defaultcredentialsprovider":
        case "DefaultCredentialsProvider": return target.isDefaultCredentialsProvider();
        case "gcpvaultconfiguration":
        case "GcpVaultConfiguration": return target.getGcpVaultConfiguration();
        case "region":
        case "Region": return target.getRegion();
        case "secretkey":
        case "SecretKey": return target.getSecretKey();
        default: return null;
        }
    }
}


text:
Sidecar ![Sidecar](views/static/Sidecar.png)
=====

Sidecar is a dynamic service discovery platform requiring no external
coordination service. It's a peer-to-peer system that uses a gossip protocol
for all communication between hosts. Sidecar health checks local services
and announces them to peer systems. It's Docker-native so your containerized
applications work out of the box.

Services communicate to each other through an HAproxy instance on each host
that is itself managed and configured by Sidecar. It is inspired by Airbnb's
SmartStack. But, we believe it has a few advantages over SmartStack:
 * Native support for Docker (works without Docker, too!)
 * No dependence on Zookeeper or other centralized services
 * Peer-to-peer, so it works on your laptop or on a large cluster
 * Static binary means it's easy to deploy, and there is no interpreter needed
 * Tiny memory usage (under 20MB) and few execution threads means its very
   light weight

**See it in Action:** We've presented Sidecar at Velocity 2015 and recorded a [YouTube
video](https://www.youtube.com/watch?v=VA43yWVUnMA) demonstrating Sidecar with
[Centurion](https://github.com/newrelic/centurion), deploying services in
Docker containers, and seeing Sidecar discover and health check them.

[![YouTube Video](views/static/youtube.png)](https://www.youtube.com/watch?v=VA43yWVUnMA)

Overview and Theory
-------------------

Sidecar is an eventually consistent service discovery platform where hosts learn
about each others' state via a gossip protocol. Hosts exchange messages about
which services they are running and which have gone away. All messages are
timestamped and the latest timestamp always wins. Each host maintains its own
local state and continually merges changes in from others. Messaging is over
UDP except when doing anti-entropy transfers.

There is an anti-entropy mechanism where full state exchanges take place
between peer nodes on an intermittent basis. This allows for any missed
messages to propagate, and helps keep state consistent across the cluster.

Sidecar hosts join a cluster by having a set of cluster seed hosts passed to them
on the command line at startup. Once in a cluster, the first thing a host does
is merge the state directly from another host. This is a big JSON blob that is
delivered over a TCP session directly between the hosts.

Now the host starts continuously polling its own services and reviewing the
services that it has in its own state, sleeping a couple of seconds in between.
It announces its services as UDP gossip messages every couple of seconds, and
also announces tombstone records for any services which have gone away.
Likewise, when a host leaves the cluster, any peers that were notified send
tombstone records for all of its services. These eventually converge and the
latest records should propagate everywhere. If the host rejoins the cluster, it
will announce new state every few seconds so the services will be picked back
up.

There are lifespans assigned to both tombstone and alive records so that:

1. A service that was not correctly tombstoned will go away in short order
2. We do not continually add to the tombstone state we are carrying

Because the gossip mechanism is UDP and a service going away is a higher
priority message, each tombstone is sent twice initially, followed by
once a second for 10 seconds. This delivers reliable messaging of service
death.

Timestamps are all local to the host that sent them. This is because we can
have clock drift on various machines. But if we always look at the origin timestamp
they will at least be comparable to each other by all hosts in the cluster. The
one exception to this is that if clock drift is more than a second or two, the
alive lifespan may be negatively impacted.

Running it
----------

It's a Go application so just install Godep and build it with:

```bash
$ godep go build
```

Or you can run it like this:

```bash
$ go run *.go --cluster-ip <boostrap_host>
```

You always need to supply at least one IP address or hostname with the
`--cluster-ip` argument. If are running solo, or are the first member, this can
be your own hostname. You may specify the argument multiple times to have
multiple hosts. It is recommended to use more than one when possible.

### Running in a Container

The easiest way to deploy Sidecar to your Docker fleet is to run it in a
container itself. [Instructions for doing that are provided](docker/README.md).

Configuration
-------------

Sidecar expects to find a TOML config file, by default named `sidecar.toml` in the
current path, to specify how it should operate. You can tell it to use a
specific file with the `--config-file` or `-f` option on the command line.

It comes supplied with an example config file called `sidecar.example.toml`
which you should copy and modify as needed.

Sidecar supports both Docker-based discovery and a discovery mechanism where
you publish services into a JSON file locally. These can then be advertised
as running services just like they would be from a Docker host.

### Discovery

Sidecar currently supports two methods of discovery and these can be set in
the `sidecar.toml` file in the `sidecar` section.

A configuration for both Docker and static discovery looks like this:

```toml
[sidecar]
discovery = [ "docker", "static" ]
```

Zero or more options may be supplied. Note that if nothing is in this section,
Sidecar will only participate in a cluster but will not announce anything.

#### Configuring Docker Discovery

Sidecar currently accepts a single option for Docker-based discovery, the URL
to use to connect to Docker. You really want this to be the local machine.
It uses the same URLs that are supported by the Docker command line tools.
The configuration block for Sidecar looks like this:

```toml
[docker_discovery]
docker_url = "tcp://localhost:2375"
```

Note that it only supports a *single* URL, unlike the Docker CLI tool.

Sidecar can now use the normal Docker environment variables for configuring
Docker discovery. If you remove the `docker_url` setting from the config
entirely, it will fall back to trying to use environment variables to configure
Docker. It uses the standard variables like `DOCKER_HOST`, `TLS_VERIFY`, etc.

##### Labels

A few Docker labels can be used to control the discovery behavior of Sidecar.
All containers need to be started with two labels defining how they are to be
health checked. To health check a service on port 9090 on the local system with
an `HttpGet` check, for example, you would use the following labels:

```
	HealthCheck=HttpGet
	HealthCheckArgs=http://:9090/status
```

The currently available check types are `HttpGet` and `External`. `External`
checks will run the command specified in the `HealthCheckArgs` label (in the
context of a bash shell). An exit status of 0 is considered healthy and
anything else is unhealthy. Nagios checks work very well with this mode of
health checking.

Additionally, it can sometimes be nice to exclude certain containers from
discovery. This is particularly useful if you are running Sidecar in a
container itself. This is accomplished with another Docker label like so:

```
	SidecarDiscover=false
```

####Configuring Static Discovery

Static Discovery requires a configuration block in the `sidecar.toml` that
looks like this:

```toml
[static_discovery]
config_file = "/my_path/static.json"
```

That in turn points to a static discovery file that looks like this:

```json
[
    {
        "Service": {
            "Name": "some_service",
            "Image": "bb6268ff91dc42a51f51db53846f72102ed9ff3f",
            "Ports": [
                {
                    "Type": "tcp",
                    "Port": 10234
                }
            ]
        },
        "Check": {
            "Type": "HttpGet",
            "Args": "http://:10234/"
        }
    },
	{
	...
	}
]
```

Here we've defined both the service itself and the health check to use
to validate its status. It supports a single health check per service.
You should supply something in place of the value for `Image` that is
meaningful to you. Usually this is a version or git commit string. It
will show up in the Sidecar web UI.

Monitoring It
-------------

The logging output is pretty (too?) verbose and contains lots of information
about what's going on and what the current state is. Or you can use the web
interface.

Currently the web interface runs on port 7777 on each machine that runs `sidecar`.

The `/services` endpoint is a very textual web interface for humans. The
`/services.json` endpoint is JSON-encoded. The JSON is still pretty-printed so
it's readable by humans.

Contributing
------------

Contributions are more than welcome. Bug reports with specific reproduction
steps are great. If you have a code contribution you'd like to make, open a
pull request with suggested code.

Pull requests should:

 * Clearly state their intent in the title
 * Have a description that explains the need for the changes
 * Include tests!
 * Not break the public API

Ping us to let us know you're working on something interesting by opening a
GitHub Issue on the project.

By contributing to this project you agree that you are granting New Relic a
non-exclusive, non-revokable, no-cost license to use the code, algorithms,
patents, and ideas in that code in our products if we so choose. You also agree
the code is provided as-is and you provide no warranties as to its fitness or
correctness for any purpose

Logo
----
The logo is used with kind permission from [Picture Esk](https://www.flickr.com/photos/22081583@N06/4226337024/).


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.github.dm.rf.android.filter;

import com.github.dm.rf.android.iterator.LongSparseIterable;

/**
 * This interface extends the {@link FilterBuilder} one by providing specific methods handling long
 * elements.
 * <p/>
 * Created by davide-maestroni on 3/16/14.
 */
public interface LongFilterBuilder extends FilterBuilder<LongSparseIterable, Long> {

    /**
     * Creates a filter matching the specified long value.
     *
     * @param element the long value to match.
     * @return the filtered iterable.
     */
    public LongSparseIterable element(long element);

    /**
     * Creates a filter matching the specified long values.
     *
     * @param elements the long values to match.
     * @return the filtered iterable.
     */
    public LongSparseIterable elements(long... elements);
}


text:
<!DOCTYPE html>

<title>The Groovy 2 Tutorial - Reserved Words</title>
<meta name="The Groovy 2 Tutorial" content="text/html; charset=utf-8" />
<meta name="description" content="An introductory text for budding Groovy developers" />

<meta name="author" content="Duncan Dickinson" />

<link rel="icon" href="../../resources/images/gico.png">
<link rel="license" href="../../Licence.html">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/github.min.css">

<link rel='stylesheet' type='text/css' href='../../resources/styles/site.css'>

The Groovy 2 Tutorial

Reserved Words

        « Previous • Next »

Groovy’s reserved words

<colgroup>
<col style="text-align:left;"/>
<col style="text-align:left;"/>
<col style="text-align:left;"/>
<col style="text-align:left;"/>
<col style="text-align:left;"/>
</colgroup>

	abstract
	as
	assert
	boolean
	break

	byte

	case

	catch

	char

	class

	const

	continue

	def

	default

	do

	double

	else

	enum

	extends

	false

	final

	finally

	float

	for

	goto

	if

	implements

	import

	in

	instanceof

	int

	interface

	long

	native

	new

	null

	package

	private

	protected

	public

	return

	short

	static

	strictfp

	super

	switch

	synchronized

	this

	threadsafe

	throw

	throws

	transient

	true

	try

	void

	volatile

	while

        « Previous • Next »

Contents

Book home

Quick reference guide

Reserved Words

Default Imports

Comments

Variables

Operators

Loops

Conditional (Branching) Statements

Groovy links

Groovy homepage

GAPI

GDK

Groovy Documentation

      © 2014-2015 Duncan Dickinson. See the Licence page for more information

    Updates regarding this book are posted to the news site


text:
<?php
namespace content_enter\google;

class model
{
	public static function get()
	{
		if(\dash\request::get('code'))
		{
			// check access from google
			$check = \dash\utility\google::check();
			if($check)
			{
				\dash\log::set('loginByGoogle');

				// go to what url
				$go_to_url           = null;

				$no_problem_to_login = false;

				$user_data = \dash\utility\google::user_info();
				// get user email
				$email = \dash\utility\google::user_info('email');
				// load data by email in field user google mail
				\dash\utility\enter::load_user_data($email, 'googlemail');
				// the user exist in system
				if(\dash\utility\enter::user_data('id'))
				{
					// check user status
					if(in_array(\dash\utility\enter::user_data('status'), ['filter', 'block']))
					{
						// the user was blocked
						\dash\utility\enter::next_step('block');
						// go to block page
						\dash\utility\enter::go_to('block');

						return false;
					}
					else
					{
						if(\dash\utility\enter::user_data('mobile'))
						{
							// no problem to login this user
							$no_problem_to_login = true;
						}
						else
						{
							if(\dash\utility\enter::user_data('dontwillsetmobile'))
							{
								if(strtotime(\dash\utility\enter::user_data('dontwillsetmobile')) > (60*60*24*365))
								{
									\dash\utility\enter::set_session('mobile_request_from', 'google_email_exist');

									\dash\utility\enter::set_session('logined_by_email', \dash\utility\google::user_info('email'));
									// go to mobile get to enter mobile
									\dash\utility\enter::next_step('mobile/request');
									// get go to url
									$go_to_url = 'mobile/request';
								}
								else
								{
									// no problem to login this user
									$no_problem_to_login = true;
								}
							}
							else
							{
								\dash\utility\enter::set_session('mobile_request_from', 'google_email_exist');

								\dash\utility\enter::set_session('logined_by_email', \dash\utility\google::user_info('email'));
								// go to mobile get to enter mobile
								\dash\utility\enter::next_step('mobile/request');
								// get go to url
								$go_to_url = 'mobile/request';
							}
						}
					}
				}
				else
				{
					// the email of this user is not exist in system
					$args = [];
					if(\dash\utility\google::user_info('name'))
					{
						$args['displayname'] = \dash\utility\google::user_info('name');
					}
					elseif(\dash\utility\google::user_info('familyName') || \dash\utility\google::user_info('givenName'))
					{
						$args['displayname'] = trim(\dash\utility\google::user_info('familyName'). ' '. \dash\utility\google::user_info('givenName'));
					}

					$args['email'] = \dash\utility\google::user_info('email');
					$args['datecreated']  = date("Y-m-d H:i:s");

					\dash\utility\enter::set_session('mobile_request_from', 'google_email_not_exist');

					\dash\log::set('loginByGoogleSignuped');

					\dash\utility\enter::set_session('must_signup', $args);

					\dash\utility\enter::set_session('logined_by_email', \dash\utility\google::user_info('email'));

					// go to mobile get to enter mobile
					\dash\utility\enter::next_step('mobile/request');
					// get go to url
					$go_to_url = 'mobile/request';
				}

				if($no_problem_to_login)
				{
					// set login session
					$redirect_url = \dash\utility\enter::enter_set_login();
					\dash\utility\enter::set_session('redirect_url', $redirect_url);
					// save redirect url in session to get from okay page
					// set okay as next step
					\dash\utility\enter::next_step('okay');
					// go to okay page
					\dash\utility\enter::go_to('okay');
				}
				else
				{
					// go to url
					if($go_to_url)
					{
						// in this time we need time to check next step
						// so we set for ever dont whill set mobile and go to next step
						// to login quick by google mail
						\dash\utility\enter::set_session('dont_will_set_mobile', true);
						// self::mobile_request_next_step();
						return;

						// \dash\utility\enter::go_to($go_to_url);
					}
					else
					{
						\dash\utility\enter::set_session('alert' ,['text' => T_("System error! try again")]);
						\dash\utility\enter::go_to('alert');
					}
				}
			}
			else
			{
				return false;
			}
		}
	}
}
?>


text:
#include "SDL_config.h"

#if SDL_VIDEO_DRIVER_X11

#include <unistd.h> /* For getpid() and readlink() */

#include "SDL_video.h"
#include "SDL_mouse.h"
#include "../SDL_sysvideo.h"
#include "../SDL_pixels_c.h"

#include "SDL_x11video.h"
#include "SDL_x11framebuffer.h"
#include "SDL_x11shape.h"
#include "SDL_x11touch.h"

#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
#include "SDL_x11opengles.h"
#endif

/* Initialization/Query functions */
static int X11_VideoInit(_THIS);
static void X11_VideoQuit(_THIS);

/* Find out what class name we should use */
static char *
get_classname()
{
    char *spot;
#if defined(__LINUX__) || defined(__FREEBSD__)
    char procfile[1024];
    char linkfile[1024];
    int linksize;
#endif

    /* First allow environment variable override */
    spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS");
    if (spot) {
        return SDL_strdup(spot);
    }

    /* Next look at the application's executable name */
#if defined(__LINUX__) || defined(__FREEBSD__)
#if defined(__LINUX__)
    SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid());
#elif defined(__FREEBSD__)
    SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file",
                 getpid());
#else
#error Where can we find the executable name?
#endif
    linksize = readlink(procfile, linkfile, sizeof(linkfile) - 1);
    if (linksize > 0) {
        linkfile[linksize] = '\0';
        spot = SDL_strrchr(linkfile, '/');
        if (spot) {
            return SDL_strdup(spot + 1);
        } else {
            return SDL_strdup(linkfile);
        }
    }
#endif /* __LINUX__ || __FREEBSD__ */

    /* Finally use the default we've used forever */
    return SDL_strdup("SDL_App");
}

/* X11 driver bootstrap functions */

static int
X11_Available(void)
{
    Display *display = NULL;
    if (SDL_X11_LoadSymbols()) {
        display = XOpenDisplay(NULL);
        if (display != NULL) {
            XCloseDisplay(display);
        }
        SDL_X11_UnloadSymbols();
    }
    return (display != NULL);
}

static void
X11_DeleteDevice(SDL_VideoDevice * device)
{
    SDL_VideoData *data = (SDL_VideoData *) device->driverdata;
    if (data->display) {
        XCloseDisplay(data->display);
    }
    SDL_free(data->windowlist);
    SDL_free(device->driverdata);
#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
    SDL_free(device->gles_data);
#endif
    SDL_free(device);

    SDL_X11_UnloadSymbols();
}

static SDL_VideoDevice *
X11_CreateDevice(int devindex)
{
    SDL_VideoDevice *device;
    SDL_VideoData *data;
    const char *display = NULL; /* Use the DISPLAY environment variable */

    if (!SDL_X11_LoadSymbols()) {
        return NULL;
    }

    /* Initialize all variables that we clean on shutdown */
    device = (SDL_VideoDevice *) SDL_calloc(1, sizeof(SDL_VideoDevice));
    if (!device) {
        SDL_OutOfMemory();
        return NULL;
    }
    data = (struct SDL_VideoData *) SDL_calloc(1, sizeof(SDL_VideoData));
    if (!data) {
        SDL_OutOfMemory();
        SDL_free(device);
        return NULL;
    }
    device->driverdata = data;

#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
    device->gles_data = (struct SDL_PrivateGLESData *) SDL_calloc(1, sizeof(SDL_PrivateGLESData));
    if (!device->gles_data) {
        SDL_OutOfMemory();
        return NULL;
    }
#endif

    /* FIXME: Do we need this?
       if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) ||
       (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) {
       local_X11 = 1;
       } else {
       local_X11 = 0;
       }
     */
    data->display = XOpenDisplay(display);
#if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC)
    /* On Tru64 if linking without -lX11, it fails and you get following message.
     * Xlib: connection to ":0.0" refused by server
     * Xlib: XDM authorization key matches an existing client!
     *
     * It succeeds if retrying 1 second later
     * or if running xhost +localhost on shell.
     */
    if (data->display == NULL) {
        SDL_Delay(1000);
        data->display = XOpenDisplay(display);
    }
#endif
    if (data->display == NULL) {
        SDL_free(device);
        SDL_SetError("Couldn't open X11 display");
        return NULL;
    }
#ifdef X11_DEBUG
    XSynchronize(data->display, True);
#endif

    /* Set the function pointers */
    device->VideoInit = X11_VideoInit;
    device->VideoQuit = X11_VideoQuit;
    device->GetDisplayModes = X11_GetDisplayModes;
    device->SetDisplayMode = X11_SetDisplayMode;
    device->SuspendScreenSaver = X11_SuspendScreenSaver;
    device->PumpEvents = X11_PumpEvents;

    device->CreateWindow = X11_CreateWindow;
    device->CreateWindowFrom = X11_CreateWindowFrom;
    device->SetWindowTitle = X11_SetWindowTitle;
    device->SetWindowIcon = X11_SetWindowIcon;
    device->SetWindowPosition = X11_SetWindowPosition;
    device->SetWindowSize = X11_SetWindowSize;
    device->ShowWindow = X11_ShowWindow;
    device->HideWindow = X11_HideWindow;
    device->RaiseWindow = X11_RaiseWindow;
    device->MaximizeWindow = X11_MaximizeWindow;
    device->MinimizeWindow = X11_MinimizeWindow;
    device->RestoreWindow = X11_RestoreWindow;
    device->SetWindowFullscreen = X11_SetWindowFullscreen;
    device->SetWindowGammaRamp = X11_SetWindowGammaRamp;
    device->SetWindowGrab = X11_SetWindowGrab;
    device->DestroyWindow = X11_DestroyWindow;
    device->CreateWindowFramebuffer = X11_CreateWindowFramebuffer;
    device->UpdateWindowFramebuffer = X11_UpdateWindowFramebuffer;
    device->DestroyWindowFramebuffer = X11_DestroyWindowFramebuffer;
    device->GetWindowWMInfo = X11_GetWindowWMInfo;

    device->shape_driver.CreateShaper = X11_CreateShaper;
    device->shape_driver.SetWindowShape = X11_SetWindowShape;
    device->shape_driver.ResizeWindowShape = X11_ResizeWindowShape;

#if SDL_VIDEO_OPENGL_GLX
    device->GL_LoadLibrary = X11_GL_LoadLibrary;
    device->GL_GetProcAddress = X11_GL_GetProcAddress;
    device->GL_UnloadLibrary = X11_GL_UnloadLibrary;
    device->GL_CreateContext = X11_GL_CreateContext;
    device->GL_MakeCurrent = X11_GL_MakeCurrent;
    device->GL_SetSwapInterval = X11_GL_SetSwapInterval;
    device->GL_GetSwapInterval = X11_GL_GetSwapInterval;
    device->GL_SwapWindow = X11_GL_SwapWindow;
    device->GL_DeleteContext = X11_GL_DeleteContext;
#endif
#if SDL_VIDEO_OPENGL_ES || SDL_VIDEO_OPENGL_ES2
    device->GL_LoadLibrary = X11_GLES_LoadLibrary;
    device->GL_GetProcAddress = X11_GLES_GetProcAddress;
    device->GL_UnloadLibrary = X11_GLES_UnloadLibrary;
    device->GL_CreateContext = X11_GLES_CreateContext;
    device->GL_MakeCurrent = X11_GLES_MakeCurrent;
    device->GL_SetSwapInterval = X11_GLES_SetSwapInterval;
    device->GL_GetSwapInterval = X11_GLES_GetSwapInterval;
    device->GL_SwapWindow = X11_GLES_SwapWindow;
    device->GL_DeleteContext = X11_GLES_DeleteContext;
#endif

    device->SetClipboardText = X11_SetClipboardText;
    device->GetClipboardText = X11_GetClipboardText;
    device->HasClipboardText = X11_HasClipboardText;

    device->free = X11_DeleteDevice;

    return device;
}

VideoBootStrap X11_bootstrap = {
    "x11", "SDL X11 video driver",
    X11_Available, X11_CreateDevice
};

static int (*handler) (Display *, XErrorEvent *) = NULL;
static int
X11_CheckWindowManagerErrorHandler(Display * d, XErrorEvent * e)
{
    if (e->error_code == BadWindow) {
        return (0);
    } else {
        return (handler(d, e));
    }
}

static void
X11_CheckWindowManager(_THIS)
{
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;
    Display *display = data->display;
    Atom _NET_SUPPORTING_WM_CHECK;
    int status, real_format;
    Atom real_type;
    unsigned long items_read, items_left;
    unsigned char *propdata;
    Window wm_window = 0;
#ifdef DEBUG_WINDOW_MANAGER
    char *wm_name;
#endif

    /* Set up a handler to gracefully catch errors */
    XSync(display, False);
    handler = XSetErrorHandler(X11_CheckWindowManagerErrorHandler);

    _NET_SUPPORTING_WM_CHECK = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", False);
    status = XGetWindowProperty(display, DefaultRootWindow(display), _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata);
    if (status == Success && items_read) {
        wm_window = ((Window*)propdata)[0];
    }
    if (propdata) {
        XFree(propdata);
    }

    if (wm_window) {
        status = XGetWindowProperty(display, wm_window, _NET_SUPPORTING_WM_CHECK, 0L, 1L, False, XA_WINDOW, &real_type, &real_format, &items_read, &items_left, &propdata);
        if (status != Success || !items_read || wm_window != ((Window*)propdata)[0]) {
            wm_window = None;
        }
        if (propdata) {
            XFree(propdata);
        }
    }

    /* Reset the error handler, we're done checking */
    XSync(display, False);
    XSetErrorHandler(handler);

    if (!wm_window) {
#ifdef DEBUG_WINDOW_MANAGER
        printf("Couldn't get _NET_SUPPORTING_WM_CHECK property\n");
#endif
        return;
    }
    data->net_wm = SDL_TRUE;

#ifdef DEBUG_WINDOW_MANAGER
    wm_name = X11_GetWindowTitle(_this, wm_window);
    printf("Window manager: %s\n", wm_name);
    SDL_free(wm_name);
#endif
}

int
X11_VideoInit(_THIS)
{
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;

    /* Get the window class name, usually the name of the application */
    data->classname = get_classname();

    /* Get the process PID to be associated to the window */
    data->pid = getpid();

    /* Open a connection to the X input manager */
#ifdef X_HAVE_UTF8_STRING
    if (SDL_X11_HAVE_UTF8) {
        data->im =
            XOpenIM(data->display, NULL, data->classname, data->classname);
    }
#endif

    /* Look up some useful Atoms */
#define GET_ATOM(X) data->X = XInternAtom(data->display, #X, False)
    GET_ATOM(WM_DELETE_WINDOW);
    GET_ATOM(_NET_WM_STATE);
    GET_ATOM(_NET_WM_STATE_HIDDEN);
    GET_ATOM(_NET_WM_STATE_MAXIMIZED_VERT);
    GET_ATOM(_NET_WM_STATE_MAXIMIZED_HORZ);
    GET_ATOM(_NET_WM_STATE_FULLSCREEN);
    GET_ATOM(_NET_WM_NAME);
    GET_ATOM(_NET_WM_ICON_NAME);
    GET_ATOM(_NET_WM_ICON);
    GET_ATOM(UTF8_STRING);

    /* Detect the window manager */
    X11_CheckWindowManager(_this);

    if (X11_InitModes(_this) < 0) {
        return -1;
    }

    if (X11_InitKeyboard(_this) != 0) {
        return -1;
    }
    X11_InitMouse(_this);

    X11_InitTouch(_this);
    return 0;
}

void
X11_VideoQuit(_THIS)
{
    SDL_VideoData *data = (SDL_VideoData *) _this->driverdata;

    if (data->classname) {
        SDL_free(data->classname);
    }
#ifdef X_HAVE_UTF8_STRING
    if (data->im) {
        XCloseIM(data->im);
    }
#endif

    X11_QuitModes(_this);
    X11_QuitKeyboard(_this);
    X11_QuitMouse(_this);
    X11_QuitTouch(_this);
}

SDL_bool
X11_UseDirectColorVisuals(void)
{
    return SDL_getenv("SDL_VIDEO_X11_NODIRECTCOLOR") ? SDL_FALSE : SDL_TRUE;
}

#endif /* SDL_VIDEO_DRIVER_X11 */

/* vim: set ts=4 sw=4 expandtab: */


text:
package apoc.es;

import apoc.Extended;
import apoc.load.LoadJsonUtils;
import apoc.result.MapResult;
import apoc.util.UrlResolver;
import apoc.util.Util;
import org.neo4j.procedure.Description;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.Procedure;

import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static apoc.util.MapUtil.map;

/**
 * @author mh
 * @since 21.05.16
 */
@Extended
public class ElasticSearch {

    private final static String fullQueryTemplate = "/%s/%s/%s?%s";

    // /{index}/{type}/_search?{query}
    private final static String fullQuerySearchTemplate = "/%s/%s/_search?%s";

    /**
     * With this pattern we can match both key:value params and key=value params
     */
    private final static Pattern KEY_VALUE = Pattern.compile("(.*)(:|=)(.*)");

    protected String getElasticSearchUrl(String hostOrKey) {
        return new UrlResolver("http", "localhost", 9200).getUrl("es", hostOrKey);
    }

    /**
     * Get the full Elasticsearch url
     *
     * @param hostOrKey
     * @param index
     * @param type
     * @param id
     * @param query
     * @return
     */
    protected String getQueryUrl(String hostOrKey, String index, String type, String id, Object query) {
        return getElasticSearchUrl(hostOrKey) + formatQueryUrl(index, type, id, query);
    }

    /**
     * @param hostOrKey
     * @param index
     * @param type
     * @param query
     * @return
     */
    protected String getSearchQueryUrl(String hostOrKey, String index, String type, Object query) {
        return getElasticSearchUrl(hostOrKey) + formatSearchQueryUrl(index, type, query);
    }

    /**
     * @param index
     * @param type
     * @param query
     * @return
     */
    private String formatSearchQueryUrl(String index, String type, Object query) {
        String queryUrl = String.format(fullQuerySearchTemplate,
                index == null ? "_all" : index,
                type == null ? "_all" : type,
                toQueryParams(query));

        return queryUrl.endsWith("?") ? queryUrl.substring(0, queryUrl.length() - 1) : queryUrl;
    }

    /**
     * Format the query url template according to the parameters.
     * The format will be /{index}/{type}/{id}?{query} if query is not empty (or null) otherwise the format will be /{index}/{type}/{id}
     *
     * @param index
     * @param type
     * @param id
     * @param query
     * @return
     */
    private String formatQueryUrl(String index, String type, String id, Object query) {
        String queryUrl = String.format(fullQueryTemplate,
                index == null ? "_all" : index,
                type == null ? "_all" : type,
                id == null ? "" : id,
                toQueryParams(query));

        return queryUrl.endsWith("?") ? queryUrl.substring(0, queryUrl.length() - 1) : queryUrl;
    }

    /**
     * @param payload
     * @return
     */
    protected String toPayload(Object payload) {
        if (payload == null) return null;
        if (payload instanceof Map) return Util.toJson(payload);
        return payload.toString();
    }

    private String contentType(Object payload) {
        return "application/json";
    }

    /**
     * @param query
     * @return
     */
    protected String toQueryParams(Object query) {
        if (query == null) return "";
        if (query instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) query;
            if (map.isEmpty()) return "";
            return map.entrySet().stream().map(e -> e.getKey() + "=" + Util.encodeUrlComponent(e.getValue().toString())).collect(Collectors.joining("&"));
        } else {
            // We have to encode only the values not the keys
            return Pattern.compile("&").splitAsStream(query.toString())
                    .map(KEY_VALUE::matcher)
                    .filter(Matcher::matches)
                    .map(matcher -> matcher.group(1) + matcher.group(2) + Util.encodeUrlComponent(matcher.group(3)))
                    .collect(Collectors.joining("&"));
        }
    }

    @Procedure
    @Description("apoc.es.stats(host-url-Key) - elastic search statistics")
    public Stream<MapResult> stats(@Name("host") String hostOrKey) {
        String url = getElasticSearchUrl(hostOrKey);
        return LoadJsonUtils.loadJsonStream(url + "/_stats", null, null);
    }

    @Procedure
    @Description("apoc.es.get(host-or-port,index-or-null,type-or-null,id-or-null,query-or-null,payload-or-null) yield value - perform a GET operation on elastic search")
    public Stream<MapResult> get(@Name("host") String hostOrKey, @Name("index") String index, @Name("type") String type, @Name("id") String id, @Name("query") Object query, @Name("payload") Object payload) {
        return LoadJsonUtils.loadJsonStream(getQueryUrl(hostOrKey, index, type, id, query), map("content-type",contentType(payload)), toPayload(payload));
    }

    @Procedure
    @Description("apoc.es.query(host-or-port,index-or-null,type-or-null,query-or-null,payload-or-null) yield value - perform a SEARCH operation on elastic search")
    public Stream<MapResult> query(@Name("host") String hostOrKey, @Name("index") String index, @Name("type") String type, @Name("query") Object query, @Name("payload") Object payload) {
        return LoadJsonUtils.loadJsonStream(getSearchQueryUrl(hostOrKey, index, type, query), map("content-type",contentType(payload)), toPayload(payload));
    }

    @Procedure
    @Description("apoc.es.getRaw(host-or-port,path,payload-or-null) yield value - perform a raw GET operation on elastic search")
    public Stream<MapResult> getRaw(@Name("host") String hostOrKey, @Name("path") String suffix, @Name("payload") Object payload) {
        String url = getElasticSearchUrl(hostOrKey);
        return LoadJsonUtils.loadJsonStream(url + "/" + suffix, map("content-type",contentType(payload)), toPayload(payload));
    }

    @Procedure
    @Description("apoc.es.postRaw(host-or-port,path,payload-or-null) yield value - perform a raw POST operation on elastic search")
    public Stream<MapResult> postRaw(@Name("host") String hostOrKey, @Name("path") String suffix, @Name("payload") Object payload) {
        String url = getElasticSearchUrl(hostOrKey);
        return LoadJsonUtils.loadJsonStream(url + "/" + suffix, map("method", "POST","content-type",contentType(payload)), toPayload(payload));
    }

    @Procedure
    @Description("apoc.es.post(host-or-port,index-or-null,type-or-null,query-or-null,payload-or-null) yield value - perform a POST operation on elastic search")
    public Stream<MapResult> post(@Name("host") String hostOrKey, @Name("index") String index, @Name("type") String type, @Name("query") Object query, @Name(value = "payload", defaultValue = "{}") Map<String,Object> payload) {
        if (payload == null)
        {
            payload = Collections.emptyMap();
        }
        return LoadJsonUtils.loadJsonStream(getQueryUrl(hostOrKey, index, type, null, query), map("method", "POST","content-type",contentType(payload)), toPayload(payload));
    }

    @Procedure
    @Description("apoc.es.put(host-or-port,index-or-null,type-or-null,id-or-null,query-or-null,payload-or-null) yield value - perform a PUT operation on elastic search")
    public Stream<MapResult> put(@Name("host") String hostOrKey, @Name("index") String index, @Name("type") String type, @Name("id") String id, @Name("query") Object query, @Name(value = "payload", defaultValue = "{}") Map<String,Object> payload) {
        if (payload == null)
        {
            payload = Collections.emptyMap();
        }
        return LoadJsonUtils.loadJsonStream(getQueryUrl(hostOrKey, index, type, id, query), map("method", "PUT","content-type",contentType(payload)), toPayload(payload));
    }
}


text:
package org.wso2.carbon.policy.mgt.core.internal;

import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ntask.core.service.TaskService;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationPoint;
import org.wso2.carbon.policy.mgt.common.PolicyInformationPoint;
import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.tenant.TenantManager;

import java.util.HashMap;
import java.util.Map;

public class PolicyManagementDataHolder {

    private RealmService realmService;
    private TenantManager tenantManager;
    private PolicyEvaluationPoint policyEvaluationPoint;
    private PolicyInformationPoint policyInformationPoint;
    private DeviceManagementProviderService deviceManagementService;
    private Map<String, PolicyMonitoringService> policyMonitoringServiceMap = new HashMap<>();
    private TaskService taskService;

    private static PolicyManagementDataHolder thisInstance = new PolicyManagementDataHolder();

    private PolicyManagementDataHolder() {}

    public static PolicyManagementDataHolder getInstance() {
        return thisInstance;
    }

    public RealmService getRealmService() {
        return realmService;
    }

    public void setRealmService(RealmService realmService) {
        this.realmService = realmService;
        this.setTenantManager(realmService);
    }

    private void setTenantManager(RealmService realmService) {
        if (realmService == null) {
            throw new IllegalStateException("Realm service is not initialized properly");
        }
        this.tenantManager = realmService.getTenantManager();
    }

    public TenantManager getTenantManager() {
        return tenantManager;
    }

    public PolicyEvaluationPoint getPolicyEvaluationPoint() {
        return policyEvaluationPoint;
    }

    public void setPolicyEvaluationPoint(PolicyEvaluationPoint policyEvaluationPoint) {
        this.policyEvaluationPoint = policyEvaluationPoint;
    }

    public PolicyInformationPoint getPolicyInformationPoint() {
        return policyInformationPoint;
    }

    public void setPolicyInformationPoint(PolicyInformationPoint policyInformationPoint) {
        this.policyInformationPoint = policyInformationPoint;
    }

    public DeviceManagementProviderService getDeviceManagementService() {
        return deviceManagementService;
    }

    public void setDeviceManagementService(DeviceManagementProviderService deviceManagementService) {
        this.deviceManagementService = deviceManagementService;
    }

    public PolicyMonitoringService getPolicyMonitoringService(String deviceType) {
        return policyMonitoringServiceMap.get(deviceType);
    }

    public void setPolicyMonitoringService(String deviceType, PolicyMonitoringService policyMonitoringService) {
        this.policyMonitoringServiceMap.put(deviceType, policyMonitoringService);
    }

    public void unsetPolicyMonitoringService(String deviceType) {
        this.policyMonitoringServiceMap.remove(deviceType);
    }

    public TaskService getTaskService() {
        return taskService;
    }

    public void setTaskService(TaskService taskService) {
        this.taskService = taskService;
    }
}


text:
package org.wso2.carbon.siddhi.store.api.rest.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.swagger.annotations.ApiModelProperty;

/**
 * This clss represents the bean class or the query reqest body
 */
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaMSF4JServerCodegen", date = "2017-11-01T11:26:25.925Z")
public class Query {
    @JsonProperty("query")
    private String query = null;
    @JsonProperty("appName")
    private String appName = null;

    public Query query(String appName, String query) {
        this.query = query;
        this.appName = appName;
        return this;
    }

    @ApiModelProperty(example = "@PrimaryKey('firstname','lastname', 'age')" +
                                "@store(type='solr', url='localhost:9983', collection='StudentStore', " +
                                "base.config='baseconfig', shards='2', replicas='2', schema='firstname string stored," +
                                "lastname string stored, age int stored', commit.async='true')" +
                                "define table FooTable(firstname string, lastname string, age int);")
    public String getAppName() {
        return appName;
    }

    public String getQuery() {
        return query;
    }

    public void setAppName(String appName){
        this.appName = appName;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Query)) {
            return false;
        }

        Query query1 = (Query) o;

        if (!query.equals(query1.query)) {
            return false;
        }
        if (!appName.equals(query1.appName)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int result = query.hashCode();
        result = 31 * result + appName.hashCode();
        return result;
    }

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

        sb.append("    appName: ").append(toIndentedString(appName)).append("\n");
        sb.append("    query: ").append(toIndentedString(query)).append("\n");
        sb.append("}");
        return sb.toString();
    }

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


text:
package org.kie.pmml.models.mining.compiler.factories;

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

import javax.xml.bind.JAXBException;

import org.junit.BeforeClass;
import org.junit.Test;
import org.kie.pmml.commons.model.KiePMMLModel;
import org.kie.pmml.models.mining.compiler.HasKnowledgeBuilderMock;
import org.kie.pmml.models.mining.model.segmentation.KiePMMLSegmentation;
import org.xml.sax.SAXException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

public class KiePMMLSegmentationFactoryTest extends AbstractKiePMMLFactoryTest {

    @BeforeClass
    public static void setup() throws IOException, JAXBException, SAXException {
        innerSetup();
    }

    @Test
    public void getSegmentation() {
        final String segmentationName = "SEGMENTATION_NAME";
        final KiePMMLSegmentation retrieved = KiePMMLSegmentationFactory.getSegmentation(DATA_DICTIONARY,
                                                                                TRANSFORMATION_DICTIONARY,
                                                                                MINING_MODEL.getSegmentation(),
                                                                                segmentationName,
                                                                                new HasKnowledgeBuilderMock(KNOWLEDGE_BUILDER));
        assertNotNull(retrieved);
        assertEquals(segmentationName, retrieved.getName());
    }

    @Test
    public void getSegmentationSourcesMap() {
        final String segmentationName = "SEGMENTATION_NAME";
        final String packageName = "packagename";
        final List<KiePMMLModel> nestedModels = new ArrayList<>();
        final Map<String, String> retrieved = KiePMMLSegmentationFactory.getSegmentationSourcesMap(packageName,
                                                                                DATA_DICTIONARY,
                                                                                TRANSFORMATION_DICTIONARY,
                                                                                MINING_MODEL.getSegmentation(),
                                                                                segmentationName,
                                                                                new HasKnowledgeBuilderMock(KNOWLEDGE_BUILDER),
                                                                                nestedModels);
        assertNotNull(retrieved);
        int expectedNestedModels = MINING_MODEL.getSegmentation().getSegments().size();
        assertEquals(expectedNestedModels, nestedModels.size());
    }
}


text:
using System;
using System.Text;

namespace MaloobaLipSync.Correlator
{
    public class Shift : EventArgs
    {
        public readonly uint Timecode;
        public readonly double[] Delay;
        public readonly double[] Confidence;
        public readonly bool[] AudioPresentA;
        public readonly bool[] AudioPresentB;

        public Shift(uint timecode)
        {
            Timecode = timecode;
            Delay = new double[16];
            Confidence = new double[16];
            AudioPresentA = new bool[16];
            AudioPresentB = new bool[16];

            for(var i = 0; i < 16; i++)
                Delay[i] = double.NaN;
        }

        public override string ToString()
        {
            var sb = new StringBuilder();
            sb.Append(Timecode.ToString("X8"));
            for(var i = 0; i < 16; i++)
            {
                if(double.IsNaN(Delay[i])) continue;
                sb.Append(" ");
                sb.Append(i.ToString("00"));
                sb.Append(":");
                sb.Append(Delay[i]);
                sb.Append(" ");
                sb.Append(Confidence[i].ToString("0.00"));
            }
            return sb.ToString();
        }
    }
}


text:
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import React, { useState } from "react";

/**
 * A toolbar of buttons that control the kind of Amazon Textract job that is
 * performed.
 *
 * @param props: Properties that determine how the buttons are displayed.
 *        props.hasImage: Indicates whether an image is currently loaded.
 *        props.extract: A function that starts an Amazon Textract job.
 *        props.extracting: Indicates whether an extraction job is currently in
 *                          progress.
 * @returns {JSX.Element}
 */
export const ExtractButtons = (props) => {
  const [syncSelection, setSyncSelection] = useState("sync");
  const [extractType, setExtractType] = useState("text");

  return (

        <input
          type="radio"
          className="btn-check"
          name="syncAsyncRadio"
          id="syncRadio"
          value="sync"
          checked={syncSelection === "sync"}
          disabled={!props.hasImage}
          onChange={(event) => setSyncSelection(event.target.value)}
          autoComplete="off"
        />

          Synchronous

        <input
          type="radio"
          className="btn-check"
          name="syncAsyncRadio"
          id="asyncRadio"
          value="async"
          checked={syncSelection === "async"}
          disabled={!props.hasImage}
          onChange={(event) => setSyncSelection(event.target.value)}
          autoComplete="off"
        />

          Asynchronous

        <input
          type="radio"
          className="btn-check"
          name="extractRadio"
          id="textRadio"
          value="text"
          checked={extractType === "text"}
          disabled={!props.hasImage}
          onChange={(event) => setExtractType(event.target.value)}
          autoComplete="off"
        />

          Text

        <input
          type="radio"
          className="btn-check"
          name="extractRadio"
          id="tableRadio"
          value="table"
          checked={extractType === "table"}
          disabled={!props.hasImage}
          onChange={(event) => setExtractType(event.target.value)}
          autoComplete="off"
        />

          Table

        <input
          type="radio"
          className="btn-check"
          name="extractRadio"
          id="formRadio"
          value="form"
          checked={extractType === "form"}
          disabled={!props.hasImage}
          onChange={(event) => setExtractType(event.target.value)}
          autoComplete="off"
        />

          Form

        <button
          type="button"
          className="btn btn-primary"
          disabled={!props.hasImage || props.extracting}
          onClick={() => props.extract(syncSelection, extractType)}
        >

          Extracting...

            Extract

        </button>

  );
};


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="User" table="User">
    <id name="userId" type="integer" column="user_id">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="username" type="string" column="username" length="45" nullable="false"/>
    <field name="password" type="string" column="password" length="32" nullable="false"/>
    <field name="email" type="string" column="email" length="45" nullable="false"/>
    <field name="gender" type="string" column="gender" length="1" nullable="false"/>
    <field name="birthDate" type="date" column="birth_date" nullable="false"/>
    <field name="city" type="string" column="city" length="45" nullable="false"/>
    <field name="phone" type="decimal" column="phone" precision="10" scale="0" nullable="false"/>
  </entity>
</doctrine-mapping>


text:
<?php declare(strict_types=1);
namespace Shale\Schema;

use Shale\Interfaces\Schema\SchemaNamedTypeInterface;

class TypeRegistry
{
    // Maps type names to schemas
    protected $typesByName = [];
    protected $typesByModelFqcn = [];

    public function __construct(...$primitiveTypes)
    {
        foreach ($primitiveTypes as $primitiveType) {
            $this->registerType($primitiveType);
        }
    }

    public function registerType(SchemaNamedTypeInterface $schemaType)
    {
        $name = $schemaType->getName();
        $this->typesByName[$name] = $schemaType;

        // XXX TODO Make this less ugly
        if ($schemaType instanceof Type\Object) {
            $this->typesByModelFqcn[$schemaType->getModelFqcn()] = $schemaType;
        }
    }

    public function getType(string $typeName): SchemaNamedTypeInterface
    {
        if (! array_key_exists($typeName, $this->typesByName)) {
            // XXX TODO This needs its own exception type
            throw new \Exception('No type with that name');
        }

        return $this->typesByName[$typeName];
    }

    public function getTypeByModelFqcn(
        string $modelFqcn
    ): SchemaNamedTypeInterface {
        return $this->typesByModelFqcn[$modelFqcn];
    }

    public function getAllTypes(): array
    {
        return $this->typesByName;
    }
}


text:
$set 7 #Slit

$ #SlitTitle
# Fanta de incarcare
$ #SlitDirection
# Orientarea fantei
$ #SlitPlacement
# Pozitia fantei


text:
require 'spec_helper'

describe Similatron::Comparison do

  it "can raise an error with all the information about itself" do

    comparison = Similatron::Comparison.new(
      expected: "one",
      actual: "other",
      diff: "some_diff",
      score: 70
    )

    expected = /Found other different from one/

    expect { comparison.raise_when_different }.to raise_error(expected)
  end

  it "doesn't raise if they are equal" do
    comparison = Similatron::Comparison.new(
      expected: "one",
      actual: "other",
      diff: nil,
      score: 0
    )

    expect { comparison.raise_when_different }.to_not raise_error
  end

  it "knows how to turn itself to JSON-like data" do
    args = {
      expected: "one",
      actual: "other",
      diff: "diff_path.png",
      score: 100
    }
    comparison = Similatron::Comparison.new(args)

    expect(comparison.as_json).to eq(args.merge(same: false, overwrite: false))
  end

end


text:
<?php

namespace Magento\Catalog\Controller\Adminhtml\Category\Widget;

class CategoriesJson extends \Magento\Catalog\Controller\Adminhtml\Category\Widget
{
    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\View\LayoutFactory $layoutFactory
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Magento\Framework\Registry $coreRegistry
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\View\LayoutFactory $layoutFactory,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Registry $coreRegistry
    ) {
        parent::__construct($context, $layoutFactory);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->_coreRegistry = $coreRegistry;
    }

    /**
     * Categories tree node (Ajax version)
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $categoryId = (int)$this->getRequest()->getPost('id');
        if ($categoryId) {
            $selected = $this->getRequest()->getPost('selected', '');
            $category = $this->_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId);
            if ($category->getId()) {
                $this->_coreRegistry->register('category', $category);
                $this->_coreRegistry->register('current_category', $category);
            }
            $categoryTreeBlock = $this->_getCategoryTreeBlock()->setSelectedCategories(explode(',', $selected));
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            $resultJson = $this->resultJsonFactory->create();
            return $resultJson->setJsonData($categoryTreeBlock->getTreeJson($category));
        }
    }
}


text:
from bs4 import BeautifulSoup as bs
from datetime import datetime
import re
import string

class parser:
    def __init__(self, html):
        self.html = filter(lambda x: x in string.printable, html)
        self.soup = bs(self.html, "lxml")

    def get_asin(self):
        asin = self.soup.find(text=re.compile('ASIN:')).next
        return asin.strip()

    def get_title(self):
        title = self.soup.find('span', {'id':'btAsinTitle'}).next
        return title.strip()

    def get_developer(self):
        developer = self.soup.find('div', {'class':'buying'}).find('a').next
        return developer.strip()

    def get_developer_url(self):
        developer_url = self.soup.find('div', {'class':'buying'}).find('a')['href']
        return 'http://www.amazon.com' + developer_url

    def get_content_rating(self):
        mas_rating = self.soup.find('span', {'class':'mas-rating-value'}).find('a').next
        return mas_rating.strip()

    def get_price(self):
        try:
            price = self.soup.find('strong', {'class':'priceLarge'}).next.strip()
        except:
            price = self.soup.find('span', {'class':'banjoPrice'}).text.strip()
        return price

    def get_iap(self):
        iap = self.soup.find('span', {'id':'offer_inapp_popover'})
        if iap:
            return True
        else:
            return False

    def get_release_date(self):
        release_date = self.soup.find(text=re.compile('Release Date:')).next.strip()
        release_date = datetime.strptime(release_date, "%B %d, %Y")
        return release_date.strftime("%Y-%m-%d")

    def get_overall_rank(self):
        try:
            sales_rank = self.soup.find(text=re.compile('Free in Appstore for Android')).strip()
            sales_rank = sales_rank.split(' ')[0][1:].replace(',','')
            return dict({'Free':int(sales_rank)})
        except:
            sales_rank = self.soup.find(text=re.compile('Paid in Appstore for Android')).strip()
            sales_rank = sales_rank.split(' ')[0][1:].replace(',','')
            return dict({'Paid':int(sales_rank)})

    def get_version(self):
        version = self.soup.find(text=re.compile('Version:')).next
        return version.strip()

    def get_size(self):
        try:
            size = self.soup.find(text=re.compile('MB'))
            size = re.findall('[\d.]+', size)[0] + ' MB'
        except:
            size = self.soup.find(text=re.compile('KB'))
            size = re.findall('[\d.]+', size)[0] + ' KB'
        return size

    def get_min_os_version(self):
        try:
            min_os_version = self.soup.find(text=re.compile('Minimum Operating System:')).next
            min_os_version = re.findall('[\d.]+', min_os_version)[0]
            return min_os_version
        except:
            return 'Varies'

    def get_total_reviews(self):
        total_reviews = self.soup.find(text=re.compile('customer review')).strip()
        total_reviews = total_reviews.split(' ')[0].replace(',','')
        return total_reviews

    def get_avg_star_rating(self):
        star_rating = self.soup.find('span', {'class':'a-icon-alt'}).next.split(' ')[0]
        return star_rating

    def get_star_rating_histogram(self):
        histogram = self.soup.findAll('div', {'class':'a-meter'})
        histogram = [int(x['aria-label'][:-1]) for x in histogram]

        star_histogram = {
                        'percent_5_star' : histogram[0],
                        'percent_4_star' : histogram[1],
                        'percent_3_star' : histogram[2],
                        'percent_2_star' : histogram[3],
                        'percent_1_star' : histogram[4]
                        }
        return star_histogram

    def get_category_rank(self):
        overall_rank = self.get_overall_rank()
        category_rank = {}
        categories = self.soup.findAll('li', {'class':'zg_hrsr_item'})
        for category in categories:
            rank = category.find('span').text[1:].replace(',','')
            category_name = category.text.strip().split('Appstore for Android > ')[1]
            category_rank[overall_rank.keys()[0] + ' > '+ category_name] = int(rank)

        category_rank.update(overall_rank)
        return category_rank

    def get_categories(self):
        names = []
        categories = self.soup.findAll('li', {'class':'zg_hrsr_item'})
        for category in categories:
            category_name = category.text.strip().split('Appstore for Android > ')[1]
            names.append(category_name)

        return names

    def get_icon_url(self):
        url = self.soup.find('img', {'class':'masrw-main-image'})['src']
        return url.strip()

    def get_permissions(self):
        perms_div = self.soup.find('div',{'id':'mas-app-permissions'}).find('ul')
        perms = perms_div.findAll('span')

        permissions = [perm.text.strip() for perm in perms]
        return permissions

    def get_developer_info(self):
        dev_info = {}
        dev_name = self.get_developer()
        dev_info['name'] = dev_name

        dev_div = self.soup.find('div', {'id':'mas-developer-info'}).findAll('span')
        dev_rows = [row.text.strip() for row in dev_div]

        for row in dev_rows:
            if '@' in row:
                dev_info['email'] = row
            if 'http://' in row:
                dev_info['website'] = row
            if 'email' in dev_info and 'website' in dev_info:
                break

        return dev_info

    def get_description(self):
        description = self.soup.find('div', {'id':'mas-product-description'})
        return description.find('div').text.strip()

    def get_similar_apps(self):
        apps = self.soup.findAll('div', {'class':'a-section a-spacing-none p13nimp p13n-asin'})
        asins = [app['data-asin'] for app in apps]
        return asins

    def get_app_info(self):
        return {'asin' : self.get_asin(),
                'title' : self.get_title(),
                'developer' : self.get_developer(),
                'developer_url' : self.get_developer_url(),
                'content_rating' : self.get_content_rating(),
                'price' : self.get_price(),
                'iap' : self.get_iap(),
                'release_date' : self.get_release_date(),
                'overall_rank' : self.get_overall_rank(),
                'version' : self.get_version(),
                'size' : self.get_size(),
                'min_os_version' : self.get_min_os_version(),
                'total_reviews' : self.get_total_reviews(),
                'avg_star_rating' : self.get_avg_star_rating(),
                'category_rank' : self.get_category_rank(),
                'categories' : self.get_categories(),
                'icon_url' : self.get_icon_url(),
                'permissions' : self.get_permissions(),
                'developer_info' : self.get_developer_info(),
                'description' : self.get_description(),
                'similar_apps' : self.get_similar_apps()}


text:
using std::shared_ptr;

// @include
template <typename T>
struct ListNode {
    T data;

    // We need to use a shared pointer since multiple nodes may point to a
    // single node. For example, in the following list, two nodes, 1 and 4,
    // point to node 2.
    // 0->1->2->3->4
    //       ^     |
    //       |_____|
    shared_ptr<ListNode<T>> next;
};
// @exclude
#endif  // SOLUTIONS_CPP_LINKED_LIST_PROTOTYPE_H_


text:
layout: page-fullwidth
subheadline: "Past Event"
title: "Thi Ca & Sử Việt 4"
meta_teaser: "Au Co Vietnamese Cultural Center San Francisco"
teaser: "Join us for a day of cultural appreciation through music and arts presented by the Au Co Vietnamese Cultural Center and Auco Productions. This rich program will include singing, dancing,folk opera excerpts, and musical performances ..."
header: no
image:
    thumb: Thi-Ca-Su-Viet-4-thumb.jpg
categories:
    - events
---

Tickets for this event can be purchased here: http://www.brownpapertickets.com/event/2477720

(Note: Please scroll down to bottom of page to view videos of past performances)

{% include next-previous-post-in-category %}


text:
package org.gradle.model.internal.core;

import com.google.common.base.Predicate;
import org.gradle.model.RuleSource;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.inspect.ExtractedRuleSource;
import org.gradle.model.internal.type.ModelType;

import javax.annotation.Nullable;
import java.util.Set;

public interface MutableModelNode extends ModelNode {
    boolean canBeViewedAs(ModelType<?> type);

    /**
     * @see ModelPromise#getTypeDescriptions(MutableModelNode)
     */
    Iterable<String> getTypeDescriptions();

    /**
     * Creates a (potentially) mutable view over this node's value. When this node is not mutable, an immutable view is returned instead.
     *
     * Callers should try to {@link ModelView#close()} the returned view when it is done with, allowing any internal cleanup to occur.
     *
     * Throws if this node can't be expressed as a mutable view of the requested type.
     */
    <T> ModelView<? extends T> asMutable(ModelType<T> type, ModelRuleDescriptor ruleDescriptor);

    /**
     * Adds a reference node to the graph. A reference node is a node that refers to some other node elsewhere in the graph, similar to a symbolic link.
     */
    <T> void addReference(String name, ModelType<T> type, ModelNode target, ModelRuleDescriptor ruleDescriptor);

    /**
     * Adds a node to the graph, linked from this node. The given registration is used to initialize the node when required.
     *
     * The path returned by {@link ModelRegistration#getPath()} is used to determine the name of the link.
     */
    void addLink(ModelRegistration registration);

    /**
     * Removes a node linked from this node from the graph.
     */
    void removeLink(String name);

    /**
     * Applies an action to this node.
     */
    void applyToSelf(ModelActionRole type, ModelAction action);

    /**
     * Applies an action to all linked nodes of this node that satisfy the given predicate.
     *
     * The predicate and the type returned by {@link ModelAction#getSubject()} are both used to filter the nodes,
     * such that the action is applied only to those linked nodes with a view of the requested type available that
     * also satisfy the predicate.
     */
    void applyTo(NodePredicate predicate, ModelActionRole role, ModelAction action);

    /**
     * Applies an action to a linked node.
     *
     * The path returned by {@link ModelAction#getSubject()} is used to select the link to apply the action to.
     */
    void applyToLink(ModelActionRole type, ModelAction action);

    /**
     * Applies the rules defined in the given rule source to this node.
     */
    void applyToSelf(Class<? extends RuleSource> rules);

    /**
     * Applies the rules defined in the given rule source to this node.
     */
    void applyToSelf(ExtractedRuleSource<?> rules);

    /**
     * Applies an action that defines further rules in the given role to the child of this node that is addressed by the subject of the action.
     */
    void defineRulesForLink(ModelActionRole role, ModelAction action);

    /**
     * Applies a rule source to all linked nodes of this node that satisfy the given predicate.
     *
     * The predicate and the type returned by {@link ModelAction#getSubject()} are both used to filter the nodes,
     * such that the action is applied only to those linked nodes with a view of the requested type available that
     * also satisfy the predicate.
     */
    void applyTo(NodePredicate predicate, Class<? extends RuleSource> rules);

    /**
     * Applies an action that defines rules for the node in the given role to all nodes linked from this node.
     *
     * The type returned by {@link ModelAction#getSubject()} is used to filter the nodes, such that the action is applied only to those linked nodes with a view of the
     * requested type available.
     */
    void defineRulesFor(NodePredicate predicate, ModelActionRole role, ModelAction action);

    boolean hasLink(String name, Predicate<? super MutableModelNode> predicate);

    @Nullable
    MutableModelNode getLink(String name);

    int getLinkCount(Predicate<? super MutableModelNode> predicate);

    Set<String> getLinkNames(Predicate<? super MutableModelNode> predicate);

    Set<String> getLinkNames();

    @Override
    Iterable<? extends MutableModelNode> getLinks(ModelType<?> type);

    Iterable<? extends MutableModelNode> getLinks(Predicate<? super MutableModelNode> predicate);

    <T> void setPrivateData(Class<? super T> type, T object);

    <T> void setPrivateData(ModelType<? super T> type, T object);

    <T> T getPrivateData(Class<T> type);

    <T> T getPrivateData(ModelType<T> type);

    Object getPrivateData();

    /**
     * Change the target of this reference node. Works only on reference nodes that are in the {@link org.gradle.model.internal.core.ModelNode.State#Registered} state.
     */
    void setTarget(ModelNode target);

    /**
     * Ensure that the views are available, with default values applied.
     */
    void ensureUsable();

    void ensureAtLeast(ModelNode.State state);

    boolean isAtLeast(ModelNode.State state);

    void setHidden(boolean hidden);

    boolean isMutable();

    MutableModelNode getParent();

    void addProjection(ModelProjection projection);
}


text:
// Copyright (c) 2009-2021 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

#include "IntegrationMethodTwoStep.h"
#include "hoomd/Integrator.h"

#include "ForceComposite.h"

#pragma once

#ifdef __HIPCC__
#error This header cannot be compiled by nvcc
#endif

#include <pybind11/pybind11.h>

/// Integrates the system forward one step with possibly multiple methods
/** See IntegrationMethodTwoStep for most of the design notes regarding group integration.
   IntegratorTwoStep merely implements most of the things discussed there.

    Notable design elements:
    - setDeltaT results in deltaT being set on all current integration methods
    - to interface with the python script, the m_methods vectors is exposed with a list like API.

   TODO: ensure that the user does not make a mistake and specify more than one method operating on
   a single particle

    There is a special registration mechanism for ForceComposites which run after the integration
   steps one and two, and which can use the updated particle positions and velocities to update any
   slaved degrees of freedom (rigid bodies).

    \ingroup updaters
*/
class PYBIND11_EXPORT IntegratorTwoStep : public Integrator
    {
    public:
    /** Anisotropic integration mode: Automatic (detect whether
        aniso forces are defined), Anisotropic (integrate
        rotational degrees of freedom regardless of whether
        anything is defining them), and Isotropic (don't integrate
        rotational degrees of freedom)
    */
    enum AnisotropicMode
        {
        Automatic,
        Anisotropic,
        Isotropic
        };

    /// Constructor
    IntegratorTwoStep(std::shared_ptr<SystemDefinition> sysdef, Scalar deltaT);

    /// Destructor
    virtual ~IntegratorTwoStep();

    /// Sets the profiler for the compute to use
    virtual void setProfiler(std::shared_ptr<Profiler> prof);

    /// Take one timestep forward
    virtual void update(uint64_t timestep);

    /// Change the timestep
    virtual void setDeltaT(Scalar deltaT);

    /// Get the list of integration methods
    std::vector<std::shared_ptr<IntegrationMethodTwoStep>>& getIntegrationMethods()
        {
        return m_methods;
        }

    /// Get the number of degrees of freedom granted to a given group
    virtual Scalar getTranslationalDOF(std::shared_ptr<ParticleGroup> group);

    /// Get the number of degrees of freedom granted to a given group
    virtual Scalar getRotationalDOF(std::shared_ptr<ParticleGroup> group);

    /// Set the anisotropic mode of the integrator
    virtual void setAnisotropicMode(const std::string& mode);

    /// Set the anisotropic mode of the integrator
    virtual const std::string getAnisotropicMode();

    /// Prepare for the run
    virtual void prepRun(uint64_t timestep);

    /// Get needed pdata flags
    virtual PDataFlags getRequestedPDataFlags();

    /// helper function to compute net force/virial
    virtual void computeNetForce(uint64_t timestep);

#ifdef ENABLE_HIP
    /// helper function to compute net force/virial on the GPU
    virtual void computeNetForceGPU(uint64_t timestep);
#endif

#ifdef ENABLE_MPI
    /// Set the communicator to use
    /** \param comm The Communicator
     */
    virtual void setCommunicator(std::shared_ptr<Communicator> comm);

    /// helper function to determine the ghost communication flags
    virtual CommFlags determineFlags(uint64_t timestep);
#endif

    /// Check if any forces introduce anisotropic degrees of freedom
    virtual bool getAnisotropic();

    /// Updates the rigid body constituent particles
    virtual void updateRigidBodies(uint64_t timestep);

    /// Set autotuner parameters
    virtual void setAutotunerParams(bool enable, unsigned int period);

    /// (Re-)initialize the integration method
    void initializeIntegrationMethods();

    /// Getter and setter for accessing rigid body objects in Python
    std::shared_ptr<ForceComposite> getRigid()
        {
        return m_rigid_bodies;
        }

    void setRigid(std::shared_ptr<ForceComposite> new_rigid)
        {
        m_rigid_bodies = new_rigid;
        }

    protected:
    /// Helper method to test if all added methods have valid restart information
    bool isValidRestart();

    std::vector<std::shared_ptr<IntegrationMethodTwoStep>>
        m_methods; //!< List of all the integration methods

    std::shared_ptr<ForceComposite> m_rigid_bodies; /// definition and updater for rigid bodies

    bool m_prepared;              //!< True if preprun has been called
    bool m_gave_warning;          //!< True if a warning has been given about no methods added
    AnisotropicMode m_aniso_mode; //!< Anisotropic mode for this integrator
    };

/// Exports the IntegratorTwoStep class to python
void export_IntegratorTwoStep(pybind11::module& m);


text:
package com.rectang.rcbot.module;

import java.io.*;
import java.net.Socket;

/**
 * A dictionary for random wordy stuff
 *
 */
public class Dictionary implements com.rectang.rcbot.Dictionary {

  private static String DEFAULT_DICT = "wn";
  private static String DICT_SERVER = "dict.org";
  private static int DICT_PORT = 2628;

  /* Based on "IRC Hacks #52" http://hacks.oreilly.com/pub/h/1984 */
  public String lookupWord(String word) {
    return lookupWord(Dictionary.DEFAULT_DICT, word);
  }

  public String lookupWord(String dict, String word) {
    try {
      Dictionary.DictConnection con = new Dictionary.DictConnection();
      String ret = lookupWord(con, dict, word);
      con.close();

      return ret;
    } catch (IOException e) {
      return "Failed to lookup word on server " + Dictionary.DICT_SERVER;
    }
  }

  private String lookupWord(Dictionary.DictConnection con, String book,
                            String word) throws IOException {
    con.getWriter().write("DEFINE " + book + " \"" + word + "\"\r\n");
    con.getWriter().flush();

    String definition = "";
    String line;
    while ((line = con.getReader().readLine( )) != null) {

      // 552 No match.
      if (line.startsWith("552")) {
        return "No matches for \"" + word + "\", try " +
            matchWord(con, book, word);
      }

      // 151 word database name - text follows.
      if (line.startsWith("151")) {
        if (book.equals("foldoc")) {
          // Skip first 2 lines returned (header and blank line).
          con.getReader().readLine( );
          con.getReader().readLine( );
        }

        definition = "";
        while ((line = con.getReader().readLine( )) != null) {
          String trimmed = line.trim();
          if (trimmed.equals("") || trimmed.startsWith("2") ||
              line.startsWith(".")) {
            break;
          } else {
            definition += line + "\n";
          }
        }
        break;
      }

      if (line.trim().startsWith("2")) {
        break;
      }
    }

    return definition;
  }

  public String matchWord(String word) {
    return matchWord(Dictionary.DEFAULT_DICT, word);
  }

  public String matchWord(String dict, String word) {
    try {
      Dictionary.DictConnection con = new Dictionary.DictConnection();
      String ret = matchWord(con, dict, word);
      con.close();

      return ret;
    } catch (IOException e) {
      return "Failed to lookup word on server " + Dictionary.DICT_SERVER;
    }
  }

  private String matchWord(Dictionary.DictConnection con, String book,
                           String word) throws IOException {
    // Levenshtein algorithm to try to get *some* result.
    con.getWriter().write("MATCH " + book + " lev \"" + word + "\"\r\n");
    con.getWriter().flush( );
    String line = con.getReader().readLine( );

    if (line.startsWith("552")) {
      // nothing found
      return "";
    } else if(line.startsWith("152")) {
      // 152 n matches found - text follows.
      String[] parts = line.split(" ");
      int numMatches = Integer.valueOf(parts[1]).intValue();

      // Some similar words were found ...
      String reply = "";
      int count = 0;
      while ((line = con.getReader().readLine( )) != null) {
        if (count > numMatches || line.startsWith(".")) {
          break;
        }

        reply += " " + line.substring(line.indexOf("\""),
            line.lastIndexOf("\"") + 1);

        count++;
      }
      return reply;
    } else {
      throw new IOException("Something unexpected happened: " + line);
    }
  }

  public String randomWord() {
    return randomWord(Dictionary.DEFAULT_DICT);
  }

  public String randomWord(String dict) {
    try {
      Dictionary.DictConnection con = new Dictionary.DictConnection();
      String ret = randomWord(con, dict);
      con.close();

      return ret;
    } catch (IOException e) {
      return "Failed to lookup word on server " + Dictionary.DICT_SERVER;
    }
  }

  private String randomWord(Dictionary.DictConnection con, String book)
      throws IOException {

    /* generate a random 3 char string to seed a substring search */
    char[] s = new char[3];
    s[0] = (char)('a' +  (int)(Math.random() * 26));
    s[1] = (char)('a' +  (int)(Math.random() * 26));
    s[2] = (char)('a' +  (int)(Math.random() * 26));
    String seed = new String(s);

    con.getWriter().write("m " + book + " substring \"" + seed + "\"\r\n");
    con.getWriter().flush( );
    String line = con.getReader().readLine( );

    if (line.startsWith("552")) {
      // nothing found - try again
      return randomWord(con, book);
    } else if(line.startsWith("152")) {
      // 152 n matches found - pick a random word from 0 to n
      String[] parts = line.split(" ");
      int numMatches = Integer.valueOf(parts[1]).intValue();
      int myPick = (int)(Math.random() * numMatches);

      String reply = null;
      int count = 0;
      while ((line = con.getReader().readLine( )) != null) {
        if (count > numMatches || line.startsWith(".")) {
          break;
        }

        if (count == myPick)
          reply = line.substring(line.indexOf("\"") + 1,
            line.lastIndexOf("\""));
        count++;
      }

      if (reply == null)
        return randomWord(con, book);
      return reply;
    } else {
      throw new IOException("Something unexpected happened: " + line);
    }
  }

  class DictConnection {

    private Socket sock;
    private BufferedReader reader;
    private BufferedWriter writer;

    public DictConnection() throws IOException {
      sock = new Socket(Dictionary.DICT_SERVER, Dictionary.DICT_PORT);
      reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      writer = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
      reader.readLine(); // ignore welcome message
    }

    public BufferedReader getReader() {
      return reader;
    }

    public BufferedWriter getWriter() {
      return writer;
    }

    public void close() throws IOException {
      sock.close();
    }
  }
}


text:
var Code = require('code');
var Lab = require('lab');
var lab = exports.lab = Lab.script();

var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

describe('True', function () {

    it('is truthy', function (done) {
        expect(true).to.be.true();
        done();
    });
});