text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE header PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN"
  "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd">

  <namespace name="boost">

    <class name="bad_polymorphic_get">
      <inherit access="public">
        <classname>boost::bad_get</classname>
      </inherit>

      <purpose>
        <simpara>The exception thrown in the event of a failed application of
        <functionname>boost::polymorphic_get</functionname> on	the given
        operand value.</simpara>
      </purpose>

      <method	name="what"	specifiers="virtual" cv="const">
        <type>const	char *</type>
      </method>
    </class>

    <overloaded-function name="polymorphic_get">
      <signature>
        <template>
          <template-type-parameter name="U"/>
          <template-type-parameter name="T1"/>
          <template-type-parameter name="T2"/>
          <template-varargs/>
          <template-type-parameter name="TN"/>
        </template>

        <type>U *</type>

        <parameter name="operand">
          <paramtype><classname>variant</classname><T1, T2, ..., TN> *</paramtype>
        </parameter>
      </signature>

      <signature>
        <template>
          <template-type-parameter name="U"/>
          <template-type-parameter name="T1"/>
          <template-type-parameter name="T2"/>
          <template-varargs/>
          <template-type-parameter name="TN"/>
        </template>

        <type>const U *</type>

        <parameter name="operand">
          <paramtype>const <classname>variant</classname><T1, T2, ..., TN> *</paramtype>
        </parameter>
      </signature>

      <signature>
        <template>
          <template-type-parameter name="U"/>
          <template-type-parameter name="T1"/>
          <template-type-parameter name="T2"/>
          <template-varargs/>
          <template-type-parameter name="TN"/>
        </template>

        <type>U &</type>

        <parameter name="operand">
          <paramtype><classname>variant</classname><T1, T2, ..., TN> &</paramtype>
        </parameter>
      </signature>

      <signature>
        <template>
          <template-type-parameter name="U"/>
          <template-type-parameter name="T1"/>
          <template-type-parameter name="T2"/>
          <template-varargs/>
          <template-type-parameter name="TN"/>
        </template>

        <type>const U &</type>

        <parameter name="operand">
          <paramtype>const <classname>variant</classname><T1, T2, ..., TN> &</paramtype>
        </parameter>
      </signature>

      <purpose>
        <simpara>Retrieves a value of a specified type from a given
          <classname>variant</classname>.</simpara>
      </purpose>

      <description>
        <simpara>The polymorphic_get function allows run-time checked,
          type-safe retrieval of the content of the given
          <classname>variant</classname>. The function succeeds
          only if the content is of the specified type U or of type
          derived from type U, with
          failure indicated as described below.</simpara>
        <simpara><emphasis role="bold">Warning</emphasis>: After either
          operand or its content is destroyed (e.g., when the
          given <classname>variant</classname> is assigned a
          value of different type), the returned reference is invalidated.
          Thus, significant care and caution must be extended when handling
          the returned reference.</simpara>
      </description>

      <notes>
        <simpara>As part of its guarantee of type-safety, polymorphic_get
        enforces const-correctness. Thus, the specified type
        U must be const-qualified whenever
        operand or its content is likewise
        const-qualified. The converse, however, is not required:
        that is, the specified type U may be
        const-qualified even when operand and its
        content are not.</simpara>
      </notes>

      <returns>
        <simpara>If passed a pointer, polymorphic_get returns a pointer to
        the value content if it is of the specified type U or of type
        derived from type U;
        otherwise, a null pointer is returned. If passed a reference,
        polymorphic_get returns a reference to the value content if it is of
        the specified type U  or of type
          derived from type U; otherwise, an exception is thrown
        (see below).</simpara>
      </returns>

      <throws>
        <simpara>Overloads taking a
        <classname>variant</classname> pointer will not
        throw; the overloads taking a
        <classname>variant</classname> reference throw
        <classname>bad_polymorphic_get</classname> if the content is not of
        the specified type Uor of type
        derived from type U.</simpara>
      </throws>

      <rationale>
        <simpara>While visitation via
        <functionname>apply_visitor</functionname>
        is generally preferred due to its greater safety, polymorphic_get may
        may be more convenient in some cases due to its straightforward
        usage.</simpara>
      </rationale>
    </overloaded-function>

  </namespace>


text:
☎Contacts lets humans create contact cards, so that they can talk to other humans without being confused.

