text:
A nodejs API and command line tool for docker.

Ducke supports:
- Listing, building, inspecting and deleting images
- Listing, creating, inspecting, running, logging, attaching and deleting containers

Ducke does not yet support:
- Searching, pushing, pulling, tagging and history of images
- System events, docker versioning, creating images from containers and authentication
- Exporting, resizing TTY, pausing, unpausing, inspecting changes for a container
- Interacting with the docker registry and hub

[![NPM version](https://badge.fury.io/js/ducke.svg)](http://badge.fury.io/js/ducke)

Inspired by [dockerode](https://github.com/apocas/dockerode/).

## Install

To use on the command line

```sh
npm install -g ducke
```

To use as an API

```sh
npm install ducke
```

## Usage

```
Usage: ducke command [parameters]
       ducke option

Common:

    ps        List all running containers
    logs      Attach to container logs
    run       Start a new container interactively
    up        Start a new container
    exec      Run a command inside an existing container

Containers:

    inspect   Show details about containers
    kill      Send SIGTERM to running containers
    stop      Stop containers
    purge     Remove week old stopped containers
    rm        Delete containers

Images:

    ls        List available images
    orphans   List all orphaned images
    rmi       Delete images
    inspecti  Show details about images

Building:

    build     Build an image from a Dockerfile
    rebuild   Build an image from a Dockerfile from scratch

Options:

-h          Display this usage information
-v          Display the version number
```

## Examples

Command

```sh
$  ~  ducke ls

  04c5d3b7b065 ubuntu:latest
  cf39b476aeec phusion/baseimage:0.9.15
    ...
  0e819813bc00 tutum/apache-php:latest
    ...
  5327fda0d529 phusion/passenger-full:0.9.11

```

```sh
$ ~  ducke ps

  stopped          happy_goldstine (234bce554bdcec9d4ad47a452bd37a95d291d825138421730aa06017da9c8412)
  stopped          loadbalancer-osx_daemon_1 (metocean/doppelganger:1.0.3)
  stopped          sleepy_turing (cf39b476aeec4d2bd097945a14a147dc52e16bd88511ed931357a5cd6f6590de)

```

```sh
$ ~  ducke run ubuntu

  running cranky_kowalevski (ubuntu)

root@09d3215f6677:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
root@09d3215f6677:/#

///

$  ~  ducke exec cranky_kowalevski

  exec cranky_kowalevski (ubuntu)

root@10a2833bdafa:/# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.4  0.3  18168  3164 ?        Ss+  04:19   0:00 bash
root        16  1.0  0.3  18172  3168 ?        S    04:19   0:00 bash
root        31  0.0  0.2  15572  2100 ?        R+   04:19   0:00 ps aux
root@10a2833bdafa:/#

```

```sh
$ ~  ducke cull happy_goldstine sleepy_turing

  deleted happy_goldstine
  deleted sleepy_turing

$  ~
```

API

```js
var Ducke = require('ducke');
var ducke = new Ducke.API(Ducke.Parameters());

// List all containers
ducke.ps(function(err, containers) {
    console.log(containers);
});

// Start a container
ducke
    .container('my_container')
    .start(function(err, result) {
        console.log(result);
    });

// Create a container
ducke
    .image('ubuntu:latest')
    .up('my_container', ['/bin/bash'], function(err, id) {
        console.log('Container id: ' + id);
    });
```

## API Reference

```js
ducke.ping(function(err, isup) {});
ducke.ps(function(err, containers) {
    // https://docs.docker.com/reference/api/docker_remote_api_v1.15/#list-containers
    containers[0].container
    // https://docs.docker.com/reference/api/docker_remote_api_v1.15/#inspect-a-container
    containers[0].inspect
});
ducke.ls(function(err, images) {
    // https://docs.docker.com/reference/api/docker_remote_api_v1.15/#list-images
    images.images[0].image
    images.graph = [
        {
            image: ...
            children: [
                {
                    image: ...
                    children: [...]
                }
            ]
        }
    ]
    images.tags = {
        'ubuntu:latest': {...}
        'my_image:0.0.1': {...}
    }
    images.ids = {
        '62b9c90893b4...': {...}
        'cd80a4b0ed6b...': {...}
    }
    ducke.lls(images, function(err, details) {
        // https://docs.docker.com/reference/api/docker_remote_api_v1.15/#inspect-an-image
        details = {
            '62b9c90893b4...': {...}
        }
    });
});
ducke
    .container('my_container')
    .inspect(function(err, inspect) {})
    .logs(function(err, stream) {})
    .resize(function(err, didresize) {})
    .start(function(err, result) {})
    .stop(function(err, result) {})
    .wait(function(err, result) {})
    .rm(function(err, result) {})
    .attach(function(err, stream) {})
    .kill(function(err, result) {})
    .exec(['/bin/bash'], process.stdin, process.stdout, process.stderr, function(err, code) {});

ducke
    .image('my_image')
    .build('/path/to/folder', console.log, function(err) {})
    .rebuild('/path/to/folder', console.log, function(err) {})
    .up('my_container', ['/bin/bash'], function(err, id) {})
    .inspect(function(err, results) {})
    .rm(function(err, results) {})
    .run(['/bin/bash'], process.stdin, process.stdout, process.stderr, function(err, code) {})
```

## Todo

- More of the docker API
- Tests


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Account;
use AppBundle\Entity\Category;
use AppBundle\Entity\Comment;
use AppBundle\Entity\Currency;
use AppBundle\Entity\News;
use AppBundle\Entity\Operation;
use AppBundle\Entity\User;
use AppBundle\Form\AddNewsType;
use AppBundle\Form\Operation\AddOperationType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/admin")
 */
class CurrencyController extends Controller
{
    /**
     * @Route("/currencies", name="currencies_list")
     */
    public function currenciesAction(Request $request)
    {
        $currencies = $this
            ->getDoctrine()
            ->getManager()
            ->getRepository(Currency::class)
            ->findAll();

        return $this->render('admin/admin_currencies.html.twig', [
            'currencies' =>$currencies
        ]);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.usergrid.persistence.collection.serialization.impl.migration;

import org.junit.Rule;
import org.junit.runner.RunWith;

import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
import org.apache.usergrid.persistence.collection.serialization.MvccEntitySerializationStrategy;
import org.apache.usergrid.persistence.collection.serialization.impl.CollectionDataVersions;
import org.apache.usergrid.persistence.collection.serialization.impl.MvccEntitySerializationStrategyV2Impl;
import org.apache.usergrid.persistence.collection.serialization.impl.MvccEntitySerializationStrategyV3Impl;
import org.apache.usergrid.persistence.core.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.core.migration.data.DataMigrationManager;
import org.apache.usergrid.persistence.core.migration.data.VersionedMigrationSet;
import org.apache.usergrid.persistence.core.test.ITRunner;
import org.apache.usergrid.persistence.core.test.UseModules;

import com.google.inject.Inject;

import net.jcip.annotations.NotThreadSafe;

@NotThreadSafe
@RunWith( ITRunner.class )
@UseModules( { TestCollectionModule.class } )
public class MvccEntityDataMigrationV2ToV3ImplTest extends AbstractMvccEntityDataMigrationV1ToV3ImplTest{

    @Inject
    @Rule
    public MigrationManagerRule migrationManagerRule;

    @Inject
    public DataMigrationManager dataMigrationManager;

    @Inject
    private MvccEntitySerializationStrategyV2Impl v2Impl;

    @Inject
    private MvccEntitySerializationStrategyV3Impl v3Impl;

    @Inject
    public MvccEntityDataMigrationImpl mvccEntityDataMigrationImpl;

    @Inject
    public VersionedMigrationSet<MvccEntitySerializationStrategy> versions;

    @Override
    public DataMigrationManager getDataMigrationManager() {
        return dataMigrationManager;
    }

    @Override
    protected MvccEntitySerializationStrategy getExpectedSourceImpl() {
        return v2Impl;
    }

    @Override
    protected MvccEntitySerializationStrategy getExpectedTargetImpl() {
        return v3Impl;
    }

    @Override
    protected CollectionDataVersions getSourceVersion() {
        return CollectionDataVersions.BUFFER_SHORT_FIX;
    }

    @Override
    protected CollectionDataVersions expectedTargetVersion() {
        return CollectionDataVersions.LOG_REMOVAL;
    }
}


text:
package id.amberjack.hod.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.ws.rs.ext.ParamConverter;
import javax.ws.rs.ext.ParamConverterProvider;

/**
 * @author indroneel
 *
 */

public class StringToValue {

	private List<ParamConverterProvider> paramProviders;

	public StringToValue(List<ParamConverterProvider> providers) {
		paramProviders = providers;
	}

	public Object convert(String value, Class<?> targetType, Type genericType, Annotation[] anns)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		String[] strArr;
		if(value == null) {
			strArr = new String[0];
		}
		else {
			strArr = new String[] { value };
		}
		return convertWithOptional(strArr, targetType, genericType, anns);
	}

	public Object convert(List<String> values, Class<?> targetType, Type genericType, Annotation[] anns)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {
		String[] strArr;
		if(values == null) {
			strArr = new String[0];
		}
		else {
			strArr = values.toArray(new String[values.size()]);
		}
		return convertWithOptional(strArr, targetType, genericType, anns);
	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// Helper methods

	private Object convertWithOptional(String[] values,
			Class<?> targetType, Type genericType, Annotation[] anns)
					throws InstantiationException, IllegalAccessException, IllegalArgumentException,
					InvocationTargetException {

		OptionalChecker oc = new OptionalChecker(targetType, genericType);
		if(oc.isOptional()) {
			if(oc.getWrappedType() == null) {
				return null;
			}
			//else
			return Optional.ofNullable(convertImpl(
					values, oc.getWrappedType(), oc.getWrappedGenericType(), anns));
		}
		//else
		return convertImpl(values, targetType, genericType, anns);
	}

	private Object convertImpl(String[] values, Class<?> targetType, Type genericType, Annotation[] anns)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {

		OptionalChecker oc = new OptionalChecker(targetType, genericType);
		if(oc.isOptional()) {
			Class<?> wrappedType = oc.getWrappedType();
			if(wrappedType == null) {
				return null;
			}
			//else
		}
		//else

		if(values == null || values.length == 0) {
			return convertOne(null, targetType);
		}

		// Use ParamConverterProvider as the first option.
		for(ParamConverterProvider pcp : paramProviders) {
			ParamConverter<?> pc = pcp.getConverter(targetType, genericType, anns);
			if(pc != null) {
				Object value = pc.fromString(values[0]);
				if(value != null) {
					return value;
				}
			}
		}

		if(List.class.equals(targetType)) {
			Class<?> dimType = getDimensionType1(genericType);
			if(dimType == null) {
				return null;
			}
			ArrayList<Object> result = new ArrayList<>();
			for(String value : values) {
				Object obj = convertOne(value, dimType);
				if(obj != null) {
					result.add(obj);
				}
			}
			return result;
		}

		if(Set.class.equals(targetType)) {
			Class<?> dimType = getDimensionType1(genericType);
			if(dimType == null) {
				return null;
			}
			HashSet<Object> result = new HashSet<>();
			for(String value : values) {
				Object obj = convertOne(value, dimType);
				if(obj != null) {
					result.add(obj);
				}
			}
			return result;
		}

		if(SortedSet.class.equals(targetType)) {
			Class<?> dimType = getDimensionType1(genericType);
			if(dimType == null) {
				return null;
			}
			TreeSet<Object> result = new TreeSet<>();
			for(String value : values) {
				Object obj = convertOne(value, dimType);
				if(obj != null) {
					result.add(obj);
				}
			}
			return result;
		}

		return convertOne(values[0], targetType);
	}

	private Object convertOne(String value, Class<?> targetType)
			throws InstantiationException, IllegalAccessException, IllegalArgumentException,
			InvocationTargetException {

		if(targetType.equals(Boolean.TYPE)) {
			try {
				return Boolean.parseBoolean(value.trim());
			}
			catch(Exception exep) {
				return false;
			}
		}
		if(targetType.equals(Byte.TYPE)) {
			try {
				return Byte.parseByte(value.trim());
			}
			catch(Exception exep) {
				return (byte) 0;
			}
		}
		if(targetType.equals(Character.TYPE)) {
			try {
				return value.charAt(0);
			}
			catch(Exception exep) {
				return (char) 0;
			}
		}
		if(targetType.equals(Short.TYPE)) {
			try {
				return Short.parseShort(value.trim());
			}
			catch(Exception exep) {
				return (short) 0;
			}
		}
		if(targetType.equals(Integer.TYPE)) {
			try {
				return Integer.parseInt(value.trim());
			}
			catch(Exception exep) {
				return (int) 0;
			}
		}
		if(targetType.equals(Long.TYPE)) {
			try {
				return Long.parseLong(value.trim());
			}
			catch(Exception exep) {
				return (long) 0;
			}
		}
		if(targetType.equals(Float.TYPE)) {
			try {
				return Float.parseFloat(value.trim());
			}
			catch(Exception exep) {
				return (float) 0.0;
			}
		}
		if(targetType.equals(Double.TYPE)) {
			try {
				return Double.parseDouble(value.trim());
			}
			catch(Exception exep) {
				return (double) 0.0;
			}
		}

		if(value == null || value.length() == 0) {
			return null;
		}

		if(targetType instanceof Class) {
			//Populate using public constructor that takes a string as a parameter
			//Note: This does not work if the target type is a non-static inner class.
			Class<?> clsType = (Class<?>) targetType;
			Constructor<?> targetCtor = null;
			for(Constructor<?> ctor : clsType.getConstructors()) {
				int mod = ctor.getModifiers();
				if((ctor.getParameterCount() == 1)
						&& (String.class.equals(ctor.getParameterTypes()[0])) && Modifier.isPublic(mod)) {
					targetCtor = ctor;
					break;
				}
			}

			if(targetCtor != null) {
				return targetCtor.newInstance(value);
			}

			//Populate using a static valueOf() or fromString() method in case of enums
			Method targetMthd = null;
			for(Method mthd : clsType.getMethods()) {
				if(clsType.isEnum() && mthd.getName().equals("fromString")) {
					targetMthd = mthd;
					break;
				}
				if(!clsType.isEnum() && mthd.getName().equals("valueOf")) {
					targetMthd = mthd;
					break;
				}
			}

			if(targetMthd != null) {
				int mod = targetMthd.getModifiers();
				if(Modifier.isPublic(mod) && Modifier.isStatic(mod)
							&& targetMthd.getReturnType().equals(targetType)) {
					return targetMthd.invoke(null, value);
				}
			}
		}

		return null;
	}

	/*
	private Class<?> getDimensionType(Class<?> targetType, Type pType) {
		if(targetType.isArray()) {
			return targetType.getComponentType();
		}

		if(pType != null && pType instanceof ParameterizedType) {
			ParameterizedType ppType = (ParameterizedType) pType;
			if(ppType.getActualTypeArguments().length > 0) {
				String typeName = ppType.getActualTypeArguments()[0].getTypeName();
				ClassLoader cl = Thread.currentThread().getContextClassLoader();
				if(cl == null) {
					cl = getClass().getClassLoader();
				}
				try {
					return cl.loadClass(typeName);
				}
				catch(Exception exep) { }
			}
		}

		return null;
	}
	*/

	private Class<?> getDimensionType1(Type genericType) {
		if(genericType != null && genericType instanceof ParameterizedType) {
			ParameterizedType pmzType = (ParameterizedType) genericType;
			if(pmzType.getActualTypeArguments().length == 1) {
				if(pmzType.getActualTypeArguments()[0] instanceof Class) {
					return (Class<?>) pmzType.getActualTypeArguments()[0];
				}
			}
		}
		return null;
	}

	////////////////////////////////////////////////////////////////////////////////////////////////
	// Inner class to check for Optional as the generic type

	private class OptionalChecker {
		private boolean optional;
		private Class<?> wrappedType;
		private Type wrappedGenericType;

		OptionalChecker(Class<?> targetType, Type genericType) {
			if(!targetType.equals(Optional.class)) {
				return;
			}
			//else
			optional = true;

			if(!(genericType instanceof ParameterizedType)) {
				//optional with no parameters.
				return;
			}

			ParameterizedType pmzType = (ParameterizedType) genericType;
			Type[] types = pmzType.getActualTypeArguments();
			if(types == null || types.length != 1) {
				//optional must have exactly one type argument, else no dice.
				return;
			}

			if(types[0] instanceof Class) {
				wrappedType = (Class<?>) types[0];
			}
			else if(types[0] instanceof ParameterizedType) {
				ParameterizedType pmzType2 = (ParameterizedType) types[0];
				wrappedType = (Class<?>) pmzType2.getRawType();
			}

			wrappedGenericType = types[0];
		}

		public boolean isOptional() {
			return optional;
		}

		public Class<?> getWrappedType() {
			return wrappedType;
		}

		public Type getWrappedGenericType() {
			return wrappedGenericType;
		}
	}
}


text:
The `\Eco\Socket\Client` and `\Eco\Socket\Server` classes are available for creating sockets (using streams, no PHP extension required).

### Client-Server Example
For this example the server can be setup using the route `'/server' => 'IndexController->server'`. The `IndexController` method `server` example:
```php
// listen on port 8081
$server = new \Eco\Socket\Server('127.0.0.1', 8081);
// create a respond only service (does not wait for client request data)
$server->listen(function(){
	return 'Server time: ' . date('H:i:s');
});
```
Next, start the server from the application root directory using CLI:
```bash
# php index.php server
```
Now a client can be setup to read from the server:
```php
// acccess port 8081
$client = new \Eco\Socket\Client('127.0.0.1', 8081);
// get server response
var_dump($client->read());
```
Example output:
```html
string(21) "Server time: 13:44:56"
```

### Client-Server Write Example
First, create a server route like in the example above. Next, create the server:
```php
// listen on port 8081
$server = new \Eco\Socket\Server('127.0.0.1', 8081);
// create request service that will wait for client request data and respond
$server->listen(true, function($request){
	switch($request)
	{
		case 'getAbc':
			return '{"status":"ok","id":"' . uniqid() . '","data":"abc"}';
			break;

		case 'getXyz':
			return '{"status":"ok","id":"' . uniqid() . '","data":"xyz"}';
			break;
	}

	return '{"status":"error","message":"unknown request"}';
});
```
Next, start the server like in the example above:
```bash
# php index.php server
```
Now a client can be setup to write to the server and receive a response:
```php
// access port 8081
$client = new \Eco\Socket\Client('127.0.0.1', 8081);
// send data + get server response
var_dump($client->write('getXyz'));
```
Example output:
```html
string(49) "{"status":"ok","id":"5c65bab756769","data":"xyz"}"
```


text:
/* eslint no-console: ["error", { allow: ["log"] }] */
const gulp = require('gulp');
const connect = require('gulp-connect');
const gopen = require('gulp-open');

const buildKs = require('./build-ks.js');
const buildJs = require('./build-js.js');
const buildLess = require('./build-less.js');
const buildComponents = require('./build-components.js');

// Tasks
gulp.task('ks', (cb) => {
  buildKs(cb);
});
gulp.task('js', (cb) => {
  buildJs(cb);
});

gulp.task('less', (cb) => {
  buildLess(cb);
});

gulp.task('components', (cb) => {
  buildComponents(cb);
});

gulp.task('build', ['js', 'less', 'components']);

gulp.task('watch', () => {
  gulp.watch('./src/**/**/*.js', ['js']);
  gulp.watch('./src/**/**/*.less', ['less']);
});

gulp.task('connect', () => {
  connect.server({
    root: ['./'],
    livereload: false,
    port: '3000',
  });
});

gulp.task('open', () => {
  gulp.src('./kitchen-sink/index.html').pipe(gopen({ uri: 'http://localhost:3000/kitchen-sink/' }));
});

gulp.task('server', ['watch', 'connect', 'open']);

gulp.task('default', ['server']);


text:
<?php

namespace Google\Service\ShoppingContent\Resource;

use Google\Service\ShoppingContent\Promotion;

/**
 * The "promotions" collection of methods.
 * Typical usage is:
 *  <code>
 *   $contentService = new Google\Service\ShoppingContent(...);
 *   $promotions = $contentService->promotions;
 *  </code>
 */
class Promotions extends \Google\Service\Resource
{
  /**
   * Inserts a promotion for your Merchant Center account. If the promotion
   * already exists, then it updates the promotion instead. To [end or delete]
   * (https://developers.google.com/shopping-
   * content/guides/promotions#end_a_promotion) a promotion update the time period
   * of the promotion to a time that has already passed. (promotions.create)
   *
   * @param string $merchantId Required. The ID of the account that contains the
   * collection.
   * @param Promotion $postBody
   * @param array $optParams Optional parameters.
   * @return Promotion
   */
  public function create($merchantId, Promotion $postBody, $optParams = [])
  {
    $params = ['merchantId' => $merchantId, 'postBody' => $postBody];
    $params = array_merge($params, $optParams);
    return $this->call('create', [$params], Promotion::class);
  }
  /**
   * Retrieves a promotion from your Merchant Center account. (promotions.get)
   *
   * @param string $merchantId Required. The ID of the account that contains the
   * collection.
   * @param string $id Required. REST ID of the promotion to retrieve.
   * @param array $optParams Optional parameters.
   * @return Promotion
   */
  public function get($merchantId, $id, $optParams = [])
  {
    $params = ['merchantId' => $merchantId, 'id' => $id];
    $params = array_merge($params, $optParams);
    return $this->call('get', [$params], Promotion::class);
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(Promotions::class, 'Google_Service_ShoppingContent_Resource_Promotions');


text:
Recent Posts

        {% for post in site.posts | limit:3 %}

              {{ post.title | strip_html | strip_newlines | truncate: 30 }}
              {{post.date | date: "%b %d, %Y" }}

        {% endfor %}

            {% if site.owner.twitter %}

@{{ site.owner.twitter }}

            {% endif %}

            {% if site.owner.dribbble %}

Dribbble

            {% endif %}

    © {{ site.time | date: '%Y' }} {{ site.owner.name }}. Powered by Jekyll using the Balzac theme.


text:
/**
 * @fileoverview Defines methods used to actually send HTTP requests from
 * abstract representations.
 */

import firebase from '@firebase/app';
import * as array from './array';
import * as backoff from './backoff';
import * as errorsExports from './error';
import { FirebaseStorageError } from './error';
import { errors } from './error';
import * as object from './object';
import * as promiseimpl from './promise_external';
import { RequestInfo } from './requestinfo';
import * as type from './type';
import * as UrlUtils from './url';
import * as XhrIoExports from './xhrio';
import { Headers, XhrIo } from './xhrio';
import { XhrIoPool } from './xhriopool';

/**
 * @template T
 */
export interface Request<T> {
  getPromise(): Promise<T>;

  /**
   * Cancels the request. IMPORTANT: the promise may still be resolved with an
   * appropriate value (if the request is finished before you call this method,
   * but the promise has not yet been resolved), so don't just assume it will be
   * rejected if you call this function.
   * @param appDelete True if the cancelation came from the app being deleted.
   */
  cancel(appDelete?: boolean): void;
}

/**
 * @struct
 * @template T
 */
class NetworkRequest<T> implements Request<T> {
  private url_: string;
  private method_: string;
  private headers_: Headers;
  private body_: string | Blob | Uint8Array | null;
  private successCodes_: number[];
  private additionalRetryCodes_: number[];
  private pendingXhr_: XhrIo | null = null;
  private backoffId_: backoff.id | null = null;
  private resolve_: Function | null = null;
  private reject_: Function | null = null;
  private canceled_: boolean = false;
  private appDelete_: boolean = false;
  private callback_: (p1: XhrIo, p2: string) => T;
  private errorCallback_:
    | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)
    | null;
  private progressCallback_: ((p1: number, p2: number) => void) | null;
  private timeout_: number;
  private pool_: XhrIoPool;
  promise_: Promise<T>;

  constructor(
    url: string,
    method: string,
    headers: Headers,
    body: string | Blob | Uint8Array | null,
    successCodes: number[],
    additionalRetryCodes: number[],
    callback: (p1: XhrIo, p2: string) => T,
    errorCallback:
      | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)
      | null,
    timeout: number,
    progressCallback: ((p1: number, p2: number) => void) | null,
    pool: XhrIoPool
  ) {
    this.url_ = url;
    this.method_ = method;
    this.headers_ = headers;
    this.body_ = body;
    this.successCodes_ = successCodes.slice();
    this.additionalRetryCodes_ = additionalRetryCodes.slice();
    this.callback_ = callback;
    this.errorCallback_ = errorCallback;
    this.progressCallback_ = progressCallback;
    this.timeout_ = timeout;
    this.pool_ = pool;
    let self = this;
    this.promise_ = promiseimpl.make(function(resolve, reject) {
      self.resolve_ = resolve;
      self.reject_ = reject;
      self.start_();
    });
  }

  /**
   * Actually starts the retry loop.
   */
  private start_() {
    let self = this;

    function doTheRequest(
      backoffCallback: (p1: boolean, ...p2: any[]) => void,
      canceled: boolean
    ) {
      if (canceled) {
        backoffCallback(false, new RequestEndStatus(false, null, true));
        return;
      }
      let xhr = self.pool_.createXhrIo();
      self.pendingXhr_ = xhr;

      function progressListener(progressEvent: ProgressEvent) {
        let loaded = progressEvent.loaded;
        let total = progressEvent.lengthComputable ? progressEvent.total : -1;
        if (self.progressCallback_ !== null) {
          self.progressCallback_(loaded, total);
        }
      }
      if (self.progressCallback_ !== null) {
        xhr.addUploadProgressListener(progressListener);
      }
      xhr
        .send(self.url_, self.method_, self.body_, self.headers_)
        .then(function(xhr: XhrIo) {
          if (self.progressCallback_ !== null) {
            xhr.removeUploadProgressListener(progressListener);
          }
          self.pendingXhr_ = null;
          xhr = xhr as XhrIo;
          let hitServer =
            xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;
          let status = xhr.getStatus();
          if (!hitServer || self.isRetryStatusCode_(status)) {
            let wasCanceled =
              xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;
            backoffCallback(
              false,
              new RequestEndStatus(false, null, wasCanceled)
            );
            return;
          }
          let successCode = array.contains(self.successCodes_, status);
          backoffCallback(true, new RequestEndStatus(successCode, xhr));
        });
    }

    /**
     * @param requestWentThrough True if the request eventually went
     *     through, false if it hit the retry limit or was canceled.
     */
    function backoffDone(
      requestWentThrough: boolean,
      status: RequestEndStatus
    ) {
      let resolve = self.resolve_ as Function;
      let reject = self.reject_ as Function;
      let xhr = status.xhr as XhrIo;
      if (status.wasSuccessCode) {
        try {
          let result = self.callback_(xhr, xhr.getResponseText());
          if (type.isJustDef(result)) {
            resolve(result);
          } else {
            resolve();
          }
        } catch (e) {
          reject(e);
        }
      } else {
        if (xhr !== null) {
          let err = errorsExports.unknown();
          err.setServerResponseProp(xhr.getResponseText());
          if (self.errorCallback_) {
            reject(self.errorCallback_(xhr, err));
          } else {
            reject(err);
          }
        } else {
          if (status.canceled) {
            let err = self.appDelete_
              ? errorsExports.appDeleted()
              : errorsExports.canceled();
            reject(err);
          } else {
            let err = errorsExports.retryLimitExceeded();
            reject(err);
          }
        }
      }
    }
    if (this.canceled_) {
      backoffDone(false, new RequestEndStatus(false, null, true));
    } else {
      this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);
    }
  }

  /** @inheritDoc */
  getPromise() {
    return this.promise_;
  }

  /** @inheritDoc */
  cancel(appDelete?: boolean) {
    this.canceled_ = true;
    this.appDelete_ = appDelete || false;
    if (this.backoffId_ !== null) {
      backoff.stop(this.backoffId_);
    }
    if (this.pendingXhr_ !== null) {
      this.pendingXhr_.abort();
    }
  }

  private isRetryStatusCode_(status: number): boolean {
    // The codes for which to retry came from this page:
    // https://cloud.google.com/storage/docs/exponential-backoff
    let isFiveHundredCode = status >= 500 && status < 600;
    let extraRetryCodes = [
      // Request Timeout: web server didn't receive full request in time.
      408,
      // Too Many Requests: you're getting rate-limited, basically.
      429
    ];
    let isExtraRetryCode = array.contains(extraRetryCodes, status);
    let isRequestSpecificRetryCode = array.contains(
      this.additionalRetryCodes_,
      status
    );
    return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;
  }
}

/**
 * A collection of information about the result of a network request.
 * @param opt_canceled Defaults to false.
 * @struct
 */
export class RequestEndStatus {
  /**
   * True if the request was canceled.
   */
  canceled: boolean;

  constructor(
    public wasSuccessCode: boolean,
    public xhr: XhrIo | null,
    opt_canceled?: boolean
  ) {
    this.canceled = !!opt_canceled;
  }
}

export function addAuthHeader_(headers: Headers, authToken: string | null) {
  if (authToken !== null && authToken.length > 0) {
    headers['Authorization'] = 'Firebase ' + authToken;
  }
}

export function addVersionHeader_(headers: Headers) {
  let number =
    typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';
  headers['X-Firebase-Storage-Version'] = 'webjs/' + number;
}

/**
 * @template T
 */
export function makeRequest<T>(
  requestInfo: RequestInfo<T>,
  authToken: string | null,
  pool: XhrIoPool
): Request<T> {
  let queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);
  let url = requestInfo.url + queryPart;
  let headers = object.clone<Headers>(requestInfo.headers);
  addAuthHeader_(headers, authToken);
  addVersionHeader_(headers);
  return new NetworkRequest<T>(
    url,
    requestInfo.method,
    headers,
    requestInfo.body,
    requestInfo.successCodes,
    requestInfo.additionalRetryCodes,
    requestInfo.handler,
    requestInfo.errorHandler,
    requestInfo.timeout,
    requestInfo.progressCallback,
    pool
  );
}


text:
import pandas as pd
from sklearn.model_selection import KFold
from sklearn.model_selection import cross_val_score
from sklearn.svm import SVC

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pred', 'age', 'class']
data = pd.read_csv('indians-diabetes.data', names=names)
array = data.values

x = array[:,0:8]
y = array[:,8]

num_fold = 10
seed = 7
kfold = KFold(n_splits=num_fold, random_state=seed)

model = SVC()
result = cross_val_score(model, x, y, cv=kfold)

print(result.mean()*100, result.std()*100)


text:
namespace System.ServiceModel.Channels
{
    using System.Runtime;
    using System.ServiceModel.Dispatcher;
    using System.Threading;

    sealed class InternalDuplexChannelFactory : LayeredChannelFactory<IDuplexChannel>
    {
        static long channelCount = 0;
        InputChannelDemuxer channelDemuxer;
        IChannelFactory<IOutputChannel> innerChannelFactory;
        IChannelListener<IInputChannel> innerChannelListener;
        LocalAddressProvider localAddressProvider;
        bool providesCorrelation;

        internal InternalDuplexChannelFactory(InternalDuplexBindingElement bindingElement, BindingContext context,
            InputChannelDemuxer channelDemuxer,
            IChannelFactory<IOutputChannel> innerChannelFactory, LocalAddressProvider localAddressProvider)
            : base(context.Binding, innerChannelFactory)
        {
            this.channelDemuxer = channelDemuxer;
            this.innerChannelFactory = innerChannelFactory;
            ChannelDemuxerFilter demuxFilter = new ChannelDemuxerFilter(new MatchNoneMessageFilter(), int.MinValue);
            this.innerChannelListener = this.channelDemuxer.BuildChannelListener<IInputChannel>(demuxFilter);
            this.localAddressProvider = localAddressProvider;
            this.providesCorrelation = bindingElement.ProvidesCorrelation;
        }

        bool CreateUniqueLocalAddress(out EndpointAddress address, out int priority)
        {
            long tempChannelCount = Interlocked.Increment(ref channelCount);
            if (tempChannelCount > 1)
            {
                AddressHeader uniqueEndpointHeader = AddressHeader.CreateAddressHeader(XD.UtilityDictionary.UniqueEndpointHeaderName,
                    XD.UtilityDictionary.UniqueEndpointHeaderNamespace, tempChannelCount);
                address = new EndpointAddress(this.innerChannelListener.Uri, uniqueEndpointHeader);
                priority = 1;
                return true;
            }
            else
            {
                address = new EndpointAddress(this.innerChannelListener.Uri);
                priority = 0;
                return false;
            }
        }

        protected override IDuplexChannel OnCreateChannel(EndpointAddress address, Uri via)
        {
            EndpointAddress localAddress;
            int priority;
            MessageFilter filter;
            // determines whether the CompositeDuplex channels created from this factory expect the UniqueEndpoint (ChannelInstance) header in its messages
            bool useUniqueHeader = false;

            if (localAddressProvider != null)
            {
                localAddress = localAddressProvider.LocalAddress;
                filter = localAddressProvider.Filter;
                priority = localAddressProvider.Priority;
            }
            else
            {
                useUniqueHeader = CreateUniqueLocalAddress(out localAddress, out priority);
                filter = new MatchAllMessageFilter();
            }

            return this.CreateChannel(address, via, localAddress, filter, priority, useUniqueHeader);

        }

        public IDuplexChannel CreateChannel(EndpointAddress address, Uri via, MessageFilter filter, int priority, bool usesUniqueHeader)
        {
            return this.CreateChannel(address, via, new EndpointAddress(this.innerChannelListener.Uri), filter, priority, usesUniqueHeader);
        }

        public IDuplexChannel CreateChannel(EndpointAddress remoteAddress, Uri via, EndpointAddress localAddress, MessageFilter filter, int priority, bool usesUniqueHeader)
        {
            ChannelDemuxerFilter demuxFilter = new ChannelDemuxerFilter(new AndMessageFilter(new EndpointAddressMessageFilter(localAddress, true), filter), priority);
            IDuplexChannel newChannel = null;
            IOutputChannel innerOutputChannel = null;
            IChannelListener<IInputChannel> innerInputListener = null;
            IInputChannel innerInputChannel = null;
            try
            {
                innerOutputChannel = this.innerChannelFactory.CreateChannel(remoteAddress, via);
                innerInputListener = this.channelDemuxer.BuildChannelListener<IInputChannel>(demuxFilter);
                innerInputListener.Open();
                innerInputChannel = innerInputListener.AcceptChannel();
                newChannel = new ClientCompositeDuplexChannel(this, innerInputChannel, innerInputListener, localAddress, innerOutputChannel, usesUniqueHeader);
            }
            finally
            {
                if (newChannel == null) // need to cleanup
                {
                    if (innerOutputChannel != null)
                    {
                        innerOutputChannel.Close();
                    }

                    if (innerInputListener != null)
                    {
                        innerInputListener.Close();
                    }

                    if (innerInputChannel != null)
                    {
                        innerInputChannel.Close();
                    }
                }
            }

            return newChannel;
        }

        protected override void OnAbort()
        {
            base.OnAbort();
            this.innerChannelListener.Abort();
        }

        protected override void OnOpen(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            base.OnOpen(timeoutHelper.RemainingTime());
            this.innerChannelListener.Open(timeoutHelper.RemainingTime());
        }

        protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, this.innerChannelListener);
        }

        protected override void OnEndOpen(IAsyncResult result)
        {
            ChainedOpenAsyncResult.End(result);
        }

        protected override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            base.OnClose(timeoutHelper.RemainingTime());
            this.innerChannelListener.Close(timeoutHelper.RemainingTime());
        }

        protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
        {
            return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerChannelListener);
        }

        protected override void OnEndClose(IAsyncResult result)
        {
            ChainedCloseAsyncResult.End(result);
        }

        public override T GetProperty<T>()
        {
            if (typeof(T) == typeof(IChannelListener))
            {
                return (T)(object)innerChannelListener;
            }

            if (typeof(T) == typeof(ISecurityCapabilities) && !this.providesCorrelation)
            {
                return InternalDuplexBindingElement.GetSecurityCapabilities<T>(base.GetProperty<ISecurityCapabilities>());
            }

            T baseProperty = base.GetProperty<T>();
            if (baseProperty != null)
            {
                return baseProperty;
            }

            IChannelListener channelListener = innerChannelListener;
            if (channelListener != null)
            {
                return channelListener.GetProperty<T>();
            }
            else
            {
                return default(T);
            }
        }

        class ClientCompositeDuplexChannel : LayeredDuplexChannel
        {
            IChannelListener<IInputChannel> innerInputListener;
            bool usesUniqueHeader;  // Perf optimization - don't check message headers if we know there's only one CompositeDuplexChannel created

            public ClientCompositeDuplexChannel(ChannelManagerBase channelManager, IInputChannel innerInputChannel, IChannelListener<IInputChannel> innerInputListener, EndpointAddress localAddress, IOutputChannel innerOutputChannel, bool usesUniqueHeader)
                : base(channelManager, innerInputChannel, localAddress, innerOutputChannel)
            {
                this.innerInputListener = innerInputListener;
                this.usesUniqueHeader = usesUniqueHeader;
            }

            protected override void OnAbort()
            {
                base.OnAbort();
                this.innerInputListener.Abort();
            }

            protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
            {
                return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerInputListener.BeginClose, this.innerInputListener.EndClose);
            }

            protected override void OnClose(TimeSpan timeout)
            {
                TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                base.OnClose(timeoutHelper.RemainingTime());
                this.innerInputListener.Close(timeoutHelper.RemainingTime());
            }

            protected override void OnEndClose(IAsyncResult result)
            {
                ChainedAsyncResult.End(result);
            }

            protected override void OnReceive(Message message)
            {
                // Mark ChannelInstance header ref params as Understood on message
                // MessageFilters will take care of proper routing of the message, but we need to mark it as understood here.

                if (usesUniqueHeader)
                {
                    // 3.0 allows for messages to be received with duplicate message headers; we cannot
                    // use MessageHeaders.FindHeader() to find the header because it will throw an exception
                    // if it encounters duplicate headers. We instead have to look through all headers.

                    for (int i = 0; i < message.Headers.Count; i++)
                    {
                        if (message.Headers[i].Name == XD.UtilityDictionary.UniqueEndpointHeaderName.Value &&
                            message.Headers[i].Namespace == XD.UtilityDictionary.UniqueEndpointHeaderNamespace.Value)
                        {
                            message.Headers.AddUnderstood(i);
                        }
                    }
                }
            }
        }
    }
}


