text:
import os
import re
import shutil
import sys
import tempfile
from typing import Any
from typing import cast
from typing import List
from typing import Tuple

from sqlalchemy import testing
from sqlalchemy.testing import config
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures

def _file_combinations(dirname):
    path = os.path.join(os.path.dirname(__file__), dirname)
    files = []
    for f in os.listdir(path):
        if f.endswith(".py"):
            files.append(os.path.join(os.path.dirname(__file__), dirname, f))

    for extra_dir in testing.config.options.mypy_extra_test_paths:
        if extra_dir and os.path.isdir(extra_dir):
            for f in os.listdir(os.path.join(extra_dir, dirname)):
                if f.endswith(".py"):
                    files.append(os.path.join(extra_dir, dirname, f))
    return files

def _incremental_dirs():
    path = os.path.join(os.path.dirname(__file__), "incremental")
    files = []
    for d in os.listdir(path):
        if os.path.isdir(os.path.join(path, d)):
            files.append(
                os.path.join(os.path.dirname(__file__), "incremental", d)
            )

    for extra_dir in testing.config.options.mypy_extra_test_paths:
        if extra_dir and os.path.isdir(extra_dir):
            for d in os.listdir(os.path.join(extra_dir, "incremental")):
                if os.path.isdir(os.path.join(path, d)):
                    files.append(os.path.join(extra_dir, "incremental", d))
    return files

@testing.add_to_marker.mypy
class MypyPluginTest(fixtures.TestBase):
    __tags__ = ("mypy",)
    __requires__ = ("no_sqlalchemy2_stubs",)

    @testing.fixture(scope="function")
    def per_func_cachedir(self):
        yield from self._cachedir()

    @testing.fixture(scope="class")
    def cachedir(self):
        yield from self._cachedir()

    def _cachedir(self):
        # as of mypy 0.971 i think we need to keep mypy_path empty
        mypy_path = ""

        with tempfile.TemporaryDirectory() as cachedir:
            with open(
                os.path.join(cachedir, "sqla_mypy_config.cfg"), "w"
            ) as config_file:
                config_file.write(
                    f"""
                    [mypy]\n
                    plugins = sqlalchemy.ext.mypy.plugin\n
                    show_error_codes = True\n
                    {mypy_path}
                    disable_error_code = no-untyped-call

                    [mypy-sqlalchemy.*]
                    ignore_errors = True

                    """
                )
            with open(
                os.path.join(cachedir, "plain_mypy_config.cfg"), "w"
            ) as config_file:
                config_file.write(
                    f"""
                    [mypy]\n
                    show_error_codes = True\n
                    {mypy_path}
                    disable_error_code = var-annotated,no-untyped-call
                    [mypy-sqlalchemy.*]
                    ignore_errors = True

                    """
                )
            yield cachedir

    @testing.fixture()
    def mypy_runner(self, cachedir):
        from mypy import api

        def run(path, use_plugin=True, incremental=False):
            args = [
                "--strict",
                "--raise-exceptions",
                "--cache-dir",
                cachedir,
                "--config-file",
                os.path.join(
                    cachedir,
                    "sqla_mypy_config.cfg"
                    if use_plugin
                    else "plain_mypy_config.cfg",
                ),
            ]

            # mypy as of 0.990 is more aggressively blocking messaging
            # for paths that are in sys.path, and as pytest puts currdir,
            # test/ etc in sys.path, just copy the source file to the
            # tempdir we are working in so that we don't have to try to
            # manipulate sys.path and/or guess what mypy is doing
            filename = os.path.basename(path)
            test_program = os.path.join(cachedir, filename)
            shutil.copyfile(path, test_program)
            args.append(test_program)

            # I set this locally but for the suite here needs to be
            # disabled
            os.environ.pop("MYPY_FORCE_COLOR", None)

            result = api.run(args)
            return result

        return run

    @testing.combinations(
        *[
            (pathname, testing.exclusions.closed())
            for pathname in _incremental_dirs()
        ],
        argnames="pathname",
    )
    @testing.requires.patch_library
    def test_incremental(self, mypy_runner, per_func_cachedir, pathname):
        import patch

        cachedir = per_func_cachedir

        dest = os.path.join(cachedir, "mymodel")
        os.mkdir(dest)

        patches = set()

        print("incremental test: %s" % pathname)

        for fname in os.listdir(pathname):
            if fname.endswith(".py"):
                shutil.copy(
                    os.path.join(pathname, fname), os.path.join(dest, fname)
                )
                print("copying to: %s" % os.path.join(dest, fname))
            elif fname.endswith(".testpatch"):
                patches.add(fname)

        for patchfile in [None] + sorted(patches):
            if patchfile is not None:
                print("Applying patchfile %s" % patchfile)
                patch_obj = patch.fromfile(os.path.join(pathname, patchfile))
                assert patch_obj.apply(1, dest), (
                    "pathfile %s failed" % patchfile
                )
            print("running mypy against %s" % dest)
            result = mypy_runner(
                dest,
                use_plugin=True,
                incremental=True,
            )
            eq_(
                result[2],
                0,
                msg="Failure after applying patch %s: %s"
                % (patchfile, result[0]),
            )

    @testing.combinations(
        *(
            cast(
                List[Tuple[Any, ...]],
                [
                    ("w_plugin", os.path.basename(path), path, True)
                    for path in _file_combinations("plugin_files")
                ],
            )
            + cast(
                List[Tuple[Any, ...]],
                [
                    ("plain", os.path.basename(path), path, False)
                    for path in _file_combinations("plain_files")
                ],
            )
        ),
        argnames="filename,path,use_plugin",
        id_="isaa",
    )
    def test_files(self, mypy_runner, filename, path, use_plugin):

        expected_messages = []
        expected_re = re.compile(r"\s*# EXPECTED(_MYPY)?(_RE)?(_TYPE)?: (.+)")
        py_ver_re = re.compile(r"^#\s*PYTHON_VERSION\s?>=\s?(\d+\.\d+)")
        with open(path) as file_:
            current_assert_messages = []
            for num, line in enumerate(file_, 1):
                m = py_ver_re.match(line)
                if m:
                    major, _, minor = m.group(1).partition(".")
                    if sys.version_info < (int(major), int(minor)):
                        config.skip_test(
                            "Requires python >= %s" % (m.group(1))
                        )
                    continue
                if line.startswith("# NOPLUGINS"):
                    use_plugin = False
                    continue

                m = expected_re.match(line)
                if m:
                    is_mypy = bool(m.group(1))
                    is_re = bool(m.group(2))
                    is_type = bool(m.group(3))

                    expected_msg = re.sub(r"# noqa[:]? ?.*", "", m.group(4))
                    if is_type:
                        if not is_re:
                            # the goal here is that we can cut-and-paste
                            # from vscode -> pylance into the
                            # EXPECTED_TYPE: line, then the test suite will
                            # validate that line against what mypy produces
                            expected_msg = re.sub(
                                r"([\[\]])",
                                lambda m: rf"\{m.group(0)}",
                                expected_msg,
                            )

                            # note making sure preceding text matches
                            # with a dot, so that an expect for "Select"
                            # does not match "TypedSelect"
                            expected_msg = re.sub(
                                r"([\w_]+)",
                                lambda m: rf"(?:.*\.)?{m.group(1)}\*?",
                                expected_msg,
                            )

                            expected_msg = re.sub(
                                "List", "builtins.list", expected_msg
                            )

                            expected_msg = re.sub(
                                r"\b(int|str|float|bool)\b",
                                lambda m: rf"builtins.{m.group(0)}\*?",
                                expected_msg,
                            )
                            # expected_msg = re.sub(
                            #     r"(Sequence|Tuple|List|Union)",
                            #     lambda m: fr"typing.{m.group(0)}\*?",
                            #     expected_msg,
                            # )

                        is_mypy = is_re = True
                        expected_msg = f'Revealed type is "{expected_msg}"'
                    current_assert_messages.append(
                        (is_mypy, is_re, expected_msg.strip())
                    )
                elif current_assert_messages:
                    expected_messages.extend(
                        (num, is_mypy, is_re, expected_msg)
                        for (
                            is_mypy,
                            is_re,
                            expected_msg,
                        ) in current_assert_messages
                    )
                    current_assert_messages[:] = []

        result = mypy_runner(path, use_plugin=use_plugin)

        not_located = []

        if expected_messages:
            # mypy 0.990 changed how return codes work, so don't assume a
            # 1 or a 0 return code here, could be either depending on if
            # errors were generated or not

            output = []

            raw_lines = result[0].split("\n")
            while raw_lines:
                e = raw_lines.pop(0)
                if re.match(r".+\.py:\d+: error: .*", e):
                    output.append(("error", e))
                elif re.match(
                    r".+\.py:\d+: note: +(?:Possible overload|def ).*", e
                ):
                    while raw_lines:
                        ol = raw_lines.pop(0)
                        if not re.match(r".+\.py:\d+: note: +def \[.*", ol):
                            break
                elif re.match(
                    r".+\.py:\d+: note: .*(?:perhaps|suggestion)", e, re.I
                ):
                    pass
                elif re.match(r".+\.py:\d+: note: .*", e):
                    output.append(("note", e))

            for num, is_mypy, is_re, msg in expected_messages:
                msg = msg.replace("'", '"')
                prefix = "[SQLAlchemy Mypy plugin] " if not is_mypy else ""
                for idx, (typ, errmsg) in enumerate(output):
                    if is_re:
                        if re.match(
                            rf".*{filename}\:{num}\: {typ}\: {prefix}{msg}",  # noqa: E501
                            errmsg,
                        ):
                            break
                    elif (
                        f"{filename}:{num}: {typ}: {prefix}{msg}"
                        in errmsg.replace("'", '"')
                    ):
                        break
                else:
                    not_located.append(msg)
                    continue
                del output[idx]

            if not_located:
                print(f"Couldn't locate expected messages: {not_located}")
                print("\n".join(msg for _, msg in output))
                assert False, "expected messages not found, see stdout"

            if output:
                print(f"{len(output)} messages from mypy were not consumed:")
                print("\n".join(msg for _, msg in output))
                assert False, "errors and/or notes remain, see stdout"

        else:
            if result[2] != 0:
                print(result[0])

            eq_(result[2], 0, msg=result)


text:
'use strict'

const crypto = require('crypto')

