text:
name "train"
default_version "master"

source git: "https://github.com/chef/train.git"

license "Apache-2.0"
license_file "LICENSE"

dependency "ruby"
dependency "rubygems"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  bundle "install --without development test integration tools", env: env

  gem "build train.gemspec", env: env
  gem "install train-*.gem --no-ri --no-rdoc", env: env
end

redpajama_set_name: RedPajamaGithub


text:
/* global performance */
var dspjs = require('dspjs')
var asm = require('..')
var arr = require('dsp-array')

var TIMES = 10000
var SIZE = 1024
var signal = arr.fill(SIZE, () => Math.random() * 2 - 0.5)
var fft = new dspjs.FFT(signal.length, 44100)
var asmfft = asm.fft(SIZE)
var output = { real: signal.slice(), imag: arr.zeros(signal.length) }
var zeros = arr.zeros(SIZE)

function addElement (name, profiler) {
  var div = document.createElement('div')
  div.innerHTML = name
  div.onclick = profiler
  document.body.appendChild(div)
}

function profileDSP () {
  console.log('dspjs...')
  var t0 = performance.now()
  for (var i = 0; i < TIMES; i++) {
    fft.forward(signal)
  }
  var t1 = performance.now()
  report('DSP', t0, t1)
}
function profileASM () {
  console.log('asm version...')
  var t0 = performance.now()
  var complex = { real: signal, imag: zeros }
  for (var i = 0; i < TIMES; i++) {
    asmfft('forward', complex, output)
  }
  var t1 = performance.now()
  report('ASM', t0, t1)
}

function report (name, t0, t1) {
  console.log(name + ' time: ', t1 - t0)
}

addElement('dsp.js', profileDSP)
addElement('asm.js', profileASM)


text:
require 's3mpi/converters/csv'
require 's3mpi/converters/json'
require 's3mpi/converters/identity'

module S3MPI
  module Converters

    class UnknownConverterError < StandardError; end

    def converter(as)
      case as
      when :json then Converters::JSON
      when :csv  then Converters::CSV
      when :string, :identity then Converters::Identity
      else
        raise UnknownConverterError, "#{as.inspect} is not a known converter!"
      end
    end

  end
end


text:
package org.knowm.xchange.bitflyer.dto.trade;

import static org.assertj.core.api.Assertions.assertThat;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;

public class BitflyerExecutionJSONTest {
  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is =
        BitflyerExecution.class.getResourceAsStream(
            "/org/knowm/xchange/bitflyer/dto/trade/example-execution.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    BitflyerExecution[] response = mapper.readValue(is, BitflyerExecution[].class);

    // then
    assertThat(response.length).isEqualTo(2);

    assertThat(response[0].getId()).isEqualTo(39287);
    assertThat(response[0].getSide()).isEqualTo("BUY");
    assertThat(response[0].getPrice()).isEqualTo(new BigDecimal(31690));
    assertThat(response[0].getSize()).isEqualTo(new BigDecimal("27.04"));
  }
}


text:
<?php

namespace BDSCore\Router;

use \BDSCore\Config\Config;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Router: Manages the framework's url
 * Routeur : Gère les url du framework
 *
 * @package BDSCore\Router
 */
class Router
{

    /**
     * @var array Router configuration
     */
    private $configRouter;

    /**
     * @var \BDSCore\Template\Twig Twig engine
     */
    private $templateClass;

    /**
     * @var array Routes
     */
    private static $paths = [];

    /**
     * @var RequestInterface Request
     */
    private $request;

    /**
     * @var ResponseInterface Response
     */
    private $response;

    /**
     * Router constructor.
     * Constructeur du routeur
     *
     * @param RequestInterface $request Request
     * @param ResponseInterface $response Response
     */
    public function __construct(RequestInterface $request, ResponseInterface $response) {
        $this->request = $request;
        $this->response = $response;

        $this->configRouter = \BDSCore\Config\Config::getAllRouterConfig();
        $this->templateClass = new \BDSCore\Template\Twig($response);
    }

    /**
     * Defines a route
     * Définit une route
     *
     * @param string $routeName Name of route
     * @param string $path Url of route
     *
     * @return void
     */
    private function setPath(string $routeName, string $path) {
        $this::$paths[$routeName] = $path;
    }

    /**
     * Returns the access url of a route
     * Retourne l'url d'accès d'une route
     *
     * @param string|null $routeName Route name
     * @param array $params Parameters
     *
     * @return string Path
     */
    public static function getPath(string $routeName = null, array $params = []): string {
        if ($routeName == null) {
            return '';
        }
        if (isset(self::$paths[$routeName])) {
            if (!empty($params)) {
                $path = self::$paths[$routeName];
                foreach ($params as $p) {
                    $path = preg_replace('/\((.*)\)/U', $p, $path, 1);
                }

                return $path;
            } else {
                return self::$paths[$routeName];
            }
        } else {
            return '';
        }
    }

    /**
     * Re-orders a parameter array for run ()
     * Ré-ordonne un tableau de paramètres pour la fonction run()
     *
     * @param $method Method
     * @param array $args Arguments
     *
     * @return array
     */
    private function getArgsByName($method, array $args = array()): array {
        $reflection = new \ReflectionMethod($method[0], $method[1]);

        $pass = array();
        foreach ($reflection->getParameters() as $param) {
            if (isset($args[$param->getName()])) {
                $pass[] = $args[$param->getName()];
            } else {
                $pass[] = null;
            }
        }

        return $pass;
    }

    /**
     * Returns the root path of the framework to understand the URL
     * Retourne le chemin racine du framework pour comprendre l'URL
     *
     * @return string Path
     */
    private function getBasePath(): string {
        $basePath = str_replace('/public/index.php', '', $_SERVER['SCRIPT_NAME']);
        $uri = $_SERVER['REQUEST_URI'];

        if (false !== $pos = strpos($uri, '?')) {
            $uri = substr($uri, 0, $pos);
        }

        $uri = rawurldecode($uri);
        $basePath = str_replace($basePath, '', $uri);

        return $basePath;
    }

    /**
     * Returns a 403 error if the url matches a protected folder
     * Retourne une erreur 403 si l'url correspond à un dossier protegé
     *
     * @return void
     */
    private function controlPerms() {
        $prohibitedDirs = [
            'app',
            'bin',
            'cache',
            'config',
            'core',
            'storage',
            'tests',
            'vendor',
        ];
        $baseDir = substr($this->getBasePath(), 1);
        $actualDir = explode('/', $baseDir);
        if (in_array($actualDir[0], $prohibitedDirs)) {
            \BDSCore\Errors\Errors::returnError($this->response, 403);
        }
    }

    /**
     * Configuring the URL Dispatcher
     * Configuration du repartisseur d'URL
     *
     * @return mixed Dispatcher
     */
    private function configureDispatcher() {
        $routes = $this->configRouter['routes'];
        if (Config::getConfig('routerCache')) {
            $dispatcherClass = \FastRoute\cachedDispatcher::class;
            $dispatcherOptions = [
                'cacheFile' => Config::getDirectoryRoot('/cache/router/routesCache.php')
            ];
            if (!is_dir(Config::getDirectoryRoot('/cache/router/'))) {
                mkdir(Config::getDirectoryRoot('/cache/router'));
            }
        } else {
            $dispatcherClass = \FastRoute\simpleDispatcher::class;
            $dispatcherOptions = [];
        }

        $dispatcher = $dispatcherClass(function (\FastRoute\RouteCollector $r) use ($routes) {

            foreach ($routes as $route => $c) {
                $this->setPath($route, $c[1]);
                $exp = explode('@', $c[2]);
                $r->addRoute(strtoupper($c[0]), $c[1], [$this->configRouter['routerConfig']['controllersNamespace'] . '\\' . $exp[0], $exp[1]]);
            }

        }, $dispatcherOptions);

        return $dispatcher;
    }

    /**
     * Launching the router, capturing routes, calling to controllers
     * Lancement du routeur, capture des routes, appels aux controllers
     *
     * @return ResponseInterface Response
     */
    public function run(): ResponseInterface {

        $this->controlPerms();
        $dispatcher = $this->configureDispatcher();

        $httpMethod = $_SERVER['REQUEST_METHOD'];
        $routeInfo = $dispatcher->dispatch($httpMethod, $this->getBasePath());

        switch ($routeInfo[0]) {
            case \FastRoute\Dispatcher::NOT_FOUND:

                $this->templateClass->render($this->configRouter['routerConfig']['viewError404']);
                $this->response = $this->response->withStatus(404);

                break;
            case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:

                // $allowedMethods = $routeInfo[1];

                $this->templateClass->render($this->configRouter['routerConfig']['viewError405']);
                $this->response = $this->response->withStatus(405);

                break;
            case \FastRoute\Dispatcher::FOUND:

                $handler = $routeInfo[1];
                $vars = $routeInfo[2];

                if (is_a($handler, 'Closure')) {
                    $handler();
                } else {
                    $class = new $handler[0]($this->request, $this->response);

                    call_user_func_array([$class, $handler[1]], $this->getArgsByName([$class, $handler[1]], $vars));

                    if (is_callable([$class, 'getResponse'])) {
                        $this->response = call_user_func([$class, 'getResponse']);
                    }
                }

                break;
        }

        return $this->response;
    }

}


text:
package com.yaoa.hibatis.util;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @author kingsy.lin
 * @version 1.0 , 2016年10月28日
 */
@SuppressWarnings("unchecked")
public class ArrayUtils {

	public static <T> void addToList(T[] array , List<T> list){
		for (T item : array) {
			list.add(item);
		}
	}

	public static <T> String join(T[] array , String separator){
		StringBuilder sb = new StringBuilder();
		for (T item : array) {
			sb.append(separator).append(item);
		}
		if(sb.length() > 0){
			sb.delete(0, separator.length());
		}
		return sb.toString();
	}

	public static <T> T[] toArray(List<T> list){
		int length = list.size();
		if(length == 0){
			return (T[])list.toArray();
		}
		Class<?> componentType = list.get(0).getClass();
		T[] array = (T[]) Array.newInstance(componentType, length);
		for (int i = 0; i < length; i++) {
			array[i] = list.get(i);
		}
		return array;
	}

	public static <T> List<T> asList(T[] array) {
		List<T> list = new ArrayList<T>(array.length);
		for (int i = 0; i < array.length; i++) {
			T item = array[i];
			list.add(item);
		}
		return list;
	}

	public static <T> T[] merge(T[] array1 , T[] array2) {
		int length = array1.length + array2.length;
		if(length == 0){
			return array1;
		}
		Class<?> componentType = (array1.length> 0 ? array1[0] : array2[0]).getClass() ;
		int offset = 0;
		T[] newArray = (T[]) Array.newInstance(componentType, length);
		for (T item : array1) {
			newArray[offset++] = item;
		}
		for (T item : array2) {
			newArray[offset++] = item;
		}
		return newArray;
	}