text:
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, backref

from aeromancer.db import models

class Module(models.Base):
    __tablename__ = 'oslo_module'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    line_id = Column(Integer, ForeignKey('line.id'))
    line = relationship(
        models.Line,
        uselist=False,
    )
    project_id = Column(Integer, ForeignKey('project.id'))
    project = relationship(
        models.Project,
        backref='oslo_modules',
    )


text:
package com.google.ads.googleads.v11.resources;

public final class CallViewProto {
  private CallViewProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_google_ads_googleads_v11_resources_CallView_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_google_ads_googleads_v11_resources_CallView_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n2google/ads/googleads/v11/resources/cal" +
      "l_view.proto\022\"google.ads.googleads.v11.r" +
      "esources\032Cgoogle/ads/googleads/v11/enums" +
      "/call_tracking_display_location.proto\032.g" +
      "oogle/ads/googleads/v11/enums/call_type." +
      "proto\032=google/ads/googleads/v11/enums/go" +
      "ogle_voice_call_status.proto\032\037google/api" +
      "/field_behavior.proto\032\031google/api/resour" +
      "ce.proto\"\221\005\n\010CallView\022@\n\rresource_name\030\001" +
      " \001(\tB)\340A\003\372A#\n!googleads.googleapis.com/C" +
      "allView\022 \n\023caller_country_code\030\002 \001(\tB\003\340A" +
      "\003\022\035\n\020caller_area_code\030\003 \001(\tB\003\340A\003\022\"\n\025call" +
      "_duration_seconds\030\004 \001(\003B\003\340A\003\022!\n\024start_ca" +
      "ll_date_time\030\005 \001(\tB\003\340A\003\022\037\n\022end_call_date" +
      "_time\030\006 \001(\tB\003\340A\003\022\210\001\n\036call_tracking_displ" +
      "ay_location\030\007 \001(\0162[.google.ads.googleads" +
      ".v11.enums.CallTrackingDisplayLocationEn" +
      "um.CallTrackingDisplayLocationB\003\340A\003\022H\n\004t" +
      "ype\030\010 \001(\01625.google.ads.googleads.v11.enu" +
      "ms.CallTypeEnum.CallTypeB\003\340A\003\022i\n\013call_st" +
      "atus\030\t \001(\0162O.google.ads.googleads.v11.en" +
      "ums.GoogleVoiceCallStatusEnum.GoogleVoic" +
      "eCallStatusB\003\340A\003:Z\352AW\n!googleads.googlea" +
      "pis.com/CallView\0222customers/{customer_id" +
      "}/callViews/{call_detail_id}B\377\001\n&com.goo" +
      "gle.ads.googleads.v11.resourcesB\rCallVie" +
      "wProtoP\001ZKgoogle.golang.org/genproto/goo" +
      "gleapis/ads/googleads/v11/resources;reso" +
      "urces\242\002\003GAA\252\002\"Google.Ads.GoogleAds.V11.R" +
      "esources\312\002\"Google\\Ads\\GoogleAds\\V11\\Reso" +
      "urces\352\002&Google::Ads::GoogleAds::V11::Res" +
      "ourcesb\006proto3"
    };
    descriptor = com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          com.google.ads.googleads.v11.enums.CallTrackingDisplayLocationProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.CallTypeProto.getDescriptor(),
          com.google.ads.googleads.v11.enums.GoogleVoiceCallStatusProto.getDescriptor(),
          com.google.api.FieldBehaviorProto.getDescriptor(),
          com.google.api.ResourceProto.getDescriptor(),
        });
    internal_static_google_ads_googleads_v11_resources_CallView_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_google_ads_googleads_v11_resources_CallView_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_google_ads_googleads_v11_resources_CallView_descriptor,
        new java.lang.String[] { "ResourceName", "CallerCountryCode", "CallerAreaCode", "CallDurationSeconds", "StartCallDateTime", "EndCallDateTime", "CallTrackingDisplayLocation", "Type", "CallStatus", });
    com.google.protobuf.ExtensionRegistry registry =
        com.google.protobuf.ExtensionRegistry.newInstance();
    registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
    registry.add(com.google.api.ResourceProto.resource);
    registry.add(com.google.api.ResourceProto.resourceReference);
    com.google.protobuf.Descriptors.FileDescriptor
        .internalUpdateFileDescriptor(descriptor, registry);
    com.google.ads.googleads.v11.enums.CallTrackingDisplayLocationProto.getDescriptor();
    com.google.ads.googleads.v11.enums.CallTypeProto.getDescriptor();
    com.google.ads.googleads.v11.enums.GoogleVoiceCallStatusProto.getDescriptor();
    com.google.api.FieldBehaviorProto.getDescriptor();
    com.google.api.ResourceProto.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


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