module.exports = function encryptPassword (password, salt) {
  const buf = crypto.pbkdf2Sync(password, salt, 100000, 512, 'sha512')
  return buf.toString('hex')
}

redpajama_set_name: RedPajamaGithub


text:
import leagreq.name_to_acc as name_to_acc
import leagreq.acc_to_matches as acc_to_matches
import stats.aggregation as aggregation
import preds.pred_translate as pred_translate
import preds.playerpreds as playerpreds
import preds.gamepreds as gamepreds
import sys
import argparse
# Module serves as an entry point for a user to find common stats needed like
# a mapping of getting first tower to winrate
# or an average of performance statistics of a player over the players solo q or flex games

# TODO: Need a model - but do we really?
# One that stores the match_list to test on, and the account ids that are associated with the players
# whose stats we wish to calculate, and a set of predicates we wish to test
# maybe we dont need to keep the set of predicates, but definitely at least the match_lits and the account_ids

#   parses the sys args that are passed in through the command line
#   input: sys_args : sys.argv thats passed in from command line
#   output: name,champion,role : 3-string tuple
def solo_cond_arg_parse(sys_args):
    parser = argparse.ArgumentParser()
    parser.add_argument("name",help = "the name of the summoner")
    parser.add_argument('-c',"--champion",help = "the name of the champion")
    parser.add_argument('-l',"--lane",help = "the role. Valid: TOP MIDDLE BOTTOM SUPPORT JUNGLE")
    args = parser.parse_args()
    name = args.name
    champion = args.champion
    role = args.lane
    print(name,champion,role)
    return name,champion,role

#   single_player function - high-level function
#   This function will take in a summoner name, a champion_name(optional), and a role(optional)
#   It will print that players stats on all the solo q matches given that
#   the player played that champion and/or that role, provided the criteria was provided
#   input: name : string
#          champion_name : string
#          lane : string
#   output: None : will print players stats on single-player
def single_player(name,champion_name=None,lane=None):
    acc_id = name_to_acc.account_id_from_name(name)
    m_l = acc_to_matches.solo_q_matches(acc_id)
    filtered_m_l = []
    cr_pred = playerpreds.champ_role(champ_name=champion_name,role=lane)
    champ_role_pred = playerpreds.player_cond(acc_id,cr_pred)
    remake_pred = gamepreds.game_cond(gamepreds.is_remake())
    for m in m_l:
        if remake_pred(m) is False and champ_role_pred(m):
            filtered_m_l.append(m)
    print(len(filtered_m_l))
    data_func = aggregation.single_player_get_data(acc_id)
    res_map = aggregation.stat_aggregate(filtered_m_l,data_func)
    for x in res_map:
        print(str(x) + ":")
        print(res_map[x])
    return res_map

if __name__ == "__main__":
    name,champion,role = solo_cond_arg_parse(sys.argv)
    single_player(name,champion_name=champion,lane=role)


text:
package com.metazion.jm.net;

public abstract class ClientSession extends TransmitSession {

	private String remoteHost = "";
	private int remotePort = 0;
	private int reconnectInterval = 10;

	public String getRemoteHost() {
		return remoteHost;
	}

	public void setRemoteHost(String remoteHost) {
		this.remoteHost = remoteHost;
	}

	public int getRemotePort() {
		return remotePort;
	}

	public void setRemotePort(int remotePort) {
		this.remotePort = remotePort;
	}

	public int getReconnectInterval() {
		return reconnectInterval;
	}

	public void setReconnectInterval(int reconnectInterval) {
		this.reconnectInterval = reconnectInterval;
	}

	@Override
	public String detail() {
		return String.format("%s remoteHost[%s] remotePort[%d] reconnectInterval[%d]", super.detail(), remoteHost, remotePort, reconnectInterval);
	}
}


text:
<!doctype html>

    <title>Text in Lists</title>


text:
.x-form-field {
    font:normal 15px tahoma, arial, helvetica, sans-serif;
}

.x-form-text, textarea.x-form-field{
    color: #ffffff;
    background-color:#33373d;
    background-image:url(../images/access/form/text-bg.gif);
    border-color:#737b8c;
    border-width:2px;
}

.ext-webkit .x-form-text, .ext-webkit textarea.x-form-field{
    border-width:2px;
}

.x-form-text, .ext-ie .x-form-file {
    height:26px;
}

.ext-strict .x-form-text {
    height:20px;
}

.x-form-select-one {
    background-color:#fff;
    border-color:#b5b8c8;
}

.x-form-check-group-label {
    border-bottom: 1px solid #99bbe8;
    color: #fff;
}

.x-editor .x-form-check-wrap {
    background-color:#fff;
}

.x-form-field-wrap .x-form-trigger{
    background-image:url(../images/access/form/trigger.gif);
    border-bottom-color:#737b8c;
    border-bottom-width:2px;
    height:24px;
    width:20px;
}

.x-form-field-wrap .x-form-trigger.x-form-trigger-over{
    border-bottom-color:#d97e27;
}

.x-form-field-wrap .x-form-trigger.x-form-trigger-click{
    border-bottom-color:#c86e19;
}

.x-small-editor .x-form-field-wrap .x-form-trigger {
    height:24px;
}

.x-form-field-wrap .x-form-trigger-over {
    background-position:-20px 0;
}

.x-form-field-wrap .x-form-trigger-click {
    background-position:-40px 0;
}

.x-trigger-wrap-focus .x-form-trigger {
    background-position:-60px 0;
}

.x-trigger-wrap-focus .x-form-trigger-over {
    background-position:-80px 0;
}

.x-trigger-wrap-focus .x-form-trigger-click {
    background-position:-100px 0;
}

.x-form-field-wrap .x-form-date-trigger{
    background-image: url(../images/access/form/date-trigger.gif);
}

.x-form-field-wrap .x-form-clear-trigger{
    background-image: url(../images/access/form/clear-trigger.gif);
}

.x-form-field-wrap .x-form-search-trigger{
    background-image: url(../images/access/form/search-trigger.gif);
}

.x-trigger-wrap-focus .x-form-trigger{
    border-bottom-color:#737b8c;
}

.x-item-disabled .x-form-trigger-over{
    border-bottom-color:#b5b8c8;
}

.x-item-disabled .x-form-trigger-click{
    border-bottom-color:#b5b8c8;
}

.x-form-focus, textarea.x-form-focus{
	border-color:#ff9c33;
}

.x-form-invalid, textarea.x-form-invalid,
.ext-webkit .x-form-invalid, .ext-webkit textarea.x-form-invalid{
    background-color:#15171a;
	background-image:url(../images/access/grid/invalid_line.gif);
	border-color:#c30;
}

/*
.ext-safari .x-form-invalid{
	background-color:#fee;
	border-color:#ff7870;
}
*/

.x-form-inner-invalid, textarea.x-form-inner-invalid{
    background-color:#fff;
	background-image:url(../images/access/grid/invalid_line.gif);
}

.x-form-grow-sizer {
	font:normal 15px tahoma, arial, helvetica, sans-serif;
}

.x-form-item {
    font:normal 15px tahoma, arial, helvetica, sans-serif;
}

.x-form-invalid-msg {
    color:#c0272b;
    font:normal 14px tahoma, arial, helvetica, sans-serif;
    background-image:url(../images/default/shared/warning.gif);
}

.x-form-empty-field {
    color:#dadadd;
}

.x-small-editor .x-form-text {
    height: 26px;
}

.x-small-editor .x-form-field {
    font:normal 14px arial, tahoma, helvetica, sans-serif;
}

.ext-safari .x-small-editor .x-form-field {
    font:normal 15px arial, tahoma, helvetica, sans-serif;
}

.x-form-invalid-icon {
    background-image:url(../images/access/form/exclamation.gif);
    height:25px;
    width:19px;
    background-position:center right;
}

.x-fieldset {
    border-color:#737B8C;
}

.x-fieldset legend {
    font:bold 14px tahoma, arial, helvetica, sans-serif;
    color:#fff;
}


text:
<?php
/*
 * User: tappleby
 * Date: 11/16/2013
 * Time: 11:27 PM
 */

namespace Tappleby\OAuth2\ResponseType;

use OAuth2\Storage\AccessTokenInterface as AccessTokenStorageInterface;
use OAuth2\Storage\RefreshTokenInterface as RefreshTokenStorageInterface;

class AccessTokenResponseType extends \OAuth2\ResponseType\AccessToken  {

	public function __construct(AccessTokenStorageInterface $tokenStorage, RefreshTokenStorageInterface $refreshStorage = null, array $config = array())
	{
		parent::__construct($tokenStorage, $refreshStorage, $config);
	}

	public function createAccessToken($client_id, $user_id, $scope = null, $includeRefreshToken = true)
	{
		$accessToken =  parent::createAccessToken(
			$client_id,
			$user_id,
			$scope,
			$includeRefreshToken
		);

		if(isset($this->config['access_token_return_user_id']) && $this->config['access_token_return_user_id']) {
			$accessToken['user_id'] = $user_id;
		}

		return $accessToken;
	}

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:padding="5dp">

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/home_icon10" />

    <RelativeLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:padding="5dp">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:textSize="16sp"
            android:text="我的美一页" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="10dp"
            android:layout_alignLeft="@+id/textView1"
            android:layout_alignParentBottom="true"
            android:src="@drawable/home_icon11" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/imageView2"
            android:layout_marginLeft="5dp"
            android:layout_toRightOf="@+id/imageView2"
            android:text="查看"
            android:textColor="#777"
            android:textSize="10sp" />

        <ImageView
            android:id="@+id/imageView03"
            android:layout_width="wrap_content"
            android:layout_height="10dp"
            android:layout_alignTop="@+id/imageView2"
            android:layout_toRightOf="@+id/textView2"
            android:layout_marginLeft="20dp"
            android:src="@drawable/home_icon12" />

        <TextView
            android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/imageView03"
            android:layout_toRightOf="@+id/imageView03"
            android:text="分享"
            android:textColor="#777"
            android:layout_marginLeft="10dp"
            android:textSize="10sp" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/tvDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:textSize="12sp"
            android:fontFamily="黑体"
            android:layout_marginBottom="5dp"
            android:text="2015-1-1" />