![Phone Gif](https://media.giphy.com/media/yPhqlJccIOaru/giphy.gif)

So, someone needs your digits? No problem, couldn't be easier. Observe:

```python
from contacts import ContactCard

card = ContactCard(
    name='David Heimann',
    first_name='David',
    last_name='Heimann',
    phone_number='+1XXXXXXX',
    photo=image_file,
    email='email@address.com',
    twitter='@david_heimann',
    website='https://about.me/dheimann'
)

# Build the card to generate a file that can be saved locally or to a server of your choosing.
card.build()
```

**⚠WARNING⚠:** Contacts is a WIP and doesn't work yet. Feel free to help out or subscribe / star and follow
along. I'll remove this when it's usable.

redpajama_set_name: RedPajamaGithub


text:
pub mod route;

use futures::Future;
use futures::future;
use hyper::Error;
use hyper::header::ContentLength;
use hyper::server::{Service, Request, Response};
use hyper::StatusCode;
use hyper::Method;

use controller::context::RequestContext;
use controller::middleware::around;
use controller::db;
use controller::user;
use self::route::Route;

pub type BoxFutureResponse = Box<Future<Item=Response, Error=Error>>;

#[derive(Debug)]
pub struct RouterService;

impl RouterService
{
    fn error_handler(status_code: StatusCode) -> Response
    {
        let error = "Routing error: page not found";
        let response = Response::new()
            .with_header(ContentLength(error.len() as u64))
            .with_body(error);

        match status_code {
            StatusCode::NotFound => response.with_status(StatusCode::NotFound),
            _ => response.with_status(StatusCode::InternalServerError)
        }
    }
}

impl Service for RouterService
{
    type Request = Request;
    type Response = Response;
    type Error = Error;
    type Future = BoxFutureResponse;

    fn call(&self, request: Request) -> Self::Future
    {
        let (request, body) = RequestContext::from_request(request);
        let uri = request.uri.path().to_string();

        match request.method.clone() {
            Method::Get if uri.is_match("/") => around(request, body, user::home),
            Method::Get if uri.is_match("/db/{name}") => around(request, body, db::index),
            Method::Get if uri.is_match("/sql/{name}") => around(request, body, db::sql),
            Method::Get if uri.is_match("/user/login") => around(request, body, user::login),
            Method::Post if uri.is_match("/user/login") => around(request, body, user::login),
            Method::Get if uri.is_match("/user/logout") => around(request, body, user::logout),
            _ => Box::new(future::ok(
                RouterService::error_handler(StatusCode::NotFound)
            ))
        }
    }
}


text:
using System;

namespace SolrNet.Commands.Cores {
    /// <summary>
    /// Creates a new core based on preexisting instanceDir/solrconfig.xml/schema.xml, and registers it.
    /// If persistence is enabled (persist=true), the configuration for this new core will be saved in 'solr.xml'.
    /// If a core with the same name exists, while the "new" created core is initalizing, the "old" one will continue to accept requests.
    /// Once it has finished, all new request will go to the "new" core, and the "old" core will be unloaded.
    /// </summary>
    public class CreateCommand : CoreCommand {
        /// <summary>
        /// Initializes a new instance of the <see cref="CreateCommand"/> class.
        /// </summary>
        /// <param name="name">The name of the core.</param>
        /// <param name="instanceDir">The Solr instance directory.</param>
        public CreateCommand(string name, string instanceDir): this(name, instanceDir, null, null, null) {}

        /// <summary>
        /// Initializes a new instance of the <see cref="CreateCommand"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="instanceDir">The Solr instance directory.</param>
        /// <param name="configFile">The config file to use. (optional)</param>
        /// <param name="schemaFile">The schema file to use. (optional)</param>
        /// <param name="dataDir">The data directory. (optional)</param>
        public CreateCommand(string name, string instanceDir, string configFile, string schemaFile, string dataDir) {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("Core Name must be specified.", "name");
            if (string.IsNullOrEmpty(instanceDir))
                throw new ArgumentException("The Solr instance directory must be specified.", "instanceDir");

            AddParameter("action", "CREATE");
            AddParameter("name", name);
            AddParameter("instanceDir", instanceDir);
            if (configFile != null)
                AddParameter("config", configFile);
            if (schemaFile != null)
                AddParameter("schema", schemaFile);
            if (dataDir != null)
                AddParameter("dataDir", dataDir);
        }
    }
}


text:
package com.google.devrel.training.conference.domain;

/**
 * A simple wrapper for announcement message.
 */
public class Announcement {

	private String message;

    public Announcement() {}

    public Announcement(String message) {
    	this.message = message;
    }

    public String getMessage() {
    	return message;
    }
}


text:
<?php

namespace Drupal\Core\Batch;

use Drupal\Core\Database\Connection;
use Drupal\Core\Database\SchemaObjectExistsException;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Drupal\Core\Access\CsrfTokenGenerator;

class BatchStorage implements BatchStorageInterface {

  /**
   * The table name.
   */
  const TABLE_NAME = 'batch';

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * The session.
   *
   * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
   */
  protected $session;

  /**
   * The CSRF token generator.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

  /**
   * Constructs the database batch storage service.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   * @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
   *   The session.
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token generator.
   */
  public function __construct(Connection $connection, SessionInterface $session, CsrfTokenGenerator $csrf_token) {
    $this->connection = $connection;
    $this->session = $session;
    $this->csrfToken = $csrf_token;
  }

  /**
   * {@inheritdoc}
   */
  public function load($id) {
    // Ensure that a session is started before using the CSRF token generator.
    $this->session->start();
    try {
      $batch = $this->connection->query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(
        ':bid' => $id,
        ':token' => $this->csrfToken->get($id),
      ))->fetchField();
    }
    catch (\Exception $e) {
      $this->catchException($e);
      $batch = FALSE;
    }
    if ($batch) {
      return unserialize($batch);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function delete($id) {
    try {
      $this->connection->delete('batch')
        ->condition('bid', $id)
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function update(array $batch) {
    try {
      $this->connection->update('batch')
        ->fields(array('batch' => serialize($batch)))
        ->condition('bid', $batch['id'])
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function cleanup() {
    try {
      // Cleanup the batch table and the queue for failed batches.
      $this->connection->delete('batch')
        ->condition('timestamp', REQUEST_TIME - 864000, '<')
        ->execute();
    }
    catch (\Exception $e) {
      $this->catchException($e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function create(array $batch) {
    // Ensure that a session is started before using the CSRF token generator.
    $this->session->start();
    $try_again = FALSE;
    try {
      // The batch table might not yet exist.
      $this->doCreate($batch);
    }
    catch (\Exception $e) {
      // If there was an exception, try to create the table.
      if (!$try_again = $this->ensureTableExists()) {
        // If the exception happened for other reason than the missing table,
        // propagate the exception.
        throw $e;
      }
    }
    // Now that the table has been created, try again if necessary.
    if ($try_again) {
      $this->doCreate($batch);
    }
  }

  /**
   * Saves a batch.
   *
   * @param array $batch
   *   The array representing the batch to create.
   */
  protected function doCreate(array $batch) {
    $this->connection->insert('batch')
      ->fields(array(
        'bid' => $batch['id'],
        'timestamp' => REQUEST_TIME,
        'token' => $this->csrfToken->get($batch['id']),
        'batch' => serialize($batch),
      ))
      ->execute();
  }

  /**
   * Check if the table exists and create it if not.
   */
  protected function ensureTableExists() {
    try {
      $database_schema = $this->connection->schema();
      if (!$database_schema->tableExists(static::TABLE_NAME)) {
        $schema_definition = $this->schemaDefinition();
        $database_schema->createTable(static::TABLE_NAME, $schema_definition);
        return TRUE;
      }
    }
    // If another process has already created the batch table, attempting to
    // recreate it will throw an exception. In this case just catch the
    // exception and do nothing.
    catch (SchemaObjectExistsException $e) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Act on an exception when batch might be stale.
   *
   * If the table does not yet exist, that's fine, but if the table exists and
   * yet the query failed, then the batch is stale and the exception needs to
   * propagate.
   *
   * @param $e
   *   The exception.
   *
   * @throws \Exception
   */
  protected function catchException(\Exception $e) {
    if ($this->connection->schema()->tableExists(static::TABLE_NAME)) {
      throw $e;
    }
  }

  /**
   * Defines the schema for the batch table.
   */
  public function schemaDefinition() {
    return [
      'description' => 'Stores details about batches (processes that run in multiple HTTP requests).',
      'fields' => [
        'bid' => [
          'description' => 'Primary Key: Unique batch ID.',
          // This is not a serial column, to allow both progressive and
          // non-progressive batches. See batch_process().
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
        ],
        'token' => [
          'description' => "A string token generated against the current user's session id and the batch id, used to ensure that only the user who submitted the batch can effectively access it.",
          'type' => 'varchar_ascii',
          'length' => 64,
          'not null' => TRUE,
        ],
        'timestamp' => [
          'description' => 'A Unix timestamp indicating when this batch was submitted for processing. Stale batches are purged at cron time.',
          'type' => 'int',
          'not null' => TRUE,
        ],
        'batch' => [
          'description' => 'A serialized array containing the processing data for the batch.',
          'type' => 'blob',
          'not null' => FALSE,
          'size' => 'big',
        ],
      ],
      'primary key' => ['bid'],
      'indexes' => [
        'token' => ['token'],
      ],
    ];
  }

}


text:
package retrotooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.content.Context;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

import static retrotooth.Utils.checkNotNull;

/**
 * Adapts a Java interface to a Bluetooth API.
 *

 * Inspired by square's Retrofit
 *

 *
 * @author James Ayvaz (james.ayvaz@gmail.com)
 */
public final class Retrotooth {
    private final Map<Method, MethodHandler<?>> methodHandlerCache = new LinkedHashMap<>();

    private final Context context;
    private final BluetoothManager bluetoothManager;
    private final BluetoothAdapter bluetoothAdapter;
    private BluetoothGatt client;
    private final BluetoothDevice bluetoothDevice;
    private final List<Converter.Factory> converterFactories;
    private final List<CallAdapter.Factory> adapterFactories;
    private final Executor callbackExecutor;
    private final RetrotoothGattCallback retrotoothGattCallback;

    private Retrotooth(Context context, BluetoothManager bluetoothManager, BluetoothAdapter bluetoothAdapter, BluetoothDevice bluetoothDevice, List<Converter.Factory> converterFactories,
                       List<CallAdapter.Factory> adapterFactories, Executor callbackExecutor) {
        this.context = context;
        this.bluetoothManager = bluetoothManager;
        this.bluetoothAdapter = bluetoothAdapter;
        this.bluetoothDevice = bluetoothDevice;
        this.converterFactories = converterFactories;
        this.adapterFactories = adapterFactories;
        this.callbackExecutor = callbackExecutor;
        this.retrotoothGattCallback = new RetrotoothGattCallback();
    }

    //region Inspect interface using reflection

    /**
     * Create an implementation of the API defined by the {@code service} interface.
     */
    @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
    public <T> T create(Class<T> service) {
        Utils.validateServiceClass(service);
        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[]{service},
                handler);
    }

    private final InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object... args) throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
                return method.invoke(this, args);
            }
            return loadMethodHandler(method).invoke(args);
        }
    };

    MethodHandler<?> loadMethodHandler(Method method) {
        MethodHandler<?> handler;
        synchronized (methodHandlerCache) {
            handler = methodHandlerCache.get(method);
            if (handler == null) {
                handler = MethodHandler.create(method, client, adapterFactories, converterFactories, retrotoothGattCallback);
                methodHandlerCache.put(method, handler);
            }
        }
        return handler;
    }
    //endregion

    public BluetoothGatt connect() {
        this.client = bluetoothDevice.connectGatt(this.context, false, this.retrotoothGattCallback);
        return this.client;
    }

    public void disconnect() {
        if (bluetoothAdapter == null || client == null) {
            throw new RuntimeException("BluetoothAdapter not initialized");
        }
        client.disconnect();
    }

    /**
     * After using a given BLE device, the app must call this method to ensure resources are
     * released properly.
     */
    public void close() {
        disconnect();
        if (client == null) {
            return;
        }
        client.close();
        client = null;
    }

    public BluetoothGatt client() {
        return client;
    }

    public BluetoothDevice bluetoothDevice() {
        return bluetoothDevice;
    }

    /**
     * TODO
     *

     * May be null.
     */
    public List<Converter.Factory> converterFactories() {
        return Collections.unmodifiableList(converterFactories);
    }

    public List<CallAdapter.Factory> callAdapterFactories() {
        return Collections.unmodifiableList(adapterFactories);
    }

    public Executor callbackExecutor() {
        return callbackExecutor;
    }

    /**
     * Build a new {@link Retrotooth}.
     *

     * Calling {@link #bluetoothDevice} is required before calling {@link #build()}. All other methods
     * are optional.
     */
    public static final class Builder {
        private BluetoothGatt client;
        private Context context;
        private BluetoothManager bluetoothManager;
        private BluetoothAdapter bluetoothAdapter;
        private String bluetoothDeviceAddress;
        private BluetoothDevice bluetoothDevice;
        private List<Converter.Factory> converterFactories = new ArrayList<>();
        private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
        private Executor callbackExecutor;

        public Builder() {
            // Add the built-in converter factory first. This prevents overriding its behavior but also
            // ensures correct behavior when using converters that consume all types.
            converterFactories.add(new BuiltInConverterFactory());
        }

        public Builder device(String address) {
            if (bluetoothAdapter == null) {
                throw new NullPointerException("bluetoothAdapter == null");
            }
            if (address == null) {
                throw new NullPointerException("address == null");
            }

            final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
            if (device == null) {
                throw new RuntimeException("Device not found.  Unable to connect.");
            }
            return this.device(device);
        }

        public Builder device(BluetoothDevice device) {
            if (bluetoothAdapter == null) {
                throw new NullPointerException("bluetoothAdapter == null");
            }
            this.bluetoothDevice = checkNotNull(device, "device == null");
            return this;
        }

        public Builder with(Context context) {
            this.context = checkNotNull(context, "context == null");

            if (bluetoothManager == null) {
                bluetoothManager = checkNotNull((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE), "bluetoothManager == null");
            }

            bluetoothAdapter = checkNotNull(bluetoothManager.getAdapter(), "bluetoothAdapter == null");

            return this;
        }

        /** Add converter factory for serialization and deserialization of objects. */
        public Builder addConverterFactory(Converter.Factory converterFactory) {
            converterFactories.add(checkNotNull(converterFactory, "converterFactory == null"));
            return this;
        }

        /**
         * TODO
         */
        public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
            adapterFactories.add(checkNotNull(factory, "factory == null"));
            return this;
        }

        /**
         * The executor on which {@link Callback} methods are invoked when returning {@link Call} from
         * your service method.
         */
        public Builder callbackExecutor(Executor callbackExecutor) {
            this.callbackExecutor = checkNotNull(callbackExecutor, "callbackExecutor == null");
            return this;
        }

        /**
         * Create the {@link Retrotooth} instances.
         */
        public Retrotooth build() {
            if (bluetoothDevice == null) {
                throw new IllegalStateException("Bluetooth device required.");
            }

            if (context == null) {
                throw new IllegalStateException("context required.");
            }

            // Make a defensive copy of the adapters and add the default Call adapter.
            List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
            adapterFactories.add(Platform.get().defaultCallAdapterFactory(callbackExecutor));

            // Make a defensive copy of the converters.
            List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);

            return new Retrotooth(context, bluetoothManager, bluetoothAdapter, bluetoothDevice, converterFactories, adapterFactories, callbackExecutor);
        }
    }
}


text:
/*********************************************************************************
* (Column sorting) Implement the following method to sort the columns in a       *
* twodimensional array. A new array is returned and the original array is intact.*
*                                                                                *
* public static double[][] sortColumns(double[][] m)                             *
*                                                                                *
* Write a test program that prompts the user to enter a 3 * 3 matrix of double   *
* values and displays a new column-sorted matrix. Here is a sample run:          *
*********************************************************************************/
import java.util.Scanner;

public class Exercise_08_27 {
	/** Main method */
	public static void main(String[] args) {
		// Get a 3 x 3 matrix of double values from user input
		double[][] matrix = getMatrix();

		// Get a new sorted matrix
		double[][] sortedMatrix = sortColumns(matrix);

		// Display new sorted matrix
		System.out.println("\nThe column-sorted array is");
		for (int i = 0; i < sortedMatrix.length; i++) {
			for (int j = 0; j < sortedMatrix.length; j++) {
				System.out.print(sortedMatrix[i][j] + " ");
			}
			System.out.println();
		}
	}

	/** getMatrix prompts the user to enter a 3 x 3
	    matrix of double values then returns it */
	public static double[][] getMatrix() {
		Scanner input = new Scanner(System.in);
		double[][] m = new double[3][3];

		System.out.println("Enter a 3-by-3 matrix row by row:");
		for (int i = 0; i < m.length; i++) {
			for (int j = 0; j < m[i].length; j++) {
				m[i][j] = input.nextDouble();
			}
		}
		return m;
	}

	/** sortColums return a new column-sorted
	    array leaving original array intact */
	public static double[][] sortColumns(double[][] m)  {
		// Create a new 3-by-3 matrix
		double[][] s = new double[m.length][m[0].length];

		// Copy elements to new matrix
		copyMatrix(m, s);

		// Sort new matrix by column
		for (int col = 0; col < s.length; col++) {
			for (int row = 0; row < s.length - 1; row++) {
				double min = s[row][col];
				int index = row;
				for (int j = row + 1; j < s.length; j++) {
					if (min > s[j][col]) {
						min = s[j][col];
						index = j;
					}
				}
				if (index != row) {
					s[index][col] = s[row][col];
					s[row][col] = min;
				}
			}
		}
		return s;
	}

	/** copyMatrix copies all the elements in the original matrix to the copy */
	public static void copyMatrix(double[][] original, double[][] copy) {
		for (int i = 0; i < original.length; i++) {
			for (int j = 0; j < original[i].length; j++) {
				copy[i][j] = original[i][j];
			}
		}
	}
}


text:
layout: page
title: Squad Holdings Trade Fair
date: 2016-05-24
author: Christina Combs
tags: weekly links, java
status: published
summary: Vestibulum eu elit non ligula facilisis eleifend eu eget.
banner: images/banner/people.jpg
booking:
  startDate: 09/04/2017
  endDate: 09/07/2017
  ctyhocn: STLSTHX
  groupCode: SHTF
published: true
---
Phasellus ut ipsum ex. Proin ornare dui vitae ex bibendum vulputate. Ut dictum enim erat, non tempus erat sollicitudin eu. Donec auctor risus lorem, id maximus lorem auctor id. Pellentesque vitae libero finibus, consequat erat non, lacinia augue. Phasellus sed ullamcorper diam. Nulla nec varius ipsum, vitae venenatis felis. Suspendisse potenti. In a turpis metus. Ut ut ex ac eros scelerisque congue nec sit amet magna. Morbi lacus lacus, gravida eget aliquet at, euismod et tortor. Praesent eu neque purus. Proin imperdiet bibendum purus a gravida. Aliquam dictum, lacus vel malesuada volutpat, leo nisl pulvinar odio, quis pulvinar mi mauris a neque. Nullam vehicula dolor ac purus varius suscipit. Maecenas convallis sagittis mi, sit amet pretium eros mollis vel.

* Vestibulum id est cursus, maximus nisl quis, laoreet nisl
* Ut tempor tellus sed semper imperdiet
* Sed faucibus nisl vitae dui pharetra rutrum
* Aenean laoreet risus ac est sollicitudin, quis feugiat ligula euismod.

Sed id auctor risus. Nunc felis leo, fermentum sit amet sapien blandit, ullamcorper feugiat dui. Nullam nec massa suscipit elit semper facilisis et sit amet dui. Donec non massa erat. Praesent condimentum libero vestibulum ultrices pellentesque. Nam malesuada posuere purus, at faucibus orci faucibus ac. Aliquam ipsum sem, sodales id magna eu, cursus consectetur ante. Nulla egestas suscipit odio, non ultricies diam. Mauris posuere tortor eget purus congue aliquam. Proin elementum non leo eget congue. Nam tempor sagittis lorem fermentum facilisis. Suspendisse risus dui, consequat dictum interdum non, tempus at mauris. Nulla accumsan mollis mauris sed rutrum. Maecenas rhoncus pellentesque odio id scelerisque. Donec tincidunt eros vel fringilla porta.


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKRENDERVIEWBASEWRAP_H
#define NATIVE_EXTENSION_VTK_VTKRENDERVIEWBASEWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkRenderViewBase.h>

#include "vtkViewWrap.h"
#include "../../plus/plus.h"

class VtkRenderViewBaseWrap : public VtkViewWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkRenderViewBaseWrap(vtkSmartPointer<vtkRenderViewBase>);
		VtkRenderViewBaseWrap();
		~VtkRenderViewBaseWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void GetInteractor(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetRenderWindow(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetRenderer(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void Render(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ResetCamera(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ResetCameraClippingRange(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetInteractor(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetRenderWindow(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetRenderer(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKRENDERVIEWBASEWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKRENDERVIEWBASEWRAP_CLASSDEF
#endif
};

#endif


text:
using namespace ise;

///////////////////////////////////////////////////////////////////////////////

class AppBusiness : public IseBusiness
{
public:
    virtual void initIseOptions(IseOptions& options);
    virtual void onTcpConnected(const TcpConnectionPtr& connection);
    virtual void onTcpSendComplete(const TcpConnectionPtr& connection, const Context& context);
};

///////////////////////////////////////////////////////////////////////////////

#endif // _HELLO_WORLD_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;
using System.Net.Mail;

namespace SocialGoal.Web.Mailers
{
	public interface IUserMailer
	{

		MvcMailMessage Welcome();
		MvcMailMessage Invite(string email, Guid groupIdToken);

		MvcMailMessage Support(string email, Guid goalIdToken);
		MvcMailMessage ResetPassword(string email,Guid passwordResetToken);

        MvcMailMessage InviteNewUser(string email, Guid registrationToken);

	}
}


text:
package pl.isa.hadoop;

import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;

import java.util.ArrayList;
import java.util.List;

public class StructUdf extends GenericUDF {
        private StringObjectInspector oi1;
        private StringObjectInspector oi2;

        public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
                if(objectInspectors.length != 2) {
                        throw new UDFArgumentException("not enought arguments");
                }

                ObjectInspector oi1 = objectInspectors[0];
                if(oi1.getCategory() != ObjectInspector.Category.PRIMITIVE ||
                        ((PrimitiveObjectInspector)oi1).getPrimitiveCategory()
                                != PrimitiveObjectInspector.PrimitiveCategory.STRING) {
                        throw new UDFArgumentException("wrong type of first param");
                }
                this.oi1 = (StringObjectInspector) oi1;

                ObjectInspector oi2 = objectInspectors[1];
                if(oi2.getCategory() != ObjectInspector.Category.PRIMITIVE ||
                        ((PrimitiveObjectInspector)oi2).getPrimitiveCategory()
                                != PrimitiveObjectInspector.PrimitiveCategory.STRING) {
                        throw new UDFArgumentException("wrong type of second param");
                }
                this.oi2 = (StringObjectInspector) oi2;

                StringObjectInspector soi = PrimitiveObjectInspectorFactory.javaStringObjectInspector;
                List<ObjectInspector> ois = new ArrayList<ObjectInspector>();
                ois.add(soi);
                ois.add(soi);

                List<String> fields = new ArrayList<String>();
                fields.add("first");
                fields.add("second");

                return ObjectInspectorFactory.getStandardStructObjectInspector(fields, ois);
        }

        public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {
                String firstArgument = oi1.getPrimitiveJavaObject(deferredObjects[0].get());
                String secondArgument = oi2.getPrimitiveJavaObject(deferredObjects[1].get());

                return new Object[]{firstArgument, secondArgument};
        }

        public String getDisplayString(String[] strings) {
                return null;
        }
}


text:
import signal
import sys
import time
import threading

class Hi():
	def __init__(self):
		signal.signal(signal.SIGINT, self.signal_handler)

		assert False

		for i in range(5000):
			print("Sleeping {}".format(i), end="\r")
			time.sleep(i)

	def signal_handler(self, signal, frame):
	    print('You pressed Ctrl+C!')
	    sys.exit(1)

try:
	x = Hi()
except Exception as e:
	 # Good this does not catch keyboardInterrupt
	print("Caught me!")
	sys.exit(0)


text:
import Tile from '../../definitions/tile';
import { Tiles as Glyphs } from '../../constants/glyphs';

export class Void extends Tile { constructor() { super(); this.opacity = 1; this.reflect = 0; }}

export class DungeonFloor extends Tile { constructor() { super(Glyphs.Floor); }}

export class Corridor extends Tile { constructor() { super(Glyphs.Corridor); } }


text:
const backbone = require('backbone');
const datasync = require('relution/datasync.js');

export const options = {
    entity: 'approvals',
    type: {
        container: 'relutionsdk MetaModelContainer',
        model: 'approval'
    },

    idAttribute: 'id',
    aclAttribute: 'aclEntries',

    backbone: backbone,
    sync: datasync.sync
};


text:
<?xml version="1.0"?>
<!--
~ Copyright 2015-present Open Networking Laboratory
~
~ 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.
-->
<project
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.onosproject</groupId>
        <artifactId>onos-app-fm</artifactId>
        <version>1.9.0-SNAPSHOT</version>
    </parent>

    <artifactId>onos-app-fm-web</artifactId>
    <packaging>bundle</packaging>
    <properties>
        <web.context>/onos/v1/fm</web.context>
        <api.version>1.0.0</api.version>
        <api.title>ONOS Fault Management Application REST API</api.title>
        <api.description>
            APIs for interacting with the Fault Management application.
        </api.description>
        <api.package>org.onosproject.faultmanagement.web</api.package>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>javax.ws.rs-api</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-incubator-api</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onlab-osgi</artifactId>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.core</groupId>
            <artifactId>jersey-client</artifactId>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-core-common</artifactId>
            <scope>test</scope>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-rest</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.onosproject</groupId>
            <artifactId>onos-rest</artifactId>
            <version>${project.version}</version>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.glassfish.jersey.test-framework</groupId>
            <artifactId>jersey-test-framework-core</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <_wab>src/main/webapp/</_wab>
                        <Include-Resource>
                            WEB-INF/classes/apidoc/swagger.json=target/swagger.json,
                            {maven-resources}
                        </Include-Resource>
                        <Bundle-SymbolicName>
                            ${project.groupId}.${project.artifactId}
                        </Bundle-SymbolicName>
                        <Import-Package>
                            *,org.glassfish.jersey.servlet
                        </Import-Package>
                        <Web-ContextPath>${web.context}</Web-ContextPath>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

namespace ZfTable\Decorator\Cell;

use Nette\Diagnostics\Debugger;
use ZfTable\Decorator\Exception;

class XEditable extends AbstractCellDecorator
{

    /**
     * Array of variable attribute for link
     * @var array
     */
    protected $vars;

    /**
     * Link url
     * @var string
     */
    protected $url;

    /**
     * Rendering decorator
     * @param string $context
     * @return string
     */
    public function render($context)
    {

        $cell = $this->getCell();
        $cell->addClass('xeditable');
        $cell->addAttr('data-column', $cell->getHeader()->getName());
        $row = $cell->getActualRow();
        if(is_object($row)) {
            $pk = $row->getId();
        } else {
            $pk = $row['id'];
        }
        return sprintf('%s', $cell->getHeader()->getName(), $pk, $cell->getTable()->getOptions()->getRowAction(), $cell->getHeader()->getName(), $context);
    }
}


text:
package org.search.nibrs.validation.groupb;

import java.util.ArrayList;
import java.util.List;

import org.search.nibrs.common.NIBRSError;
import org.search.nibrs.model.GroupBArrestReport;
import org.search.nibrs.model.codes.NIBRSErrorCode;
import org.search.nibrs.validation.rules.NotBlankRule;
import org.search.nibrs.validation.rules.NumericValueRule;
import org.search.nibrs.validation.rules.Rule;

/**
 * Factory class that provides Rule implementations to validate the elements contained on the Group B report administrative segment.
 */
public class GroupBArrestReportRulesFactory {

	private List<Rule<GroupBArrestReport>> rulesList;

	public GroupBArrestReportRulesFactory() {

		rulesList = new ArrayList<Rule<GroupBArrestReport>>();
	}

	/**
	 * Get the list of rules for the GroupB Arrest Report segment factory.
	 *
	 * @return the list of rules
	 */
	public List<Rule<GroupBArrestReport>> getRulesList() {
		rulesList.add(getRule101("ori", "1"));
		rulesList.add(getRule101("yearOfTape", "Year of Tape"));
		rulesList.add(getRule101("monthOfTape", "Month of Tape"));
		rulesList.add(getRule104("yearOfTape"));
		rulesList.add(getRule104("monthOfTape"));
		return rulesList;
	}

	Rule<GroupBArrestReport> getRule101(String propertyName, String dataElementIdentifier) {
		return new NotBlankRule<GroupBArrestReport>(propertyName, dataElementIdentifier, GroupBArrestReport.class, NIBRSErrorCode._701);
	}

	Rule<GroupBArrestReport> getRule104(String propertyName) {
		Rule<GroupBArrestReport> ret = null;
		if ("yearOfTape".equals(propertyName)) {
			ret = new NumericValueRule<>(
					subject -> {
						return subject.getYearOfTape();
					},
					(value, target) -> {
						NIBRSError e = null;
						if (value != null && 1991 > value.intValue()) {
							e = target.getErrorTemplate();
							e.setNIBRSErrorCode(NIBRSErrorCode._104);
							e.setDataElementIdentifier("Year of Tape");
							e.setValue(value);
						}
						return e;
					});
		} else if ("monthOfTape".equals(propertyName)) {
			ret = new NumericValueRule<>(
					subject -> {
						return subject.getMonthOfTape();
					},
					(value, target) -> {
						NIBRSError e = null;
						if (value != null && (1 > value.intValue() || 12 < value.intValue())) {
							e = target.getErrorTemplate();
							e.setNIBRSErrorCode(NIBRSErrorCode._104);
							e.setDataElementIdentifier("Month of Tape");
							e.setValue(value);
						}
						return e;
					});
		}
		return ret;
	}

}


text:
#ifndef GLTRANS_H
#define GLTRANS_H

#include "state/cr_statetypes.h"

#ifdef __cplusplus
extern "C" {
#endif

#define NUM_MATRICES 4

typedef struct {
	CRbitvalue dirty[CR_MAX_BITARRAY];
	CRbitvalue *currentMatrix; /* points to one of the following */
	CRbitvalue matrixMode[CR_MAX_BITARRAY];
	CRbitvalue modelviewMatrix[CR_MAX_BITARRAY];
	CRbitvalue projectionMatrix[CR_MAX_BITARRAY];
	CRbitvalue colorMatrix[CR_MAX_BITARRAY];
	CRbitvalue textureMatrix[CR_MAX_BITARRAY];
	CRbitvalue programMatrix[CR_MAX_BITARRAY];
	CRbitvalue clipPlane[CR_MAX_BITARRAY];
	CRbitvalue enable[CR_MAX_BITARRAY];
	CRbitvalue base[CR_MAX_BITARRAY];
} CRTransformBits;

typedef struct {
   CRmatrix *top;      /* points into stack */
   CRmatrix *stack;    /* array [maxDepth] of CRmatrix */
   GLuint depth;       /* 0 <= depth < maxDepth */
   GLuint maxDepth;    /* size of stack[] array */
} CRMatrixStack;

typedef struct {
	GLvectord  *clipPlane;
	GLboolean  *clip;

	GLenum matrixMode;

	/* matrix stacks */
	CRMatrixStack modelViewStack;
	CRMatrixStack projectionStack;
	CRMatrixStack colorStack;
	CRMatrixStack textureStack[CR_MAX_TEXTURE_UNITS];
	CRMatrixStack programStack[CR_MAX_PROGRAM_MATRICES];
	CRMatrixStack *currentStack;

	GLboolean modelViewProjectionValid;
	CRmatrix  modelViewProjection;  /* product of modelview and projection */

#ifdef CR_OPENGL_VERSION_1_2
	GLboolean rescaleNormals;
#endif
#ifdef CR_IBM_rasterpos_clip
	GLboolean rasterPositionUnclipped;
#endif
	GLboolean normalize;
} CRTransformState;

void crStateTransformInit(CRContext *ctx);
void crStateTransformDestroy(CRContext *ctx);

void
crStateInitMatrixStack(CRMatrixStack *stack, int maxDepth);

void crStateLoadMatrix(const CRmatrix *m);

void crStateTransformUpdateTransform(CRTransformState *t);
void crStateTransformXformPoint(CRTransformState *t, GLvectorf *p);

void crStateTransformXformPointMatrixf(const CRmatrix *m, GLvectorf *p);
void crStateTransformXformPointMatrixd(const CRmatrix *m, GLvectord *p);

void crStateTransformDiff(CRTransformBits *t, CRbitvalue *bitID,
                          CRContext *fromCtx, CRContext *toCtx);

void crStateTransformSwitch(CRTransformBits *bb, CRbitvalue *bitID,
                            CRContext *fromCtx, CRContext *toCtx);

#ifdef __cplusplus
}
#endif

#endif /* CR_STATE_TRANSFORM_H */


text:
<?php

return array(
    'Used message from PHP (t, regular category)'   => 'Used message from PHP (t, regular category)',
    'Used message from PHP (t, slashed category)'   => 'Used message from PHP (t, slashed category)',
    'Used message from PHP (registerTranslations)'  => 'Used message from PHP (registerTranslations)',
    'Used message from HTML'                        => 'Used message from HTML',
    'Used message from TWIG (t)'                    => 'Used message from TWIG (t)',
    'Used message from TWIG (registerTranslations)' => 'Used message from TWIG (registerTranslations)',

    <weak_warning descr="[Yii2] This translation seems to be not used">'Unused message' => 'Unused message'</weak_warning>,
);


text:
package cromwell.database.slick

import com.typesafe.config.{Config, ConfigFactory}
import cromwell.database.slick.tables.EngineDataAccessComponent
import cromwell.database.sql.EngineSqlDatabase

object EngineSlickDatabase {
  def fromParentConfig(parentConfig: Config = ConfigFactory.load): EngineSlickDatabase = {
    val databaseConfig = SlickDatabase.getDatabaseConfig("engine", parentConfig)
    new EngineSlickDatabase(databaseConfig)
  }
}

class EngineSlickDatabase(originalDatabaseConfig: Config)
  extends SlickDatabase(originalDatabaseConfig)
    with EngineSqlDatabase
    with WorkflowStoreSlickDatabase
    with JobKeyValueSlickDatabase
    with JobStoreSlickDatabase
    with CallCachingSlickDatabase
    with SubWorkflowStoreSlickDatabase
    with DockerHashStoreSlickDatabase {
  override lazy val dataAccess = new EngineDataAccessComponent(slickConfig.profile)
}


text:
//
//  CMCCIOTShowAdvertisementView.m
//  AdvertisementScroll
//
//  Created by yue wang on 15/9/7.
//  Copyright (c) 2015年 cmcc. All rights reserved.
//

#import "CMCCIOTShowAdvertisementView.h"
#import "UIImageView+WebCache.h"
#define w self.bounds.size.width
#define h self.bounds.size.height
#define timeInterval 5.0
@interface CMCCIOTShowAdvertisementView ()<UIScrollViewDelegate>
{
    UIScrollView *_mainScrollView;
    UIPageControl *_pageCountrol;
    NSTimer *_timer;
    BOOL _draging;//标记是否drag
}
@end

@implementation CMCCIOTShowAdvertisementView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)dealloc
{
    [self invalidateTimer];
}
-(void)invalidateTimer
{
    if (_timer && [_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
}

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

        _draging = NO;

        _mainScrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        _mainScrollView.contentInset = UIEdgeInsetsMake(0, w, 0, w);
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.delegate = self;
        [self addSubview:_mainScrollView];

        _pageCountrol = [[UIPageControl alloc]initWithFrame:CGRectMake((w-100)/2, h-40, 100, 20)];
        [self addSubview:_pageCountrol];

    }
    return self;
}

-(void)setImageURLArray:(NSArray *)imageURLArray
{
    _imageURLArray = imageURLArray;

    for (UIView *view in _mainScrollView.subviews) {
        if ([view isMemberOfClass:[UIImageView class]]) {
            [view removeFromSuperview];
        }
    }

    if (_imageURLArray.count > 0) {
        _pageCountrol.numberOfPages = _imageURLArray.count;

        [self addImageViewWithIndex:-1 urlStrIndex:(int)_imageURLArray.count-1];

        for (int i=0; i<_imageURLArray.count; i++) {
            [self addImageViewWithIndex:i urlStrIndex:i];
        }

        [self addImageViewWithIndex:(int)_imageURLArray.count urlStrIndex:0];
    }
    _mainScrollView.contentSize = CGSizeMake(_imageURLArray.count*w, h);

    //添加定时器
    [self performSelector:@selector(delayTimer) withObject:nil afterDelay:timeInterval];

}
//延时timeInterval后添加定时器
-(void)delayTimer
{
    [self invalidateTimer];

    _timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(timerLoop) userInfo:nil repeats:YES];
    [_timer fire];
}
//添加imageView到scrollView上的方法 i:offSetX的基数  index:取图片imageURLArray里的哪一张
-(void)addImageViewWithIndex:(int)i urlStrIndex:(int)index
{
    UIImageView *aImageView = [[UIImageView alloc]initWithFrame:CGRectMake(i*w, 0, w, h)];
    aImageView.userInteractionEnabled = YES;
    aImageView.tag = index;
    [aImageView sd_setImageWithURL:[NSURL URLWithString:_imageURLArray[index]]];
   // [aImageView sd_setImageWithURL:[NSURL URLWithString:_imageURLArray[index]] placeholderImage:[UIImage imageNamed:@"laptopBackground.png"]];
    [_mainScrollView addSubview:aImageView];

    //手势
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImage:)];
    [aImageView addGestureRecognizer:gesture];
}

//手势点击事件
-(void)tapImage:(UITapGestureRecognizer *)gesture
{
    NSInteger tag =  gesture.view.tag;
    if (_delegate &&[_delegate respondsToSelector:@selector(loopCurrentIndex:)])
        [_delegate loopCurrentIndex:tag];
}

#pragma mark - timer
-(void)timerLoop
{

    [UIView animateWithDuration:0.3 animations:^{
        CGPoint aContentOffset = _mainScrollView.contentOffset;
        aContentOffset.x += w;
        _mainScrollView.contentOffset = aContentOffset;
    } completion:^(BOOL finished) {
        CGPoint aContentOffset = _mainScrollView.contentOffset;
        int tag = (int)aContentOffset.x/w;
        if (tag == _imageURLArray.count) {

            aContentOffset.x = 0;
            _mainScrollView.contentOffset = aContentOffset;
        }
        _pageCountrol.currentPage = tag%_imageURLArray.count;
    }];
}

#pragma mark - scrollview delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_draging) {     //drag时有效,不drag无效,定时器的方法timerLoop不受下面代码影响

        CGPoint contentOffset = scrollView.contentOffset;
        if (contentOffset.x == w*_imageURLArray.count) {
            _pageCountrol.currentPage = 0;
            contentOffset.x = 0;
            scrollView.contentOffset = contentOffset;
        }
        else if(contentOffset.x == -w){
            _pageCountrol.currentPage = _imageURLArray.count-1;
            contentOffset.x = (_imageURLArray.count-1)*w;
            scrollView.contentOffset = contentOffset;
        }
        else{
            _pageCountrol.currentPage = (int)contentOffset.x/w;
        }

    }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [_timer setFireDate:[NSDate distantFuture]];//当手动滑动图片时,让定时器挂起
    _draging = YES;//标记正在drag
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _draging = NO;//标记drag结束
    [_timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:timeInterval]];//当手动滑动结束图片停止运动时,重启定时器
}

@end


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

import com.facebook.presto.block.BlockAssertions;
import com.facebook.presto.operator.OperatorAssertion;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import org.apache.commons.math3.distribution.BinomialDistribution;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.facebook.presto.operator.aggregation.AggregationTestUtils.assertApproximateAggregation;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static org.testng.Assert.assertTrue;

public abstract class AbstractTestApproximateAggregationFunction
        extends AbstractTestAggregationFunction
{
    private static final int WEIGHT = 10;
    protected abstract Type getType();

    // values may contain nulls
    protected abstract Double getExpectedValue(List<Number> values);

    @Override
    public double getConfidence()
    {
        return 0.5;
    }

    @Override
    protected boolean isApproximate()
    {
        return true;
    }

    @Override
    protected List<String> getFunctionParameterTypes()
    {
        return ImmutableList.of(getType().getName());
    }

    @Override
    public Block getSequenceBlock(int start, int length)
    {
        BlockBuilder blockBuilder = getType().createBlockBuilder(new BlockBuilderStatus());
        for (int i = start; i < start + length; i++) {
            if (getType() == BIGINT) {
                BIGINT.writeLong(blockBuilder, (long) i);
            }
            else {
                DOUBLE.writeDouble(blockBuilder, (double) i);
            }
        }
        return blockBuilder.build();
    }

    @Override
    public Double getExpectedValue(int start, int length)
    {
        List<Number> values = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            if (getType() == BIGINT) {
                for (int j = 0; j < WEIGHT; j++) {
                    values.add((long) start + i);
                }
            }
            else {
                for (int j = 0; j < WEIGHT; j++) {
                    values.add((double) start + i);
                }
            }
        }

        return getExpectedValue(values);
    }

    @Override
    public Double getExpectedValueIncludingNulls(int start, int length, int lengthIncludingNulls)
    {
        List<Number> values = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            if (getType() == BIGINT) {
                for (int j = 0; j < WEIGHT; j++) {
                    values.add((long) start + i);
                }
            }
            else {
                for (int j = 0; j < WEIGHT; j++) {
                    values.add((double) start + i);
                }
            }
        }
        for (int i = length; i < lengthIncludingNulls; i++) {
            for (int j = 0; j < WEIGHT; j++) {
                values.add(null);
            }
        }

        return getExpectedValue(values);
    }

    @Test
    public void testCorrectnessOnGaussianData()
            throws Exception
    {
        int originalDataSize = 10000;
        Random distribution = new Random(0);
        List<Number> list = new ArrayList<>();
        for (int i = 0; i < originalDataSize; i++) {
            list.add(distribution.nextGaussian() * 100);
        }

        testCorrectnessOfErrorFunction(list);
    }

    @Test
    public void testCorrectnessOnUniformData()
            throws Exception
    {
        int originalDataSize = 10000;
        Random distribution = new Random(0);
        List<Number> list = new ArrayList<>();
        for (int i = 0; i < originalDataSize; i++) {
            list.add(distribution.nextDouble() * 1000);
        }

        testCorrectnessOfErrorFunction(list);
    }

    private void testCorrectnessOfErrorFunction(List<Number> inputList)
            throws Exception
    {
        int inRange = 0;
        int numberOfRuns = 1000;
        double sampleRatio = 1 / (double) WEIGHT;
        double actual = getExpectedValue(inputList);
        Random rand = new Random(1);

        for (int i = 0; i < numberOfRuns; i++) {
            //Compute Sampled Value using sampledList (numberOfRuns times)
            ImmutableList.Builder<Number> sampledList = ImmutableList.builder();
            for (Number x : inputList) {
                if (rand.nextDouble() < sampleRatio) {
                    sampledList.add(x);
                }
            }

            BlockBuilder builder = getType().createBlockBuilder(new BlockBuilderStatus());
            for (Number sample : sampledList.build()) {
                if (getType() == BIGINT) {
                    BIGINT.writeLong(builder, sample.longValue());
                }
                else if (getType() == DOUBLE) {
                    DOUBLE.writeDouble(builder, sample.doubleValue());
                }
                else {
                    throw new AssertionError("Can only handle longs and doubles");
                }
            }
            Page page = new Page(builder.build());
            page = OperatorAssertion.appendSampleWeight(ImmutableList.of(page), WEIGHT).get(0);
            Accumulator accumulator = getFunction().bind(ImmutableList.of(0), Optional.<Integer>absent(), Optional.of(page.getChannelCount() - 1), getConfidence()).createAccumulator();

            accumulator.addInput(page);
            Block result = accumulator.evaluateFinal();

            String approxValue = BlockAssertions.toValues(accumulator.getFinalType(), result).get(0).toString();
            double approx = Double.parseDouble(approxValue.split(" ")[0]);
            double error = Double.parseDouble(approxValue.split(" ")[2]);

            //Check if actual answer lies within [approxAnswer - error, approxAnswer + error]
            if (Math.abs(approx - actual) <= error) {
                inRange++;
            }
        }

        BinomialDistribution binomial = new BinomialDistribution(numberOfRuns, getConfidence());
        int lowerBound = binomial.inverseCumulativeProbability(0.01);
        int upperBound = binomial.inverseCumulativeProbability(0.99);
        assertTrue(lowerBound < inRange && inRange < upperBound, String.format("%d out of %d passed. Expected [%d, %d]", inRange, numberOfRuns, lowerBound, upperBound));
    }

    @Override
    protected void testAggregation(Object expectedValue, Block block)
    {
        Page page = OperatorAssertion.appendSampleWeight(ImmutableList.of(new Page(block)), WEIGHT).get(0);
        assertApproximateAggregation(getFunction(), page.getChannelCount() - 1, getConfidence(), (Double) expectedValue, page);
    }
}


text: A HighchartsChartTest is a test class for testing the behavior of HighchartsChart


text:
package org.loon.framework.android.game.action.sprite;

import java.util.HashMap;
import java.util.LinkedList;

import org.loon.framework.android.game.action.map.AStarFinder;
import org.loon.framework.android.game.action.map.Field2D;
import org.loon.framework.android.game.core.LObject;
import org.loon.framework.android.game.core.LSystem;
import org.loon.framework.android.game.core.geom.RectBox;
import org.loon.framework.android.game.core.geom.Vector2D;
import org.loon.framework.android.game.core.graphics.LImage;
import org.loon.framework.android.game.core.graphics.Screen.LTouch;
import org.loon.framework.android.game.core.graphics.device.LGraphics;
import org.loon.framework.android.game.core.timer.LTimer;
import org.loon.framework.android.game.utils.CollectionUtils;

import android.graphics.Bitmap;

// 用以让精灵响应触屏操作自动行走。与Actor中MoveTo最大的区别是,该类不缓存行走路径,
// 也不在单独线程中运行,同时却提供了更多的单项操作。
public class TouchSprite extends LObject implements ISprite {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private static HashMap<Integer, int[][]> lazyMaps;

	private Field2D field2D;

	private boolean allDirection;

	private LinkedList<Vector2D> findPath = new LinkedList<Vector2D>();

	private int startX, startY, endX, endY, moveX, moveY;

	private int direction, speed, touchX, touchY, mapID;

	private int width, height, tileWidth, tileHeight;

	private int readerWidth, readerHeight;

	protected final static int BLOCK_SIZE = 32;

	private LImage image;

	private boolean isComplete, isVisible, isColse;

	private float alpha;

	private ISprite sprite;

	private Bind bind;

	private LTimer timer;

	public TouchSprite() {
		this(true);
	}

	public TouchSprite(boolean all) {
		this((LImage) null, BLOCK_SIZE, BLOCK_SIZE, all);
	}

	public TouchSprite(String path) {
		this(path, true);
	}

	/**
	 * all为true时八方向行走,否则为四方向行走。
	 *
	 * @param path
	 * @param all
	 */
	public TouchSprite(String path, boolean all) {
		this(LImage.createImage(path), 0, 0, all);
	}

	public TouchSprite(int tileWidth, int tileHeight) {
		this(tileWidth, tileHeight, true);
	}

	public TouchSprite(int tileWidth, int tileHeight, boolean all) {
		this((LImage) null, tileWidth, tileHeight, all);
	}

	public TouchSprite(String path, int tileWidth, int tileHeight, boolean all) {
		this(LImage.createImage(path), tileWidth, tileHeight, all);
	}

	public TouchSprite(LImage tex2d, int tileWidth, int tileHeight, boolean all) {
		this(null, tex2d, tileWidth, tileHeight, LSystem.screenRect.width,
				LSystem.screenRect.height, all);
	}

	public TouchSprite(Field2D field, LImage tex2d, int tileWidth,
			int tileHeight, int maxWidth, int maxHeight, boolean all) {
		if (lazyMaps == null) {
			lazyMaps = new HashMap<Integer, int[][]>();
		}
		this.readerWidth = maxWidth;
		this.readerHeight = maxHeight;
		this.timer = new LTimer(0);
		this.isVisible = true;
		this.isColse = false;
		this.isComplete = false;
		this.allDirection = all;
		this.setTexture(tex2d);
		if (field == null) {
			if (tileWidth > 0) {
				this.tileWidth = tileWidth;
			} else {
				this.tileWidth = this.width;
			}
			if (tileHeight > 0) {
				this.tileHeight = tileHeight;
			} else {
				this.tileHeight = this.height;
			}
			int w = maxWidth / this.tileWidth;
			int h = maxHeight / this.tileHeight;
			this.mapID = LSystem.unite(mapID, w);
			this.mapID = LSystem.unite(mapID, h);
			int[][] maps = lazyMaps.get(mapID);
			if (maps == null) {
				maps = new int[h][w];
			}
			this.field2D = new Field2D(maps, this.tileWidth, this.tileHeight);
		} else {
			this.tileWidth = field.getTileWidth();
			this.tileHeight = field.getTileHeight();
			this.field2D = field;
		}
		this.speed = 4;
	}

	public void updateMove() {
		synchronized (TouchSprite.class) {
			if (!getCollisionBox().contains(touchX, touchY)) {
				if (findPath != null) {
					findPath.clear();
				}
				findPath = AStarFinder.find(field2D, field2D
						.pixelsToTilesWidth(x()), field2D
						.pixelsToTilesHeight(y()), field2D
						.pixelsToTilesWidth(touchX), field2D
						.pixelsToTilesHeight(touchY), allDirection);
			} else if (findPath != null) {
				findPath.clear();
			}
		}
	}

	public int hashCode() {
		if (field2D == null) {
			return super.hashCode();
		}
		int hashCode = 1;
		hashCode = LSystem.unite(hashCode, allDirection);
		hashCode = LSystem.unite(hashCode, field2D.pixelsToTilesWidth(x()));
		hashCode = LSystem.unite(hashCode, field2D.pixelsToTilesHeight(y()));
		hashCode = LSystem.unite(hashCode, field2D.pixelsToTilesWidth(touchX));
		hashCode = LSystem.unite(hashCode, field2D.pixelsToTilesHeight(touchY));
		hashCode = LSystem.unite(hashCode, field2D.getWidth());
		hashCode = LSystem.unite(hashCode, field2D.getHeight());
		hashCode = LSystem.unite(hashCode, field2D.getTileWidth());
		hashCode = LSystem.unite(hashCode, field2D.getTileHeight());
		hashCode = LSystem.unite(hashCode, CollectionUtils.hashCode(field2D
				.getMap()));
		return hashCode;
	}

	public void setTexture(String path) {
		this.setTexture(LImage.createImage(path));
	}

	public void setTexture(LImage tex2d) {
		if (tex2d != null) {
			this.image = tex2d;
			this.width = image.getWidth() > LSystem.screenRect.width ? BLOCK_SIZE
					: image.getWidth();
			this.height = image.getHeight() > LSystem.screenRect.height ? BLOCK_SIZE
					: image.getHeight();
		} else {
			this.width = BLOCK_SIZE;
			this.height = BLOCK_SIZE;
		}
	}

	public Field2D getField2D() {
		return new Field2D(field2D);
	}

	public void onTouch(LTouch e) {
		this.onTouch(e.x(), e.y());
	}

	public void onTouch(int x, int y) {
		this.touchX = x;
		this.touchY = y;
		this.updateMove();
	}

	public int getTouchX() {
		return touchX;
	}

	public int getTouchY() {
		return touchY;
	}

	public void onPosition(LTouch e) {
		this.onPosition(e.getX(), e.getY());
	}

	public void onPosition(float x, float y) {
		if (findPath == null) {
			return;
		}
		synchronized (findPath) {
			if (findPath != null) {
				findPath.clear();
			}
		}
		this.setLocation(x, y);
	}

	public void update(long elapsedTime) {
		if (field2D == null || findPath == null) {
			return;
		}
		if (isComplete()) {
			return;
		}
		if (timer.action(elapsedTime)) {
			synchronized (findPath) {
				if (endX == startX && endY == startY) {
					if (findPath != null) {
						if (findPath.size() > 1) {
							Vector2D moveStart = (Vector2D) findPath.get(0);
							Vector2D moveEnd = (Vector2D) findPath.get(1);
							startX = field2D.tilesToWidthPixels(moveStart.x());
							startY = field2D.tilesToHeightPixels(moveStart.y());
							endX = moveEnd.x() * field2D.getTileWidth();
							endY = moveEnd.y() * field2D.getTileHeight();
							moveX = moveEnd.x() - moveStart.x();
							moveY = moveEnd.y() - moveStart.y();
							direction = Field2D.getDirection(moveX, moveY);
							findPath.remove(0);
						} else {
							findPath.clear();
						}
					}
				}
				switch (direction) {
				case Field2D.TUP:
					startY -= speed;
					if (startY < endY) {
						startY = endY;
					}
					break;
				case Field2D.TDOWN:
					startY += speed;
					if (startY > endY) {
						startY = endY;
					}
					break;
				case Field2D.TLEFT:
					startX -= speed;
					if (startX < endX) {
						startX = endX;
					}
					break;
				case Field2D.TRIGHT:
					startX += speed;
					if (startX > endX) {
						startX = endX;
					}
					break;
				case Field2D.UP:
					startX += speed;
					startY -= speed;
					if (startX > endX) {
						startX = endX;
					}
					if (startY < endY) {
						startY = endY;
					}
					break;
				case Field2D.DOWN:
					startX -= speed;
					startY += speed;
					if (startX < endX) {
						startX = endX;
					}
					if (startY > endY) {
						startY = endY;
					}
					break;
				case Field2D.LEFT:
					startX -= speed;
					startY -= speed;
					if (startX < endX) {
						startX = endX;
					}
					if (startY < endY) {
						startY = endY;
					}
					break;
				case Field2D.RIGHT:
					startX += speed;
					startY += speed;
					if (startX > endX) {
						startX = endX;
					}
					if (startY > endY) {
						startY = endY;
					}
					break;
				}
				setLocation(startX, startY);
				if (sprite != null) {
					try {
						if (bind != null && bind.isBindPos()) {
							synchronized (sprite) {
								bind.callPos(getX(), getY());
							}
						}
					} catch (Exception e) {
					}
					sprite.update(elapsedTime);
				}
			}
		}
	}

	public long getDelay() {
		return timer.getDelay();
	}

	public void setDelay(long d) {
		timer.setDelay(d);
	}

	public int getWidth() {
		return width;
	}

	public int getHeight() {
		return height;
	}

	public int getDirection() {
		return direction;
	}

	public int getSpeed() {
		return speed;
	}

	public void setSpeed(int speed) {
		this.speed = speed;
	}

	public boolean isComplete() {
		return findPath == null || findPath.size() == 0 || isComplete;
	}

	public void setComplete(boolean c) {
		this.isComplete = true;
	}

	public void createUI(LGraphics g) {
		if (!isVisible || isColse) {
			return;
		}
		if (findPath == null) {
			if (sprite != null) {
				sprite.createUI(g);
				return;
			}
			if (alpha > 0 && alpha < 1) {
				g.setAlpha(alpha);
			}
			if (image != null) {
				g.drawImage(image, x(), y());
			}
			if (alpha > 0 && alpha < 1) {
				g.setAlpha(1);
			}

		} else {
			synchronized (findPath) {
				if (sprite != null) {
					sprite.createUI(g);
					return;
				}
				if (alpha > 0 && alpha < 1) {
					g.setAlpha(alpha);
				}
				if (image != null) {
					g.drawImage(image, x(), y());
				}
				if (alpha > 0 && alpha < 1) {
					g.setAlpha(1);
				}
			}
		}
	}

	public ISprite getBindSprite() {
		return sprite;
	}

	public void bind(ISprite sprite) {
		if (sprite == null) {
			this.sprite = null;
			this.bind = null;
		} else {
			this.sprite = sprite;
			this.bind = new Bind(sprite);
		}
	}

	public float getAlpha() {
		return alpha;
	}

	public void setAlpha(float a) {
		this.alpha = a;
	}

	public Bitmap getBitmap() {
		return image.getBitmap();
	}

	public RectBox getCollisionBox() {
		return getRect(x(), y(), width, height);
	}

	public boolean isVisible() {
		return isVisible;
	}

	public void setVisible(boolean v) {
		this.isVisible = v;
	}

	public void dispose() {
		this.isColse = true;
		if (image != null) {
			image.dispose();
			image = null;
		}
		if (findPath != null) {
			findPath.clear();
			findPath = null;
		}
		if (lazyMaps != null) {
			lazyMaps.remove(mapID);
		}
	}

	public int getReaderHeight() {
		return readerHeight;
	}

	public int getReaderWidth() {
		return readerWidth;
	}

	public void disposeAll() {
		if (lazyMaps != null) {
			lazyMaps.clear();
			lazyMaps = null;
			LSystem.gc();
		}
	}

}


text:
import BaseTransformComponent from 'math/transform/2d/components/BaseTransformComponent.js';

export default class Pivot extends BaseTransformComponent {

    constructor (transform, x = 0, y = 0) {

        super(transform, x, y);

    }

    addProperties (target) {

        if (!target.hasOwnProperty('pivot'))
        {
            target.pivot = {};
        }

        Object.defineProperties(target.pivot, {

            'x': {
                enumerable: true,
                get: () => this.getX(),
                set: (value) => this.setX(value)
            },

            'y': {
                enumerable: true,
                get: () => this.getY(),
                set: (value) => this.setY(value)
            }

        });

    }

}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Sergey Lisitsyn
 */

#ifndef _HASHED_DENSEFEATURES_H__
#define _HASHED_DENSEFEATURES_H__

#include <shogun/lib/config.h>

#include <shogun/features/DenseFeatures.h>
#include <shogun/features/DotFeatures.h>

namespace shogun
{
template <class ST> class DenseFeatures;
class DotFeatures;

/** @brief This class is identical to the DenseFeatures class
 * except that it hashes each dimension to a new feature space.
 */
template <class ST> class HashedDenseFeatures : public DotFeatures
{
public:

	/** constructor
	 *
	 * @param size cache size
	 * @param use_quadr whether to use quadratic features or not
	 * @param keep_lin_terms whether to maintain the linear terms in the computations
	 */
	HashedDenseFeatures(int32_t size=0, bool use_quadr = false, bool keep_lin_terms = true);

	/** constructor
	 *
	 * @param feats	the dense features to use as a base
	 * @param d new feature space dimension
	 * @param use_quadr whether to use quadratic features or not
	 * @param keep_lin_terms whether to maintain the linear terms in the computations
	 */
	HashedDenseFeatures(std::shared_ptr<DenseFeatures<ST>> feats, int32_t d, bool use_quadr = false,
			bool keep_lin_terms = true);

	/** constructor
	 *
	 * @param matrix feature matrix
	 * @param dm new feature space dimension
	 * @param use_quadr whether to use quadratic features or not
	 * @param keep_lin_terms whether to maintain the linear terms in the computations
	 */
	HashedDenseFeatures(SGMatrix<ST> matrix, int32_t dm, bool use_quadr = false,
			bool keep_lin_terms = true);

	/** constructor
	 *
	 * @param src feature matrix
	 * @param num_feat number of features in matrix
	 * @param num_vec number of vectors in matrix
	 * @param d new feature space dimension
	 * @param use_quadr whether to use quadratic features or not
	 * @param keep_lin_terms whether to maintain the linear terms in the computations
	 */
	HashedDenseFeatures(ST* src, int32_t num_feat, int32_t num_vec, int32_t d,
			bool use_quadr = false, bool keep_lin_terms = true);

	/** constructor loading features from file
	 *
	 * @param loader File object via which to load data
	 * @param d new feature space dimension
	 * @param use_quadr whether to use quadratic features or not
	 * @param keep_lin_terms whether to maintain the linear terms in the computations
	 */
	HashedDenseFeatures(std::shared_ptr<File> loader, int32_t d, bool use_quadr = false,
			bool keep_lin_terms = false);

	/** copy constructor */
	HashedDenseFeatures(const HashedDenseFeatures& orig);

	/** duplicate */
	std::shared_ptr<Features> duplicate() const override;

	/** destructor */
	~HashedDenseFeatures() override;

	/** obtain the dimensionality of the feature space
	 *
	 * (not mix this up with the dimensionality of the input space, usually
	 * obtained via get_num_features())
	 *
	 * @return dimensionality
	 */
	int32_t get_dim_feature_space() const override;

	/** compute dot product between vector1 and vector2,
	 * appointed by their indices
	 *
	 * possible with subset
	 *
	 * @param vec_idx1 index of first vector
	 * @param df DotFeatures (of same kind) to compute dot product with
	 * @param vec_idx2 index of second vector
	 */
	float64_t dot(int32_t vec_idx1, std::shared_ptr<DotFeatures> df,
			int32_t vec_idx2) const override;

	/** compute dot product between vector1 and a dense vector
	 *
	 * possible with subset
	 *
	 * @param vec_idx1 index of first vector
	 * @param vec2 dense vector
	 */
	float64_t
	dot(int32_t vec_idx1, const SGVector<float64_t>& vec2) const override;

	/** add vector 1 multiplied with alpha to dense vector2
	 *
	 * possible with subset
	 *
	 * @param alpha scalar alpha
	 * @param vec_idx1 index of first vector
	 * @param vec2 pointer to real valued vector
	 * @param vec2_len length of real valued vector
	 * @param abs_val if true add the absolute value
	 */
	void add_to_dense_vec(float64_t alpha, int32_t vec_idx1,
			float64_t* vec2, int32_t vec2_len, bool abs_val = false) const override;

	/** get number of non-zero features in vector
	 *
	 * @param num which vector
	 * @return number of non-zero features in vector
	 */
	int32_t get_nnz_features_for_vector(int32_t num) const override;

	/** iterate over the non-zero features
	 *
	 * call get_feature_iterator first, followed by get_next_feature and
	 * free_feature_iterator to cleanup
	 *
	 * possible with subset
	 *
	 * @param vector_index the index of the vector over whose components to
	 *			iterate over
	 * @return feature iterator (to be passed to get_next_feature)
	 */
	void* get_feature_iterator(int32_t vector_index) override;

	/** iterate over the non-zero features
	 *
	 * call this function with the iterator returned by get_first_feature
	 * and call free_feature_iterator to cleanup
	 *
	 * possible with subset
	 *
	 * @param index is returned by reference (-1 when not available)
	 * @param value is returned by reference
	 * @param iterator as returned by get_first_feature
	 * @return true if a new non-zero feature got returned
	 */
	bool get_next_feature(int32_t& index, float64_t& value,
			void* iterator) override;

	/** clean up iterator
	 * call this function with the iterator returned by get_first_feature
	 *
	 * @param iterator as returned by get_first_feature
	 */
	void free_feature_iterator(void* iterator) override;

	/** @return object name */
	const char* get_name() const override;

	/** get feature type
	 *
	 * @return templated feature type
	 */
	EFeatureType get_feature_type() const override;

	/** get feature class
	 *
	 * @return feature class DENSE
	 */
	EFeatureClass get_feature_class() const override;

	/** get number of feature vectors
	 *
	 * @return number of feature vectors
	 */
	int32_t get_num_vectors() const override;

	/** get the hashed representation of the requested vector
	 *
	 * @param vec_idx the index of the vector
	 * @return the hashed representation of the vector
	 */
	SGSparseVector<ST> get_hashed_feature_vector(int32_t vec_idx) const;

	/** returns a hashed represenation of vector vec in a new feature space of dimension dim
	 *
	 * @param vec the vector to hash
	 * @param dim the size of the new dimension
	 * @param use_quadratic whether to use quadratic features or not
	 * @param keep_linear_terms whether to maintain the linear terms in the computations
	 * @return the hashed representation
	 */
	static SGSparseVector<ST> hash_vector(SGVector<ST> vec, int32_t dim, bool use_quadratic = false,
			bool keep_linear_terms = true);

private:
	void init(std::shared_ptr<DenseFeatures<ST>> feats, int32_t d, bool use_quadr, bool keep_lin_terms);

protected:

	/** dense features */
	std::shared_ptr<DenseFeatures<ST>> dense_feats;

	/** new feature space dimension */
	int32_t dim;

	/** use quadratic feature or not */
	bool use_quadratic;

	/** keep linear terms or not */
	bool keep_linear_terms;
};
}

#endif // _HASHED_DENSEFEATURES_H__


text:
@protocol NativeObjectExport <JSExport>

- (void)log:(NSString*)string;

@end

@interface NativeObject : NSObject <NativeObjectExport>

@end


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="MeshLibrary" inherits="Resource" category="Core" version="3.2">
	<brief_description>
		Library of meshes.
	</brief_description>
	<description>
		Library of meshes. Contains a list of [Mesh] resources, each with name and ID. Useful for GridMap or painting Terrain.
	</description>
	<tutorials>
	</tutorials>
	<methods>
		<method name="clear">
			<return type="void">
			</return>
			<description>
				Clear the library.
			</description>
		</method>
		<method name="create_item">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
				Create a new item in the library, supplied an id.
			</description>
		</method>
		<method name="find_item_by_name" qualifiers="const">
			<return type="int">
			</return>
			<argument index="0" name="name" type="String">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_item_list" qualifiers="const">
			<return type="PoolIntArray">
			</return>
			<description>
				Return the list of items.
			</description>
		</method>
		<method name="get_item_mesh" qualifiers="const">
			<return type="Mesh">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
				Return the mesh of the item.
			</description>
		</method>
		<method name="get_item_name" qualifiers="const">
			<return type="String">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
				Return the name of the item.
			</description>
		</method>
		<method name="get_item_navmesh" qualifiers="const">
			<return type="NavigationMesh">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_item_navmesh_transform" qualifiers="const">
			<return type="Transform">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_item_preview" qualifiers="const">
			<return type="Texture">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_item_shapes" qualifiers="const">
			<return type="Array">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_last_unused_item_id" qualifiers="const">
			<return type="int">
			</return>
			<description>
				Get an unused id for a new item.
			</description>
		</method>
		<method name="remove_item">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
				Remove the item.
			</description>
		</method>
		<method name="set_item_mesh">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="mesh" type="Mesh">
			</argument>
			<description>
				Set the mesh of the item.
			</description>
		</method>
		<method name="set_item_name">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="name" type="String">
			</argument>
			<description>
				Set the name of the item.
			</description>
		</method>
		<method name="set_item_navmesh">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="navmesh" type="NavigationMesh">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_item_navmesh_transform">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="navmesh" type="Transform">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_item_preview">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="texture" type="Texture">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_item_shapes">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="shapes" type="Array">
			</argument>
			<description>
			</description>
		</method>
	</methods>
	<constants>
	</constants>
</class>


text:
const shell = require("shelljs");

const cmdArguments = process.argv.slice(2);
const semverType = cmdArguments[0];

if (!semverType || !semverType.match(/^(major|minor|patch)$/)) {
  console.log(`Usage: major|minor|patch`);
  process.exit(1);
}

execCommand(`npm version ${semverType}`);
execCommand(`yarn run build`);
execCommand(`yarn run test`);
execCommand(`git push`);
execCommand(`git push --tags`);
execCommand(`yarn publish`);

function execCommand(command) {
  const result = shell.exec(command);
  if (!!result.code) {
    console.log(result.stdout);
    process.exit(1);
  }
}


text:
var user = {
"login": "bholben",
"id": 4744788,
"avatar_url": "https://avatars.githubusercontent.com/u/4744788?v=3",
"gravatar_id": "",
"url": "https://api.github.com/users/bholben",
"html_url": "https://github.com/bholben",
"followers_url": "https://api.github.com/users/bholben/followers",
"following_url": "https://api.github.com/users/bholben/following{/other_user}",
"gists_url": "https://api.github.com/users/bholben/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bholben/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bholben/subscriptions",
"organizations_url": "https://api.github.com/users/bholben/orgs",
"repos_url": "https://api.github.com/users/bholben/repos",
"events_url": "https://api.github.com/users/bholben/events{/privacy}",
"received_events_url": "https://api.github.com/users/bholben/received_events",
"type": "User",
"site_admin": false,
"name": "Bob Holben",
"company": "HyperGenius",
"blog": "",
"location": "Atlanta",
"email": "bholben@gmail.com",
"hireable": true,
"bio": null,
"public_repos": 39,
"public_gists": 1,
"followers": 3,
"following": 17,
"created_at": "2013-06-20T04:18:24Z",
"updated_at": "2015-01-26T15:26:42Z"
};


text:
#region S# License

#endregion S# License
namespace SampleAlfa
{
	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Windows;
	using System.Windows.Media;

	using Ecng.Common;
	using Ecng.Xaml;

	using MoreLinq;

	using StockSharp.BusinessEntities;
	using StockSharp.AlfaDirect;
	using StockSharp.Logging;
	using StockSharp.Localization;

	public partial class MainWindow
	{
		private bool _isConnected;

		public AlfaTrader Trader;

		private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
		private readonly TradesWindow _tradesWindow = new TradesWindow();
		private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
		private readonly OrdersWindow _ordersWindow = new OrdersWindow();
		private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
		private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow();
		private readonly NewsWindow _newsWindow = new NewsWindow();

		private readonly LogManager _logManager = new LogManager();

		public MainWindow()
		{
			InitializeComponent();
			Instance = this;

			_ordersWindow.MakeHideable();
			_myTradesWindow.MakeHideable();
			_tradesWindow.MakeHideable();
			_securitiesWindow.MakeHideable();
			_portfoliosWindow.MakeHideable();
			_stopOrdersWindow.MakeHideable();
			_newsWindow.MakeHideable();

			_logManager.Listeners.Add(new FileLogListener());
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			_ordersWindow.DeleteHideable();
			_myTradesWindow.DeleteHideable();
			_tradesWindow.DeleteHideable();
			_securitiesWindow.DeleteHideable();
			_portfoliosWindow.DeleteHideable();
			_stopOrdersWindow.DeleteHideable();
			_newsWindow.DeleteHideable();

			_securitiesWindow.Close();
			_tradesWindow.Close();
			_myTradesWindow.Close();
			_ordersWindow.Close();
			_portfoliosWindow.Close();
			_stopOrdersWindow.Close();
			_newsWindow.Close();

			if (Trader != null)
			{
				_logManager.Sources.Remove(Trader);
				Trader.Dispose();
			}

			base.OnClosing(e);
		}

		public static MainWindow Instance { get; private set; }

		private void ConnectClick(object sender, RoutedEventArgs e)
		{
			try
			{
				if (!_isConnected)
				{
					if (Trader == null)
					{
						// создаем подключение
						Trader = new AlfaTrader { LogLevel = LogLevels.Debug };

						_logManager.Sources.Add(Trader);

						Trader.Restored += () => this.GuiAsync(() =>
						{
							// разблокируем кнопку Экспорт (соединение было восстановлено)
							ChangeConnectStatus(true);
							MessageBox.Show(this, LocalizedStrings.Str2958);
						});

						// подписываемся на событие успешного соединения
						Trader.Connected += () =>
						{
							this.GuiAsync(() => ChangeConnectStatus(true));

							// запускаем подписку на новости
							Trader.RegisterNews();
						};

						// подписываемся на событие успешного отключения
						Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));

						// подписываемся на событие разрыва соединения
						Trader.ConnectionError += error => this.GuiAsync(() =>
						{
							// заблокируем кнопку Экспорт (так как соединение было потеряно)
							ChangeConnectStatus(false);

							MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
						});

						// подписываемся на ошибку обработки данных (транзакций и маркет)
						Trader.Error += error =>
							this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));

						// подписываемся на ошибку подписки маркет-данных
						Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
							this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));

						Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
						Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades);
						Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
						Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
						Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders);
						Trader.NewPortfolios += portfolios =>
						{
							portfolios.ForEach(Trader.RegisterPortfolio);
							_portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
						};
						Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);

						// подписываемся на событие о неудачной регистрации заявок
						Trader.OrdersRegisterFailed += OrdersFailed;
						// подписываемся на событие о неудачном снятии заявок
						Trader.OrdersCancelFailed += OrdersFailed;

						// подписываемся на событие о неудачной регистрации стоп-заявок
						Trader.StopOrdersRegisterFailed += OrdersFailed;
						// подписываемся на событие о неудачном снятии стоп-заявок
						Trader.StopOrdersCancelFailed += OrdersFailed;

						Trader.MassOrderCancelFailed += (transId, error) =>
							this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));

						// устанавливаем поставщик маркет-данных
						_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;

						// set news provider
						_newsWindow.NewsPanel.NewsProvider = Trader;

						ShowSecurities.IsEnabled = ShowNews.IsEnabled =
						ShowMyTrades.IsEnabled = ShowOrders.IsEnabled = ShowStopOrders.IsEnabled =
						ShowPortfolios.IsEnabled = true;

						Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news);
					}

					Trader.Login = TextBoxLogin.Text;
					Trader.Password = PasswordBox.Password;
					Trader.Connect();
				}
				else
				{
					Trader.UnRegisterNews();

					Trader.Disconnect();
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, ex.Message, LocalizedStrings.Str152);
			}
		}

		private void OrdersFailed(IEnumerable<OrderFail> fails)
		{
			this.GuiAsync(() =>
			{
				foreach (var fail in fails)
					MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
			});
		}

		private void ChangeConnectStatus(bool isConnected)
		{
			_isConnected = isConnected;

			ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
			ConnectionStatus.Content = isConnected ? LocalizedStrings.Connected : LocalizedStrings.Disconnected;
			ConnectionStatus.Background = new SolidColorBrush(isConnected ? Colors.LightGreen : Colors.LightPink);
		}

		private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_securitiesWindow);
		}

		private void ShowTradesClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_tradesWindow);
		}

		private void ShowMyTradesClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_myTradesWindow);
		}

		private void ShowOrdersClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_ordersWindow);
		}

		private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_portfoliosWindow);
		}

		void ShowStopOrdersClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_stopOrdersWindow);
		}

		private void ShowNewsClick(object sender, RoutedEventArgs e)
		{
			ShowOrHide(_newsWindow);
		}

		private static void ShowOrHide(Window window)
		{
			if (window == null)
				throw new ArgumentNullException(nameof(window));

			if (window.Visibility == Visibility.Visible)
				window.Hide();
			else
				window.Show();
		}
	}
}