namespace MathParserDataStructures
{
    public enum Nonterminal
    {
        End /*stands for $*/,
        Expression,
        W, X,
        Term,
        K, Y,
        Power,
        V, Z,
        Factor,
        ParenthesisClose,
        Constant,   //a
        NoValue,
        AnyValue
    }
}


text:
require 'fix/engine/logger'
require 'fix/engine/server'
require 'fix/engine/client_connection'

#
# Main FIX namespace
#
module Fix

  #
  # Main Fix::Engine namespace
  #
  module Engine

    # The default IP on which the server will listen
    DEFAULT_IP    = '0.0.0.0'

    # The default port on which the server will listen
    DEFAULT_PORT  = 8359

    #
    # Runs a FIX server engine
    #
    def self.run!(ip = DEFAULT_IP, port = DEFAULT_PORT, handler = FE::ServerConnection, &block)
      Server.new(ip, port, handler, &block).run!
    end

    #
    # Alias the +Fix::Engine+ namespace to +FE+ if possible, because lazy is not necessarily dirty
    #
    def self.alias_namespace!
      Object.const_set(:FE, Engine) unless Object.const_defined?(:FE)
    end

  end
end

Fix::Engine.alias_namespace!


text:
package org.spongepowered.common.map.decoration.orientation;

import org.spongepowered.api.map.decoration.orientation.MapDecorationOrientation;