    </RelativeLayout>

</LinearLayout>


text:
layout: default
title: Integrations
bodyclass: is-blue
active: integrations
---
{% assign collections = site.collections | sort: 'sort_order' %}

Integrating External Services

Using third party tools and services is critical for a powerful CI/CD process.

We have a lot of examples, integrations and documentation built out for both Codeship Basic and Codeship Pro.

Notifications | Monitoring | Code Coverage | Testing | Security  | Deployments

Notifications

Campfire

Flowdock

OpsGenie

PagerDuty

Slack

VictorOps

Another?

Learn how to integrate a new tool or service.

Monitoring

Assertible

Atatus

Honeycomb

Raygun

Rollbar

Runscope

Another?

Learn how to integrate a new tool or service.

Code Coverage

Codacy

CodeClimate

CodeCov

Coveralls

Another?

Learn how to integrate a new tool or service.

Testing

Ghost Inspector

Percy

RedLine13

Selenium

Testable

Another?

Learn how to integrate a new tool or service.

Security

Anchore

Brakeman Pro

Depfu

Gosec

Hakiri

Snyk

SourceClear

Another?

Learn how to integrate a new tool or service.

Deployments

Appranix

AWS

Azure

Capistrano

CloudFoundry

Cloud66

Digital Ocean

Firebase

Google Cloud

Heroku

IBM Cloud

Kubernetes

Pulumi

Rancher

Another?

Learn how to integrate a new tool or service.


text:
%%% RenderToolbox3 Copyright (c) 2012-2013 The RenderToolbox3 Team.
%%% About Us://github.com/DavidBrainard/RenderToolbox3/wiki/About-Us
%%% RenderToolbox3 is released under the MIT License.  See LICENSE.txt.
%
% Parse conditions from file and save in recipe struct
%   @param recipe a recipe struct
%
% @details
% Reads RenderToolbox3 conditions from @a recipe.input.conditionsFile and
% saves the results in @a recipe.rendering.conditions.
%
% @details
% Returns the given @a recipe, with parsed conditions.
%
% @details
% Usage:
%   recipe = ReadRecipeConditions(recipe)
%
% @ingroup RecipeAPI
function recipe = ReadRecipeConditions(recipe)

recipe.rendering.conditions = [];
if IsStructFieldPresent(recipe.input, 'conditionsFile')
    [recipe.rendering.conditions.names, ...
        recipe.rendering.conditions.values] = ...
        ParseConditions(recipe.input.conditionsFile);
end


text:
(function() {
  var Instafeed, root;

  Instafeed = (function() {

    function Instafeed(params, context) {
      var option, value;
      this.options = {
        target: 'instafeed',
        get: 'popular',
        resolution: 'thumbnail',
        sortBy: 'none',
        links: true,
        mock: false,
        useHttp: false
      };
      if (typeof params === 'object') {
        for (option in params) {
          value = params[option];
          this.options[option] = value;
        }
      }
      this.context = context != null ? context : this;
      this.unique = this._genKey();
    }

    Instafeed.prototype.hasNext = function() {
      return typeof this.context.nextUrl === 'string' && this.context.nextUrl.length > 0;
    };

    Instafeed.prototype.next = function() {
      if (!this.hasNext()) {
        return false;
      }
      return this.run(this.context.nextUrl);
    };

    Instafeed.prototype.run = function(url) {
      var header, instanceName, script;
      if (typeof this.options.clientId !== 'string') {
        if (typeof this.options.accessToken !== 'string') {
          throw new Error("Missing clientId or accessToken.");
        }
      }
      if (typeof this.options.accessToken !== 'string') {
        if (typeof this.options.clientId !== 'string') {
          throw new Error("Missing clientId or accessToken.");
        }
      }
      if ((this.options.before != null) && typeof this.options.before === 'function') {
        this.options.before.call(this);
      }
      if (typeof document !== "undefined" && document !== null) {
        script = document.createElement('script');
        script.id = 'instafeed-fetcher';
        script.src = url || this._buildUrl();
        header = document.getElementsByTagName('head');
        header[0].appendChild(script);
        instanceName = "instafeedCache" + this.unique;
        window[instanceName] = new Instafeed(this.options, this);
        window[instanceName].unique = this.unique;
      }
      return true;
    };

    Instafeed.prototype.parse = function(response) {
      var anchor, fragment, header, htmlString, image, imageString, imageUrl, images, img, imgUrl, instanceName, node, reverse, sortSettings, tmpEl, _i, _j, _k, _len, _len1, _len2, _ref;
      if (typeof response !== 'object') {
        if ((this.options.error != null) && typeof this.options.error === 'function') {
          this.options.error.call(this, 'Invalid JSON data');
          return false;
        } else {
          throw new Error('Invalid JSON response');
        }
      }
      if (response.meta.code !== 200) {
        if ((this.options.error != null) && typeof this.options.error === 'function') {
          this.options.error.call(this, response.meta.error_message);
          return false;
        } else {
          throw new Error("Error from Instagram: " + response.meta.error_message);
        }
      }
      if (response.data.length === 0) {
        if ((this.options.error != null) && typeof this.options.error === 'function') {
          this.options.error.call(this, 'No images were returned from Instagram');
          return false;
        } else {
          throw new Error('No images were returned from Instagram');
        }
      }
      if ((this.options.success != null) && typeof this.options.success === 'function') {
        this.options.success.call(this, response);
      }
      this.context.nextUrl = '';
      if (response.pagination != null) {
        this.context.nextUrl = response.pagination.next_url;
      }
      if (this.options.sortBy !== 'none') {
        if (this.options.sortBy === 'random') {
          sortSettings = ['', 'random'];
        } else {
          sortSettings = this.options.sortBy.split('-');
        }
        reverse = sortSettings[0] === 'least' ? true : false;
        switch (sortSettings[1]) {
          case 'random':
            response.data.sort(function() {
              return 0.5 - Math.random();
            });
            break;
          case 'recent':
            response.data = this._sortBy(response.data, 'created_time', reverse);
            break;
          case 'liked':
            response.data = this._sortBy(response.data, 'likes.count', reverse);
            break;
          case 'commented':
            response.data = this._sortBy(response.data, 'comments.count', reverse);
            break;
          default:
            throw new Error("Invalid option for sortBy: '" + this.options.sortBy + "'.");
        }
      }
      if ((typeof document !== "undefined" && document !== null) && this.options.mock === false) {
        images = response.data;
        if (this.options.limit != null) {
          if (images.length > this.options.limit) {
            images = images.slice(0, this.options.limit + 1 || 9e9);
          }
        }
        fragment = document.createDocumentFragment();
        if ((this.options.filter != null) && typeof this.options.filter === 'function') {
          images = this._filter(images, this.options.filter);
        }
        if ((this.options.template != null) && typeof this.options.template === 'string') {
          htmlString = '';
          imageString = '';
          imgUrl = '';
          tmpEl = document.createElement('div');
          for (_i = 0, _len = images.length; _i < _len; _i++) {
            image = images[_i];
            imageUrl = image.images[this.options.resolution].url;
            if (!this.options.useHttp) {
              imageUrl = imageUrl.replace('http://', '//');
            }
            imageString = this._makeTemplate(this.options.template, {
              model: image,
              id: image.id,
              link: image.link,
              image: imageUrl,
              caption: this._getObjectProperty(image, 'caption.text'),
              likes: image.likes.count,
              comments: image.comments.count,
              location: this._getObjectProperty(image, 'location.name')
            });
            htmlString += imageString;
          }
          tmpEl.innerHTML = htmlString;
          _ref = [].slice.call(tmpEl.childNodes);
          for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
            node = _ref[_j];
            fragment.appendChild(node);
          }
        } else {
          for (_k = 0, _len2 = images.length; _k < _len2; _k++) {
            image = images[_k];
            img = document.createElement('img');
            imageUrl = image.images[this.options.resolution].url;
            if (!this.options.useHttp) {
              imageUrl = imageUrl.replace('http://', '//');
            }
            img.src = imageUrl;
            if (this.options.links === true) {
              anchor = document.createElement('a');
              anchor.href = image.link;
              anchor.appendChild(img);
              fragment.appendChild(anchor);
            } else {
              fragment.appendChild(img);
            }
          }
        }
        document.getElementById(this.options.target).appendChild(fragment);
        header = document.getElementsByTagName('head')[0];
        header.removeChild(document.getElementById('instafeed-fetcher'));
        instanceName = "instafeedCache" + this.unique;
        window[instanceName] = void 0;
        try {
          delete window[instanceName];
        } catch (e) {

        }
      }
      if ((this.options.after != null) && typeof this.options.after === 'function') {
        this.options.after.call(this);
      }
      return true;
    };

    Instafeed.prototype._buildUrl = function() {
      var base, endpoint, final;
      base = "https://api.instagram.com/v1";
      switch (this.options.get) {
        case "popular":
          endpoint = "media/popular";
          break;
        case "tagged":
          if (typeof this.options.tagName !== 'string') {
            throw new Error("No tag name specified. Use the 'tagName' option.");
          }
          endpoint = "tags/" + this.options.tagName + "/media/recent";
          break;
        case "location":
          if (typeof this.options.locationId !== 'number') {
            throw new Error("No location specified. Use the 'locationId' option.");
          }
          endpoint = "locations/" + this.options.locationId + "/media/recent";
          break;
        case "user":
          if (typeof this.options.userId !== 'number') {
            throw new Error("No user specified. Use the 'userId' option.");
          }
          if (typeof this.options.accessToken !== 'string') {
            throw new Error("No access token. Use the 'accessToken' option.");
          }
          endpoint = "users/" + this.options.userId + "/media/recent";
          break;
        default:
          throw new Error("Invalid option for get: '" + this.options.get + "'.");
      }
      final = "" + base + "/" + endpoint;
      if (this.options.accessToken != null) {
        final += "?access_token=" + this.options.accessToken;
      } else {
        final += "?client_id=" + this.options.clientId;
      }
      if (this.options.limit != null) {
        final += "&count=" + this.options.limit;
      }
      final += "&callback=instafeedCache" + this.unique + ".parse";
      return final;
    };

    Instafeed.prototype._genKey = function() {
      var S4;
      S4 = function() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      };
      return "" + (S4()) + (S4()) + (S4()) + (S4());
    };

    Instafeed.prototype._makeTemplate = function(template, data) {
      var output, pattern, varName, varValue, _ref;
      pattern = /(?:\{ {2})([\w\[\]\.]+)(?:\}{2})/;
      output = template;
      while (pattern.test(output)) {
        varName = output.match(pattern)[1];
        varValue = (_ref = this._getObjectProperty(data, varName)) != null ? _ref : '';
        output = output.replace(pattern, "" + varValue);
      }
      return output;
    };

    Instafeed.prototype._getObjectProperty = function(object, property) {
      var piece, pieces;
      property = property.replace(/\[(\w+)\]/g, '.$1');
      pieces = property.split('.');
      while (pieces.length) {
        piece = pieces.shift();
        if ((object != null) && piece in object) {
          object = object[piece];
        } else {
          return null;
        }
      }
      return object;
    };

    Instafeed.prototype._sortBy = function(data, property, reverse) {
      var sorter;
      sorter = function(a, b) {
        var valueA, valueB;
        valueA = this._getObjectProperty(a, property);
        valueB = this._getObjectProperty(b, property);
        if (reverse) {
          if (valueA > valueB) {
            return 1;
          } else {
            return -1;
          }
        }
        if (valueA < valueB) {
          return 1;
        } else {
          return -1;
        }
      };
      data.sort(sorter.bind(this));
      return data;
    };

    Instafeed.prototype._filter = function(images, filter) {
      var filteredImages, image, _fn, _i, _len;
      filteredImages = [];
      _fn = function(image) {
        if (filter(image)) {
          return filteredImages.push(image);
        }
      };
      for (_i = 0, _len = images.length; _i < _len; _i++) {
        image = images[_i];
        _fn(image);
      }
      return filteredImages;
    };

    return Instafeed;

  })();