text:
//
//  MCHTMLRenderer.h
//  testUI
//
//  Created by DINH Viêt Hoà on 1/23/13.
//  Copyright (c) 2013 MailCore. All rights reserved.
//

#ifndef __MAILCORE_MCHTMLRENDERER_H_
#define __MAILCORE_MCHTMLRENDERER_H_

#include <MailCore/MCAbstract.h>
#include <MailCore/MCIMAP.h>
#include <MailCore/MCRFC822.h>

#ifdef __cplusplus

namespace mailcore {

    class MessageParser;
    class HTMLRendererTemplateCallback;
    class HTMLRendererIMAPCallback;

    class HTMLRenderer {
    public:
        static String * htmlForRFC822Message(MessageParser * message,
                                             HTMLRendererTemplateCallback * htmlCallback);

        static String * htmlForIMAPMessage(String * folder,
                                           IMAPMessage * message,
                                           HTMLRendererIMAPCallback * dataCallback,
                                           HTMLRendererTemplateCallback * htmlCallback);

        static Array * attachmentsForMessage(AbstractMessage * message);
        static Array * htmlInlineAttachmentsForMessage(AbstractMessage * message);
    };
};

#endif

#endif /* defined(__testUI__MCHTMLRenderer__) */


text:
Assignment

<form class="form-horizontal" role="form">

Task Details

        Task #

{{collective.task.id}}

        Name

{{collective.task.name}}

        Tag

{{collective.task.tag}}

        Severity

{{collective.task.severity}}

        Content

{{collective.task.content}}

Assignment Details

        Service Assigned

{{assignment.service}}

        Unit Name

{{assignment.peer.name}}

        Unit Email

{{assignment.peer.email}}

        Running Time

{{assignment.runningTime}}

        Status

{{assignment.status}}

	            <button ng-click="updateStatus(collective.id, assignment.peer.elementId, button.action, button.title)" class="btn" ng-class="button.clazz">{{button.title}}</button>

</form>


text:
'use strict';

describe('Controller: ConceptCtrl', function () {

  // load the controller's module
  beforeEach(module('globalgamejam2015App'));

  var ConceptCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ConceptCtrl = $controller('ConceptCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, nonatomic) NSArray* sandwiches;

@end