public class SpongeMapDecorationOrientation implements MapDecorationOrientation {

    private final int orientationNumber;

    public SpongeMapDecorationOrientation(final int orientationNumber) {
        this.orientationNumber = orientationNumber;
    }

    public int getOrientationNumber() {
        return this.orientationNumber;
    }
}


text:
<!--
Copyright 2015 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<script>

ga = function(cmd, type, category, action, label, value) {
};

</script>


text:
NSString * kPTEBaseURLString = @"https://api.stackexchange.com/2.2/questions?order=desc&sort=creation&site=stackoverflow";

@implementation PTEFeed

#pragma mark - Feed

+ (PTEFeed *)questionFeedWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
    return (PTEFeed *)[managedObjectContext cds_retrieveFirstEntryForEntityClass:[PTEFeed class]];
}

+ (PTEFeed *)questionFeed
{
    return [PTEFeed questionFeedWithManagedObjectContext:[CDSServiceManager sharedInstance].mainManagedObjectContext];
}

#pragma mark - Pages

- (NSArray *)orderedPages
{
    NSSortDescriptor *createdDateSort = [NSSortDescriptor sortDescriptorWithKey:@"index"
                                                                      ascending:YES];

    return [self.pages sortedArrayUsingDescriptors:@[createdDateSort]];
}