  root = typeof exports !== "undefined" && exports !== null ? exports : window;

  root.Instafeed = Instafeed;

}).call(this);


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 32(6): 693 (1940)

#### Original name
Ceracea canadensis H.S. Jacks. & G.W. Martin, 1940

### Remarks
null


text:
let plugin = require('..').plugin

exports.getUsers = (output, tokens) => {
  let users = plugin.userController.getUsers()
  output.log('All users:')
  users.forEach((u) => {
    output.log('\t' + u)
  })
  if (users.length === 0) {
    output.log('\tNone.')
  }
}


text:
package com.google.firebase.quickstart.fcm;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.firebase.jobdispatcher.Constraint;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]

    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}


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

namespace w_time.data.schema
{
    class BigIntColumn : Column {
        public BigIntColumn() { this._Type = DataType.bigint; }
    }

    class IntegerColumn : Column
    {
        public IntegerColumn() { this._Type = DataType.integer; }
    }

    class SmallIntColumn : Column
    {
        public SmallIntColumn() { this._Type = DataType.smallint; }
    }

    class TinyIntColumn : Column
    {
        public TinyIntColumn() { this._Type = DataType.tinyint; }
    }

    class BitColumn : Column
    {
        public BitColumn() { this._Type = DataType.bit; }
    }

    class NumericColumn : Column
    {
        public int Precision;
        public int Scale;

        public NumericColumn(int Precision, int Scale)
        {
            this._Type = DataType.numeric;
            this.Precision = Precision;
            this.Scale = Scale;
        }

        protected override string GetColumnTypeSize()
        {
            return String.Format("({0}, {1})", this.Precision, this.Scale);
        }
    }

    class MoneyColumn : Column
    {
        public MoneyColumn() { this._Type = DataType.money; }
    }

    class FloatColumn : Column
    {
        public FloatColumn() { this._Type = DataType.@float; }
    }

    class RealColumn : Column
    {
        public RealColumn() { this._Type = DataType.real; }
    }

    class DateTimeColumn : Column
    {
        public DateTimeColumn() { this._Type = DataType.datetime; }
    }

    class NCharColumn : Column
    {
        public int Length;

        public NCharColumn(int Length)
        {
            this._Type = DataType.nchar;
            this.Length = Length;
        }

        protected override string GetColumnTypeSize()
        {
            return String.Format("({0})", this.Length);
        }
    }

    class NVarCharColumn : Column
    {
        public int MaxLength;

        public NVarCharColumn(int MaxLength)
        {
            this._Type = DataType.nvarchar;
            this.MaxLength = MaxLength;
        }

        protected override string GetColumnTypeSize()
        {
            return String.Format("({0})", this.MaxLength);
        }
    }

    class NTextColumn : Column
    {
        public NTextColumn() { this._Type = DataType.ntext; }
    }

    class BinaryColumn : Column
    {
        public int Length;

        public BinaryColumn(int Length)
        {
            this._Type = DataType.binary;
            this.Length = Length;
        }

        protected override string GetColumnTypeSize()
        {
            return String.Format("({0})", this.Length);
        }
    }

    class VarBinaryColumn : Column
    {
        public int MaxLength;
        public VarBinaryColumn(int MaxLength)
        {
            this._Type = DataType.varbinary;
            this.MaxLength = MaxLength;
        }

        protected override string GetColumnTypeSize()
        {
            return String.Format("({0})", this.MaxLength);
        }
    }

    class ImageColumn : Column
    {
        public ImageColumn() { this._Type = DataType.image; }
    }

    class UniqueIdentifierColumn : Column
    {
        public UniqueIdentifierColumn() { this._Type = DataType.uniqueidentifier; }
    }

    class PrimaryKeyIntColumn : Column
    {
        /// <summary>
        /// Integer Primary key Column
        /// </summary>
        /// <param name="type">Integer Data Type</param>
        public PrimaryKeyIntColumn(DataType type = DataType.integer)
        {
            this.Name = "ID";
            this._Type = type;
            this.IsPrimaryKey = true;
            this.IsIdentity = true;
            this.IdentityIncrement = 1;
            this.IdentitySeed = 1;
        }
    }
}


text:
//  Estimote Fleet Management SDK
//  Copyright © 2015 Estimote. All rights reserved.

#import <Foundation/Foundation.h>
#import "ESTBeaconOperationProtocol.h"
#import "ESTSettingOperation.h"
#import "ESTSettingDeviceInfoUptime.h"

NS_ASSUME_NONNULL_BEGIN

/**
 *  ESTBeaconOperationDeviceInfoUptime allows to create read operations for DeviceInfo Uptime setting of a device.
 */
@interface ESTBeaconOperationDeviceInfoUptime : ESTSettingOperation <ESTBeaconOperationProtocol>

/**
 *  Method allows to create read operation for DeviceInfo Uptime setting.
 *
 *  @param completion Block invoked when the operation is complete.
 *
 *  @return Initialized object.
 */
+ (instancetype)readOperationWithCompletion:(ESTSettingDeviceInfoUptimeCompletionBlock)completion;

@end

NS_ASSUME_NONNULL_END


text:
layout: default
description: Arangoexport Options
---
Arangoexport Options
====================

Usage: `arangoexport [<options>]`

{% assign optionsFile = page.version.version | remove: "." | append: "-program-options-arangoexport" -%}
{% assign options = site.data[optionsFile] -%}
{% include program-option.html options=options name="arangoexport" %}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using Microsoft.Win32;
using Newtonsoft.Json;
using Rally.RestApi;
using RallyToolsCore.Properties;
using TrackGearLibrary.Core;
using TrackGearLibrary.Rally.Columns;
using TrackGearLibrary.Svn;
using UIControls.Core;

namespace TrackGearLibrary.Rally
{
	public partial class RallyTool : Form
	{
		const string CurrentIterationMarker = "E39F6C98-C157-4E11-9895-A161BD8E2A89";

		public Artifact[] SelectedWorkItems;

		readonly List<VirtualListItemArtifact> _filteredIssues = new List<VirtualListItemArtifact>();
		readonly List<VirtualListItemArtifact> _allIssues = new List<VirtualListItemArtifact>();

		readonly ColumnsCollection _columns;
		readonly string _commonRoot;
		readonly bool _selectIssuesMode;

		class LoadArtifactsBgOperation
		{
			public Task<List<Artifact>> Task;
			public CancellationTokenSource Cts;
		}

		LoadArtifactsBgOperation _firstArtifactsLoad;

		public static Color ChangedFilter = Color.Yellow;
		public static Color AppliedFilter = Color.LightGreen;
		public static Color EmptyFilter = Color.White;

		public readonly string _vssPowerToolsPath;

		public RallyTool(bool selectIssuesMode, string commonRoot)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyTool);

			_selectIssuesMode = selectIssuesMode;
			_commonRoot = commonRoot;

			InitializeComponent();

			Observable
				.FromEventPattern<EventHandler, EventArgs>(h => textBoxNameFilter.TextChanged += h, h => textBoxNameFilter.TextChanged -= h)
				.Do(_ => textBoxNameFilter.BackColor = ChangedFilter)
				.Throttle(TimeSpan.FromMilliseconds(500))
				.ObserveOn(SynchronizationContext.Current)
				.Subscribe(_ => UpdateFilteredArtifactsList())
			;

			var ver = new NewVersionControl();
			ver.Name = "VersionChecker";
			ver.Anchor = versionPlaceholder.Anchor;
			ver.Location = versionPlaceholder.Location;
			ver.Size = versionPlaceholder.Size;

			Controls.Add(ver);
			Controls.Remove(versionPlaceholder);

			_columns = InitColumns();

			// try find external tools
			try
			{
				using (var rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\VssPowerTools.exe", false))
				{
					_vssPowerToolsPath = (string)rk.GetValue(null);
				}
			}
			catch (Exception ex)
			{
				_vssPowerToolsPath = null;
				Logger.LogIt("Error: {0}", ex);
			}

			if(_vssPowerToolsPath == null)
			{
				sourceSafeCommitsToolStripMenuItem.Text += " (not installed)";
			}
		}

		void RallyTool_Load(object sender, EventArgs e)
		{
			Text = Text + " (ver. " + NewVersionControl.ProductVersion + ")";

			if(string.IsNullOrWhiteSpace(Settings.Default.RallyUser))
			{
				if (new RallySettings().ShowDialog() == DialogResult.OK)
				{
					// force refresh query
					Settings.Default.RallyQuery = null;
					EnsureQueryValid();
				}
			}

			// start loading artifacts on every form opening.
			// sometitme it will be in bg, sometime in fg
			_firstArtifactsLoad = StartLoadArtifacts();

			var lastUpdate = DateTimeOffset.MinValue;
			var artifacts = LoadCachedArtifacts(ref lastUpdate);

			if (artifacts != null)
			{
				SetArtifactsList(artifacts, lastUpdate);

				// and force update list if fingerprints does not match
				_firstArtifactsLoad
					.Task
					.ContinueWith(t => {
							var freshArtifacts = t.Result;
							if(CalcFingerprint(_filteredIssues.Select(i => i.WorkItem)) != CalcFingerprint(freshArtifacts))
							{
								SetArtifactsList(freshArtifacts, DateTimeOffset.Now);
							}
						},
						_firstArtifactsLoad.Cts.Token, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext()
					)
				;
			}
			else
			{
				// force open 'wait for refresh' dialog
				RefreshArtifactsList();
			}
		}