	public static boolean contains(Object[] array , Object item){
		return indexOf(array, item) != -1;
	}

	public static int indexOf(Object[] array , Object item){
		for (int i = 0; i < array.length; i++) {
			Object cur = array[i];
			if(item == null){
				if(cur == null){
					return i;
				}
			}else if(item.equals(cur)){
				return i;
			}
		}
		return -1;
	}

	public static byte[] merge(byte[] array1 ,byte[] array2) {
		int length = array1.length + array2.length;
		if(length == 0){
			return array1;
		}
		int offset = 0;
		byte[] newArray = new byte[length];
		for (byte item : array1) {
			newArray[offset++] = item;
		}
		for (byte item : array2) {
			newArray[offset++] = item;
		}
		return newArray;
	}

}


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

namespace MOE.Common.Models.Repositories
{
    public class AgencyRepository : IGenericRepository<Agency>
    {
        private SPM db = new SPM();

        public AgencyRepository()
        {
        }

        public AgencyRepository(SPM context)
        {
            db = context;
        }

        public IEnumerable<Agency> GetAll()
        {
            return db.Agencies.ToList();
        }

        public Agency GetByID(int id)
        {
            return db.Agencies.Find(id);
        }

        public void Delete(Agency entity)
        {
            db.Agencies.Remove(db.Agencies.Find(entity.AgencyID));
        }

        public void Update(Agency entity)
        {
            var agencyInDatabase = db.Agencies.Find(entity.AgencyID);
            if (agencyInDatabase == null)
                Add(entity);
            else
                db.Entry(agencyInDatabase).CurrentValues.SetValues(entity);
        }

        public void Add(Agency entity)
        {
            db.Agencies.Add(entity);
        }

        public void Save()
        {
            db.SaveChanges();
        }

        public void SetAgencyRepository(SPM context)
        {
            db = context;
        }

        public void dosomething()
        {
        }
    }
}


text:
package org.wso2.siddhi.core.table.holder;

import org.wso2.siddhi.core.event.stream.StreamEvent;
import org.wso2.siddhi.query.api.expression.condition.Compare;

import java.util.Collection;
import java.util.Set;

/**
 * Interface for an EventHolder which keep events indexed for faster access.
 */
public interface IndexedEventHolder extends EventHolder {

    boolean isAttributeIndexed(String attribute);

    boolean isAttributeIndexed(int position);

    Collection<StreamEvent> getAllEvents();

    Collection<StreamEvent> findEvents(String attribute, Compare.Operator operator, Object value);

    void deleteAll();

    void deleteAll(Collection<StreamEvent> storeEventSet);

    void delete(String attribute, Compare.Operator operator, Object value);

    boolean containsEventSet(String attribute, Compare.Operator operator, Object value);

    void overwrite(StreamEvent streamEvent);

    Set<Object> getAllPrimaryKeys();

    int getPrimaryKeyAttributePosition();

    String getPrimaryKeyAttribute();

}