@end


text:
module Reports
  class Graphs
    def order_count_by_day
      total = 0

      order_count = Order.group("date(created_at)").count
      order_count = Hash[order_count.sort_by { |k, _| k }]
      Hash[order_count.map do |k, v|
        total += v
        [k, total]
      end]
    end

    def order_count_by_month
      results = {}

      order_count = Order.all.group_by { |m| m.created_at.beginning_of_month }
      order_count.each { |k, v| results[k.to_date] = v.count }

      results
    end

    def items_sent_count_by_month
      results = {}

      order_details = OrderDetail.joins(:order).where(orders: { status: 6 })
                                 .group_by { |m| m.created_at.beginning_of_month }
      order_details.each { |datetime, od| results[datetime.strftime("%b %y")] = od.map(&:quantity).sum }

      results
    end
  end
end


text:
document.write('<script type="text/javascript" src="scripts/prototype.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/scriptaculous.js"><\/script>');

//JQUERY
document.write('<script type="text/javascript" src="scripts/jquery/jquery-1.4.2.min.js"></script>');
document.write('<link href="scripts/jquery/showLoading/css/showLoading.css" rel="stylesheet" media="screen" /> ');
document.write('<script type="text/javascript" src="scripts/jquery/showLoading/js/jquery.showLoading.min.js"></script>');
document.write('<link href="scripts/jquery/ui/css/custom-theme/jquery-ui-1.8.4.custom.css" rel="stylesheet" media="screen" /> ');
document.write('<script type="text/javascript" src="scripts/jquery/ui/js/jquery-ui-1.8.4.custom.min.js"></script>');
document.write('<script type="text/javascript" src="scripts/jquery/caretRange/caretRange.js"></script>');

//General helpers
document.write('<script type="text/javascript" src="scripts/dom.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/ajax.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/helper.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/json.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/debugger.js"><\/script>');
// document.write('<script type="text/javascript" src="scripts/ws_rotateimg.js"><\/script>');

// GREYBOX
//document.write('<script type="text/javascript">var GB_ROOT_DIR = "./scripts/";<\/script>');
//document.write('<script type="text/javascript" src="scripts/AJS.js"><\/script>');
//document.write('<script type="text/javascript" src="scripts/AJS_fx.js"><\/script>');
//document.write('<script type="text/javascript" src="scripts/gb_scripts.js"><\/script>');
//document.write('<link href="scripts/gb_styles.css" rel="stylesheet" type="text/css" media="all" />');

//SYNTAX HIGHLIGHTER
document.write('<script type="text/javascript" src="scripts/shCore.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushJava.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushPhp.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushRuby.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushAlloy.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushNuSMV.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/shBrushXml.js"><\/script>');
document.write('<link href="scripts/shCore.css" rel="stylesheet" type="text/css" />');
document.write('<link href="scripts/shThemeDefault.css" rel="stylesheet" type="text/css" />');

//INLINE EDITING
document.write('<script type="text/javascript" src="scripts/inlineeditor.js"><\/script>');

//VML System
document.write('<link href="scripts/styles.css" rel="stylesheet" type="text/css" />');
document.write('<script type="text/javascript" src="scripts/vml_page.js"><\/script>');
document.write('<script type="text/javascript" src="scripts/vml_action.js"><\/script>');


text:
require "rdoc/generator/mdoc/helpers"

class RDoc::Generator::Mdoc
  class RenderContext
    include Helpers

    def initialize(assigns)
      assigns.each do |name, value|
        instance_variable_set("@#{name}", value)
      end
    end

    def binding
      super
    end
  end
end


text:
from yapsy.IPlugin import IPlugin
from yapsy.PluginManager import PluginManager
from django.template import loader, Context
from django.db.models import Count
from server.models import *
from django.shortcuts import get_object_or_404
import server.utils as utils
from datetime import datetime, timedelta, date
import django.utils.timezone

now = django.utils.timezone.now()
this_day = now - timedelta(hours=24)
week_ago = this_day - timedelta(days=7)
month_ago = this_day - timedelta(days=30)

class NewMachines(IPlugin):
    def plugin_type(self):
        return 'builtin'
    def widget_width(self):
        return 4

    def get_description(self):
        return 'New machines'

    def widget_content(self, page, machines=None, theid=None):
        # The data is data is pulled from the database and passed to a template.

        # There are three possible views we're going to be rendering to - front, bu_dashbaord and group_dashboard. If page is set to bu_dashboard, or group_dashboard, you will be passed a business_unit or machine_group id to use (mainly for linking to the right search).
        if page == 'front':
            t = loader.get_template('newmachines/templates/front.html')

        if page == 'bu_dashboard':
            t = loader.get_template('newmachines/templates/id.html')

        if page == 'group_dashboard':
            t = loader.get_template('newmachines/templates/id.html')

        try:
            today = machines.filter(first_checkin__gte=this_day).count()
        except:
            today = 0

        try:
            this_week = machines.filter(first_checkin__gte=week_ago).count()
        except:
            this_week = 0

        try:
            this_month = machines.filter(first_checkin__gte=month_ago).count()
        except:
            this_month = 0

        c = Context({
            'title': 'New Machines',
            'today_label': 'Today',
            'today_count': today,
            'week_label': 'This Week',
            'week_count': this_week,
            'month_label': 'This Month',
            'month_count': this_month,
            'plugin': 'NewMachines',
            'theid': theid,
            'page': page
        })
        return t.render(c)

    def filter_machines(self, machines, data):
        if data == 'day':
            machines = machines.filter(first_checkin__gte=this_day)
            title = 'Machines first seen today'

        elif data == 'week':
            machines = machines.filter(first_checkin__gte=week_ago)
            title = 'Machines first seen this week'

        elif data == 'month':
            machines = machines.filter(first_checkin__gte=month_ago)
            title = 'Machines first seen this month'

        else:
            machines = None

        return machines, title


text:
ENV["TEST"] = "1"
# Ensures aws api never called. Fixture home folder does not contain ~/.aws/credentails
ENV["HOME"] = "spec/fixtures/home"
ENV["SONIC_ROOT"] = "spec/fixtures/project"

# CodeClimate test coverage: https://docs.codeclimate.com/docs/configuring-test-coverage
# require 'simplecov'
# SimpleCov.start

require "pp"
require "byebug"
root = File.expand_path("../", File.dirname(__FILE__))
require "#{root}/lib/sonic"

module Helper
  def execute(cmd)
    puts "Running: #{cmd}" if show_command?
    out = `#{cmd}`
    puts out if show_command?
    out
  end

  # Added SHOW_COMMAND because DEBUG is also used by other libraries like
  # bundler and it shows its internal debugging logging also.
  def show_command?
    ENV['DEBUG'] || ENV['SHOW_COMMAND']
  end
end

RSpec.configure do |c|
  c.include Helper
end


text:
<?php $__env->startSection('main-content'); ?>

         <?php $__env->startSection('contentheader_title'); ?>

Cadastrar Professor

         <?php $__env->stopSection(); ?>

            <a class="btn btn-primary" href="<?php echo e(route('professor.index')); ?>"> Voltar

<?php if(count($errors) > 0): ?>
<div class="alert alert-danger"

        <?php foreach($errors->all() as $error): ?>

<?php echo e($error); ?>

        <?php endforeach; ?>

<?php endif; ?>
<?php echo Form::open(array('route' => 'professor.store','method'=>'POST')); ?>

            Nome:
            <?php echo Form::text('nome', null, array('placeholder' => 'Digite seu nome completo','class' => 'form-control')); ?>

            Matricula:
            <?php echo Form::text('matricula', null, array('placeholder' => '','class' => 'form-control')); ?>

            Email:
            <?php echo Form::text('email', null, array('placeholder' => '','class' => 'form-control')); ?>

            Telefone:
            <?php echo Form::text('telefone', null, array('placeholder' => '','class' => 'form-control')); ?>

            Area de Atuação:
            <?php echo Form::text('areaDeAtuacao', null, array('placeholder' => '','class' => 'form-control')); ?>

            Titulação:
            <?php echo Form::text('titulacao', null, array('placeholder' => '','class' => 'form-control')); ?>

            Classe:
            <?php echo Form::text('classe', null, array('placeholder' => '','class' => 'form-control')); ?>

            Regime de Trabalho:
            <?php echo Form::text('regimeDeTrabalho', null, array('placeholder' => '','class' => 'form-control')); ?>

            Tipo de Vinculo:
            <?php echo Form::text('tipoVincluo', null, array('placeholder' => '','class' => 'form-control')); ?>

            Data de Nascimento:
            <?php echo Form::text('dataNasc', null, array('placeholder' => '','class' => 'form-control')); ?>

            Departamento:
            <?php echo Form::select('fk_departamento', $departamentos, null, array('class' => 'form-control')); ?>

            Curso:
            <?php echo Form::select('fk_curso', $cursos, null, array('class' => 'form-control')); ?>

        <button type="submit" class="btn btn-primary">Salvar</button>

<?php echo Form::close(); ?>

<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>