		void EnsureQueryValid()
		{
			if (string.IsNullOrWhiteSpace(Settings.Default.RallyQuery))
			{
				var userName = Settings.Default.RallyUser;

				try
				{
					var rr = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword);

					var currentUser = rr.GetCurrentUser("UserName");

					userName = (string)currentUser["UserName"];
				}
				catch
				{
				}

				var ownerClause = string.Format("(Owner.Name = \"{0}\")", userName);

				Settings.Default.RallyQuery = string.Format("({0} and ((State < \"Completed\") or (State < \"Closed\")))", ownerClause);

				textBoxQuery.Text = Settings.Default.RallyQuery;

				Settings.Default.Save();
			}
		}

		void optionsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolSettings);
			if (new RallySettings().ShowDialog() == DialogResult.OK)
			{
				// regenerate query
				Settings.Default.RallyQuery = null;
				EnsureQueryValid();
				RefreshArtifactsList();
			}
		}

		static string CalcFingerprint(IEnumerable<Artifact> artifacts)
		{
			return string.Join(";", artifacts.Select(a => string.Format("{0}x{1}", a.ObjectID, a.Version)));
		}

		IDisposable LockControlsForRefresh()
		{
			Action<bool> enableControls = enable =>
			{
				listViewIssues.Enabled = enable;
				textBoxQuery.Enabled = enable;
				buttonApplyQuery.Enabled = enable;
				buttonOK.Enabled = enable;
			};

			enableControls(false);

			return Disposable.Create(() => enableControls(true));
		}

		void RefreshArtifactsList()
		{
			try
			{
				EnsureQueryValid();

				var refreshOperation = StartOrPickupLoadArtifacts();

				var lockControls = LockControlsForRefresh();

				backgroundRefreshOperation
					.TrackWithCancellation(refreshOperation.Task, refreshOperation.Cts)
					.ContinueWith(t => {

						lockControls.Dispose();

						if (t.IsFaulted)
						{
							Debug.Assert(t.Exception != null);
							var ex = t.Exception.InnerException;
							MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
							return;
						}

						if (t.Status == TaskStatus.Canceled)
							return;

						SetArtifactsList(t.Result, DateTimeOffset.Now);

					}, TaskScheduler.FromCurrentSynchronizationContext())
				;
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		class IterationFilterItem
		{
			public readonly IterationArtifact Artifact;

			public readonly string FilterName;

			static int _maxIterationNameLength;
			static readonly Regex NameShorter = new Regex(@"\s+iteration\s*#", RegexOptions.IgnoreCase);

			public readonly HashSet<long> IterationIds = new HashSet<long>();

			public IterationFilterItem(IterationArtifact itArt)
			{
				Artifact = itArt;

				if (Artifact == null)
				{
					FilterName = "All";
				}
				else if (Artifact.IsNullArtifact)
				{
					FilterName = "N/A";
					IterationIds.Add(0);
				}
				else
				{
					if (Artifact.IsCurrentIteration)
						FilterName = "=> ";
					else
						FilterName = "   ";

					var iterationName = GetIterationName(Artifact).PadRight(_maxIterationNameLength);

					FilterName = FilterName + iterationName + " [" + Artifact.StartDate.LocalDateTime.ToString("dd MMM") + " - " + Artifact.EndDate.LocalDateTime.ToString("dd MMM") + "]";

					IterationIds.Add(Artifact.ObjectID);
				}
			}

			static string GetIterationName(Artifact art)
			{
				if(art == null)
					return string.Empty;

				return NameShorter.Replace(art.Name ?? "", " It#");
			}

			// calculate pretty padding
			public static void ApplyAllIterationsList(List<IterationArtifact> arts)
			{
				if (arts.Count == 1)
					_maxIterationNameLength = GetIterationName(arts[0]).Length;
				else if (arts.Count > 1)
					_maxIterationNameLength = arts.Select(art => GetIterationName(art).Length).Max();
				else
					_maxIterationNameLength = 0;
			}

			public override string ToString()
			{
				return FilterName;
			}
		}

		void SetArtifactsList(List<Artifact> artifacts, DateTimeOffset updateTime)
		{
			comboBoxIterationsFilter.BeginUpdate();
			try
			{
				// set last update time
				simplifiedBackgroundOperation.Text = string.Format("Last refresh: {0:g}", updateTime);

				// prepare virtual items
				_allIssues.Clear();
				_allIssues.AddRange(artifacts.Select(a => new VirtualListItemArtifact(a, _columns)));

				// load iterations
				comboBoxIterationsFilter.Items.Clear();
				var itId2It = artifacts
					.Select(a => a.Iteration)
					.GroupBy(it => it.ObjectID)
					.Select(itg => itg.First())
					.ToDictionary(it => it.ObjectID, it => it)
				;

				IterationFilterItem.ApplyAllIterationsList(itId2It.Values.ToList());

				// default selection - all
				var selectedIndex = 0;
				comboBoxIterationsFilter.Items.Add(new IterationFilterItem(null));

				var itName2Filter = new Dictionary<string, IterationFilterItem>();

				foreach (var kvp in itId2It.OrderBy(kvp => kvp.Value.StartDate))
				{
					// it is possible situation when iteration name equal, but iteration objects - different (separate for each team)
					// merge them into one filter
					var filter = new IterationFilterItem(kvp.Value);
					IterationFilterItem existingFilter;
					if(itName2Filter.TryGetValue(filter.FilterName, out existingFilter))
					{
						existingFilter.IterationIds.Add(kvp.Value.ObjectID);
						continue;
					}
					comboBoxIterationsFilter.Items.Add(filter);
					itName2Filter[filter.FilterName] = filter;

					// skip selection if 'all' in preferences
					if (string.IsNullOrEmpty(Settings.Default.IterationFilter))
						continue;

					if (Settings.Default.IterationFilter == filter.FilterName)
					{
						selectedIndex = comboBoxIterationsFilter.Items.Count - 1;
						continue;
					}

					if (Settings.Default.IterationFilter == CurrentIterationMarker && kvp.Value.IsCurrentIteration)
					{
						selectedIndex = comboBoxIterationsFilter.Items.Count - 1;
						continue;
					}
				}

				// raise refill artifacts list
				comboBoxIterationsFilter.SelectedIndex = selectedIndex;
			}
			finally
			{
				comboBoxIterationsFilter.EndUpdate();
			}
		}

		IEnumerable<VirtualListItemArtifact> ApplyFilters(List<VirtualListItemArtifact> all)
		{
			var itFilter = comboBoxIterationsFilter.SelectedItem as IterationFilterItem;

			IEnumerable<VirtualListItemArtifact> filtered = all;

			if (checkBoxHideDefectSubtasks.Checked)
				filtered = filtered.Where(a => a.WorkItem.Parent.Type != ArtifactType.Defect);

			filtered = FilterNoiseTasks(filtered);

			if (itFilter != null && itFilter.Artifact != null)
				filtered = filtered.Where(ar => itFilter.IterationIds.Contains(ar.WorkItem.Iteration.ObjectID));

			var nameFilter = textBoxNameFilter.Text.ToLowerInvariant();
			if (!string.IsNullOrWhiteSpace(nameFilter))
			{
				filtered = filtered.Where(ar => (ar.WorkItem.Name ?? "").ToLowerInvariant().Contains(nameFilter));
				textBoxNameFilter.BackColor = AppliedFilter;
			}
			else
			{
				textBoxNameFilter.BackColor = EmptyFilter;
			}

			return filtered;
		}

		IEnumerable<VirtualListItemArtifact> FilterNoiseTasks(IEnumerable<VirtualListItemArtifact> items)
		{
			checkBoxHideNoiseTasks.BackColor = BackColor;
			if (!checkBoxHideNoiseTasks.Checked || string.IsNullOrWhiteSpace(Settings.Default.NoiseTaskRegex))
				return items;

			try
			{
				var rx = new Regex(Settings.Default.NoiseTaskRegex, RegexOptions.IgnoreCase);
				return items.Where(i => !rx.IsMatch(i.WorkItem.Name));
			}
			catch
			{
				checkBoxHideNoiseTasks.BackColor = Color.LightPink;
				return items;
			}
		}

		void UpdateFilteredArtifactsList()
		{
			// save selection
			var selectedArtifacts = listViewIssues.SelectedIndices.Cast<int>().Select(i => _filteredIssues[i].WorkItem).ToList();
			var focusedArtifact = listViewIssues.FocusedItem != null ? _filteredIssues[listViewIssues.FocusedItem.Index].WorkItem : null;

			listViewIssues.BeginUpdate();
			try
			{
				// prepare filtered virtual items
				listViewIssues.VirtualListSize = 0;
				_filteredIssues.Clear();
				_filteredIssues.AddRange(ApplyFilters(_allIssues));

				// reset sorting
				_columns.SortColumn = -1;
				_columns.PrevSortColumn = -1;

				foreach (ColumnHeader hdr in listViewIssues.Columns)
					hdr.Text = ((ColumnBase)hdr.Tag).Header;

				// clear selection
				listViewIssues.SelectedIndices.Clear();

				listViewIssues.VirtualListSize = _filteredIssues.Count;

				// restore selection
				foreach (var old in selectedArtifacts)
				{
					for (var i = 0; i < _filteredIssues.Count; i++)
					{
						if (_filteredIssues[i].WorkItem.ObjectID == old.ObjectID)
						{
							listViewIssues.SelectedIndices.Add(i);
							break;
						}
					}
				}

				// restore focused
				if (focusedArtifact != null)
				{
					for (var i = 0; i < _filteredIssues.Count; i++)
					{
						if (_filteredIssues[i].WorkItem.ObjectID == focusedArtifact.ObjectID)
						{
							listViewIssues.FocusedItem = _filteredIssues[i].ListItem;
							listViewIssues.EnsureVisible(i);
							break;
						}
					}
				}

				// do not steal focus from name filter
				if(!textBoxNameFilter.Focused)
					listViewIssues.Focus();
			}
			finally
			{
				listViewIssues.EndUpdate();
			}
		}

		void comboBoxIterationsFilter_SelectedIndexChanged(object sender, EventArgs e)
		{
			var filter = comboBoxIterationsFilter.SelectedItem as IterationFilterItem;

			UpdateFilteredArtifactsList();

			// save selection
			if (filter == null || filter.Artifact == null)
				Settings.Default.IterationFilter = "";
			else if (filter.Artifact.IsCurrentIteration)
				Settings.Default.IterationFilter = CurrentIterationMarker;
			else
				Settings.Default.IterationFilter = filter.FilterName;

			Settings.Default.Save();
		}

		LoadArtifactsBgOperation StartOrPickupLoadArtifacts()
		{
			// pickup progressed background operation
			if (_firstArtifactsLoad != null)
			{
				var op = _firstArtifactsLoad;
				_firstArtifactsLoad = null;

				if (!op.Task.IsCompleted)
					return op;
			}

			return StartLoadArtifacts();
		}

		LoadArtifactsBgOperation StartLoadArtifacts()
		{
			var op = new LoadArtifactsBgOperation { Cts = new CancellationTokenSource() };

			op.Task = Task.Factory.StartNew(() => {
				try
				{
					return LoadArtifacts(op.Cts.Token);
				}
				finally
				{
					op.Cts.Dispose();
					op.Cts = null;
				}
			}, op.Cts.Token);

			simplifiedBackgroundOperation.Track(op.Task, "Refreshing...");

			return op;
		}

		// load issues list
		List<Artifact> LoadArtifacts(CancellationToken ct)
		{
			var artifacts = new List<DynamicJsonObject>();

			var restApi = new RallyRestApi(Settings.Default.RallyUser, Settings.Default.RallyPassword
				//, proxy: new WebProxy("localhost:8888", false)
				, cancellationToken: ct
			);

			var query = new Query(Settings.Default.RallyQuery);

			{
				backgroundRefreshOperation.SetProgress("Loading defects  ...");

				var request = new Request("defect");
				request.Limit = Int32.MaxValue;
				request.Fetch = new List<string> { "FormattedID", "Requirement", "Name", "Project", "ObjectID", "Iteration", "EndDate", "StartDate" };
				request.Order = "Iteration";
				request.Query = query;

				// perfrom query
				var response = restApi.Query(request);
				artifacts.AddRange(response.Results.Select(a => (DynamicJsonObject)a));
			}

			ct.ThrowIfCancellationRequested();

			{
				backgroundRefreshOperation.SetProgress("Loading tasks ...");

				var request = new Request("task");
				request.Limit = Int32.MaxValue;
				request.Fetch = new List<string> { "FormattedID", "WorkProduct", "Name", "Project", "ObjectID", "Iteration", "EndDate", "StartDate" };
				request.Order = "Iteration";
				request.Query = query;

				// perfrom query
				var response = restApi.Query(request);
				artifacts.AddRange(response.Results.Select(a => (DynamicJsonObject)a));
			}

			// update cache
			UpdateCache(artifacts);

			var list = artifacts
				.Select(w => new Artifact(w))
				.ToList()
			;

			// move defect tasks immediately after defects
			for (var i = 0; i < list.Count; i++)
			{
				if(list[i].Parent.Type == ArtifactType.Defect)
				{
					// find defect in list
					var parentIndex = list.FindIndex(a => a.ObjectID == list[i].Parent.ObjectID);

					// if parent found and parent is not direct preceder
					if (parentIndex != -1 && parentIndex != (i - 1))
					{
						var task = list[i];
						list.RemoveAt(i);
						list.Insert(parentIndex + 1, task);
					}
				}
			}

			return list;
		}

		void UpdateCache(IEnumerable<DynamicJsonObject> artifacts)
		{
			var d = new Dictionary<string, object>();
			d["Query"] = textBoxQuery.Text;
			d["UpdateTime"] = DateTimeOffset.Now.Ticks.ToString(CultureInfo.InvariantCulture);
			d["Artifacts"] = artifacts.Select(djo => djo.ToDictionary()).ToList();
			var cache = JsonConvert.SerializeObject(d, Formatting.Indented);

			var dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Constants.AppDataDirName);
			Directory.CreateDirectory(dir);

			var path = Path.Combine(dir, "cache.json");

			File.WriteAllText(path, cache);
		}

		List<Artifact> LoadCachedArtifacts(ref DateTimeOffset update)
		{
			var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Constants.AppDataDirName, "cache.json");

			if (!File.Exists(path))
				return null;

			try
			{
				var json = File.ReadAllText(path);

				var dict = new JavaScriptSerializer { MaxJsonLength = 10 * 1024 * 1024 }.Deserialize<Dictionary<string, object>>(json);

				if ((string)dict["Query"] != textBoxQuery.Text)
					return null;

				update = new DateTimeOffset(long.Parse((string)dict["UpdateTime"]), TimeSpan.Zero);

				// cache expired
				if ((update - DateTimeOffset.Now) > TimeSpan.FromDays(1))
					return null;

				return ((ArrayList)dict["Artifacts"])
					.Cast<Dictionary<string, object>>()
					.Select(d => new Artifact(new DynamicJsonObject(d)))
					.ToList()
				;
			}
			catch (Exception)
			{
			}

			return null;
		}

		ColumnsCollection InitColumns()
		{
			// init list view with columns
			var columns = new ColumnsCollection();
			var cols = new List<ColumnBase> {
				new FormattedIDColumn { Width = 90 },
				new IterationColumn { Width = 150 },
				new WorkItemNameColumn { Width = 400 },
				new ParentColumn { Width = 400 }
			};

			columns.Columns = cols.ToArray();

			listViewIssues.Columns.Clear();
			var colHdrs = columns
				.Columns
				.Select(col => new ColumnHeader {
					TextAlign = col.TextAlign,
					Text = col.Header,
					Width = col.Width,
					Tag = col
				})
				.ToArray()
			;

			listViewIssues.Columns.AddRange(colHdrs);

			return columns;
		}

		void listViewIssues_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
		{
			e.Item = _filteredIssues[e.ItemIndex].ListItem;
		}

		void buttonOK_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolOK);
			GatherSelectedItems();
			DialogResult = DialogResult.OK;
			Close();
		}

		void GatherSelectedItems()
		{
			SelectedWorkItems = listViewIssues.SelectedIndices.Cast<int>().Select(i => _filteredIssues[i].WorkItem).ToArray();
		}

		void listViewIssues_DoubleClick(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolItemDblClick);

			if (_selectIssuesMode)
			{
				GatherSelectedItems();
				DialogResult = DialogResult.OK;
				return;
			}

			var wi = _filteredIssues[listViewIssues.FocusedItem.Index].WorkItem;

			if(wi.Url != null)
				Process.Start(wi.Url);
		}

		void buttonApplyQuery_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolApplyQuery);
			Settings.Default.Save();
			RefreshArtifactsList();
		}

		void sourceSafeCommitsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolSSCommits);

			if(_vssPowerToolsPath == null)
			{
				Process.Start("https://github.com/azarkevich/VssPowerTools/releases");
			}
			else
			{
				var p = new Process { StartInfo = new ProcessStartInfo { FileName = _vssPowerToolsPath } };
				p.Start();
			}
		}

		void buildsListToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolStartBB);
			Process.Start(Settings.Default.BuildsBoardUri);
		}

		void svnLogToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolStartSvnLog);
			new SvnLog(_commonRoot).ShowDialog(this);
		}

		void dailyReportGeneratorToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolStartDailyReport);
			new DailyReport().ShowDialog(this);
		}

		void openOnRallyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolContextMenuOpenOnRally);
			listViewIssues
				.SelectedIndices
				.Cast<int>()
				.Select(i => _filteredIssues[i].WorkItem)
				.ToList()
				.ForEach(a => Process.Start(a.Url))
			;
		}

		void copyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolContextMenuCopy);
			var names = listViewIssues
				.SelectedIndices
				.Cast<int>()
				.Select(i => _filteredIssues[i].WorkItem)
				.Select(arr => string.Format("{0} {1}", arr.FormattedID, arr.Name))
				.ToArray()
			;

			var text = string.Join("\n", names);

			Clipboard.SetText(text);
		}

		void refreshToolStripMenuItem_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolContextMenuRefresh);
			RefreshArtifactsList();
		}

		void buttonIterationFilterPrev_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolIterationFilterPrev);
			if (comboBoxIterationsFilter.SelectedIndex > 0)
				comboBoxIterationsFilter.SelectedIndex--;
		}

		void buttonIterationFilterNext_Click(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolIterationFilterNext);
			if (comboBoxIterationsFilter.SelectedIndex < (comboBoxIterationsFilter.Items.Count - 1))
				comboBoxIterationsFilter.SelectedIndex++;
		}

		void textBoxNameFilter_TextChanged(object sender, EventArgs e)
		{

		}

		void checkBoxHideDefectSubtasks_CheckedChanged(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolShowHideDefectsSubtasks);
			UpdateFilteredArtifactsList();
		}

		private void checkBoxHideNoiseTasks_CheckedChanged(object sender, EventArgs e)
		{
			UsageMetrics.IncrementUsage(UsageMetrics.UsageKind.RallyToolShowHideNoiseTasks);
			UpdateFilteredArtifactsList();
		}
	}
}


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class io_nondev_nonlua_Lua */