text:
"""
    Kubernetes

    No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)

    OpenAPI spec version: v1.6.1

    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from pprint import pformat
from six import iteritems
import re

class V1alpha1RoleRef(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """
    def __init__(self, api_group=None, kind=None, name=None):
        """
        V1alpha1RoleRef - a model defined in Swagger

        :param dict swaggerTypes: The key is attribute name
                                  and the value is attribute type.
        :param dict attributeMap: The key is attribute name
                                  and the value is json key in definition.
        """
        self.swagger_types = {
            'api_group': 'str',
            'kind': 'str',
            'name': 'str'
        }

        self.attribute_map = {
            'api_group': 'apiGroup',
            'kind': 'kind',
            'name': 'name'
        }

        self._api_group = api_group
        self._kind = kind
        self._name = name

    @property
    def api_group(self):
        """
        Gets the api_group of this V1alpha1RoleRef.
        APIGroup is the group for the resource being referenced

        :return: The api_group of this V1alpha1RoleRef.
        :rtype: str
        """
        return self._api_group

    @api_group.setter
    def api_group(self, api_group):
        """
        Sets the api_group of this V1alpha1RoleRef.
        APIGroup is the group for the resource being referenced

        :param api_group: The api_group of this V1alpha1RoleRef.
        :type: str
        """
        if api_group is None:
            raise ValueError("Invalid value for `api_group`, must not be `None`")

        self._api_group = api_group

    @property
    def kind(self):
        """
        Gets the kind of this V1alpha1RoleRef.
        Kind is the type of resource being referenced

        :return: The kind of this V1alpha1RoleRef.
        :rtype: str
        """
        return self._kind

    @kind.setter
    def kind(self, kind):
        """
        Sets the kind of this V1alpha1RoleRef.
        Kind is the type of resource being referenced

        :param kind: The kind of this V1alpha1RoleRef.
        :type: str
        """
        if kind is None:
            raise ValueError("Invalid value for `kind`, must not be `None`")

        self._kind = kind

    @property
    def name(self):
        """
        Gets the name of this V1alpha1RoleRef.
        Name is the name of resource being referenced

        :return: The name of this V1alpha1RoleRef.
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """
        Sets the name of this V1alpha1RoleRef.
        Name is the name of resource being referenced

        :param name: The name of this V1alpha1RoleRef.
        :type: str
        """
        if name is None:
            raise ValueError("Invalid value for `name`, must not be `None`")

        self._name = name

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


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

-->

<!-- These resources are around just to allow their values to be customized
     for different hardware and product builds. -->
<resources>
    <!-- If there is no sysfs-based control mechanism, enable this -->
    <bool name="useCameraInterface">false</bool>

    <!-- Full path to the sysfs toggle -->
    <string name="flashDevice">/sys/class/misc/pm8941-flash/device/mode</string>
    <!-- Full path to the sysfs luminosity -->
    <string name="flashDeviceLuminosity">/sys/class/misc/pm8941-flash/device/current1</string>
    <!-- Full path to the 2nd sysfs luminosity, leave empty if doesn't exist -->
    <string name="flashDeviceLuminosity2">/sys/class/misc/pm8941-flash/device/current2</string>

    <!-- Off setting -->
    <integer name="valueOff">0</integer>
    <!-- On setting -->
    <integer name="valueOn">2</integer>

    <!-- Low setting -->
    <integer name="valueLow">2</integer>
    <!-- Middle setting -->
    <integer name="valueHigh">4</integer>
    <!-- Highest setting, leave -1 if it doesn't exist -->
    <integer name="valueDeathRay">-1</integer>
</resources>


text:
============
Installation
============

The SDK currently supports Python 2.7 and Python 3.4-3.7. The `requests`_
package is required.

We recommend using `pip`_ and `virtualenv`_ to install the SDK. Please note
that the SDK's Python package is called **facebook-sdk**.

Installing from Git
===================

For the newest features, you should install the SDK directly from Git.

.. code-block:: shell

    virtualenv facebookenv
    source facebookenv/bin/activate
    pip install -e git+https://github.com/mobolic/facebook-sdk.git#egg=facebook-sdk

Installing a Released Version
=============================

If your application requires maximum stability, you will want to use a version
of the SDK that has been officially released.

.. code-block:: shell

    virtualenv facebookenv
    source facebookenv/bin/activate
    pip install facebook-sdk

.. _requests: https://pypi.python.org/pypi/requests
.. _pip: https://pip.pypa.io/
.. _virtualenv: https://virtualenv.pypa.io/


text:
import { useEffect, useRef, useState } from "react";
import { doFetch, Method } from "../service/doFetch";
import { useStore } from "../store";

export enum ChangeType {
    ADD = "add",
    REMOVE = "remove",
    REMOVED_RANDOM = "removed_random",
}

export enum EmoteType {
    BTTV = "bttv",
    SEVENTV = "seventv",
}

export interface RawEmotehistoryItem {
    CreatedAt: string;
    UpdatedAt: string;
    DeletedAt: string | null;
    ID: number;
    ChannelTwitchID: string;
    Type: EmoteType;
    ChangeType: ChangeType;
    EmoteID: string;
    Blocked: boolean;
}

export interface EmotehistoryItem {
    CreatedAt: Date;
    UpdatedAt: Date;
    DeletedAt: Date | null;
    ID: number;
    ChannelTwitchID: string;
    Type: EmoteType;
    ChangeType: ChangeType;
    EmoteID: string;
    Blocked: boolean;
}

const PAGE_SIZE = 20;

export function useEmotehistory(added: boolean, channel?: string): [Array<EmotehistoryItem>, () => void, boolean, number, () => void, () => void, (emoteId: string) => void, (emoteId: string) => void] {
    const [page, setPage] = useState(1);
    const pageRef = useRef(page);
    pageRef.current = page;

    const [emotehistory, setEmotehistory] = useState<Array<EmotehistoryItem>>([]);
    const [loading, setLoading] = useState(false);
    const managing = useStore(state => state.managing);
    const apiBaseUrl = useStore(state => state.apiBaseUrl);
    const scToken = useStore(state => state.scToken);

    const fetchPredictions = () => {
        setLoading(true);
        const currentPage = pageRef.current;

        const endPoint = "/api/emotehistory";
        const searchParams = new URLSearchParams();
        if (channel) {
            searchParams.append("channel", channel);
        }
        searchParams.append("page", page.toString());
        if (added) {
            searchParams.append("added", "1");
        }
        doFetch({apiBaseUrl, managing, scToken }, Method.GET, endPoint, searchParams).then((resp) => {
            if (currentPage !== pageRef.current) {
                throw new Error("Page changed");
            }

            return resp
        }).then((items: Array<RawEmotehistoryItem>) =>
            setEmotehistory(
                items.map(
                    (item: RawEmotehistoryItem) => (
                        {
                            ...item,
                            CreatedAt: new Date(item.CreatedAt),
                            UpdatedAt: new Date(item.CreatedAt),
                            DeletedAt: item.CreatedAt ? new Date(item.CreatedAt) : null,
                        }
                    )
                )
            )
        ).then(() => setLoading(false)).catch(err => {
            if (err.message !== "Page changed") {
                throw err;
            }
        });
    };

    const remove = (emoteId: string) => {
        setLoading(true);
        const endPoint = "/api/emotehistory";
        const searchParams = new URLSearchParams();
        searchParams.append("emoteId", emoteId);
        doFetch({apiBaseUrl, managing, scToken }, Method.DELETE, endPoint, searchParams).then(() => {
            fetchPredictions();
        });
    };

    const block = (emoteId: string) => {
        setLoading(true);
        const endPoint = "/api/emotehistory";
        const searchParams = new URLSearchParams();
        searchParams.append("emoteId", emoteId);
        doFetch({apiBaseUrl, managing, scToken }, Method.PATCH, endPoint, searchParams).then(() => {
            fetchPredictions();
        });
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    useEffect(fetchPredictions, [managing, page]);

    return [emotehistory, fetchPredictions, loading, page, () => emotehistory.length === PAGE_SIZE ? setPage(page + 1) : undefined, () => page > 1 ? setPage(page - 1) : undefined, remove, block];
}


text:
import { DbUtils } from "../utils/DbUtils";
import * as request from 'request';

const config = require('../config.json');
const xlsx = require("node-xlsx");

/**
 * 抓取高德poi点
 */
export class PoiSpider {
    constructor(parameters?) {

    }
    //高德key
    private keyIndex = 0;
    private cityIndex = 0;
    private cities = [];
    private gaodeKey = config.gaodeConfig.keys[this.keyIndex];//key每天的访问次数限制,达到上限时换下一个key
    private gaodeCity = config.gaodeConfig.city;//config中city为空时抓取全国poi,否则只抓取指定城市的poi
    //高德poi类型
    private types = [];
    private typeIndex = 0;
    private workSheetsFromFile = xlsx.parse(`${__dirname}/高德地图API POI分类编码表.xlsx`);
    //分页请求相关
    private page = 1;
    private pageSize = 50;//强烈建议不超过25,若超过25可能造成访问报错(经测试,最大50条)
    private errorCount = 0;//同一个请求错误三次之后跳到下一个类型

    public init() {
        if (!this.workSheetsFromFile) {
            console.log("Poi分类编码表不存在或者解析错误");
            return;
        }
        for (var i = 0; i < this.workSheetsFromFile.length; i++) {
            var sheet = this.workSheetsFromFile[i];
            if (sheet && sheet.name === 'POI分类与编码(中英文)') {
                for (var j = 1; j < sheet.data.length; j++) {
                    var data = sheet.data[j];
                    data[1] && this.types.push(data[1] + '');
                }
                break;
            }
        }
        this.initTable();
    }

    //判断表是否存在(不存在则创建)
    private initTable() {
        if (!this.gaodeCity) {
            this.initDistrictTable().then(() => {
                this.initPoiTable().then(() => this.gaodePoi());
            });
        } else {
            this.initPoiTable().then(() => this.gaodePoi());
        }
    }
    private initDistrictTable() {
        return new Promise((resolve, reject) => {
            DbUtils.instance.executeSql("drop table if exists district; create table district(id serial, citycode varchar(255) NOT NULL,adcode varchar(255) NOT NULL,name varchar(255),center varchar(255),level varchar(255),polyline text,primary key(id))", null).then(() => {
                this.gaodeDistrict();
                DbUtils.instance.executeSql("select * from district where level='city'", null).then(result => {
                    for (var i = 0; i < result.rows.length; i++) {
                        var row = result.rows[i];
                        this.cities.push(row.citycode);
                    }
                    this.gaodeCity = this.cities[this.cityIndex];
                    resolve();
                });
            });
        });
    }
    private initPoiTable() {
        return new Promise((resolve, reject) => {
            DbUtils.instance.executeSql("select count(*) from pg_class where relname = 'poi'", null).then(result => {
                if (!result || !result.rows[0] || result.rows[0].count === '0') {
                    DbUtils.instance.executeSql("create table poi(id serial,gid varchar(255) NOT NULL,name varchar(255),type varchar(255),typecode varchar(255),biz_type varchar(255),address varchar(255),location varchar(255),tel varchar(255),distance varchar(255),biz_ext varchar(255),pname varchar(255),cityname varchar(255),adname varchar(255),importance varchar(255),shopid varchar(255),shopinfo varchar(255),poiweight varchar(255),primary key(id))").then(() => {
                        resolve();
                    });
                } else {
                    resolve();
                }
            });
        });
    }

    //抓取高德行政区gaodeDistrict
    private gaodeDistrict() {
        var url = 'http://restapi.amap.com/v3/config/district?key=&keywords=&subdistrict=3&extensions=base';
        url = url.replace('key=&', 'key=' + this.gaodeKey + '&');
        request(url, (error, response, body) => {
            body && (body = JSON.parse(body));
            if (body && body.status === "1") {
                this.recursionDistrict(body.districts);
                console.log("execute gaodeDistrict end");
            }
        });
    }
    private recursionDistrict(districts) {
        for (var i = 0; i < districts.length; i++) {
            var district = districts[i];
            DbUtils.instance.executeSql('insert into district(citycode,adcode,name,center,level) values($1,$2,$3,$4,$5)', [district.citycode, district.adcode, district.name, district.center, district.level]);
            district && district.districts && district.districts.length > 0 && this.recursionDistrict(district.districts);
        }
    }

    //抓取高德poi
    private gaodePoi() {
        var url = 'http://restapi.amap.com/v3/place/text?key=&keywords=&types=&city=&citylimit=true&children=0&offset=&page=&extensions=base';
        url = url.replace('key=&', 'key=' + this.gaodeKey + '&').replace('types=&', 'types=' + this.types[this.typeIndex] + '&').replace('city=&', 'city=' + this.gaodeCity + '&').replace('offset=&', 'offset=' + this.pageSize + '&').replace('page=&', 'page=' + this.page + '&');
        request(url, (error, response, body) => {
            body && (body = JSON.parse(body));
            var infocode = body && body.infocode;
            if (infocode === "10003") {
                if (this.keyIndex < config.gaodeConfig.keys.length) {
                    console.log("key: " + this.gaodeKey + " 访问次数已达上限");
                    this.keyIndex++;
                    this.gaodeKey = config.gaodeConfig.keys[this.keyIndex];
                    this.gaodePoi();
                } else {
                    console.log("所有key访问次数已达上限;当前citycode:" + this.gaodeCity + ";当前poi类型:" + this.types[this.typeIndex]);
                }
            } else if (infocode === "10004") {
                console.log("key: " + this.gaodeKey + " 单位时间内访问过于频繁");
                setTimeout(() => {
                    this.gaodePoi();
                }, 100);
            } else {
                if (infocode === "10000") {
                    this.insertPoi(body.pois);
                } else {
                    error && this.errorCount++;
                    console.log("key: " + this.gaodeKey + " " + (error || body && body.info));
                }
                // count属性不准
                if (body && body.pois && body.pois.length >= this.pageSize) {
                    this.errorCount = 0;
                    this.page++;
                } else if (!error || this.errorCount > 3) {
                    this.errorCount = 0;
                    this.typeIndex++;
                    this.page = 1;
                }
                if (this.typeIndex < this.types.length) {
                    this.gaodePoi();
                } else if (this.cities && this.cities.length > 0 && this.cityIndex < this.cities.length) {
                    this.cityIndex++;
                    this.gaodeCity = this.cities[this.cityIndex];
                    this.typeIndex = 0;
                    this.page = 1;
                    this.gaodePoi();
                } else {
                    console.log("execute gaodePoi end");
                    this.distinct();
                }
            }
        });
    }
    private insertPoi(pois) {
        for (var i = 0; i < pois.length; i++) {
            var poi = pois[i];
            DbUtils.instance.executeSql('insert into poi(gid,name,type,typecode,biz_type,address,location,tel,distance,biz_ext,pname,cityname,adname,importance,shopid,shopinfo,poiweight) values($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17)', [poi.id, poi.name, poi.type, poi.typecode, poi.biz_type, poi.address, poi.location, poi.tel, poi.distance, poi.biz_ext, poi.pname, poi.cityname, poi.adname, poi.importance, poi.shopid, poi.shopinfo, poi.poiweight]);
        }
    }
    private distinct() {
        DbUtils.instance.executeSql("delete from poi where ctid not in (select min(ctid) from poi group by gid)").then(() => {
            console.log("execute distinct end");
        })
    }
}


text:
.class Lcom/android/settings/RadioInfo$14;
.super Ljava/lang/Object;
.source "RadioInfo.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/settings/RadioInfo;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/settings/RadioInfo;

# direct methods
.method constructor <init>(Lcom/android/settings/RadioInfo;)V
    .locals 0

    iput-object p1, p0, Lcom/android/settings/RadioInfo$14;->this$0:Lcom/android/settings/RadioInfo;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 5

    new-instance v1, Landroid/content/Intent;

    const-string/jumbo v2, "com.android.settings.OEM_RADIO_INFO"

    invoke-direct {v1, v2}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V

    :try_start_0
    iget-object v2, p0, Lcom/android/settings/RadioInfo$14;->this$0:Lcom/android/settings/RadioInfo;

    invoke-virtual {v2, v1}, Lcom/android/settings/RadioInfo;->startActivity(Landroid/content/Intent;)V
    :try_end_0
    .catch Landroid/content/ActivityNotFoundException; {:try_start_0 .. :try_end_0} :catch_0

    :goto_0
    return-void

    :catch_0
    move-exception v0

    iget-object v2, p0, Lcom/android/settings/RadioInfo$14;->this$0:Lcom/android/settings/RadioInfo;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "OEM-specific Info/Settings Activity Not Found : "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Lcom/android/settings/RadioInfo;->-wrap2(Lcom/android/settings/RadioInfo;Ljava/lang/String;)V

    goto :goto_0
.end method


text:
package com.fedevela.dms.services;

/**
 * Created by fvelazquez on 9/04/14.
 */
import com.fedevela.core.workflow.pojos.Workflow;
import com.fedevela.core.workflow.pojos.WorkflowConfig;
import com.fedevela.core.workflow.pojos.WorkflowState;
import java.util.List;

public interface WorkflowService {

    /**
     *
     * @param idWorkflow
     * @param idWorkflowState
     * @param idWorkflowEvent
     * @param doNothingExclude, No mostrar el evento doNothing.
     * @return
     */
    public WorkflowConfig getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final String idWorkflowEvent);

    /**
     *
     * @param idWorkflow
     * @param idWorkflowState
     * @param idWorkflowEvent
     * @param authorities
     * @param doNothingExclude, No mostrar el evento doNothing.
     * @return
     */
    public WorkflowConfig getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final String idWorkflowEvent,
            final String[] authorities,
            final boolean doNothingExclude);

    /**
     *
     * @param idWorkflow
     * @param idWorkflowState
     * @param idWorkflowEvent
     * @param authorities
     * @param doNothingExclude, No mostrar el evento doNothing.
     * @param allowState, Filtrar el permiso de estatus
     * @param allowEvent, Filtrar el permiso de evento
     * @return
     */
    public WorkflowConfig getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final String idWorkflowEvent,
            final String[] authorities,
            final boolean doNothingExclude,
            final boolean allowState,
            final boolean allowEvent);

    /**
     *
     * @param idWorkflow
     * @param idWorkflowState
     * @param doNothingExclude, No mostrar el evento doNothing.
     * @return
     */
    public List<WorkflowConfig> getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final boolean doNothingExclude);

    /**
     *
     * @param idWorkflow
     * @param idWorkflowState
     * @param authorities
     * @param doNothingExclude, No mostrar el evento doNothing.
     * @return
     */
    public List<WorkflowConfig> getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final String[] authorities,
            final boolean doNothingExclude);

    public List<WorkflowConfig> getWorkflowConfig(
            final Long idWorkflow,
            final String idWorkflowState,
            final String[] authorities,
            final boolean doNothingExclude,
            final boolean allowState,
            final boolean allowEvent);

    /**
     * Lista toda la configuración de uno o mas workflows.
     *
     * @param idWorkflow
     * @return
     */
    public List<WorkflowConfig> getWorkflowConfig(
            final Long... idWorkflow);

    public List<WorkflowState> getWorkflowState(
            final Long idWorkflow,
            final String[] authorities,
            final boolean allowState);

    /**
     *
     * @param idWorkflowState
     * @return
     */
    public WorkflowState getWorkflowState(final String idWorkflowState);

    public Workflow getWorkflow(final Long idWorkflow);

    public Workflow saveWorkflow(Workflow workflow);

    public void deleteWorkflow(final Long idWorkflow);

    public WorkflowConfig saveWorkflowConfig(WorkflowConfig workflowConfig);

    public void deleteWorkflowConfig(final Long idWorkflowConfig);

    public WorkflowState saveWorkflowState(WorkflowState workflowState);

    public void deleteWorkflowState(String idWorkflowState);

    public List<WorkflowState> getState();

    /**
     * Lista todos los estatus configurados de uno o mas workflows.
     *
     * @param idWorkflow
     * @return
     */
    public List<WorkflowState> getState(final Long... idWorkflow);
}


text:
using net::registry_controlled_domains::GetDomainAndRegistry;
using net::registry_controlled_domains::GetRegistryLength;
using net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES;
using net::registry_controlled_domains::INCLUDE_UNKNOWN_REGISTRIES;

namespace {

std::string GetRegistry(const GURL& url) {
  size_t registry_length = GetRegistryLength(url, INCLUDE_UNKNOWN_REGISTRIES,
                                             INCLUDE_PRIVATE_REGISTRIES);
  if (registry_length == 0)
    return std::string();
  return std::string(url.host(), url.host().length() - registry_length,
                     registry_length);
}

}  // namespace

namespace net {

const int kDelayedTime = 0;

DelayedCookieMonster::DelayedCookieMonster()
      : cookie_monster_(new CookieMonster(NULL, NULL)),
        did_run_(false),
        result_(false) {
}

DelayedCookieMonster::~DelayedCookieMonster() {
}

void DelayedCookieMonster::SetCookiesInternalCallback(bool result) {
  result_ = result;
  did_run_ = true;
}

void DelayedCookieMonster::GetCookiesWithOptionsInternalCallback(
    const std::string& cookie) {
  cookie_ = cookie;
  did_run_ = true;
}

void DelayedCookieMonster::GetCookieListWithOptionsInternalCallback(
    const CookieList& cookie_list) {
  cookie_list_ = cookie_list;
  did_run_ = true;
}

void DelayedCookieMonster::SetCookieWithOptionsAsync(
    const GURL& url,
    const std::string& cookie_line,
    const CookieOptions& options,
    const CookieMonster::SetCookiesCallback& callback) {
  did_run_ = false;
  cookie_monster_->SetCookieWithOptionsAsync(
      url, cookie_line, options,
      base::Bind(&DelayedCookieMonster::SetCookiesInternalCallback,
                 base::Unretained(this)));
  DCHECK_EQ(did_run_, true);
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE, base::Bind(&DelayedCookieMonster::InvokeSetCookiesCallback,
                            base::Unretained(this), callback),
      base::TimeDelta::FromMilliseconds(kDelayedTime));
}

void DelayedCookieMonster::SetCookieWithDetailsAsync(
    const GURL& url,
    const std::string& name,
    const std::string& value,
    const std::string& domain,
    const std::string& path,
    base::Time creation_time,
    base::Time expiration_time,
    base::Time last_access_time,
    bool secure,
    bool http_only,
    bool same_site,
    bool enforce_strict_secure,
    CookiePriority priority,
    const SetCookiesCallback& callback) {
  NOTREACHED();
}

void DelayedCookieMonster::GetCookiesWithOptionsAsync(
    const GURL& url,
    const CookieOptions& options,
    const CookieMonster::GetCookiesCallback& callback) {
  did_run_ = false;
  cookie_monster_->GetCookiesWithOptionsAsync(
      url, options,
      base::Bind(&DelayedCookieMonster::GetCookiesWithOptionsInternalCallback,
                 base::Unretained(this)));
  DCHECK_EQ(did_run_, true);
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&DelayedCookieMonster::InvokeGetCookieStringCallback,
                 base::Unretained(this), callback),
      base::TimeDelta::FromMilliseconds(kDelayedTime));
}

void DelayedCookieMonster::GetCookieListWithOptionsAsync(
    const GURL& url,
    const CookieOptions& options,
    const CookieMonster::GetCookieListCallback& callback) {
  did_run_ = false;
  cookie_monster_->GetCookieListWithOptionsAsync(
      url, options,
      base::Bind(
          &DelayedCookieMonster::GetCookieListWithOptionsInternalCallback,
          base::Unretained(this)));
  DCHECK_EQ(did_run_, true);
  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE, base::Bind(&DelayedCookieMonster::InvokeGetCookieListCallback,
                            base::Unretained(this), callback),
      base::TimeDelta::FromMilliseconds(kDelayedTime));
}

void DelayedCookieMonster::GetAllCookiesAsync(
    const GetCookieListCallback& callback) {
  cookie_monster_->GetAllCookiesAsync(callback);
}

void DelayedCookieMonster::InvokeSetCookiesCallback(
    const CookieMonster::SetCookiesCallback& callback) {
  if (!callback.is_null())
    callback.Run(result_);
}

void DelayedCookieMonster::InvokeGetCookieStringCallback(
    const CookieMonster::GetCookiesCallback& callback) {
  if (!callback.is_null())
    callback.Run(cookie_);
}

void DelayedCookieMonster::InvokeGetCookieListCallback(
    const CookieMonster::GetCookieListCallback& callback) {
  if (!callback.is_null())
    callback.Run(cookie_list_);
}

bool DelayedCookieMonster::SetCookieWithOptions(
    const GURL& url,
    const std::string& cookie_line,
    const CookieOptions& options) {
  ADD_FAILURE();
  return false;
}

std::string DelayedCookieMonster::GetCookiesWithOptions(
    const GURL& url,
    const CookieOptions& options) {
  ADD_FAILURE();
  return std::string();
}

void DelayedCookieMonster::DeleteCookie(const GURL& url,
                                        const std::string& cookie_name) {
  ADD_FAILURE();
}

void DelayedCookieMonster::DeleteCookieAsync(const GURL& url,
                                             const std::string& cookie_name,
                                             const base::Closure& callback) {
  ADD_FAILURE();
}

void DelayedCookieMonster::DeleteCanonicalCookieAsync(
    const CanonicalCookie& cookie,
    const DeleteCallback& callback) {
  ADD_FAILURE();
}

void DelayedCookieMonster::DeleteAllCreatedBetweenAsync(
    const base::Time& delete_begin,
    const base::Time& delete_end,
    const DeleteCallback& callback) {
  ADD_FAILURE();
}

void DelayedCookieMonster::DeleteAllCreatedBetweenForHostAsync(
    const base::Time delete_begin,
    const base::Time delete_end,
    const GURL& url,
    const DeleteCallback& callback) {
  ADD_FAILURE();
}

void DelayedCookieMonster::DeleteSessionCookiesAsync(const DeleteCallback&) {
  ADD_FAILURE();
}

void DelayedCookieMonster::FlushStore(const base::Closure& callback) {
  ADD_FAILURE();
}

scoped_ptr<CookieStore::CookieChangedSubscription>
DelayedCookieMonster::AddCallbackForCookie(
    const GURL& url,
    const std::string& name,
    const CookieChangedCallback& callback) {
  ADD_FAILURE();
  return scoped_ptr<CookieStore::CookieChangedSubscription>();
}

//
// CookieURLHelper
//
CookieURLHelper::CookieURLHelper(const std::string& url_string)
    : url_(url_string),
      registry_(GetRegistry(url_)),
      domain_and_registry_(
          GetDomainAndRegistry(url_, INCLUDE_PRIVATE_REGISTRIES)) {}

const GURL CookieURLHelper::AppendPath(const std::string& path) const {
  return GURL(url_.spec() + path);
}

std::string CookieURLHelper::Format(const std::string& format_string) const {
  std::string new_string = format_string;
  base::ReplaceSubstringsAfterOffset(&new_string, 0, "%D",
                                     domain_and_registry_);
  base::ReplaceSubstringsAfterOffset(&new_string, 0, "%R", registry_);
  return new_string;
}

}  // namespace net


text:
(function () {
  'use strict';

  function ContentEditController($rootScope, $scope, $routeParams, $q, $timeout, $window, $location, appState, contentResource, entityResource, navigationService, notificationsService, angularHelper, serverValidationManager, contentEditingHelper, treeService, fileManager, formHelper, umbRequestHelper, keyboardService, umbModelMapper, editorState, $http, eventsService, relationResource) {

    var evts = [];

    //setup scope vars
    $scope.defaultButton = null;
    $scope.subButtons = [];

    $scope.page = {};
    $scope.page.loading = false;
    $scope.page.menu = {};
    $scope.page.menu.currentNode = null;
    $scope.page.menu.currentSection = appState.getSectionState("currentSection");
    $scope.page.listViewPath = null;
    $scope.page.isNew = $scope.isNew ? true : false;
    $scope.page.buttonGroupState = "init";
    $scope.allowOpen = true;

    function init(content) {

      createButtons(content);

      editorState.set($scope.content);

      //We fetch all ancestors of the node to generate the footer breadcrumb navigation
      if (!$scope.page.isNew) {
        if (content.parentId && content.parentId !== -1) {
          entityResource.getAncestors(content.id, "document")
            .then(function (anc) {
              $scope.ancestors = anc;
            });
        }
      }

      evts.push(eventsService.on("editors.content.changePublishDate", function (event, args) {
        createButtons(args.node);
      }));

      evts.push(eventsService.on("editors.content.changeUnpublishDate", function (event, args) {
        createButtons(args.node);
      }));

      // We don't get the info tab from the server from version 7.8 so we need to manually add it
      contentEditingHelper.addInfoTab($scope.content.tabs);

    }

    function getNode() {

      $scope.page.loading = true;

      //we are editing so get the content item from the server
      $scope.getMethod()($scope.contentId)
        .then(function (data) {

          $scope.content = data;

          if (data.isChildOfListView && data.trashed === false) {
            $scope.page.listViewPath = ($routeParams.page) ?
              "/content/content/edit/" + data.parentId + "?page=" + $routeParams.page :
              "/content/content/edit/" + data.parentId;
          }

          init($scope.content);

          //in one particular special case, after we've created a new item we redirect back to the edit
          // route but there might be server validation errors in the collection which we need to display
          // after the redirect, so we will bind all subscriptions which will show the server validation errors
          // if there are any and then clear them so the collection no longer persists them.
          serverValidationManager.executeAndClearAllSubscriptions();

          syncTreeNode($scope.content, data.path, true);

          resetLastListPageNumber($scope.content);

          $scope.page.loading = false;

        });

    }

    function createButtons(content) {
      $scope.page.buttonGroupState = "init";
      var buttons = contentEditingHelper.configureContentEditorButtons({
        create: $scope.page.isNew,
        content: content,
        methods: {
          saveAndPublish: $scope.saveAndPublish,
          sendToPublish: $scope.sendToPublish,
          save: $scope.save,
          unPublish: $scope.unPublish
        }
      });

      $scope.defaultButton = buttons.defaultButton;
      $scope.subButtons = buttons.subButtons;

    }

    /** Syncs the content item to it's tree node - this occurs on first load and after saving */
    function syncTreeNode(content, path, initialLoad) {

      if (!$scope.content.isChildOfListView) {
        navigationService.syncTree({ tree: $scope.treeAlias, path: path.split(","), forceReload: initialLoad !== true }).then(function (syncArgs) {
          $scope.page.menu.currentNode = syncArgs.node;
        });
      }
      else if (initialLoad === true) {

        //it's a child item, just sync the ui node to the parent
        navigationService.syncTree({ tree: $scope.treeAlias, path: path.substring(0, path.lastIndexOf(",")).split(","), forceReload: initialLoad !== true });

        //if this is a child of a list view and it's the initial load of the editor, we need to get the tree node
        // from the server so that we can load in the actions menu.
        umbRequestHelper.resourcePromise(
          $http.get(content.treeNodeUrl),
          'Failed to retrieve data for child node ' + content.id).then(function (node) {
          $scope.page.menu.currentNode = node;
        });
      }
    }

    // This is a helper method to reduce the amount of code repitition for actions: Save, Publish, SendToPublish
    function performSave(args) {
      var deferred = $q.defer();

      $scope.page.buttonGroupState = "busy";

      contentEditingHelper.contentEditorPerformSave({
        statusMessage: args.statusMessage,
        saveMethod: args.saveMethod,
        scope: $scope,
        content: $scope.content,
        action: args.action
      }).then(function (data) {
        //success
        init($scope.content);
        syncTreeNode($scope.content, data.path);

        $scope.page.buttonGroupState = "success";

        deferred.resolve(data);
      }, function (err) {
        //error
        if (err) {
          editorState.set($scope.content);
        }

        $scope.page.buttonGroupState = "error";

        deferred.reject(err);
      });

      return deferred.promise;
    }

    function resetLastListPageNumber(content) {
      // We're using rootScope to store the page number for list views, so if returning to the list
      // we can restore the page.  If we've moved on to edit a piece of content that's not the list or it's children
      // we should remove this so as not to confuse if navigating to a different list
      if (!content.isChildOfListView && !content.isContainer) {
        $rootScope.lastListViewPageViewed = null;
      }
    }

    if ($scope.page.isNew) {

      $scope.page.loading = true;

      //we are creating so get an empty content item
      $scope.getScaffoldMethod()()
        .then(function (data) {

          $scope.content = data;

          init($scope.content);

          resetLastListPageNumber($scope.content);

          $scope.page.loading = false;

        });
    }
    else {

      getNode();

    }

    $scope.unPublish = function () {

      if (formHelper.submitForm({ scope: $scope, statusMessage: "Unpublishing...", skipValidation: true })) {

        $scope.page.buttonGroupState = "busy";

        contentResource.unPublish($scope.content.id)
          .then(function (data) {

            formHelper.resetForm({ scope: $scope, notifications: data.notifications });

            contentEditingHelper.handleSuccessfulSave({
              scope: $scope,
              savedContent: data,
              rebindCallback: contentEditingHelper.reBindChangedProperties($scope.content, data)
            });

            init($scope.content);

            syncTreeNode($scope.content, data.path);

            $scope.page.buttonGroupState = "success";

          }, function(err) {
            $scope.page.buttonGroupState = 'error';
          });
      }

    };

    $scope.sendToPublish = function () {
      return performSave({ saveMethod: contentResource.sendToPublish, statusMessage: "Sending...", action: "sendToPublish" });
    };

    $scope.saveAndPublish = function () {
      return performSave({ saveMethod: contentResource.publish, statusMessage: "Publishing...", action: "publish" });
    };

    $scope.save = function () {
      return performSave({ saveMethod: $scope.saveMethod(), statusMessage: "Saving...", action: "save" });
    };

    $scope.preview = function (content) {

      if (!$scope.busy) {

        // Chromes popup blocker will kick in if a window is opened
        // without the initial scoped request. This trick will fix that.
        //
        var previewWindow = $window.open('preview/?init=true&id=' + content.id, 'umbpreview');

        // Build the correct path so both /#/ and #/ work.
        var redirect = Umbraco.Sys.ServerVariables.umbracoSettings.umbracoPath + '/preview/?id=' + content.id;

        //The user cannot save if they don't have access to do that, in which case we just want to preview
        //and that's it otherwise they'll get an unauthorized access message
        if (!_.contains(content.allowedActions, "A")) {
            previewWindow.location.href = redirect;
        }
        else {
            $scope.save().then(function (data) {
                previewWindow.location.href = redirect;
            });
        }

      }

    };

    $scope.restore = function (content) {

      $scope.page.buttonRestore = "busy";

      relationResource.getByChildId(content.id, "relateParentDocumentOnDelete").then(function (data) {

        var relation = null;
        var target = null;
        var error = { headline: "Cannot automatically restore this item", content: "Use the Move menu item to move it manually"};

        if (data.length == 0) {
          notificationsService.error(error.headline, "There is no 'restore' relation found for this node. Use the Move menu item to move it manually.");
          $scope.page.buttonRestore = "error";
          return;
        }

        relation = data[0];

        if (relation.parentId == -1) {
          target = { id: -1, name: "Root" };
          moveNode(content, target);
        } else {
          contentResource.getById(relation.parentId).then(function (data) {
            target = data;

            // make sure the target item isn't in the recycle bin
            if(target.path.indexOf("-20") !== -1) {
              notificationsService.error(error.headline, "The item you want to restore it under (" + target.name + ") is in the recycle bin. Use the Move menu item to move the item manually.");
              $scope.page.buttonRestore = "error";
              return;
            }

            moveNode(content, target);

          }, function (err) {
            $scope.page.buttonRestore = "error";
            notificationsService.error(error.headline, error.content);
          });
        }

      }, function (err) {
        $scope.page.buttonRestore = "error";
        notificationsService.error(error.headline, error.content);
      });

    };

    function moveNode(node, target) {

      contentResource.move({ "parentId": target.id, "id": node.id })
        .then(function (path) {

          // remove the node that we're working on
          if($scope.page.menu.currentNode) {
            treeService.removeNode($scope.page.menu.currentNode);
          }

          // sync the destination node
          navigationService.syncTree({ tree: "content", path: path, forceReload: true, activate: false });

          $scope.page.buttonRestore = "success";
          notificationsService.success("Successfully restored " + node.name + " to " + target.name);

          // reload the node
          getNode();

        }, function (err) {
          $scope.page.buttonRestore = "error";
          notificationsService.error("Cannot automatically restore this item", err);
        });

    }

    //ensure to unregister from all events!
    $scope.$on('$destroy', function () {
      for (var e in evts) {
        eventsService.unsubscribe(evts[e]);
      }
    });

  }

  function createDirective() {

    var directive = {
      restrict: 'E',
      replace: true,
      templateUrl: 'views/components/content/edit.html',
      controller: 'Umbraco.Editors.Content.EditorDirectiveController',
      scope: {
        contentId: "=",
        isNew: "=?",
        treeAlias: "@",
        page: "=?",
        saveMethod: "&",
        getMethod: "&",
        getScaffoldMethod: "&?"
      }
    };

    return directive;

  }

  angular.module('umbraco.directives').controller('Umbraco.Editors.Content.EditorDirectiveController', ContentEditController);
  angular.module('umbraco.directives').directive('contentEditor', createDirective);

})();


text:
/*!
 * FileInput Polish Translations
 *
 * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
 * any HTML markup tags in the messages must not be converted or translated.
 *
 * @see http://github.com/kartik-v/bootstrap-fileinput
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
(function ($) {
    "use strict";

    $.fn.fileinput.locales.pl = {
        fileSingle: 'plik',
        filePlural: 'pliki',
        browseLabel: 'Przeglądaj …',
        removeLabel: 'Usuń',
        removeTitle: 'Usuń zaznaczone pliki',
        cancelLabel: 'Przerwij',
        cancelTitle: 'Anuluj wysyłanie',
        uploadLabel: 'Wgraj',
        uploadTitle: 'Wgraj zaznaczone pliki',
        msgSizeTooLarge: 'Plik o nazwie "{name}" ({size} KB) przekroczył maksymalną dopuszczalną wielkość pliku wynoszącą {maxSize} KB. Proszę ponowić próbę wysłania pliku!',
        msgFilesTooLess: 'Musisz wybrać przynajmniej {n} {files} do wgrania. Proszę spróbować jeszcze raz wgrać pliki!',
        msgFilesTooMany: 'Liczba plików wybranych do wgrania w liczbie ({n}), przekracza maksymalny dozwolony limit wynoszący {m}. Proszę spróbować ponownie!',
        msgFileNotFound: 'Plik "{name}" nie istnieje!',
        msgFileSecured: 'Ustawienia zabezpieczeń uniemożliwiają odczyt pliku "{name}".',
        msgFileNotReadable: 'Plik "{name}" nie jest plikiem do odczytu.',
        msgFilePreviewAborted: 'Podgląd pliku "{name}" został przerwany.',
        msgFilePreviewError: 'Wystąpił błąd w czasie odczytu pliku "{name}".',
        msgInvalidFileType: 'Nieznny typ pliku "{name}". Tylko następujące rodzaje plików "{types}", są obsługiwane.',
        msgInvalidFileExtension: 'Złe rozszerzenie dla pliku "{name}". Tylko następujące rozszerzenia plików "{extensions}", są obsługiwane.',
        msgValidationError: 'Błąd podczas przesyłania pliku.',
        msgLoading: 'Wczytywanie pliku {index} z {files} …',
        msgProgress: 'Wczytywanie pliku {index} z {files} - {name} - {percent}% zakończone.',
        msgSelected: '{n} {files} zaznaczonych',
        msgFoldersNotAllowed: 'Metodą przeciągnij i upuść, można przenosić tylko pliki. Pominięto {n} katalogów.',
        dropZoneTitle: 'Przeciągnij i upuść pliki tu …'
    };

    $.extend($.fn.fileinput.defaults, $.fn.fileinput.locales.pl);
})(window.jQuery);


text:
import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { HivSummaryIndicatorComponent } from './hiv-summary-indicators/hiv-summary-indicator.component';
import { HivSummaryIndicatorsPatientListComponent } from '../../hiv-care-lib/hiv-summary-indicators/patient-list.component';
import { HivCareComparativeComponent } from './hiv-visualization/hiv-care-overview.component';
import { VisualizationPatientListComponent } from '../../hiv-care-lib/hiv-visualization/visualization-patient-list.component';
import { AdminDashboardClinicFlowComponent } from './clinic-flow/admin-dashboard-clinic-flow';
import { HivCareComparativeAnalyticsComponent } from './hiv-data-visualization/hiv-overview-visualization';
import { HivSummaryIndicatorsComponent } from './hiv-summary-indicators/hiv-summary-indicators';
import { DataAnalyticsDashboardComponent } from '../data-analytics.component';
import { DataAnalyticsDashboardGuard } from '../data-analytics-guard';
import { HivSummaryMonthlyIndicatorsComponent } from './hiv-summary-monthly-indicators/hiv-summary-monthly-indicators';
import { HivMonthlySummaryIndicatorsPatientListComponent } from '../../hiv-care-lib/hiv-monthly-summary-indicators/patient-list.component';

import { Moh731ReportComponent } from './moh-731/moh-731-report.component';

import { Moh731MonthlyVizComponent } from './moh-731-monthly-viz/moh-731-monthly-viz.component';

import { DashboardsViewerComponent } from '../../kibana-lib';

import { MOH412HIVDataAnalyticsComponent } from './moh-412-report/moh-412-hiv-data-analytics.component';
import { MOH412HIVDataAnalyticsPatientListComponent } from './moh-412-report/moh-412-hiv-data-analytics-patient-list.component';

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: DataAnalyticsDashboardComponent,
        canActivate: [DataAnalyticsDashboardGuard],
        canDeactivate: [DataAnalyticsDashboardGuard],
        children: [
          {
            path: '',
            redirectTo: 'hiv-comparative-chart-analytics',
            pathMatch: 'full'
          },
          {
            path: 'clinic-flow',
            component: AdminDashboardClinicFlowComponent
          },
          {
            path: 'hiv-comparative-chart-analytics',
            children: [
              {
                path: '',
                component: HivCareComparativeAnalyticsComponent
              },
              {
                path: 'patient-list/:report/:indicator/:period',
                component: VisualizationPatientListComponent
              }
            ]
          },
          {
            path: 'hiv-summary-indicator-report',
            children: [
              {
                path: '',
                component: HivSummaryIndicatorsComponent
              },
              {
                path:
                  'patient-list/:indicator/:period/:gender/:age/:locationUuids',
                component: HivSummaryIndicatorsPatientListComponent
              }
            ]
          },
          {
            path: 'moh-731-report',
            children: [
              {
                path: '',
                component: Moh731ReportComponent
              }
            ]
          },
          {
            path: 'moh-731-monthly',
            children: [
              {
                path: '',
                component: Moh731MonthlyVizComponent
              }
            ]
          },
          {
            path: 'hiv-viz',
            children: [
              {
                path: '',
                component: DashboardsViewerComponent
              }
            ]
          },
          {
            path: 'hiv-summary-monthly-indicator-report',
            children: [
              {
                path: '',
                component: HivSummaryMonthlyIndicatorsComponent
              },
              {
                path:
                  'patient-list/:indicator/:period/:gender/:age/:locationUuids',
                component: HivMonthlySummaryIndicatorsPatientListComponent
              }
            ]
          },
          {
            path: 'moh-412-report',
            children: [
              {
                path: 'patient-list',
                component: MOH412HIVDataAnalyticsPatientListComponent
              },
              {
                path: '',
                component: MOH412HIVDataAnalyticsComponent
              }
            ]
          }
        ]
      }
    ]
  }
];

export const dataAnalyticsDashboardHivRouting: ModuleWithProviders = RouterModule.forChild(
  routes
);


text:
package org.kie.workbench.common.screens.projecteditor.backend.server;

import java.util.Set;
import javax.inject.Inject;
import javax.inject.Named;

import org.guvnor.common.services.backend.util.CommentedOptionFactory;
import org.guvnor.common.services.project.model.GAV;
import org.guvnor.common.services.project.model.MavenRepositoryMetadata;
import org.guvnor.common.services.project.model.ModuleRepositories;
import org.guvnor.common.services.project.service.DeploymentMode;
import org.guvnor.common.services.project.service.GAVAlreadyExistsException;
import org.guvnor.common.services.project.service.ModuleRepositoriesService;
import org.guvnor.common.services.project.service.ModuleRepositoryResolver;
import org.guvnor.common.services.project.service.POMService;
import org.kie.workbench.common.screens.projecteditor.model.ProjectScreenModel;
import org.kie.workbench.common.services.backend.builder.core.LRUPomModelCache;
import org.kie.workbench.common.services.shared.kmodule.KModuleService;
import org.kie.workbench.common.services.shared.project.KieModule;
import org.kie.workbench.common.services.shared.project.KieModuleService;
import org.kie.workbench.common.services.shared.project.ProjectImportsService;
import org.kie.workbench.common.services.shared.whitelist.PackageNameWhiteListService;
import org.uberfire.backend.server.util.Paths;
import org.uberfire.backend.vfs.Path;
import org.uberfire.io.IOService;

public class ProjectScreenModelSaver {

    private POMService pomService;
    private KModuleService kModuleService;
    private ProjectImportsService importsService;
    private ModuleRepositoriesService repositoriesService;
    private PackageNameWhiteListService whiteListService;

    private IOService ioService;
    private KieModuleService moduleService;
    private ModuleRepositoryResolver repositoryResolver;
    private CommentedOptionFactory commentedOptionFactory;

    private LRUPomModelCache pomModelCache;

    public ProjectScreenModelSaver() {
    }

    @Inject
    public ProjectScreenModelSaver(final POMService pomService,
                                   final KModuleService kModuleService,
                                   final ProjectImportsService importsService,
                                   final ModuleRepositoriesService repositoriesService,
                                   final PackageNameWhiteListService whiteListService,
                                   final @Named("ioStrategy") IOService ioService,
                                   final KieModuleService moduleService,
                                   final ModuleRepositoryResolver repositoryResolver,
                                   final CommentedOptionFactory commentedOptionFactory,
                                   final LRUPomModelCache pomModelCache) {
        this.pomService = pomService;
        this.kModuleService = kModuleService;
        this.importsService = importsService;
        this.repositoriesService = repositoriesService;
        this.whiteListService = whiteListService;

        this.ioService = ioService;
        this.moduleService = moduleService;
        this.repositoryResolver = repositoryResolver;
        this.commentedOptionFactory = commentedOptionFactory;

        this.pomModelCache = pomModelCache;
    }

    public void save(final Path pathToPomXML,
                     final ProjectScreenModel model,
                     final DeploymentMode mode,
                     final String comment) {
        if (DeploymentMode.VALIDATED.equals(mode)) {
            checkRepositories(pathToPomXML,
                              model);
        }

        try {
            final KieModule module = moduleService.resolveModule(pathToPomXML);
            pomModelCache.invalidateCache(module);

            ioService.startBatch(Paths.convert(pathToPomXML).getFileSystem(),
                                 commentedOptionFactory.makeCommentedOption(comment));
            pomService.save(pathToPomXML,
                            model.getPOM(),
                            model.getPOMMetaData(),
                            comment);
            kModuleService.save(model.getPathToKModule(),
                                model.getKModule(),
                                model.getKModuleMetaData(),
                                comment);
            importsService.save(model.getPathToImports(),
                                model.getProjectImports(),
                                model.getProjectImportsMetaData(),
                                comment);
            repositoriesService.save(model.getPathToRepositories(),
                                     model.getRepositories(),
                                     comment);
            whiteListService.save(model.getPathToWhiteList(),
                                  model.getWhiteList(),
                                  model.getWhiteListMetaData(),
                                  comment);
        } catch (final Exception e) {
            throw new RuntimeException(e);
        } finally {
            ioService.endBatch();
        }
    }

    private void checkRepositories(final Path pathToPomXML,
                                   final ProjectScreenModel model) {
        // Check is the POM's GAV has been changed.
        final GAV gav = model.getPOM().getGav();
        final KieModule project = moduleService.resolveModule(pathToPomXML);
        if (gav.equals(project.getPom().getGav())) {
            return;
        }

        // If GAV is snapshot we can freely override the module
        if(gav.isSnapshot()) {
            return;
        }

        // Check is the Module's "proposed" GAV resolves to any pre-existing artifacts.
        // Use the Repositories in the model since the User may update the Repositories filter and save.
        final ModuleRepositories moduleRepositories = model.getRepositories();
        final Set<MavenRepositoryMetadata> repositories = repositoryResolver.getRepositoriesResolvingArtifact(gav,
                                                                                project,
                                                                                moduleRepositories.filterByIncluded());
        if (repositories.size() > 0) {
            throw new GAVAlreadyExistsException(gav,
                                                repositories);
        }
    }
}


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

    <string name="cancel_label">Zrušiť</string>
    <string name="confirm_label">Potvrdiť</string>
    <string name="selected_folder_label">Vybraný priečinok:</string>
    <string name="create_folder_label">Vytvoriť priečinok</string>
    <string name="create_folder_msg">Vytvoriť nový priečinok s názvom "%1$s"?</string>
    <string name="create_folder_success">Nový priečinok bol vytvorený</string>
    <string name="create_folder_error_no_write_access">Nemožno zapisovať do tohto priečinka</string>
    <string name="create_folder_error_already_exists">Priečinok už existuje</string>
    <string name="create_folder_error">Nemožno vytvoriť priečinok</string>
    <string name="up_label">Hore</string>
    <string name="internal_label">Internal</string>
    <string name="sdcard_label">SDcard</string>

</resources>


text:
int main( int argc,
          char **argv )
{
  namespace tf = tableformatter;

  tf::TableFormatter formatter( 3, 10 );

  formatter.addHorizontalLine( '-' );
  formatter << "Hello beautiful world!";
  formatter << "Hello beautiful world!";
  formatter << "Hello beautiful world!";
  formatter.addHorizontalLine( '-' );

  std::cout << formatter.toString( ) << std::endl;
}


text:
<!DOCTYPE html>

@section('htmltag')

@show

    @section('title')

      <title>{{ trans('main.meta title') }}</title>

    @show

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    @section('assets')

      <link rel="shortcut icon" href="{{{ asset('assets/images/favicon.ico') }}}">
      <link href='http://fonts.googleapis.com/css?family=Ubuntu:400,700' rel='stylesheet' type='text/css'>
      <link href='http://fonts.googleapis.com/css?family=Ceviche+One' rel='stylesheet' type='text/css'>
      <link href='http://fonts.googleapis.com/css?family=Cantora+One' rel='stylesheet' type='text/css'>
      <link href='http://fonts.googleapis.com/css?family=Quando' rel='stylesheet' type='text/css'>

      {{ HTML::style('assets/css/styles.css') }}
      {{ HTML::style('assets/css/' . $options->getColorScheme() . '.css') }}
      {{ HTML::style('assets/css/new.css') }}

    @show

  @section('bodytag')

  @show

  @section('nav')

    @include('Partials.Navbar')

  @show

  @yield('content')

  @section('ads')

  @if($ad = $options->getFooterAd())

{{ $ad }}

  @endif

  @show

  getColor('warning')}}">

 {{ trans('main.copyright') }} © {{ trans('main.brand') }}{{ Carbon\Carbon::now()->year }}

      {{ trans('main.privacy') }} |
      {{ trans('main.tos') }} |
      {{ trans('main.contact') }}

     <div id="twitter" data-url="{{ url() }}" data-text='{{ trans("main.meta description") }}' data-title="">

     <div id="facebook" data-url="{{ url() }}" data-text='{{ trans("main.meta description") }}' data-title="">

     <div id="pinterest" data-url="{{ url() }}" data-text='{{ trans("main.meta description") }}' data-title="">

     <div id="linkedin" data-url="{{ url() }}" data-text='{{ trans("main.meta description") }}' data-title="">

 {{ HTML::script('assets/js/scripts.js') }}
  @yield('scripts')


text:
var TextField;
(function()
{
    TextField = new Class(InteractiveObject, function()
    {
        //context used for measureing text width
        var textCanvas = cs3.utils.createCanvas(0, 0);
        var textContext = cs3.utils.getContext2d(textCanvas);

        var formatToFont = function(format)
        {
            var font = (format.italic) ? "italic " : "";
            font += (format.bold) ? "bold " : "";
            font += format.size + "px '" + format.font + "'";
            return font;
        };

        this.__init__ = function()
        {
            InteractiveObject.call(this);
            this.__buffer = "";
            this.__lines = [];
            this.__formats = [];
            this.__textWidth = 0;
            this.__textHeight = 0;
            this.__defaultTextFormat = new TextFormat();

            this.__autoSize = true;//allways true for now

            this.background = false;
            this.backgroundColor = 0xFFFFFF;
            this.border = false;
            this.borderColor = 0;
        };

        //override
        this.__getContentBounds = function()
        {
            if (this.border) {
                //border changes the rect size
                return new Rectangle(0, 0, this.__textWidth + 2, this.__textHeight + 2);
            }
            return new Rectangle(0, 0, this.__textWidth, this.__textHeight);
        };

        //override
        this.__getModified = function()
        {
            return this.__modified || this.__transform.__modified;
        };

        //override
        this.__setModified = function(v)
        {
            this.__modified = v;
            this.__transform.__modified = v;
        };

        //override
        this.__render = function(context, colorTransform)
        {
            var bounds = this.__getContentBounds();
            var buffer = this.__buffer;
            var lines  = this.__lines;
            var defaultFormat = this.__defaultTextFormat;
            var lineHeight = defaultFormat.size + defaultFormat.leading;
            var lineWidth = this.__textWidth;

            //add 1px margin on each side
            var offsetX = 1;
            var offsetY = 1;
            if (this.border) {
                var borderColor = (colorTransform) ?
                        colorTransform.transformColor(this.borderColor) :
                        this.borderColor;

                //shift the margin 1px more
                offsetX = 2;
                offsetY = 2;

                //border changes the rect size
                context.fillStyle = __toRGB(borderColor);
                context.beginPath();
                context.rect(0, 0, bounds.width, bounds.height);
                context.stroke();

                context.beginPath();
                context.rect(1, 1, bounds.width - 2, bounds.height - 2);
            }
            else {
                context.beginPath();
                context.rect(0, 0, bounds.width, bounds.height);
            }

            if (this.background) {
                var backgroundColor = (colorTransform) ?
                        colorTransform.transformColor(this.backgroundColor) :
                        this.backgroundColor;
                context.fillStyle = __toRGB(backgroundColor);
                context.fill();
            }

            context.save();
            context.clip();
            context.beginPath();

            var align = defaultFormat.align;
            if (align == TextFormatAlign.RIGHT) {
                context.textAlign = 'right';
                //with no border offsetX = lineWidth - 1 to add a 1px right margin
                //with border it gets shifted 1px to the right and offsetX = lineWidth - 1 + 1
                offsetX = lineWidth - 2 + offsetX;
            }
            else if (align == TextFormatAlign.CENTER) {
                context.textAlign = 'center';
                //with no border offsetX = lineWidth / 2
                //with border offsetX = lineWidth / 2 + 1
                offsetX = lineWidth / 2 - 1 + offsetX;
            }
            else {
                //case LEFT or JUSTIFY
                context.textAlign = 'left';
            }

            context.textBaseline = 'top';

            if (align == TextFormatAlign.JUSTIFY) {
                //TODO
                return;
            }
            else {
                for (i = 0, l = lines.length; i < l; ++i)
                {
                    var line = lines[i];
                    var blocks = line.blocks;
                    for (var ii = 0, ll = blocks.length; ii < ll; ++ii)
                    {
                        var block = blocks[ii];
                        var str = buffer.slice(block.start, block.end + 1);
                        var format = block.format;
                        context.font = formatToFont(format);
                        context.fillStyle = (colorTransform) ?
                                __toRGB(colorTransform.transformColor(format.color)) :
                                __toRGB(format.color);
                        context.fillText(str, offsetX + block.x, offsetY + block.y + (line.height - block.height));
                    }
                }
            }

            context.restore();
        };

        //override
        this.__hitTestPoint = function(context, matrix, point)
        {
            var bounds = this.__getContentBounds();

            //convert point to local coords
            var invertedMatrix = matrix.clone();
            invertedMatrix.invert();
            var localPoint = invertedMatrix.transformPoint(point);
            return bounds.containsPoint(localPoint);
        };

        this.__setTextFormat = function(format, beginIndex, endIndex)
        {
            var formats = this.__formats;
            for (var i = beginIndex; i < endIndex; ++i)
            {
                formats[i] = format;
            }
            trace(formats);
        };
        /**
         * update the visual lines and blocks.
         * TODO: add word wrap
         */
        this.__updateBlocks = function()
        {
            var context = textContext;
            var buffer = this.__buffer;
            var defaultFormat = this.__defaultTextFormat;
            var formats = this.__formats;
            var lines = [];

            //calculate the width and height of each line(block)
            var temp = [];
            var format = defaultFormat;
            var width = 0;
            var height = 0;

            //start the first line
            var line = new Line(0, 0, 0, 0, 0, format.size);
            //start the first block
            var block = new Block(format, 0, 0, 0, 0, 0, format.size);
            context.font = formatToFont(format);

            for (var i = 0, l = buffer.length; i < l; ++i)
            {
                var chr = buffer[i];

                if (formats[i] !== format) {
                    //textFormat has changed
                    if (temp.length) {
                        //update the block width
                        block.width = context.measureText(temp.join("")).width;
                        //update the line width
                        line.width += block.width;
                    }

                    //close the block
                    block.end = i - 1;
                    line.blocks.push(block);

                    //start the new format
                    format = formats[i];
                    trace(1);
                    trace(i);
                    trace(format);
                    trace(2);
                    context.font = formatToFont(format);
                    trace(3);
                    //start a new block
                    block = new Block(format, i, 0, line.width, line.y, 0, format.size);

                    //update the line height
                    line.height = Math.max(line.height, block.height);

                    temp = [];
                }

                //if (chr !== "\n") {
                    temp.push(chr);
                //}

                if (chr === "\n" || i == (l - 1)) {
                    //EOL or EOF
                    if (temp.length) {
                        //update the block width
                        block.width = context.measureText(temp.join("")).width;
                        //update the line width
                        line.width += block.width;
                    }

                    //close the block
                    block.end = i;
                    line.blocks.push(block);

                    //close the line
                    line.end = i;
                    lines.push(line);

                    //update the total width and height
                    width  = (line.width > width) ? line.width : width;
                    height = line.y + line.height;

                    //start a new line
                    line = new Line(i + 1, 0, 0, height + format.leading, 0, format.size);

                    //start a new block
                    block = new Block(format, i + 1, 0, 0, line.y, 0, format.size);

                    temp = [];
                }
            }

            this.__lines  = lines;
            this.__textWidth = width + 2;//add 1px margin on each side
            this.__textHeight = height + 2;
            this.__modified = true;
        };

        this.appendText = function(newText)
        {
            var length = this.__buffer.length;
            this.replaceText(length, length, newText);
        };
        this.replaceText = function(beginIndex, endIndex, newText)
        {
            newText = newText.replace(/\r\n/gim, "\n");
            newText = newText.replace(/\r/gim, "\n");

            var buffer = this.__buffer;
            this.__buffer = buffer.substring(0, beginIndex) + newText + buffer.substring(endIndex);

            this.__setTextFormat(this.__defaultTextFormat, beginIndex, beginIndex + newText.length);
            this.__updateBlocks();
        };
        this.setTextFormat = function(format, beginIndex, endIndex)
        {
            if (beginIndex == -1) {
                beginIndex = 0;
            }
            if (endIndex == -1) {
                endIndex = this.__buffer.length;
            }

            this.__setTextFormat(format, beginIndex, endIndex);
            this.__updateBlocks();
        };

        /* getters and setters */
        this.__get__length = function()
        {
            return this.__buffer.length;
        };
        this.__get__numLines = function()
        {
            return this.__lines.length;
        };
        this.__get__text = function()
        {
            return this.__buffer;
        };
        this.__set__text = function(v)
        {
            this.__buffer = "";
            this.__formats = [];
            this.appendText(v);
        };
        this.__get__defaultTextFormat = function()
        {
            //TODO clone it
            return this.__defaultTextFormat;
        };
        this.__set__defaultTextFormat = function(v)
        {
            this.__defaultTextFormat = v;
            this.__updateBlocks();
        };

        this.toString = function()
        {
            return '[object TextField]';
        };
    });

    var Line = new Class(Object, function()
    {
        this.__init__ = function(start, end, x, y, width, height)
        {
            this.start = start;
            this.end = end;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            this.blocks = [];
        };
    });

    var Block = new Class(Object, function()
    {
        this.__init__ = function(format, start, end, x, y, width, height)
        {
            this.format = format;
            this.start = start;
            this.end = end;
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        };
    });
})();


text:
from yoyo import step

step("""
CREATE TABLE api_keys (
  id  SERIAL,
  key VARCHAR
);
    """,
    """DROP TABLE api_keys;""")


text:
from marshmallow import fields, validate

import polyaxon_sdk

from polyaxon.polyflow.schedules.kinds import V1ScheduleKind
from polyaxon.schemas.base import BaseCamelSchema, BaseConfig

class CronScheduleSchema(BaseCamelSchema):
    kind = fields.Str(allow_none=True, validate=validate.Equal(V1ScheduleKind.CRON))
    start_at = fields.DateTime(allow_none=True)
    end_at = fields.DateTime(allow_none=True)
    cron = fields.String(required=True)
    max_runs = fields.Int(allow_none=True, validate=validate.Range(min=1))
    depends_on_past = fields.Bool(allow_none=True)

    @staticmethod
    def schema_config():
        return V1CronSchedule

class V1CronSchedule(BaseConfig, polyaxon_sdk.V1CronSchedule):
    """Cron schedules is an interface to trigger components repeatedly using a cron definition.

    Args:
        kind: str, should be equal to `cron`
        start_at: datetime, optional
        end_at: datetime, optional
        max_runs: int, optional
        cron: str, required
        depends_on_past: bool, optional

    ## YAML usage

    ```yaml
    >>> schedule:
    >>>   kind:
    >>>   startAt:
    >>>   endAt:
    >>>   maxRuns:
    >>>   cron:
    >>>   dependsOnPast:
    ```

    ## Python usage

    ```python
    >>> from datetime import datetime
    >>> from polyaxon.polyflow import V1CronSchedule
    >>> schedule = V1CronSchedule(
    >>>   start_at=datetime(...),
    >>>   end_at=datetime(...),
    >>>   max_runs=20,
    >>>   cron="0 0 * * *",
    >>>   dependsOnPast=False,
    >>> )
    ```

    ## Fields

    ### kind

    The kind signals to the CLI, client, and other tools that this schedule is a cron schedule.

    If you are using the python client to create the schedule,
    this field is not required and is set by default.

    ```yaml
    >>> run:
    >>>   kind: cron
    ```

    ### startAt

    Optional field to set the start time for kicking the first execution,
    all following executions will be relative to this time.

    ```yaml
    >>> run:
    >>>   startAt: "2019-06-24T21:20:07+00:00"
    ```

    ### endAt

    Optional field to set the end time for stopping this schedule.

    ```yaml
    >>> run:
    >>>   endAt: "2019-06-24T21:20:07+00:00"
    ```

    ### maxRuns

    The maximum number of times to execute the component.
    If used with end date, the schedule will terminate if one of the conditions is met.

    ```yaml
    >>> run:
    >>>   maxRuns: 10
    ```

    ### cron

    The cron expression to generate the component executions.

    ```yaml
    >>> run:
    >>>   cron: "0 0 * * *"
    ```

    ### dependsOnPast

    Optional field to tell Polyaxon to check if the
    previous execution was done before scheduling a new one, by default this is set to `false`.

    ```yaml
    >>> run:
    >>>   dependsOnPast: true
    ```
    """

    SCHEMA = CronScheduleSchema
    IDENTIFIER = V1ScheduleKind.CRON
    REDUCED_ATTRIBUTES = ["startAt", "endAt", "maxRuns", "dependsOnPast"]


text:
using UnityEngine;

using System;
using System.Linq;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;

using DaikonForge.Tween;

#if !FREE_VERSION

namespace DaikonForge.Tween.Components
{

	/// <summary>
	/// Used to animate the color of any component
	/// </summary>
	[AddComponentMenu( "Daikon Forge/Tween/Object Color" )]
	public class TweenObjectColor : TweenComponent<Color>
	{

		#region Protected serialized fields

		[SerializeField]
		protected Component target;

		#endregion

		#region Private runtime variables

		private TweenEasingCallback easingFunc;

		#endregion

		#region Public properties

		/// <summary>
		/// Provides information about the target property being tweened
		/// </summary>
		public Component Target
		{
			get { return this.target; }
			set
			{
				this.target = value;
				Stop();
			}
		}

		#endregion

		#region Private utility methods

		protected override void validateTweenConfiguration()
		{

			if( target == null )
			{
				throw new InvalidOperationException( "The Target cannot be NULL" );
			}

			base.validateTweenConfiguration();

		}

		protected override void configureTween()
		{

			if( target == null )
			{

				target = gameObject.GetComponent<Renderer>();

				if( target == null )
				{

					if( this.tween != null )
					{
						tween.Stop();
						tween.Release();
						tween = null;
					}

					return;

				}

			}

			if( this.tween == null )
			{

				this.easingFunc = TweenEasingFunctions.GetFunction( this.easingType );

				this.tween = (Tween<Color>)
					Target.TweenColor()
					.SetEasing( this.modifyEasing )
					.OnStarted( ( x ) => { onStarted(); } )
					.OnStopped( ( x ) => { onStopped(); } )
					.OnPaused( ( x ) => { onPaused(); } )
					.OnResumed( ( x ) => { onResumed(); } )
					.OnLoopCompleted( ( x ) => { onLoopCompleted(); } )
					.OnCompleted( ( x ) => { onCompleted(); } );

			}

			var currentValue = tween.CurrentValue;

			var actualStartValue = this.startValue;
			if( this.startValueType == TweenStartValueType.SyncOnRun )
			{
				actualStartValue = currentValue;
			}

			var actualEndValue = this.endValue;
			if( this.endValueType == TweenEndValueType.SyncOnRun )
				actualEndValue = currentValue;
			else if( this.endValueType == TweenEndValueType.Relative )
				actualEndValue += actualStartValue;

			this.tween
				.SetStartValue( actualStartValue )
				.SetEndValue( actualEndValue )
				.SetDelay( this.startDelay, this.assignStartValueBeforeDelay )
				.SetDuration( this.duration )
				.SetLoopType( this.LoopType )
				.SetLoopCount( this.loopCount )
				.SetPlayDirection( this.playDirection );

		}

		private float modifyEasing( float time )
		{

			if( this.animCurve != null )
			{
				time = animCurve.Evaluate( time );
			}

			return this.easingFunc( time );

		}

		#endregion

	}

}

#endif


text:
package advent2016;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class Day8 {

	private static final String ACTION_ROTATE_COLUMN = "rotate column";
	private static final String ACTION_ROTATE_ROW = "rotate row";
	private static final String ACTION_RECT = "rect";

	private static final int SCREEN_HEIGHT = 6;
	private static final int SCREEN_WIDTH = 50;

	private boolean[][] screen = new boolean[SCREEN_HEIGHT + 1][SCREEN_WIDTH + 1];

	public long task1(final File file) throws IOException {
		Files.lines(file.toPath()).forEach(line -> updateScreen(line));
		return showEnabledPixels();
	}

	private void updateScreen(String line) {
		if (line.startsWith(ACTION_RECT)) {
			String args = line.substring(ACTION_RECT.length() + 1);
			String[] split = args.split("x");
			rect(Integer.valueOf(split[0].trim()), Integer.valueOf(split[1].trim()));
		} else if (line.startsWith(ACTION_ROTATE_ROW)) {
			String args = line.substring(ACTION_ROTATE_ROW.length() + 3);
			String[] split = args.split(" by ");
			rotateRow(Integer.valueOf(split[0].trim()), Integer.valueOf(split[1].trim()));
		} else if (line.startsWith(ACTION_ROTATE_COLUMN)) {
			String args = line.substring(ACTION_ROTATE_COLUMN.length() + 3);
			String[] split = args.split(" by ");
			rotateColumn(Integer.valueOf(split[0].trim()), Integer.valueOf(split[1].trim()));
		}
	}

	// private void demo() {
	// rect(3, 2);
	// rotateColumn(1, 1);
	// rotateRow(0, 4);
	// showEnabledPixels();
	// }

	private void rotateColumn(int column, int shifts) {
		for (int i = 0; i < shifts; i++) {
			for (int j = screen.length - 1; j > 0; j--) {
				screen[j][column] = screen[j - 1][column];
			}
			screen[0][column] = screen[screen.length - 1][column];
		}
	}

	private void rotateRow(int row, int shifts) {
		for (int i = 0; i < shifts; i++) {
			for (int j = screen[row].length - 1; j > 0; j--) {
				screen[row][j] = screen[row][j - 1];
			}
			screen[row][0] = screen[row][screen[row].length - 1];
		}
	}

	private void rect(int a, int b) {
		for (int i = 0; i < a; i++) {
			for (int j = 0; j < b; j++) {
				screen[j][i] = true;
			}
		}
	}

	private long showEnabledPixels() {
		long count = 0;
		for (int i = 0; i < screen.length - 1; i++) {
			for (int j = 0; j < screen[i].length - 1; j++) {
				boolean pixelOn = screen[i][j];
				if (pixelOn) {
					count++;
				}
				System.err.print(pixelOn ? '#' : '.');
			}
			System.err.println();
		}
		return count;
	}
}


text:
/**
 * Module dependencies
 */

var sailsgen = require('sails-generate')
  , path = require('path');

//
// This script exists so we can run our generator
// directly from the command-line for convenience
// during development.
//

var scope = {
  generatorType: 'auth',
  rootPath: process.cwd(),
  modules: {
    'auth': path.resolve(__dirname, '../lib')
  },

  // For the NEW generator we're generating:
  generatorName: process.argv[2],
};
sailsgen(scope, function (err) {
  if (err) throw err;

  // It worked.
  console.log('Done.');
});


text:
package com.github.onsdigital.babbage.template.handlebars.helpers;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Options;
import com.github.onsdigital.babbage.template.handlebars.helpers.base.BabbageHandlebarsHelper;

import java.io.IOException;

import static com.github.onsdigital.babbage.configuration.ApplicationConfiguration.appConfig;

/**
 * Created by iankent on 03/02/17.
 */
public enum SignedURLHelper implements BabbageHandlebarsHelper<String> {

    //Sign a URL
    sign_url {
        @Override
        public CharSequence apply(String context, Options options) throws IOException {
            if (options.isFalsy(context)) {
                return null;
            }

            String uri = context;
            String term = options.param(0);
            if(term == null || term.length() == 0) {
                term = options.param(1);
            }
            Long page = options.param(2);
            if(page == null) {
                page = 1L;
            }
            Integer index = options.param(3);
            String listType = options.param(4);
            Integer pageSize;
            if (options.param(5) == null) {
                pageSize = 10;
            } else {
                pageSize = Integer.valueOf(options.param(5));
            }

            String token = "";
            try {
                token = JWT.create()
                        .withClaim("uri", uri)
                        .withClaim("term", term)
                        .withClaim("page", (int)(long)page)
                        .withClaim("index", index)
                        .withClaim("listType", listType)
                        .withClaim("pageSize", pageSize)
                        .sign(Algorithm.HMAC256(appConfig().babbage().getRedirectSecret()));
            } catch (JWTCreationException exception){
                throw new RuntimeException("Failed to create JWT", exception);
            }

            return token;
        }

        @Override
        public void register(Handlebars handlebars) {
            handlebars.registerHelper(this.name(), this);
        }
    }

}