text:
typedef enum : NSUInteger {
    ORTextCycleStyleDefault, //只有文字长度大于label长度 滚动
    ORTextCycleStyleAlways, //无论文字长短,一直滚动
}  ORTextCycleStyle;

IB_DESIGNABLE
@interface ORCycleLabel : UIView

@property (nonatomic, assign) ORTextCycleStyle style; //默认ORTextCycleStyleDefault
@property (nonatomic, assign)IBInspectable CGFloat interval; //间隔 默认 70
@property (nonatomic, assign)IBInspectable CGFloat rate;//速率 0~1 默认 0.5

@property (nonatomic, copy)IBInspectable NSString *text;
@property (nonatomic, strong) UIFont *font;
@property (nonatomic, strong)IBInspectable UIColor *textColor;
@property (nonatomic, assign) NSTextAlignment textAlignment;

- (void)start; //默认开启
- (void)pause;
- (void)stop;

@end


text:
import React from 'react';
import { connect } from 'react-redux'
import { resetPassword } from '../../actions/auth';
import Messages from '../Messages';

class Reset extends React.Component {
  constructor(props) {
    super(props);
    this.state = { password: '', confirm: '' };
  }

  handleChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  handleReset(event) {
    event.preventDefault();
    this.props.dispatch(resetPassword(this.state.password, this.state.confirm, this.props.params.token));
  }

  render() {
    return (

        <Messages messages={this.props.messages}/>
        <form onSubmit={this.handleReset.bind(this)}>

Reset Password

          New Password
          <input type="password" name="password" id="password" placeholder="New password" value={this.state.password} onChange={this.handleChange.bind(this)} autoFocus/>
          Confirm Password
          <input type="password" name="confirm" id="confirm" placeholder="Confirm password" value={this.state.confirm} onChange={this.handleChange.bind(this)}/>

          <button type="submit">Change Password</button>
        </form>

    );
  }
}

const mapStateToProps = (state) => {
  return state;
};

export default connect(mapStateToProps)(Reset);


text:
<?php

switch ($messaggio) {

case "Le date sono sbagliate":  		$messaggio = "Las fechas están equivocadas"; break;
case "Si deve inserire il tipo di tariffa":  	$messaggio = "Hay que insertar el tipo de tarifa"; break;
case "tariffa":  				$messaggio = "tarifa"; break;
case "Non è stato ancora inserito il prezzo della":	$messaggio = "No ha sido todavía insertado el precio de la"; break;
case "per la settimana dal":  			$messaggio = "para la semana desde el"; break;
case "per il giorno dal":  			$messaggio = "para el día desde el"; break;
case "al":  					$messaggio = "hasta el"; break;
case "La settimana dal":  			$messaggio = "La semana desde el"; break;
case "Il giorno dal":  				$messaggio = "El día desde el"; break;
case "è piena":  				$messaggio = "está llena"; break;
case "è pieno":  				$messaggio = "está lleno"; break;
case "Il numero di settimane del costo aggiuntivo settimanale nº":	$messaggio = "El número de semanas del coste añadido semanal nº"; break;
case "Il numero di giorni del costo aggiuntivo giornaliero nº":	$messaggio = "El número de días del coste añadido diario nº"; break;
case "supera il numero totale di settimane della prenotazione":	$messaggio = "supera el número total de semanas de la reserva"; break;
case "supera il numero totale di giorni della prenotazione":	$messaggio = "supera el número total de días de la reserva"; break;
case "persone":  				$messaggio = "personas"; break;
case "Si dovrà occupare almeno un periodo della regola di assegnazione 1":	$messaggio = "Habrá que ocupar por lo menos un período de la regla de asignación 1"; break;
case "Si devono fare i seguenti spostamenti nei periodi della regola di assegnazione 1":	$messaggio = "Hay que hacer los siguientes movimientos en los períodos de la regla de asignación 1"; break;
case "Sono stati fatti i seguenti spostamenti nei periodi della regola di assegnazione 1":	$messaggio = "Se han llevado a cabo los siguientes movimientos en los períodos de la regla de asignación 1"; break;
case "La prenotazione dal":  			$messaggio = "La reserva desde el"; break;
case "a nome di":  				$messaggio = "a nombre de"; break;
case "Non si può procedere perchè la tabella prenotazioni è cambiata nel frattempo":	$messaggio = "No se puede continuar porque ha cambiado la tabla de reservas mientras tanto"; break;
case "Continua lo stesso":  			$messaggio = "Continua lo mismo"; break;
case "Torna indietro":  			$messaggio = "Vuelve atrás"; break;
case "Non esistono clienti chiamati":  		$messaggio = "No existen clientes llamados"; break;
case "nel database":  				$messaggio = "en la base de datos"; break;
case "Inserisci i dati di un nuovo cliente":  	$messaggio = "Inserta los datos de un nuevo cliente"; break;
case "Esistono i seguenti clienti con un cognome uguale o simile":	$messaggio = "Existen los siguientes clientes con apedillo igual o similar"; break;
case "Esistono i seguenti clienti con un cognome e nome uguale o simile":	$messaggio = "Existen los siguientes clientes con apedillo y nombre igual o similar"; break;
case "nato il":	  				$messaggio = "nacido el"; break;
case "nata il":	  				$messaggio = "nacida el"; break;
case "CAP":  					$messaggio = "codigo postal"; break;
case "Telefono":  				$messaggio = "Teléfono"; break;
case "2º telefono":  				$messaggio = "2º teléfono"; break;
case "3º telefono":  				$messaggio = "3º teléfono"; break;
case "Utilizza il cliente":  			$messaggio = "Utiliza el cliente"; break;
case "per la prenotazione":  			$messaggio = "para la reserva"; break;
case "Modifica i dati del cliente":  		$messaggio = "Modificar los datos del cliente"; break;
case "Inserisci un nuovo cliente":  		$messaggio = "Inserta un nuevo cliente"; break;
case "É necessario inserire il cognome del cliente":	$messaggio = "Hay que insertar el apellido del cliente"; break;
case "I dati del cliente":  			$messaggio = "Los datos del cliente"; break;
case "sono stati inseriti":  			$messaggio = "han sido insertados"; break;
case "Inserisci o modifica i dati di un cliente":	$messaggio = "Inserta o modifica los datos de un cliente"; break;
case "Cognome":  				$messaggio = "Apellido"; break;
case "nome":  					$messaggio = "nombre"; break;
case "sesso":  					$messaggio = "sexo"; break;
case "Data di nascita":  			$messaggio = "Fecha de nacimiento"; break;
case "anno con 4 cifre":  			$messaggio = "año con 4 cifras"; break;
case "Nazione":  				$messaggio = "Nación"; break;
case "città":  					$messaggio = "ciudad"; break;
case "Via":  					$messaggio = "Calle"; break;
case "Piazza":  				$messaggio = "Plaza"; break;
case "Viale":  					$messaggio = "Avenida"; break;
case "Piazzale":  				$messaggio = "Paseo"; break;
case "Vicolo":  				$messaggio = "Bulevard"; break;
case "Numero di telefono":  			$messaggio = "Número de teléfono"; break;
case "Secondo telefono":  			$messaggio = "Seguno teléfono"; break;
case "Terzo telefono":  			$messaggio = "Tercer teléfono"; break;
case "Numero di fax":  				$messaggio = "Número de fax"; break;
case "Seconda persona di riferimento":  	$messaggio = "Segunda persona de referencia"; break;
case "Inserisci i dati":  			$messaggio = "Inserta los datos"; break;
case "Torna al menù principale":  		$messaggio = "Volver al menú principal"; break;
case "Italia":  				$messaggio = ""; break;
case "non verrano modificati i dati specifici delle 2 persone di riferimento":	$messaggio = "no serán modificados los datos específicos de las 2 personas de referencia"; break;
case "sono stati modificati":  			$messaggio = "han sido modificados"; break;
case "e":  					$messaggio = "y"; break;
case "Il numero di prenotazioni è sbagliato":	$messaggio = "El número de reservas está equivocado"; break;
case "Aggiungi":  				$messaggio = "Añade"; break;
case "Nº di tipologie da aggiungere":  		$messaggio = "Nº de tipologías a añadir"; break;
case "Non si è trovato nessun cliente chiamato":	$messaggio = "No se ha encontrado ningún cliente llamado"; break;
case "Non c'è nussun periodo delle regole 1 in cui sia consentito inserire prenotazioni per l'utente":	$messaggio = "No hay ningún período de las reglas 1 en el que esté consentido insertar reservas para el usuario"; break;
case "Il numero di persone è sbagliato":  	$messaggio = "El número de personas está equivocado"; break;
case "I dati di un costo aggiuntivo sono errati":	$messaggio = "Los datos de un coste añadido están equivocados"; break;
case "Non si può inserire più di un costo aggiuntivo con percentuale sul prezzo totale per prenotazione":	$messaggio = "No se puede insertar mas de un coste añadido con percentual sobre el precio total por reserva"; break;
case "Non si puo inserire il costo aggiuntivo":	$messaggio = "No se puede insertar el coste añadido"; break;
case "in questo periodo":  			$messaggio = "en este periodo"; break;
case "Scegliere le settimane in cui applicare il costo aggiuntivo":	$messaggio = "Escoger las semanas en las que aplicar el coste añadido"; break;
case "Scegliere i giorni in cui applicare il costo aggiuntivo":	$messaggio = "Escoger los días en las que aplicar el coste añadido"; break;
case "Continua":  				$messaggio = "Continua"; break;
case "Non si possono inserire altri costi":  	$messaggio = "No se pueden insertar mas costes"; break;
case "in questo periodo, già":  		$messaggio = "en este periodo, ya"; break;
case "presenti":  				$messaggio = "presentes"; break;
case "Si deve inserire il numero delle persone per il costo aggiuntivo":	$messaggio = "Hay que insertar el número de personas para el coste añadido"; break;
case "Il costo aggiuntivo":  			$messaggio = "El coste añadido"; break;
case "è incompatibile con la tariffa selezionata":	$messaggio = "es incompatible con la tarifa seleccionada"; break;
case "non può essere applicato":  		$messaggio = "no puede ser aplicado"; break;
case "regione":  				$messaggio = "región"; break;
case "Documento":  				$messaggio = "Documento"; break;
case "scadenza":  				$messaggio = "expiración"; break;
case "Torna all'inserimento clienti":  		$messaggio = "Vuelve a la inserción de los clientes"; break;
case "Annulla":  				$messaggio = "Anular"; break;
case "Ospite della prenotazione":  		$messaggio = "Huésped de la reserva"; break;
case "tipologia":  				$messaggio = "tipología"; break;
case "Ospiti della prenotazione":  		$messaggio = "Huéspedes de la reserva"; break;
case "Altri ospiti":  				$messaggio = "Otros huéspedes"; break;
case "nato":  					$messaggio = "nacido"; break;
case "nata":  					$messaggio = "nacida"; break;
case "il":  					$messaggio = "el"; break;
case " a":  					$messaggio = " en"; break;
case "scade":  					$messaggio = "caduca"; break;
case "cittadinanza":  				$messaggio = "nacionalidad"; break;
case "città di nascita":  			$messaggio = "ciudad de nacimiento"; break;
case "reg./prov. di nascita":  			$messaggio = "región de nacimiento"; break;
case "nazione di nascita":  			$messaggio = "nación de nacimiento"; break;
case "Residenza":  				$messaggio = "Residencia"; break;
case "reg./prov.":  				$messaggio = "región"; break;
case "nazione":  				$messaggio = "nación"; break;
case "rilasciato da":  				$messaggio = "emitido por"; break;
case "nazione di rilascio":  			$messaggio = "nación emisora"; break;
case "parentela":  				$messaggio = "emparentado"; break;
case "Codice fiscale":  			$messaggio = "N. Identificación Fiscal"; break;
case "con i costi aggiuntivi selezionati":  	$messaggio = "con los costes añadidos seleccionados"; break;
case "I beni richiesti dal costo":  		$messaggio = "Los bienes necesarios para el coste"; break;
case "non sono disponibili nell'inventario":  	$messaggio = "no están disponibles en el inventario"; break;
case "Si deve inserire il numero delle persone per questa tariffa":	$messaggio = "Hay que insertar el número de personas para esta tarifa"; break;
case "Partita iva":  				$messaggio = "Cert. Identificación Fiscal"; break;
case "lo sconto è sbagliato":  			$messaggio = "el descuento está equivocado"; break;
case "la caparra è sbagliata":  		$messaggio = "la fianza está equivocada"; break;
case "soprannome":  				$messaggio = "apodo"; break;
case "le commissioni sono sbagliate":  		$messaggio = "las comisiones están equivocas"; break;
case "lingua":  				$messaggio = "idioma"; break;
case "ln.":  					$messaggio = "id."; break;
case "non può essere moltiplicato per più di":	$messaggio = "no puede ser multiplicado por más de"; break;
case "La tariffa richiesta è chiusa in questo periodo":	$messaggio = "La tarifa seleccionada está cerrada en este período"; break;
case "Commento":  				$messaggio = "Comentario"; break;
case "":  		$messaggio = ""; break;
case "":  		$messaggio = ""; break;

} # fine switch ($messaggio)