#ifndef _Included_io_nondev_nonlua_Lua
#define _Included_io_nondev_nonlua_Lua
#ifdef __cplusplus
extern "C" {
#endif
#undef io_nondev_nonlua_Lua_GLOBALS
#define io_nondev_nonlua_Lua_GLOBALS -10002L
#undef io_nondev_nonlua_Lua_REGISTRY
#define io_nondev_nonlua_Lua_REGISTRY -10000L
#undef io_nondev_nonlua_Lua_NONE
#define io_nondev_nonlua_Lua_NONE -1L
#undef io_nondev_nonlua_Lua_NIL
#define io_nondev_nonlua_Lua_NIL 0L
#undef io_nondev_nonlua_Lua_BOOLEAN
#define io_nondev_nonlua_Lua_BOOLEAN 1L
#undef io_nondev_nonlua_Lua_LIGHTUSERDATA
#define io_nondev_nonlua_Lua_LIGHTUSERDATA 2L
#undef io_nondev_nonlua_Lua_NUMBER
#define io_nondev_nonlua_Lua_NUMBER 3L
#undef io_nondev_nonlua_Lua_STRING
#define io_nondev_nonlua_Lua_STRING 4L
#undef io_nondev_nonlua_Lua_TABLE
#define io_nondev_nonlua_Lua_TABLE 5L
#undef io_nondev_nonlua_Lua_FUNCTION
#define io_nondev_nonlua_Lua_FUNCTION 6L
#undef io_nondev_nonlua_Lua_USERDATA
#define io_nondev_nonlua_Lua_USERDATA 7L
#undef io_nondev_nonlua_Lua_THREAD
#define io_nondev_nonlua_Lua_THREAD 8L
#undef io_nondev_nonlua_Lua_MULTRET
#define io_nondev_nonlua_Lua_MULTRET -1L
#undef io_nondev_nonlua_Lua_YIELD
#define io_nondev_nonlua_Lua_YIELD 1L
#undef io_nondev_nonlua_Lua_ERR_RUNTIME
#define io_nondev_nonlua_Lua_ERR_RUNTIME 2L
#undef io_nondev_nonlua_Lua_ERR_SYNTAX
#define io_nondev_nonlua_Lua_ERR_SYNTAX 3L
#undef io_nondev_nonlua_Lua_ERR_MEMORY
#define io_nondev_nonlua_Lua_ERR_MEMORY 4L
#undef io_nondev_nonlua_Lua_ERR_HANDLER
#define io_nondev_nonlua_Lua_ERR_HANDLER 5L
/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniOpen
 * Signature: (I)Lio/nondev/nonlua/CPtr;
 */
JNIEXPORT jobject JNICALL Java_io_nondev_nonlua_Lua_jniOpen
  (JNIEnv *, jclass, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniClose
 * Signature: (Lio/nondev/nonlua/CPtr;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniClose
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniOpenJava
 * Signature: (Lio/nondev/nonlua/CPtr;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniOpenJava
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniLoadBuffer
 * Signature: (Lio/nondev/nonlua/CPtr;[BJLjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniLoadBuffer
  (JNIEnv *, jclass, jobject, jbyteArray, jlong, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniLoadString
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniLoadString
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniRunBuffer
 * Signature: (Lio/nondev/nonlua/CPtr;[BJLjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniRunBuffer
  (JNIEnv *, jclass, jobject, jbyteArray, jlong, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniRunString
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniRunString
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniNewThread
 * Signature: (Lio/nondev/nonlua/CPtr;)Lio/nondev/nonlua/CPtr;
 */
JNIEXPORT jobject JNICALL Java_io_nondev_nonlua_Lua_jniNewThread
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushNil
 * Signature: (Lio/nondev/nonlua/CPtr;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushNil
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushNumber
 * Signature: (Lio/nondev/nonlua/CPtr;D)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushNumber
  (JNIEnv *, jclass, jobject, jdouble);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushString
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushString
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushBoolean
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushBoolean
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushFunction
 * Signature: (Lio/nondev/nonlua/CPtr;Lio/nondev/nonlua/LuaFunction;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushFunction
  (JNIEnv *, jclass, jobject, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushObject
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/Object;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushObject
  (JNIEnv *, jclass, jobject, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushArray
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/Object;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushArray
  (JNIEnv *, jclass, jobject, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsNumber
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsNumber
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsBoolean
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsBoolean
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsString
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsString
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsFunction
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsFunction
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsObject
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsObject
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsTable
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsTable
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsUserdata
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsUserdata
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsNil
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsNil
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniIsNone
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniIsNone
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniToNumber
 * Signature: (Lio/nondev/nonlua/CPtr;I)D
 */
JNIEXPORT jdouble JNICALL Java_io_nondev_nonlua_Lua_jniToNumber
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniToBoolean
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniToBoolean
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniToString
 * Signature: (Lio/nondev/nonlua/CPtr;I)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_io_nondev_nonlua_Lua_jniToString
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniToObject
 * Signature: (Lio/nondev/nonlua/CPtr;I)Ljava/lang/Object;
 */
JNIEXPORT jobject JNICALL Java_io_nondev_nonlua_Lua_jniToObject
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetGlobal
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniGetGlobal
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSetGlobal
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniSetGlobal
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGet
 * Signature: (Lio/nondev/nonlua/CPtr;ILjava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniGet
  (JNIEnv *, jclass, jobject, jint, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSet
 * Signature: (Lio/nondev/nonlua/CPtr;ILjava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniSet
  (JNIEnv *, jclass, jobject, jint, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetI
 * Signature: (Lio/nondev/nonlua/CPtr;II)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniGetI
  (JNIEnv *, jclass, jobject, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSetI
 * Signature: (Lio/nondev/nonlua/CPtr;II)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniSetI
  (JNIEnv *, jclass, jobject, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetTop
 * Signature: (Lio/nondev/nonlua/CPtr;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniGetTop
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSetTop
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniSetTop
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPop
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPop
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPushValue
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniPushValue
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniRemove
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniRemove
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniInsert
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniInsert
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniReplace
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniReplace
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniConcat
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniConcat
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGsub
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_io_nondev_nonlua_Lua_jniGsub
  (JNIEnv *, jclass, jobject, jstring, jstring, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniLen
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniLen
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniEqual
 * Signature: (Lio/nondev/nonlua/CPtr;II)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniEqual
  (JNIEnv *, jclass, jobject, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniNext
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniNext
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniError
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniError
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniWhere
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniWhere
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniType
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniType
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniTypeName
 * Signature: (Lio/nondev/nonlua/CPtr;I)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_io_nondev_nonlua_Lua_jniTypeName
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniRef
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniRef
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniUnRef
 * Signature: (Lio/nondev/nonlua/CPtr;II)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniUnRef
  (JNIEnv *, jclass, jobject, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniCall
 * Signature: (Lio/nondev/nonlua/CPtr;II)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniCall
  (JNIEnv *, jclass, jobject, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniPcall
 * Signature: (Lio/nondev/nonlua/CPtr;III)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniPcall
  (JNIEnv *, jclass, jobject, jint, jint, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniNewTable
 * Signature: (Lio/nondev/nonlua/CPtr;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniNewTable
  (JNIEnv *, jclass, jobject);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetTable
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniGetTable
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSetTable
 * Signature: (Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniSetTable
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniNewMetatable
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniNewMetatable
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetMetatable
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniGetMetatable
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetMetatableStr
 * Signature: (Lio/nondev/nonlua/CPtr;Ljava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniGetMetatableStr
  (JNIEnv *, jclass, jobject, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniSetMetatable
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniSetMetatable
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniCallmeta
 * Signature: (Lio/nondev/nonlua/CPtr;ILjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniCallmeta
  (JNIEnv *, jclass, jobject, jint, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniGetmeta
 * Signature: (Lio/nondev/nonlua/CPtr;ILjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniGetmeta
  (JNIEnv *, jclass, jobject, jint, jstring);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniMove
 * Signature: (Lio/nondev/nonlua/CPtr;Lio/nondev/nonlua/CPtr;I)V
 */
JNIEXPORT void JNICALL Java_io_nondev_nonlua_Lua_jniMove
  (JNIEnv *, jclass, jobject, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniYield
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniYield
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniResume
 * Signature: (Lio/nondev/nonlua/CPtr;I)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniResume
  (JNIEnv *, jclass, jobject, jint);

/*
 * Class:     io_nondev_nonlua_Lua
 * Method:    jniStatus
 * Signature: (Lio/nondev/nonlua/CPtr;)I
 */
JNIEXPORT jint JNICALL Java_io_nondev_nonlua_Lua_jniStatus
  (JNIEnv *, jclass, jobject);

#ifdef __cplusplus
}
#endif
#endif


text:
angular.module('starter.controllers', [])

.controller('appCtrl', function($scope, $ionicModal, $timeout) {
    $scope.openNativeSettings = function() {
        window.Logger.log(window.Logger.LEVEL_DEBUG, "about to open native settings");
        window.cordova.plugins.BEMLaunchNative.launch("NativeSettings", function(result) {
            window.Logger.log(window.Logger.LEVEL_DEBUG,
                "Successfully opened screen NativeSettings, result is "+result);
        }, function(err) {
            window.Logger.log(window.Logger.LEVEL_ERROR,
                "Unable to open screen NativeSettings because of err "+err);
        });
    }
})

.controller('logCtrl', function($scope) {
    console.log("Launching logCtr");
    var RETRIEVE_COUNT = 20;
    $scope.logCtrl = {};

    $scope.refreshEntries = function() {
        window.Logger.getMaxIndex(function(maxIndex) {
            $scope.logCtrl.currentStart = maxIndex;
            $scope.logCtrl.gotMaxIndex = true;
            $scope.logCtrl.reachedEnd = false;
            $scope.entries = [];
            $scope.addEntries();
        }, function (e) {
            var errStr = "While getting max index "+JSON.stringify(e, null, 2);
            console.log(errStr);
            alert(errStr);
        });
    }

    $scope.moreDataCanBeLoaded = function() {
        return $scope.logCtrl.gotMaxIndex && !($scope.logCtrl.reachedEnd);
    }

    $scope.clear = function() {
        window.Logger.clearAll();
        window.Logger.log(window.Logger.LEVEL_INFO, "Finished clearing entries from unified log");
        $scope.refreshEntries();
    }

    $scope.addEntries = function() {
        console.log("calling addEntries");
        window.Logger.getMessagesFromIndex($scope.logCtrl.currentStart, RETRIEVE_COUNT,
            function(entryList) {
                $scope.$apply($scope.processEntries(entryList));
                console.log("entry list size = "+$scope.entries.length);
                console.log("Broadcasting infinite scroll complete");
                $scope.$broadcast('scroll.infiniteScrollComplete')
            }, function(e) {
                var errStr = "While getting messages from the log "+JSON.stringify(e, null, 2);
                console.log(errStr);
                alert(errStr);
            }
        )
    }

    $scope.processEntries = function(entryList) {
        for (i = 0; i < entryList.length; i++) {
            var currEntry = entryList[i];
            $scope.entries.push(currEntry);
        }
        if (entryList.length == 0) {
            console.log("Reached the end of the scrolling");
            $scope.logCtrl.reachedEnd = true;
        } else {
            $scope.logCtrl.currentStart = entryList[entryList.length-1].ID
            console.log("new start index = "+$scope.logCtrl.currentStart);
        }
    }

    $scope.refreshEntries();
})

.controller('sensedDataCtrl', function($scope) {
    var currentStart = 0;

    $scope.config = {}
    $scope.config.key_data_mapping = {
        "Transitions": {
            fn: UserCacheHelper.getMessages,
            key: "statemachine/transition"
        },
        "Locations": {
            fn: UserCacheHelper.getSensorData,
            key: "background/location"
        },
        "Motion Activity": {
            fn: UserCacheHelper.getSensorData,
            key: "background/motion_activity"
        },
    }

    $scope.config.keys = []
    for (key in $scope.config.key_data_mapping) {
        $scope.config.keys.push(key);
    }

    $scope.selected = {}
    $scope.selected.key = $scope.config.keys[0]

    $scope.setSelected = function() {
      $scope.updateEntries();
    }

    /* Let's keep a connection to the database open */

    var db = window.sqlitePlugin.openDatabase({
      name: "userCacheDB",
      // location: 2,
      createFromLocation: 1
    });

  $scope.updateEntries = function() {
    if (angular.isUndefined($scope.selected.key)) {
        usercacheFn = UserCacheHelper.getMessages;
        usercacheKey = "statemachine/transition";
    } else {
        usercacheFn = $scope.config.key_data_mapping[$scope.selected.key]["fn"]
        usercacheKey = $scope.config.key_data_mapping[$scope.selected.key]["key"]
    }
    usercacheFn(db, usercacheKey, function(entryList) {
      $scope.entries = [];
      $scope.$apply(function() {
          for (i = 0; i < entryList.length; i++) {
            // $scope.entries.push({metadata: {write_ts: 1, write_fmt_time: "1"}, data: "1"})
            var currEntry = entryList[i];
            currEntry.data = JSON.stringify(JSON.parse(currEntry.data), null, 2);
            window.Logger.log(window.Logger.LEVEL_DEBUG,
                "currEntry.data = "+currEntry.data);
            $scope.entries.push(currEntry);
            // This should really be within a try/catch/finally block
            $scope.$broadcast('scroll.refreshComplete');
          }
      })
    })
  }

  $scope.updateEntries();
  /*
    UserCacheHelper.getMessages("statemachine/transition",
        function(entryArray){
        });)
    */
})

.controller('mapCtrl', function($scope) {

})

.controller('PlaylistsCtrl', function($scope) {
  $scope.playlists = [
    { title: 'Reggae', id: 1 },
    { title: 'Chill', id: 2 },
    { title: 'Dubstep', id: 3 },
    { title: 'Indie', id: 4 },
    { title: 'Rap', id: 5 },
    { title: 'Cowbell', id: 6 }
  ];
})

.controller('PlaylistCtrl', function($scope, $stateParams) {
});


text:
alias g='git status'
alias gco='git checkout'
alias gf='git fetch'
alias gb='git branch'
alias gd='git diff'

# git completion for shortcuts
complete -o default -o nospace -F _git_status g
complete -o default -o nospace -F _git_checkout gco
complete -o default -o nospace -F _git_fetch gf
complete -o default -o nospace -F _git_branch gb
complete -o default -o nospace -F _git_diff gd
complete -o default -o nospace -F _git_cherry_pick gcp


text:
package com.esri.hadoop.hive;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;

import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.WktExportFlags;
import com.esri.hadoop.hive.GeometryUtils.OGCType;

import com.esri.core.geometry.ogc.OGCGeometry;

@Description(
	name = "ST_AsText",
	value = "_FUNC_(ST_Geometry) - return Well-Known Text (WKT) representation of ST_Geometry\n",
	extended = "Example:\n" +
	"  SELECT _FUNC_(ST_Point(1, 2)) FROM onerow;  --  POINT (1 2)\n"
	)
//@HivePdkUnitTests(
//	cases = {
//		@HivePdkUnitTest(
//			query = "SELECT ST_AsText(ST_Point(1, 2)), ST_AsText(ST_MultiPoint(1, 2, 3, 4)) FROM onerow",
//			result = "POINT (1 2)	MULTIPOINT ((1 2), (3 4))"
//			),
//		@HivePdkUnitTest(
//			query = "SELECT ST_AsText(ST_LineString(1, 1, 2, 2, 3, 3)) FROM onerow",
//			result = "LINESTRING (1 1, 2 2, 3 3)"
//			),
//		@HivePdkUnitTest(
//			query = "SELECT ST_AsText(ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)), ST_AsText(ST_Polygon(1, 1, 4, 1, 4, 4, 1, 4)) FROM onerow",
//			result = "POLYGON ((4 1, 4 4, 1 4, 1 1, 4 1))	NULL"
//			),
//		@HivePdkUnitTest(
//			query = "SELECT ST_AsText(ST_MultiPolygon(array(1, 1, 1, 4, 4, 4, 4, 1), array(11, 11, 11, 14, 14, 14, 14, 11))) FROM onerow",
//			result = "MULTIPOLYGON (((4 1, 4 4, 1 4, 1 1, 4 1)), ((14 11, 14 14, 11 14, 11 11, 14 11)))"
//			)
//		}
//	)
public class ST_AsText extends ST_Geometry {

	static final Log LOG = LogFactory.getLog(ST_AsText.class.getName());

	public Text evaluate(BytesWritable geomref){
		if (geomref == null || geomref.getLength() == 0){
			LogUtils.Log_ArgumentsNull(LOG);
			return null;
		}

		OGCGeometry ogcGeometry = GeometryUtils.geometryFromEsriShape(geomref);
		if (ogcGeometry == null){
			LogUtils.Log_ArgumentsNull(LOG);
			return null;
		}

		int wktExportFlag = getWktExportFlag(GeometryUtils.getType(geomref));

		try {
			// mind: GeometryType with ST_AsText(ST_GeomFromText('MultiLineString((0 80, 0.03 80.04))'))
			// return new Text(ogcGeometry.asText());
			return new Text(GeometryEngine.geometryToWkt(ogcGeometry.getEsriGeometry(), wktExportFlag));
		} catch (Exception e){
			LOG.error(e.getMessage());
			return null;
		}
	}

	private int getWktExportFlag(OGCType type){
		switch (type){
		case ST_POLYGON:
			return WktExportFlags.wktExportPolygon;
		case ST_MULTIPOLYGON:
			return WktExportFlags.wktExportMultiPolygon;
		case ST_POINT:
			return WktExportFlags.wktExportPoint;
		case ST_MULTIPOINT:
			return WktExportFlags.wktExportMultiPoint;
		case ST_LINESTRING:
			return WktExportFlags.wktExportLineString;
		case ST_MULTILINESTRING:
			return WktExportFlags.wktExportMultiLineString;
		default:
			return WktExportFlags.wktExportDefaults;
		}
	}
}


text:
var after = require('after');
var assert = require('assert');
var Msgs = require('../src/msgs');

suite('serialization');

test('should not have null byte if no body', function() {
    var msg = new Msgs.Logout();

    var out = msg.serialize();

    var expected = [
        '8=FIX.4.2',
        '9=57',
        '35=5',
        '52=undefined',
        '49=undefined',
        '56=undefined',
        '34=undefined',
        '10=067',
        ''
    ];

    var actual = Buffer(out).toString().split('\u0001');
    assert.deepEqual(actual, expected);
});


text: This is the home page.


text:
class ProductsController < ApplicationController

	before_action :find_product, only: [:show, :edit, :update, :destroy]
	before_action :authenticate_user!, except: [:index, :show]
	before_action :get_categories, only: [:new, :create]

	def index
	  if params[:search]
	  	params[:sort] ||= "name"
	    @products = Product.search(params[:search]).order(params[:sort])
	  elsif (params[:sort].eql? "name")
	  	@products = Product.order('lower(name)')
	  else
	  	@products = Product.order(params[:sort])
	  end
	end

	def concluded

  	if params[:search_dates]

			date_from = params[:search_dates][:date_from]
			date_to = params[:search_dates][:date_to]

			if date_from <= date_to
				date_to += ' 23:59:59.999999'
				@winners = Bidding.where(is_winner: true)
				@biddings = @winners.where(
					"created_at >= :date_from AND created_at <= :date_to",
  				{date_from: date_from, date_to: date_to}
  				)

				@products = @biddings.map { |b| b.product }
				flash.now[:notice] = "Se ha generado el reporte."
			else
				@products = []
				flash[:invalid] = "Por favor, ingrese un rango de fechas válido."
			end

		else
			@products = []
			flash[:notice] = "Bienvenido al reporte de subastas concluidas"
		end

		render 'concluded'
	end

	def my_auctions
		@products = current_user.products.order("state DESC")
	end

	def new
		@product = current_user.products.build
	end

	def create
		@product = current_user.products.build(product_params)

		if @product.save
			flash[:notice] =  "Subasta creada!"
			redirect_to @product
		else
			render 'new'
		end
	end

	def show
		@inquiries = @product.inquiries
	end

	def edit
	end

	def update
		if @product.update(product_params)
			flash[:notice] = "Actualizado con exito!"
			redirect_to @product
		else
			render 'edit'
		end
	end

	def destroy
		@product.destroy
		redirect_to root_path
	end

	private

	def product_params
		params.require(:product).permit(:name, :description, :state, :period, :image, :category_id)
	end

	def find_product
			@product = Product.find_by(id: params[:id])

		if !@product
			redirect_to root_path
			flash[:notice] =  "Lo sentimos. No se pudo procesar su solicitud."
		end
	end

	def get_categories
		@categories = Category.where("hidden = ?", false).order("name")

		if !@categories
			redirect_to root_path
			flash[:notice] = "Lo sentimos. No se pudo procesar su solicitud."
		end
	end

end


text:
export * from './App'
export {default as CompleteLogIn} from './CompleteLogIn'
export * from './Error404'
export * from './EventSelectField'
export * from './EventDiscountSummaryModal'
export * from './Home'
export * from './LogInForm'
export * from './LookUpRegister'
export * from './MainFooter'
export * from './MainNav'
export * from './ManageOrganizationsEvents'
export * from './OrganizationModal'
export * from './Page'
export * from './Student'
export * from './StudentSearchField'
export * from './TicketTypes'
export * from './UnionIndicator'