?>


text:
Small app to feed all the historical data from Runkeeper into Withings

[![build status](https://secure.travis-ci.org/carlosvillademor/runkeeper-withings-sync.png)](http://travis-ci.org/carlosvillademor/runkeeper-withings-sync)

## Installation

This module is installed via npm:

``` bash
$ npm install runkeeper-withings-sync
```

## Example Usage

``` js
var runkeeperWithingsSync = require('runkeeper-withings-sync');
```


text:
#!/usr/bin/env node

/* eslint-disable unicorn/no-process-exit */

const {spawn} = require('child_process');
const net = require('net');

const airtunes = require('airtunes');
const Mqtt = require('mqtt');
const log = require('yalm');

const pkg = require('./package.json');
const config = require('./config.js');

log.setLevel(config.verbosity);

if (typeof config.speaker === 'string') {
    config.speaker = [config.speaker];
}

const speakers = {};
let count = 0;
let connected = false;
let io;

log.info(pkg.name, pkg.version, 'starting');

const mqtt = Mqtt.connect(config.mqttUrl, {will: {topic: config.name + '/connected', payload: '0', retain: true}});

config.speaker.forEach(speaker => {
    let port;
    let [name, host, portStart, portEnd] = speaker.split(':');
    if (typeof portEnd === 'undefined') {
        port = portStart;
        portStart = undefined;
    }
    if (name && host && (port || (portStart && portEnd))) {
        speakers[name] = {host, port, portStart, portEnd};
        mqttPub(config.name + '/status/' + name + '/enable', '0', {retain: true});
    } else {
        console.error('invalid speaker config', speaker);
        process.exit(1);
    }
});

mqtt.on('connect', () => {
    log.info('mqtt connected', config.mqttUrl);

    mqttPub(config.name + '/connected', connected ? '2' : '1', {retain: true});

    const topic = config.name + '/set/#';
    log.info('mqtt subscribe ' + topic);
    mqtt.subscribe(topic);
});

mqtt.on('close', () => {
    log.info('mqtt closed ' + config.mqttUrl);
});

mqtt.on('error', err => {
    log.error('mqtt', err.toString());
});

mqtt.on('offline', () => {
    log.error('mqtt offline');
});

mqtt.on('reconnect', () => {
    log.info('mqtt reconnect');
});

mqtt.on('message', (topic, message) => {
    message = message.toString();
    log.debug('mqtt < ', topic, message);
    const [, , speaker, command] = topic.split('/');
    if (!speakers[speaker]) {
        log.info('unknown speaker', speaker);
        return;
    }

    let obj;

    switch (command) {
        case 'enable':
            if (message === 'false' || message === '0') {
                stop(speaker);
            } else if (message === 'true' || parseInt(message, 10) > 0) {
                add(speaker);
            } else {
                try {
                    obj = JSON.parse(message);
                    if (obj.val) {
                        add(speaker);
                    } else {
                        stop(speaker);
                    }
                } catch (error) {
                    add(speaker);
                }
            }
            break;
        case 'disable':
            stop(speaker);
            break;
        case 'volume':
            if (isNaN(message)) {
                try {
                    obj = JSON.parse(message);
                    setVolume(speaker, obj.val);
                } catch (error) {}
            } else {
                setVolume(speaker, parseInt(message, 10));
            }
            break;
        default:
    }
});

airtunes.on('buffer', status => {
    log.debug('buffer', status);
});

startPipe();

function add(speaker, volume, nosearch) {
    log.debug('add', speaker, JSON.stringify({host: speakers[speaker].host, port: speakers[speaker].port, portStart: speakers[speaker].portStart, portEnd: speakers[speaker].portEnd}));
    if (speakers[speaker].portStart && !nosearch) {
        findport(speakers[speaker].host, speakers[speaker].portStart, speakers[speaker].portEnd, p => {
            if (p) {
                speakers[speaker].port = p;
                log.debug('found port', speaker, p);
                add(speaker, volume, true);
            } else {
                speakers[speaker].connected = false;

                mqttPub(config.name + '/status/' + speaker + '/enable', '0', {retain: true});
                if (io) {
                    io.emit('enabled', {name: speaker, enabled: false});
                }
            }
        });
        return;
    }

    if (speakers[speaker] && speakers[speaker].device) {
        log.warn('speaker', speaker, 'already added');
        return;
    }

    if (typeof volume === 'undefined') {
        volume = (speakers[speaker] && typeof speakers[speaker].volume === 'undefined') ? 20 : speakers[speaker].volume;
    }

    mqttPub(config.name + '/status/' + speaker + '/volume', String(volume), {retain: true});
    if (io) {
        io.emit('volume', {name: speaker, volume});
    }

    log.info('add ' + speaker + ' ' + speakers[speaker].host + ':' + speakers[speaker].port);

    mqttPub(config.name + '/status/' + speaker + '/connected', '1', {retain: true});
    if (io) {
        io.emit('enabled', {name: speaker, enabled: true});
    }

    speakers[speaker].volume = volume;
    speakers[speaker].device = airtunes.add(speakers[speaker].host, {
        port: speakers[speaker].port,
        volume,
        password: speakers[speaker].password
    });

    speakers[speaker].device.on('status', status => {
        log.info('status', speaker, status);
        if (status === 'ready') {
            speakers[speaker].connected = true;
            activeSpeakers();
            mqttPub(config.name + '/status/' + speaker + '/enable', '1', {retain: true});
            if (io) {
                io.emit('enabled', {name: speaker, enabled: true});
            }
        } else if (status === 'stopped') {
            delete speakers[speaker].device;
            speakers[speaker].connected = false;
            activeSpeakers();

            mqttPub(config.name + '/status/' + speaker + '/enable', '0', {retain: true});
            if (io) {
                io.emit('enabled', {name: speaker, enabled: false});
            }
        }
    });

    function speakerError(speaker, ev, err) {
        log.error(ev, speaker, err);
        delete speakers[speaker].device;
        speakers[speaker].connected = false;
        activeSpeakers();
        mqttPub(config.name + '/status/' + speaker + '/enable', '0', {retain: true});
        if (io) {
            io.emit('enabled', {name: speaker, enabled: false});
        }
    }

    speakers[speaker].device.on('error', err => {
        speakerError(speaker, 'error', err);
    });
    speakers[speaker].device.on('timeout', err => {
        speakerError(speaker, 'timeout', err);
    });
    speakers[speaker].device.on('connection_refused', err => {
        speakerError(speaker, 'connection_refused', err);
    });
    speakers[speaker].device.on('busy', err => {
        speakerError(speaker, 'busy', err);
    });
    speakers[speaker].device.on('disconnected', err => {
        speakerError(speaker, 'disconnected', err);
    });
    speakers[speaker].device.on('need_password', err => {
        speakerError(speaker, 'need_password', err);
    });
    speakers[speaker].device.on('bad_password', err => {
        speakerError(speaker, 'bad_password', err);
    });
    speakers[speaker].device.on('udp_ports', err => {
        speakerError(speaker, 'udp_ports', err);
    });
    speakers[speaker].device.on('rtsp_socket', err => {
        speakerError(speaker, 'rtsp_socket', err);
    });
}

function activeSpeakers() {
    count = 0;
    for (const s in speakers) {
        if (speakers[s].connected === true) {
            count += 1;
        }
    }
    mqttPub(config.name + '/status/activeSpeakers', String(count), {retain: true});
}

function stop(speaker) {
    if (!speakers[speaker] || !speakers[speaker].device) {
        log.warn('cant stop', speaker);
        return;
    }

    speakers[speaker].device.stop(() => {
        log.info('removed', speaker);
        delete speakers[speaker].device;
        speakers[speaker].connected = false;
        activeSpeakers();
    });
}

function setVolume(speaker, volume) {
    if (!speakers[speaker]) {
        return;
    }
    log.debug('volume', speaker, volume);
    speakers[speaker].volume = volume;
    if (speakers[speaker].device) {
        speakers[speaker].device.setVolume(volume);
    }
    mqttPub(config.name + '/status/' + speaker + '/volume', String(volume), {retain: true});
    if (io) {
        io.emit('volume', {name: speaker, volume});
    }
}

let arecord;

function startPipe() {
    if (config.loopback) {
        arecord = spawn('/usr/bin/arecord', ['-f', 'cd', '-D', config.device]);
        arecord.stdout.pipe(airtunes);
        connected = true;
        log.info('Loopback connected');
        mqttPub(config.name + '/connected', '2', {retain: true});
        arecord.on('exit', () => {
            connected = false;
            log.info('Loopback disconnected');
            mqttPub(config.name + '/connected', '1', {retain: true});
        });
    } else {
        const server = net.createServer(c => {
            log.info('tcp client', c.remoteAddress + ':' + c.remotePort, 'connected');
            mqttPub(config.name + '/connected', '2', {retain: true});

            c.on('end', () => {
                connected = false;
                log.info('tcp client disconnected');
                c.end();
                mqttPub(config.name + '/connected', '1', {retain: true});
            });

            c.on('error', err => {
                log.error('tcp error', err);
            });

            c.on('timeout', err => {
                log.error('tcp timeout', err);
            });

            c.pipe(airtunes, {end: false});
            connected = true;
        });

        server.listen(config.port, () => {
            log.info('tcp listener bound on port', config.port);
        });
    }
}

function findport(host, start, end, cb) {
    const timeout = setTimeout(() => {
        cb(null);
        cb = null;
    }, 5000);
    for (let p = start; p <= end; p++) {
        const client = net.connect({host, port: p}, () => {
            clearTimeout(timeout);
            if (cb) {
                cb(p);
            }
            cb = null;
            client.end();
        });
        client.on('error', () => {});
    }
}

function mqttPub(topic, payload, options) {
    log.debug('mqtt >', topic, payload);
    mqtt.publish(topic, payload, options);
}

if (!config.disableWeb) {
    const path = require('path');
    const express = require('express');
    const app = express();
    const server = require('http').createServer(app);
    io = require('socket.io')(server);

    io.on('connection', client => {
        log.info('socket.io connection');

        client.on('speakers', callback => {
            const data = {};
            Object.keys(speakers).forEach(name => {
                data[name] = {
                    enabled: speakers[name].connected,
                    volume: speakers[name].volume
                };
            });
            callback(data);
        });

        client.on('volume', data => {
            setVolume(data.name, data.volume);
        });

        client.on('enabled', data => {
            if (data.enabled) {
                add(data.name);
            } else {
                stop(data.name);
            }
        });
    });

    server.listen(config.webPort);

    app.get('/', (req, res) => {
        res.redirect(301, '/ui');
    });
    app.use('/ui', express.static(path.join(__dirname, '/www')));
}


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

namespace DesignPatterns.Behavioral.Visitor
{
    public class Director : Employee
    {
        public Director(string name, double income, int vacationDays)
            : base(name, income, vacationDays) { }
    }
}


text:
namespace FreeRiders.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public class EventsUsers
    {
        [Key]
        public int ID { get; set; }

        public string UserID { get; set; }

        public virtual User User { get; set; }

        public int EventID { get; set; }

        public virtual Event Event { get; set; }
    }
}


text:
package examples

import (
    "fmt"
    "encoding/base64"
)

func ExampleDecodeString1() {

    src := "dGhpcyBpcyBhIHRlc3Qgc3RyaW5nLg=="
    dst, _ := base64.StdEncoding.DecodeString(src)
    fmt.Println(string(dst) == "this is a test string.")

    dst, _ = base64.StdEncoding.DecodeString("")
    fmt.Println(string(dst) == "")

    dst, _ = base64.StdEncoding.DecodeString("Zg==")
    fmt.Println(string(dst) == "f")

    dst, _ = base64.StdEncoding.DecodeString("Zm8=")
    fmt.Println(string(dst) == "fo")

    dst, _ = base64.StdEncoding.DecodeString("Zm9v")
    fmt.Println(string(dst) == "foo")

    dst, _ = base64.StdEncoding.DecodeString("Zm9vYg==")
    fmt.Println(string(dst) == "foob")

    dst, _ = base64.StdEncoding.DecodeString("Zm9vYmE=")
    fmt.Println(string(dst) == "fooba")

    dst, _ = base64.StdEncoding.DecodeString("Zm9vYmFy")
    fmt.Println(string(dst) == "foobar")

    // Output:
    // true
    // true
    // true
    // true
    // true
    // true
    // true
    // true

}


text:
export const CHANGE_LANGUAGE = 'CHANGE_LANGUAGE'
export const SHOW_POPUP_LOADING = 'SHOW_POPUP_LOADING'
export const HIDE_POPUP_LOADING = 'HIDE_POPUP_LOADING'


text:
[![Build Status](https://travis-ci.org/CSCfi/ansible-role-arc-frontend.svg)](https://travis-ci.org/CSCfi/ansible-role-arc-frontend)
ansible-role-arc-frontend
=========

Ansible role that installs and configures a Nordugrid ARC Grid Frontend

Requirements
------------

Role Variables
--------------

There are many variables to be set.

See tasks/main.yml , templates/arc.conf.j2 and defaults/main.yml

 - arc_frontend_nis: false
 - add_slurm_accts: false

These services are set to disabled:
<pre>
arc_frontend_services:
 - arched
</pre>

Dependencies
------------

A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.

Example Playbook
----------------

Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:

    - hosts: servers
      roles:
         - { role: ansible-role-arc-frontend }

License
-------

MIT

Author Information
------------------


text: OzCat framework


text:
import logging
import os
import re
import subprocess
import threading

_CHROME_SRC = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
_LLVM_SYMBOLIZER_PATH = os.path.join(
    _CHROME_SRC, 'third_party', 'llvm-build', 'Release+Asserts', 'bin',
    'llvm-symbolizer')

_BINARY = re.compile(r'0b[0,1]+')
_HEX = re.compile(r'0x[0-9,a-e]+')
_OCTAL = re.compile(r'0[0-7]+')

_UNKNOWN = '<UNKNOWN>'

def _CheckValidAddr(addr):
  """
  Check whether the addr is valid input to llvm symbolizer.
  Valid addr has to be octal, binary, or hex number.

  Args:
    addr: addr to be entered to llvm symbolizer.

  Returns:
    whether the addr is valid input to llvm symbolizer.
  """
  return _HEX.match(addr) or _OCTAL.match(addr) or _BINARY.match(addr)

class LLVMSymbolizer(object):
  def __init__(self):
    """Create a LLVMSymbolizer instance that interacts with the llvm symbolizer.

    The purpose of the LLVMSymbolizer is to get function names and line
    numbers of an address from the symbols library.
    """
    self._llvm_symbolizer_subprocess = None
    # Allow only one thread to call GetSymbolInformation at a time.
    self._lock = threading.Lock()

  def Start(self):
    """Start the llvm symbolizer subprocess.

    Create a subprocess of the llvm symbolizer executable, which will be used
    to retrieve function names etc.
    """
    if os.path.isfile(_LLVM_SYMBOLIZER_PATH):
      self._llvm_symbolizer_subprocess = subprocess.Popen(
          [_LLVM_SYMBOLIZER_PATH],
          stdout=subprocess.PIPE,
          stdin=subprocess.PIPE,
          universal_newlines=True)
    else:
      logging.error('Cannot find llvm_symbolizer here: %s.' %
                    _LLVM_SYMBOLIZER_PATH)
      self._llvm_symbolizer_subprocess = None

  def Close(self):
    """Close the llvm symbolizer subprocess.

    Close the subprocess by closing stdin, stdout and killing the subprocess.
    """
    with self._lock:
      if self._llvm_symbolizer_subprocess:
        self._llvm_symbolizer_subprocess.kill()
        self._llvm_symbolizer_subprocess = None

  def __enter__(self):
    """Start the llvm symbolizer subprocess."""
    self.Start()
    return self

  def __exit__(self, exc_type, exc_val, exc_tb):
    """Close the llvm symbolizer subprocess."""
    self.Close()

  def GetSymbolInformation(self, lib, addr):
    """Return the corresponding function names and line numbers.

    Args:
      lib: library to search for info.
      addr: address to look for info.

    Returns:
      A list of (function name, line numbers) tuple.
    """
    if (self._llvm_symbolizer_subprocess is None or not lib
        or not _CheckValidAddr(addr) or not os.path.isfile(lib)):
      return [(_UNKNOWN, lib)]

    proc = self._llvm_symbolizer_subprocess
    with self._lock:
      proc.stdin.write('%s %s\n' % (lib, addr))
      proc.stdin.flush()
      result = []
      # Read until an empty line is observed, which indicates the end of the
      # output. Each line with a function name is always followed by one line
      # with the corresponding line number.
      while True:
        line = proc.stdout.readline()
        if line != '\n':
          line_numbers = proc.stdout.readline()
          result.append((line[:-1], line_numbers[:-1]))
        else:
          return result


text:
CREATE OR REPLACE FUNCTION cleanup_pgadapter()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
    TRUNCATE TABLE car_makers RESTART IDENTITY;
    TRUNCATE TABLE cars RESTART IDENTITY;
END $$;


text:
package vmutils

// Copyright 2017 Microsoft Corporation
//
//    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.

import (
	"fmt"

	vm "github.com/Azure/azure-sdk-for-go/services/classic/management/virtualmachine"
)

// ConfigureDeploymentFromRemoteImage configures VM Role to deploy from a remote
// image source. "remoteImageSourceURL" can be any publically accessible URL to
// a VHD file, including but not limited to a SAS Azure Storage blob url. "os"
// needs to be either "Linux" or "Windows". "label" is optional.
func ConfigureDeploymentFromRemoteImage(
	role *vm.Role,
	remoteImageSourceURL string,
	os string,
	newDiskName string,
	destinationVhdStorageURL string,
	label string) error {
	if role == nil {
		return fmt.Errorf(errParamNotSpecified, "role")
	}

	role.OSVirtualHardDisk = &vm.OSVirtualHardDisk{
		RemoteSourceImageLink: remoteImageSourceURL,
		MediaLink:             destinationVhdStorageURL,
		DiskName:              newDiskName,
		OS:                    os,
		DiskLabel:             label,
	}
	return nil
}

// ConfigureDeploymentFromPlatformImage configures VM Role to deploy from a
// platform image. See osimage package for methods to retrieve a list of the
// available platform images. "label" is optional.
func ConfigureDeploymentFromPlatformImage(
	role *vm.Role,
	imageName string,
	mediaLink string,
	label string) error {
	if role == nil {
		return fmt.Errorf(errParamNotSpecified, "role")
	}

	role.OSVirtualHardDisk = &vm.OSVirtualHardDisk{
		SourceImageName: imageName,
		MediaLink:       mediaLink,
	}
	return nil
}

// ConfigureDeploymentFromPublishedVMImage configures VM Role to deploy from
// a published (public) VM image.
func ConfigureDeploymentFromPublishedVMImage(
	role *vm.Role,
	vmImageName string,
	mediaLocation string,
	provisionGuestAgent bool) error {
	if role == nil {
		return fmt.Errorf(errParamNotSpecified, "role")
	}

	role.VMImageName = vmImageName
	role.MediaLocation = mediaLocation
	role.ProvisionGuestAgent = provisionGuestAgent
	return nil
}

// ConfigureDeploymentFromUserVMImage configures VM Role to deploy from a previously
// captured (user generated) VM image.
func ConfigureDeploymentFromUserVMImage(
	role *vm.Role,
	vmImageName string) error {
	if role == nil {
		return fmt.Errorf(errParamNotSpecified, "role")
	}

	role.VMImageName = vmImageName
	return nil
}

// ConfigureDeploymentFromExistingOSDisk configures VM Role to deploy from an
// existing disk. 'label' is optional.
func ConfigureDeploymentFromExistingOSDisk(role *vm.Role, osDiskName, label string) error {
	role.OSVirtualHardDisk = &vm.OSVirtualHardDisk{
		DiskName:  osDiskName,
		DiskLabel: label,
	}
	return nil
}