text:
title: Serialization
layout: documentation
documentation: true
---
This page is about how the serialization system in Storm works for versions 0.6.0 and onwards. Storm used a different serialization system prior to 0.6.0 which is documented on [Serialization (prior to 0.6.0)](Serialization-\(prior-to-0.6.0\).html).

Tuples can be comprised of objects of any types. Since Storm is a distributed system, it needs to know how to serialize and deserialize objects when they're passed between tasks.

Storm uses [Kryo](https://github.com/EsotericSoftware/kryo) for serialization. Kryo is a flexible and fast serialization library that produces small serializations.

By default, Storm can serialize primitive types, strings, byte arrays, ArrayList, HashMap, and HashSet. If you want to use another type in your tuples, you'll need to register a custom serializer.

### Dynamic typing

There are no type declarations for fields in a Tuple. You put objects in fields and Storm figures out the serialization dynamically. Before we get to the interface for serialization, let's spend a moment understanding why Storm's tuples are dynamically typed.

Adding static typing to tuple fields would add large amount of complexity to Storm's API. Hadoop, for example, statically types its keys and values but requires a huge amount of annotations on the part of the user. Hadoop's API is a burden to use and the "type safety" isn't worth it. Dynamic typing is simply easier to use.

Further than that, it's not possible to statically type Storm's tuples in any reasonable way. Suppose a Bolt subscribes to multiple streams. The tuples from all those streams may have different types across the fields. When a Bolt receives a `Tuple` in `execute`, that tuple could have come from any stream and so could have any combination of types. There might be some reflection magic you can do to declare a different method for every tuple stream a bolt subscribes to, but Storm opts for the simpler, straightforward approach of dynamic typing.

Finally, another reason for using dynamic typing is so Storm can be used in a straightforward manner from dynamically typed languages like Clojure and JRuby.

### Custom serialization

As mentioned, Storm uses Kryo for serialization. To implement custom serializers, you need to register new serializers with Kryo. It's highly recommended that you read over [Kryo's home page](https://github.com/EsotericSoftware/kryo) to understand how it handles custom serialization.

Adding custom serializers is done through the "topology.kryo.register" property in your topology config or through a ServiceLoader described later. The config takes a list of registrations, where each registration can take one of two forms:

1. The name of a class to register. In this case, Storm will use Kryo's `FieldsSerializer` to serialize the class. This may or may not be optimal for the class -- see the Kryo docs for more details.
2. A map from the name of a class to register to an implementation of [com.esotericsoftware.kryo.Serializer](https://github.com/EsotericSoftware/kryo/blob/master/src/com/esotericsoftware/kryo/Serializer.java).

Let's look at an example.

```
topology.kryo.register:
  - com.mycompany.CustomType1
  - com.mycompany.CustomType2: com.mycompany.serializer.CustomType2Serializer
  - com.mycompany.CustomType3
```

`com.mycompany.CustomType1` and `com.mycompany.CustomType3` will use the `FieldsSerializer`, whereas `com.mycompany.CustomType2` will use `com.mycompany.serializer.CustomType2Serializer` for serialization.

Storm provides helpers for registering serializers in a topology config. The [Config](javadocs/org/apache/storm/Config.html) class has a method called `registerSerialization` that takes in a registration to add to the config.

There's an advanced config called `Config.TOPOLOGY_SKIP_MISSING_KRYO_REGISTRATIONS`. If you set this to true, Storm will ignore any serializations that are registered but do not have their code available on the classpath. Otherwise, Storm will throw errors when it can't find a serialization. This is useful if you run many topologies on a cluster that each have different serializations, but you want to declare all the serializations across all topologies in the `storm.yaml` files.

#### SerializationRegister Service Loader

If you want to provide language bindings to storm, have a library that you want to interact cleanly with storm or have some other reason to provide serialization bindings and don't want to force the user to update their configs you can use the org.apache.storm.serialization.SerializationRegister service loader.

You may use this like any other service loader and storm will register the bindings without forceing users to update their configs. The storm-clojure package uses this to provide transparent support for clojure types.

### Java serialization

If Storm encounters a type for which it doesn't have a serialization registered, it will use Java serialization if possible. If the object can't be serialized with Java serialization, then Storm will throw an error.

Beware that Java serialization is extremely expensive, both in terms of CPU cost as well as the size of the serialized object. It is highly recommended that you register custom serializers when you put the topology in production. The Java serialization behavior is there so that it's easy to prototype new topologies.

You can turn off the behavior to fall back on Java serialization by setting the `Config.TOPOLOGY_FALL_BACK_ON_JAVA_SERIALIZATION` config to false.

### Component-specific serialization registrations

Storm 0.7.0 lets you set component-specific configurations (read more about this at [Configuration](Configuration.html)). Of course, if one component defines a serialization that serialization will need to be available to other bolts -- otherwise they won't be able to receive messages from that component!

When a topology is submitted, a single set of serializations is chosen to be used by all components in the topology for sending messages. This is done by merging the component-specific serializer registrations with the regular set of serialization registrations. If two components define serializers for the same class, one of the serializers is chosen arbitrarily.

To force a serializer for a particular class if there's a conflict between two component-specific registrations, just define the serializer you want to use in the topology-specific configuration. The topology-specific configuration has precedence over component-specific configurations for serialization registrations.

redpajama_set_name: RedPajamaGithub


text:
package cc.emberwalker.artemis.compat

import cc.emberwalker.artemis.compat.mods.GregTech
import net.minecraftforge.fml.common.Loader

/**
 * Mod compatibility handler.
 *
 * @author Arkan <arkan@drakon.io>
 */
object CompatController {

  def loadCompatMods() {
    val mods = Array(GregTech) // Declare modules here.
    for (m <- mods) {
      if (Loader.isModLoaded(m.getModId)) m.setupCompat()
    }
  }

}


text:
package model

import "strconv"

// Snowflake is a discord data type representing a globally unique ID
type Snowflake uint64

// ParseSnowflake parses the input snowflake string
func ParseSnowflake(input string) (Snowflake, error) {
	val, err := strconv.ParseUint(input, 10, 64)
	return Snowflake(val), err
}

// Format stringifies a string.
func (s Snowflake) Format() string {
	return strconv.FormatUint(uint64(s), 10)
}


text:
import generate
import interface
import shelve

def main():
    ## clear shell
    interface.clear_window()
    ## vraag naam via interface functie
    x = interface.name()
    ## clear shell
    interface.clear_window()
    ## Geef hoofdmenu
    print(interface.main_menu(x))
    interface.handle(main, interface.pick_number(1,4))

main()


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Enum2862688501.h"
#include "mscorlib_System_AttributeTargets3344548922.h"

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.AttributeTargets
struct  AttributeTargets_t3344548922
{
public:
	// System.Int32 System.AttributeTargets::value__
	int32_t ___value___1;

public:
	inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(AttributeTargets_t3344548922, ___value___1)); }
	inline int32_t get_value___1() const { return ___value___1; }
	inline int32_t* get_address_of_value___1() { return &___value___1; }
	inline void set_value___1(int32_t value)
	{
		___value___1 = value;
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
/** @file   ptarmd_main.c
 *  @brief  ptarmd entry point
 */
#include <stdio.h>
#include <pthread.h>
#include <getopt.h>
#include <signal.h>

#define LOG_TAG     "ptarmd_main"
#include "utl_log.h"
#include "utl_addr.h"
#include "utl_net.h"

#include "ptarmd.h"
#include "conf.h"
#include "btcrpc.h"

//version
#include "../boost/boost/version.hpp"
#include "curl/curlver.h"
#include "mbedtls/version.h"
#include "event.h"
#include "jansson.h"
#include "lmdb.h"
#include "zlib.h"
#ifdef USE_OPENSSL
#include "openssl/opensslv.h"
#endif
#include "../version.h"
#include "ln_version.h"

/**************************************************************************
 * macros
 **************************************************************************/

#define M_OPTSTRING     "p:n:a:c:d:xNhv"

#define M_OPT_CLEARCHANNELDB            '\x10'
#define M_OPT_BITCOINRPCUSER            '\x11'
#define M_OPT_BITCOINRPCPASSWORD        '\x12'
#define M_OPT_BITCOINRPCURL             '\x13'
#define M_OPT_BITCOINRPCPORT            '\x14'
#define M_OPT_ANNOUNCEIP_FORCE          '\x15'

/********************************************************************
 * prototypes
 ********************************************************************/

static void reset_getopt(void);
static void sig_set_catch_sigs(sigset_t *pSigSet);
static void *sig_handler_start(void *pArg);
static void show_version(void);

/********************************************************************
 * entry point
 ********************************************************************/

int main(int argc, char *argv[])
{
    bool bret;
    rpc_conf_t rpc_conf;
    ln_node_t node = LN_NODE_INIT;
    int opt;
    uint16_t my_rpcport = 0;
    bool announceip_force = false;
#if defined(USE_BITCOIND)
    char bitcoinconf[PATH_MAX] = "";
    char bitcoinrpcuser[SZ_RPC_USER + 1] = "";
    char bitcoinrpcpassword[SZ_RPC_PASSWD + 1] = "";
    char bitcoinrpcurl[SZ_RPC_URL + 1] = "";
    uint16_t bitcoinrpcport = 0;
#endif

    const struct option OPTIONS[] = {
        { "network", required_argument, NULL, 'N' },
        { "port", required_argument, NULL, 'p' },
        { "alias", required_argument, NULL, 'n' },
#if defined(USE_BITCOIND)
        { "conf", required_argument, NULL, 'c' },
        { "announceip", required_argument, NULL, 'a' },
        { "announceip_force", no_argument, NULL, M_OPT_ANNOUNCEIP_FORCE },
#endif
        { "datadir", required_argument, NULL, 'd' },
        { "color", required_argument, NULL, 'C' },
        { "rpcport", required_argument, NULL, 'P' },
        { "version", no_argument, NULL, 'v' },
        { "clear_channel_db", no_argument, NULL, M_OPT_CLEARCHANNELDB },
#if defined(USE_BITCOIND)
        { "bitcoinrpcuser", required_argument, NULL, M_OPT_BITCOINRPCUSER },
        { "bitcoinrpcpassword", required_argument, NULL, M_OPT_BITCOINRPCPASSWORD },
        { "bitcoinrpcurl", required_argument, NULL, M_OPT_BITCOINRPCURL },
        { "bitcoinrpcport", required_argument, NULL, M_OPT_BITCOINRPCPORT },
#endif
        { "help", no_argument, NULL, 'h' },
        { 0, 0, 0, 0 }
    };

    bret = ptarmd_execpath_set();
    if (!bret) {
        fprintf(stderr, "fail: %s\n", ptarmd_execpath_get());
        exit(-1);
    }

    //`d` option is used to change working directory.
    // It is done at the beginning of this process.
    while ((opt = getopt_long(argc, argv, M_OPTSTRING, OPTIONS, NULL)) != -1) {
        switch (opt) {
        case 'd':
            if (chdir(optarg) != 0) {
                fprintf(stderr, "fail: change the working directory\n");
                return -1;
            }
            break;
        case 'p':
            //port num
            node.addr.port = (uint16_t)atoi(optarg);
            break;
#if defined(USE_BITCOIND)
        case M_OPT_ANNOUNCEIP_FORCE:
            announceip_force = true;
            break;
#endif
        case '?':
            //invalid option
            return -1;
        default:
            break;
        }
    }
    reset_getopt();

#ifdef ENABLE_PLOG_TO_STDOUT
    utl_log_init_stdout();
#else
    utl_log_init();
#endif

    conf_btcrpc_init(&rpc_conf);
    btc_block_chain_t chain = btc_block_get_param_from_index(0)->chain;

    char prompt[5];
    while ((opt = getopt_long(argc, argv, M_OPTSTRING, OPTIONS, NULL)) != -1) {
        switch (opt) {
        //case 'd':
        //    //`d` option is used to change working directory.
        //    // It is done at the beginning of this process.
        //    break;
        case 'n':
            //node name(alias)
            if (strlen(optarg) > LN_SZ_ALIAS_STR) {
                fprintf(stderr, "fail(-n): alias too long\n");
                return -1;
            }
            strncpy(node.alias, optarg, LN_SZ_ALIAS_STR);
            node.alias[LN_SZ_ALIAS_STR] = '\0';
            break;
        case 'a':
            //ip address
            {
                uint8_t ipbin[LN_ADDR_DESC_ADDR_LEN_IPV4];
                bool addrret = utl_addr_ipv4_str2bin(ipbin, optarg);
                if (!addrret) {
                    LOGD("resolve..\n");
                    char ip_str[SZ_CONN_STR + 1];
                    addrret = utl_net_resolve(ip_str, optarg, node.addr.port);
                    if (addrret) {
                        addrret = utl_addr_ipv4_str2bin(ipbin, ip_str);
                    }
                }
                if (!addrret) {
                    fprintf(stderr, "fail(--announceip): invalid address format\n");
                    return -1;
                }
                node.addr.type = LN_ADDR_DESC_TYPE_IPV4;
                memcpy(node.addr.addr, ipbin, sizeof(ipbin));
                if (announceip_force || utl_net_ipv4_addr_is_routable(node.addr.addr)) {
                    LOGD("announce ipv4=");
                    DUMPD(node.addr.addr, sizeof(node.addr.addr));
                } else {
                    fprintf(stderr, "fail(--announceip): not routable address\n");
                    return -1;
                }
            }
            break;
        case 'c':
#if defined(USE_BITCOIND)
            if (strlen(optarg) > sizeof(bitcoinconf) - 1) {
                fprintf(stderr, "fail: conf file path too long.\n");
                return -1;
            }
            strncpy(bitcoinconf, optarg, sizeof(bitcoinconf) - 1);
            bitcoinconf[sizeof(bitcoinconf) - 1] = '\0';
#endif
            break;
        case 'N':
            //network
            {
                const btc_block_param_t *p_chain = btc_block_get_param_from_name(optarg);
                if (p_chain != NULL) {
                    chain = p_chain->chain;
                } else {
                    fprintf(stderr, "fail: invalid network(%s).\n", optarg);
                    return -1;
                }
            }
            break;
        case 'P':
            //my rpcport num
            my_rpcport = (uint16_t)atoi(optarg);
            break;
        case 'C':
            bret = false;
            if (strlen(optarg) == 6) {
                bret = utl_str_str2bin(node.color, sizeof(node.color), optarg);
            }
            if (!bret) {
                fprintf(stderr, "fail: invalid color(%s).\n", optarg);
                return -1;
            }
            break;
        case 'v':
            show_version();
            exit(0);
        case 'h':
            //help
            fprintf(stderr, "show help\n");
            goto LABEL_EXIT;
        case M_OPT_CLEARCHANNELDB:
            //clear_channel_db
            printf("!!!!!!!!!!!!!!\n");
            printf("!!! DANGER !!!\n");
            printf("!!!!!!!!!!!!!!\n\n");
            printf("This command delete all channel data from DB.\n");
            printf("Do you execute ? : (YES or no)\n");
            {
                char *ret = fgets(prompt, sizeof(prompt), stdin);
                if ((ret != NULL) && (memcmp(prompt, "YES\n", 4) == 0)) {
                    (void)ln_db_reset();
                } else {
                    printf("canceled.\n");
                }
            }
            return 0;
#if defined(USE_BITCOIND)
        case M_OPT_BITCOINRPCUSER:
            if (strlen(optarg) > sizeof(bitcoinrpcuser) - 1) {
                fprintf(stderr, "fail: RPCUSER too long.\n");
                return -1;
            }
            strncpy(bitcoinrpcuser, optarg, sizeof(bitcoinrpcuser) - 1);
            bitcoinrpcuser[sizeof(bitcoinrpcuser) - 1] = '\0';
            break;
        case M_OPT_BITCOINRPCPASSWORD:
            if (strlen(optarg) > sizeof(bitcoinrpcpassword) - 1) {
                fprintf(stderr, "fail: RPCPASSWORD too long.\n");
                return -1;
            }
            strncpy(bitcoinrpcpassword, optarg, sizeof(bitcoinrpcpassword) - 1);
            bitcoinrpcpassword[sizeof(bitcoinrpcpassword) - 1] = '\0';
            break;
        case M_OPT_BITCOINRPCURL:
            if (strlen(optarg) > sizeof(bitcoinrpcurl) - 1) {
                fprintf(stderr, "fail: RPCURL too long.\n");
                return -1;
            }
            strncpy(bitcoinrpcurl, optarg, sizeof(bitcoinrpcurl) - 1);
            bitcoinrpcurl[sizeof(bitcoinrpcurl) - 1] = '\0';
            break;
        case M_OPT_BITCOINRPCPORT:
            bret = utl_str_scan_u16(&bitcoinrpcport, optarg);
            if (!bret || (bitcoinrpcport == 0)) {
                fprintf(stderr, "fail: invaoid RPCPORT.\n");
                return -1;
            }
            break;
#endif
        default:
            break;
        }
    }

#if defined(USE_BITCOIND)
    //load bitcoin.conf file
    if (strlen(bitcoinconf) > 0) {
        bret = conf_btcrpc_load(bitcoinconf, &rpc_conf, chain);
        if (!bret) {
            fprintf(stderr, "fail: load bitcoin conf.\n");
            goto LABEL_EXIT;
        }
    }
    if ((strlen(rpc_conf.rpcuser) == 0) || (strlen(rpc_conf.rpcpasswd) == 0)) {
        //bitcoin.confから読込む
        bret = conf_btcrpc_load_default(&rpc_conf, chain);
        if (!bret) {
            fprintf(stderr, "fail: wrong conf file.\n");
            goto LABEL_EXIT;
        }
        if (strlen(bitcoinrpcuser) > 0) {
            strncpy(rpc_conf.rpcuser, bitcoinrpcuser, SZ_RPC_USER - 1);
            rpc_conf.rpcuser[SZ_RPC_USER - 1] = '\0';
        }
        if (strlen(bitcoinrpcpassword) > 0) {
            strncpy(rpc_conf.rpcpasswd, bitcoinrpcpassword, SZ_RPC_PASSWD - 1);
            rpc_conf.rpcuser[SZ_RPC_PASSWD - 1] = '\0';
        }
        if (bitcoinrpcport != 0) {
            rpc_conf.rpcport = bitcoinrpcport;
        }
        if ( (strlen(rpc_conf.rpcuser) == 0) ||
             (strlen(rpc_conf.rpcpasswd) == 0) ||
             (rpc_conf.rpcport == 0) ) {
            fprintf(stderr, "fail: RPC configuration.\n");
            goto LABEL_EXIT;
        }
    }
    if (strlen(bitcoinrpcurl) > 0) {
        strncpy(rpc_conf.rpcurl, bitcoinrpcurl, SZ_RPC_URL - 1);
        rpc_conf.rpcurl[SZ_RPC_URL - 1] = '\0';
    }
#endif
    bret = btc_init(chain, true);
    if (!bret) {
        fprintf(stderr, "fail: btc_init()\n");
        return -1;
    }

    //O'REILLY Japan: BINARY HACKS #52
    sigset_t ss;
    pthread_t th_sig;
    sig_set_catch_sigs(&ss);
    sigprocmask(SIG_BLOCK, &ss, NULL);
    signal(SIGPIPE , SIG_IGN);   //ignore SIGPIPE
    pthread_create(&th_sig, NULL, &sig_handler_start, NULL);

    //bitcoind起動確認
    uint8_t genesis[BTC_SZ_HASH256];
    bret = btcrpc_init(&rpc_conf, chain);
    if (!bret) {
        fprintf(stderr, "fail: initialize btcrpc\n");
        return -1;
    }
    bret = btcrpc_getgenesisblock(genesis);
    if (!bret) {
        fprintf(stderr, "fail: bitcoin getblockhash\n");
        return -1;
    }
    btc_block_chain_t gentype = ln_genesishash_set(genesis);
    if (gentype != chain) {
        fprintf(stderr, "ERROR: chain not match. check --network option and your chain\n");
        fprintf(stderr, "\tbitcoin-cli getblockchaininfo | jq -e \'.chain\'\n");
        goto LABEL_EXIT;
    }

    ptarmd_start(my_rpcport, &node, gentype);

    btcrpc_term();

    //already detached
    //pthread_join(th_sig, NULL);

    LOGD("$$$ ptarmd: exit\n");
    utl_log_term(); //stop logging

    return 0;

LABEL_EXIT:
    fprintf(stderr, "[usage]\n");
    fprintf(stderr, "\t%s [OPTION]...\n", argv[0]);
    fprintf(stderr, "\n");
    fprintf(stderr, "\t\t--help : help\n");
    fprintf(stderr, "\t\t--version : version\n");
    fprintf(stderr, "\t\t--network NETWORK : chain(");
    const btc_block_param_t *p_param;
    uint8_t lp = 0;
    while ((p_param = btc_block_get_param_from_index(lp)) != NULL) {
        if (lp != 0) {
            fprintf(stderr, "/");
        }
        fprintf(stderr, "%s", p_param->chain_name);
        if (lp == 0) {
            fprintf(stderr, "(default)");
        }
        lp++;
    }
    fprintf(stderr, ")\n");
    fprintf(stderr, "\t\t--port PORT : node port(default: 9735 or previous saved)\n");
    fprintf(stderr, "\t\t--alias NAME : alias name(default: \"node_xxxxxxxxxxxx\" or previous saved)\n");
#if defined(USE_BITCOIND)
    fprintf(stderr, "\t\t--conf BITCOIN_CONF_FILE : using bitcoin.conf(default: ~/.bitcoin/bitcoin.conf)\n");
    fprintf(stderr, "\t\t--bitcoinrpcuser USER : bitcoin RPC user\n");
    fprintf(stderr, "\t\t--bitcoinrpcpassword PASS : bitcoin RPC password\n");
    fprintf(stderr, "\t\t--bitcoinrpcurl URL : bitcoin RPC URL\n");
    fprintf(stderr, "\t\t--bitcoinrpcport PORT : bitcoin RPC port number\n");
    fprintf(stderr, "\t\t--announceip IPADDRv4 : announce IPv4 address(default: none)\n");
#endif
    fprintf(stderr, "\t\t--datadir DIR_PATH : working directory(default: current)\n");
    fprintf(stderr, "\t\t--color RRGGBB : node color(default: 000000)\n");
    fprintf(stderr, "\t\t--rpcport PORT : JSON-RPC port(default: node port+1)\n");
    return -1;
}

/********************************************************************
 * private functions
 ********************************************************************/

static void reset_getopt(void)
{
    //optreset = 1;
    //optind = 1;

    //ref. http://man7.org/linux/man-pages/man3/getopt.3.html#NOTES
    optind = 0;
}

//捕捉するsignal設定
static void sig_set_catch_sigs(sigset_t *pSigSet)
{
    sigemptyset(pSigSet);
    sigaddset(pSigSet, SIGHUP);
    sigaddset(pSigSet, SIGINT);
    sigaddset(pSigSet, SIGQUIT);
    sigaddset(pSigSet, SIGTERM);
    sigaddset(pSigSet, SIGABRT);
    sigaddset(pSigSet, SIGSEGV);
}

//signal捕捉スレッド
static void *sig_handler_start(void *pArg)
{
    (void)pArg;

    LOGD("signal handler\n");
    pthread_detach(pthread_self());

    sigset_t ss;
    siginfo_t info;
    sig_set_catch_sigs(&ss);
    while (1) {
        if (sigwaitinfo(&ss, &info) > 0) {
            fprintf(stderr, "!!! SIGNAL DETECT: %d !!!\n", info.si_signo);
            LOGD("!!! SIGNAL DETECT: %d !!!\n", info.si_signo);
            exit(-1);
        }
    }
    return NULL;
}

static void show_version(void)
{
    fprintf(stderr, "ptarmigan version: %s\n", PTARM_VERSION);
    fprintf(stderr, "DB version: %d\n", LN_DB_VERSION);

    fprintf(stderr, "library version:\n");
    // from version API/macro
    fprintf(stderr, "\tMbedTLS: %s\n", MBEDTLS_VERSION_STRING_FULL);
    fprintf(stderr, "\tlmdb: %s\n", mdb_version(NULL, NULL, NULL));
    fprintf(stderr, "\tjansson: %s\n", JANSSON_VERSION);
    fprintf(stderr, "\tcurl: %s\n", LIBCURL_VERSION);
    fprintf(stderr, "\tlibev: %s\n", event_get_version());
    fprintf(stderr, "\tzlib: %s\n", ZLIB_VERSION);
    fprintf(stderr, "\tboost: %s\n", BOOST_LIB_VERSION);
#ifdef USE_OPENSSL
    fprintf(stderr, "\t" OPENSSL_VERSION_TEXT  "\n");
#endif
    // no version API
    fprintf(stderr, "\tinih: r47\n");
    fprintf(stderr, "\tlibbase58: commit 1cb26b5bfff6b52995a2d88a4b7e1041df589d35\n");
    fprintf(stderr, "\tjsonrpc-c(customized): localonly_r2\n");
}


text:
import unittest
from simpy.tests.tutils import get_current_folder_path
import os
import simpy
from enum import Enum

class MyTestCase(unittest.TestCase):
    def test_read(self):
        xml_path = os.path.join(get_current_folder_path(),'resources', 'simulation_cfg.xml')
        tr = simpy.read_from_xml(xml_path)
        self.assertTrue(tr.test_list.__len__() == 1)
        self.assertTrue(isinstance(tr.test_list, list))
        self.assertTrue(tr.param_configurations.__len__() == 2)
        self.assertTrue(isinstance(tr.param_configurations, dict))
        self.assertTrue(isinstance(tr.global_param, dict))

    def test_enum(self):
        xml_path = os.path.join(get_current_folder_path(),'resources', 'enum_example.xml')
        tr = simpy.read_from_xml(xml_path)

        class TestEnum(Enum):
            Test0 = 0
            Test2 = 1
            Test1 = 2

        for t in tr:
            er = t.read_enum(TestEnum)
            self.assertTrue(isinstance(er, list))
            self.assertTrue(er.__len__() == 2)
            self.assertTrue(TestEnum.Test0 in er)
            self.assertTrue(TestEnum.Test2 in er)

    def test_overwrite(self):
        xml_path = os.path.join(get_current_folder_path(),'resources', 'test_example_overwrite.xml')
        tr = simpy.read_from_xml(xml_path)
        for t in tr:
            self.assertTrue(t.get_param('decay_steps') == 20)

if __name__ == '__main__':
    unittest.main()


text:
{% load boards %}

    {% last_comments 10 as last_comments %}
    {% for last_comment in last_comments %}
        {% with card=last_comment.card %}
            {% with board=card.board %}

                                {{board.name}}

                                 commented in
                                {{card.name}}

{{last_comment.content}}

                          {# See comment in context#}

            {% endwith %}
        {% endwith %}
    {% endfor %}


text:
/* $Id$ */

#ifndef ALIANALYSISTASKUPCETAC_H
#define ALIANALYSISTASKUPCETAC_H

class TClonesArray;
class TTree;
class TH1;
class TH2;
class TList;
class AliPIDResponse;
class AliAODEvent;
class AliESDEvent;
class AliTOFTriggerMask;

#define ntrg 17
#include "AliAnalysisTaskSE.h"

class AliAnalysisTaskUpcEtaC : public AliAnalysisTaskSE {
 public:
  AliAnalysisTaskUpcEtaC();
  AliAnalysisTaskUpcEtaC(const char *name);
  virtual ~AliAnalysisTaskUpcEtaC();

  virtual void Init();
  virtual void UserCreateOutputObjects();
  virtual void UserExec(Option_t *option);
  virtual void RunAODtrig();
  virtual void RunAODhist();
  virtual void RunAODtree();
  virtual void RunAODMC(AliAODEvent *aod);
  virtual void RunAODsystematics(AliAODEvent *aod);
  virtual void RunESDtrig();
  virtual void RunESDhist();
  virtual void RunESDtree();
  virtual void RunESDMC(AliESDEvent *esd);
  virtual void Terminate(Option_t *);
  void SetRunTree(Bool_t runTree){fRunTree = runTree;}
  void SetRunHist(Bool_t runHist){fRunHist = runHist;}
  void SetRunSyst(Bool_t runSyst){fRunSystematics = runSyst;}
  void SetTracking(Int_t tracking){fTracking = tracking;}
  void SetIsMC(Bool_t MC){isMC = MC;}
  void InitSystematics();
  Double_t GetMedian(Double_t *daArray);
  Bool_t CheckMeritCutWinner(int cutChoice, double oldPars[3], double newPars[3]);
  void BoostCut(TLorentzVector d1, TLorentzVector d2, TLorentzVector parent, Double_t *boostInfo);

 private:
  Int_t fType; // 0 - ESD, 1 - AOD
  Int_t fTracking; //0 - Global, 1 - ITSsa
  Bool_t isMC;
  Bool_t fRunTree;
  Bool_t fRunHist;
  Bool_t fRunSystematics;

  int fMeritCutChoice; //set to 4 by default

  AliPIDResponse *fPIDResponse;

  //event tree
  TTree *fEtaCK0sChannelTree;
  TTree *fEtaCTree;
  //tree variables
  Int_t fRunNum;
  UInt_t fPerNum, fOrbNum;
  //trigger
  Bool_t fTrigger[ntrg];
  Bool_t fTriggerInputsMC[ntrg];
  UInt_t fL0inputs, fL1inputs;
  AliTOFTriggerMask *fTOFmask;
  Bool_t fIsPhysicsSelected;

  //PID for EtC->Pi+Pi-K+K- Channel
  Double_t fPIDTPCMuon[7];
  Double_t fPIDTPCElectron[7];
  Double_t fPIDTPCPion[7];
  Double_t fPIDTPCKaon[7];
  Double_t fPIDTPCProton[7];

  Double_t fPIDTOFMuon[7];
  Double_t fPIDTOFElectron[7];
  Double_t fPIDTOFPion[7];
  Double_t fPIDTOFKaon[7];
  Double_t fPIDTOFProton[7];

  //PID for EtC->K0s K+- Pi-+ Channel
  Double_t fPIDTPCMuonPos[7];
  Double_t fPIDTPCElectronPos[7];
  Double_t fPIDTPCPionPos[7];
  Double_t fPIDTPCKaonPos[7];
  Double_t fPIDTPCProtonPos[7];

  Double_t fPIDTOFMuonPos[7];
  Double_t fPIDTOFElectronPos[7];
  Double_t fPIDTOFPionPos[7];
  Double_t fPIDTOFKaonPos[7];
  Double_t fPIDTOFProtonPos[7];

  Double_t fPIDTPCMuonNeg[7];
  Double_t fPIDTPCElectronNeg[7];
  Double_t fPIDTPCPionNeg[7];
  Double_t fPIDTPCKaonNeg[7];
  Double_t fPIDTPCProtonNeg[7];

  Double_t fPIDTOFMuonNeg[7];
  Double_t fPIDTOFElectronNeg[7];
  Double_t fPIDTOFPionNeg[7];
  Double_t fPIDTOFKaonNeg[7];
  Double_t fPIDTOFProtonNeg[7];

  Int_t fVtxContrib;
  Double_t fVtxPos[3];
  Double_t fMCVtxPos[3];
  Double_t fVtxErr[3];
  Double_t fVtxChi2,fVtxNDF;
  Double_t fKfVtxPos[3];
  Int_t fSpdVtxContrib;
  Double_t fSpdVtxPos[3];

  Bool_t fIsVtxContributor[7];

  UShort_t fBCrossNum, fNtracklets, fNLooseTracks;
  //vzero, zdc
  Double_t fZNAenergy, fZNCenergy;
  Double_t fZPAenergy, fZPCenergy;
  Double_t fZDCAtime, fZDCCtime;
  Int_t fV0Adecision, fV0Cdecision;
  Int_t fADAdecision, fADCdecision;
  //input data
  TObjString *fDataFilnam;
  Short_t fRecoPass;
  Long64_t fEvtNum;
  //tracks
  TClonesArray *fJPsiAODTracks;
  TClonesArray *fJPsiESDTracks;
  TClonesArray *fEtaCAODTracks;
  TClonesArray *fEtaCESDTracks;
    //mc
  TClonesArray *fGenPart;

  TList *fListTrig;
  TH1D *fHistCcup4TriggersPerRun;
  TH1D *fHistCcup7TriggersPerRun;
  TH1D *fHistCcup2TriggersPerRun;
  TH1D *fHistCint1TriggersPerRun;
  TH1D *fHistCint6TriggersPerRun;
  TH1D *fHistC0tvxAndCint1TriggersPerRun;
  TH1D *fHistZedTriggersPerRun;
  TH1D *fHistCvlnTriggersPerRun;
  TH1D *fHistMBTriggersPerRun;
  TH1D *fHistCentralTriggersPerRun;
  TH1D *fHistSemiCentralTriggersPerRun;

  TH1D *fHistCTest58TriggersPerRun;
  TH1D *fHistCTest59TriggersPerRun;
  TH1D *fHistCTest60TriggersPerRun;
  TH1D *fHistCTest61TriggersPerRun;

  TH1D *fHistCcup8TriggersPerRun;
  TH1D *fHistCcup9TriggersPerRun;
  TH1D *fHistCcup10TriggersPerRun;
  TH1D *fHistCcup11TriggersPerRun;
  TH1D *fHistCcup12TriggersPerRun;
  TH1D *fHistCtrueTriggersPerRun;

  //My histos and stuff
  TList *fListHist;

  TH1D *fHistNeventsEtaC; //Count potential EtaC events at each step
  TH2D *fMPiKvsMPiK; //Dalitz Plot, Mass first PiK combo vs Mass second PiK combo
  //2 Kstar case
  TH1D *f2KstarPtPiPlus;
  TH1D *f2KstarPtPiMinus;
  TH1D *f2KstarPtKPlus;
  TH1D *f2KstarPtKMinus;
  TH2D *f2KstarTPCsignalPion; //dEdx correlation Pions
  TH2D *f2KstarTPCsignalKaon; //dEdx correlation Kaons
  TH2D *f2KstarDedxVsPtPion;
  TH2D *f2KstarDedxVsPtKaon;
  TH2D *f2KstarTPCsignalVsQPtPion; //dEdx Pions vs Q*Pt
  TH2D *f2KstarTPCsignalVsQPtKaon; //dEdx Kaons vs Q*Pt
  TH2D *f2KstarPtVsMinvFirstKstar;
  TH2D *f2KstarPtVsMinvSecondKstar;
  //    TH1D *f2KstarMinvFirstKstar;
  //    TH1D *f2KstarMinvSecondKstar;
  TH2D *f2KstarPtVsMinvEtaC;
  //    TH1D *f2KstarMinvEtaC;
  //1 Kstar case
  TH1D *f1KstarPtPiPlus;
  TH1D *f1KstarPtPiMinus;
  TH1D *f1KstarPtKPlus;
  TH1D *f1KstarPtKMinus;
  TH2D *f1KstarTPCsignalPion; //dEdx correlation Pions
  TH2D *f1KstarTPCsignalKaon; //dEdx correlation Kaons
  TH2D *f1KstarDedxVsPtPion;
  TH2D *f1KstarDedxVsPtKaon;
  TH2D *f1KstarTPCsignalVsQPtPion; //dEdx Pions vs Q*Pt
  TH2D *f1KstarTPCsignalVsQPtKaon; //dEdx Kaons vs Q*Pt
  TH2D *f1KstarPtVsMinvKstar;
  TH2D *f1KstarPtVsMinvOtherPiKcombo;
  //    TH1D *f1KstarMinvKstar;
  //    TH1D *f1KstarMinvOtherPiKcombo;
  TH2D *f1KstarPtVsMinvEtaC;
  //    TH1D *f1KstarMinvEtaC;
  //0 Kstar case
  TH1D *f0KstarPtPiPlus;
  TH1D *f0KstarPtPiMinus;
  TH1D *f0KstarPtKPlus;
  TH1D *f0KstarPtKMinus;
  TH2D *f0KstarTPCsignalPion; //dEdx correlation Pions
  TH2D *f0KstarTPCsignalKaon; //dEdx correlation Kaons
  TH2D *f0KstarDedxVsPtPion;
  TH2D *f0KstarDedxVsPtKaon;
  TH2D *f0KstarTPCsignalVsQPtPion; //dEdx Pions vs Q*Pt
  TH2D *f0KstarTPCsignalVsQPtKaon; //dEdx Kaons vs Q*Pt
  TH2D *f0KstarPtVsMinvFirstPiKcombo;
  TH2D *f0KstarPtVsMinvSecondPiKcombo;
  //    TH1D *f0KstarMinvFirstPiKcombo;
  //    TH1D *f0KstarMinvSecondPiKcombo;
  TH2D *f0KstarPtVsMinvEtaC;
  //    TH1D *f0KstarMinvEtaC;

  //K0s Channel
  TH1D *fHistK0sCandidatesPerEvent; //Track number of K0s candidates per event
  TH1D *fK0sPosDaughterPt;
  TH1D *fK0sNegDaughterPt;
  TH2D *fK0sPosVsNegDaughterPt;
  TH1D *fPionK0sChannelPt;
  TH1D *fKaonK0sChannelPt;
  TH2D *fK0sPtVsMinv;
  //  TH1D *fK0sMinv;
  TH2D *fKPiPtVsMinvK0sChannel;
  //  TH1D *fKPiMinvK0sChannel;
  TH2D *fMK0sVsMKPiK0sChannel; //Dalitz Plot, Mass K0s vs Mass of PiK combo
  TH2D *fEtaCPtVsMinvK0sChannel;
  //  TH1D *fEtaCMinvK0sChannel;
  TH1D *fK0sDecayLength;

  TH2D *fHistEtaCMassVsPt;
  TH1D *fHistEtaCMassCoherent;

  TH1D *fHistNeventsEtaCK0sChannel; //Count potential EtaC events at each step

  //Diagnostic histos to understand what kind of events are being analyzed.
  TH1D *fHistNpion;
  TH1D *fHistNK0sPion;
  TH1D *fHistNkaon;
  TH1D *fHistPiMinusK;

  //New diagnostic histos to investigate alternative PID approaches.
  TH2D *fNSigmaPionTPCvsNSigmaPionTOFLowPt;
  TH2D *fNSigmaPionTPCvsNSigmaPionTOFMidPt;
  TH2D *fNSigmaPionTPCvsNSigmaPionTOFHighPt;
  TH2D *fNSigmaKaonTPCvsNSigmaKaonTOFLowPt;
  TH2D *fNSigmaKaonTPCvsNSigmaKaonTOFMidPt;
  TH2D *fNSigmaKaonTPCvsNSigmaKaonTOFHighPt;
  TH2D *fTPCdEdxVsTOFbetaAll;
  TH2D *fTPCdEdxVsTOFbetaPionsWithPID;
  TH2D *fTPCdEdxVsTOFbetaKaonsWithPID;
  TH2D *fTOFTimeVsTPCdEdxAll;
  TH2D *fTOFTimeVsTPCdEdxPionsWithPID;
  TH2D *fTOFTimeVsTPCdEdxKaonsWithPID;
  TH2D *fTOFbetaVsPtAll;
  TH2D *fTOFbetaVsPtPionsWithPID;
  TH2D *fTOFbetaVsPtKaonsWithPID;
  TH1D *fNTracksWithTOFPIDPerEvent;
  TH1D *fNTracksMissingDueToTOFPerEvent;

  TH1D *fV0DaughterDca;
  TH1D *fK0sDcaToPrimVertex;
  TH1D *fK0sDaughterDcaToPrimVertex;
  TH1D *fK0sMassDistribution;
  TH1D *fV0DecayLength;
  TH1D *fV0Eta;
  TH1D *fCosPointingAngle;

  //RhoRho Channel histos.
  TH1D *fHistNeventsEtaCRhoChannel;
  TH2D *f2RhoPtVsMinvRho;
  TH2D *f4PionPtVsMinvRho;
  TH2D *f2RhoPtVsMinvEtaC;
  TH2D *f4PionPtVsMinvEtaC;

  TH2D *f2RhoPtVsMinvOtherRho;
  TH2D *f2RhoPtVsMinvNonRhoPairs;

  //3PiPi Channel histos
  TH1D *fHistNeventsEtaC3PiPiChannel;
  TH2D *f3PiPiPtVsMinvEtaC;

  //Helicity cut histos
  TH1D *fKstarParentPx;
  TH1D *fKstarParentPy;
  TH1D *fKstarParentPz;
  TH1D *fKstarDaughterParentAngle;
  TH1D *fKstarDaughterDaughterAngle;
  TH1D *fKstarDaughterDaughterCosAngle;
  TH1D *fKstarDaughterPtotal;
  TH1D *fKstarDaughterPtotalNorm;

  //Helicity cut histos - Check histos
  TH1D *fKstarParentPxCheck;
  TH1D *fKstarParentPyCheck;
  TH1D *fKstarParentPzCheck;
  TH1D *fKstarDaughterParentAngleCheck;
  TH1D *fKstarDaughterDaughterAngleCheck;
  TH1D *fKstarDaughterDaughterCosAngleCheck;
  TH1D *fKstarDaughterPtotalCheck;
  TH1D *fKstarDaughterPtotalNormCheck;

  //2Rho0 channel Helicity cut histos
  TH1D *f2RhoParentPx;
  TH1D *f2RhoParentPy;
  TH1D *f2RhoParentPz;
  TH1D *f2RhoDaughterParentAngle;
  TH1D *f2RhoDaughterDaughterAngle;
  TH1D *f2RhoDaughterDaughterCosAngle;
  TH1D *f2RhoDaughterPtotal;

  //2Rho0 channel Helicity cut histos - Check histos
  TH1D *f2RhoParentPxCheck;
  TH1D *f2RhoParentPyCheck;
  TH1D *f2RhoParentPzCheck;
  TH1D *f2RhoDaughterParentAngleCheck;
  TH1D *f2RhoDaughterDaughterAngleCheck;
  TH1D *f2RhoDaughterDaughterCosAngleCheck;
  TH1D *f2RhoDaughterPtotalCheck;

  TH1D *fHistZDCCuts;

  TList *fListSystematics;
  TList *fListJPsiLoose;
  TList *fListJPsiTight;
  TList *fListEtaCLoose;
  TList *fListEtaCTight;

  AliAnalysisTaskUpcEtaC(const AliAnalysisTaskUpcEtaC&); //not implemented
  AliAnalysisTaskUpcEtaC& operator =(const AliAnalysisTaskUpcEtaC&); //not implemented

  ClassDef(AliAnalysisTaskUpcEtaC, 5);
};

#endif


text:
package tsm1

import (
	"archive/tar"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
	"time"

	"github.com/influxdb/influxdb/models"
	"github.com/influxdb/influxdb/tsdb"
)

// Ensure an engine containing cached values responds correctly to queries.
func TestEngine_QueryCache_Ascending(t *testing.T) {
	// Generate temporary file.
	f, _ := ioutil.TempFile("", "tsm")
	f.Close()
	os.Remove(f.Name())
	walPath := filepath.Join(f.Name(), "wal")
	os.MkdirAll(walPath, 0777)
	defer os.RemoveAll(f.Name())

	// Create a few points.
	p1 := parsePoint("cpu,host=A value=1.1 1000000000")
	p2 := parsePoint("cpu,host=A value=1.2 2000000000")
	p3 := parsePoint("cpu,host=A value=1.3 3000000000")

	// Write those points to the engine.
	e := NewEngine(f.Name(), walPath, tsdb.NewEngineOptions())
	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}
	if err := e.WritePoints([]models.Point{p1, p2, p3}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	// Start a query transactions and get a cursor.
	tx := tx{engine: e.(*Engine)}
	ascCursor := tx.Cursor("cpu,host=A", []string{"value"}, nil, true)

	k, v := ascCursor.SeekTo(1)
	if k != 1000000000 {
		t.Fatalf("failed to seek to before first key: %v %v", k, v)
	}

	k, v = ascCursor.SeekTo(1000000000)
	if k != 1000000000 {
		t.Fatalf("failed to seek to first key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != 2000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != 3000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != -1 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.SeekTo(4000000000)
	if k != -1 {
		t.Fatalf("failed to seek to past last key: %v %v", k, v)
	}
}

// Ensure an engine containing cached values responds correctly to queries.
func TestEngine_QueryTSM_Ascending(t *testing.T) {
	fs := NewFileStore("")

	// Setup 3 files
	data := []keyValues{
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(1, 0), 1.0)}},
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(2, 0), 2.0)}},
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(3, 0), 3.0)}},
	}

	files, err := newFiles(data...)
	if err != nil {
		t.Fatalf("unexpected error creating files: %v", err)
	}

	fs.Add(files...)

	// Start a query transactions and get a cursor.
	ascCursor := devCursor{
		tsmKeyCursor: fs.KeyCursor("cpu,host=A#!~#value"),
		series:       "cpu,host=A",
		fields:       []string{"value"},
		ascending:    true,
	}

	k, v := ascCursor.SeekTo(1)
	if k != 1000000000 {
		t.Fatalf("failed to seek to before first key: %v %v", k, v)
	}

	k, v = ascCursor.SeekTo(1000000000)
	if k != 1000000000 {
		t.Fatalf("failed to seek to first key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != 2000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != 3000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.Next()
	if k != -1 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = ascCursor.SeekTo(4000000000)
	if k != -1 {
		t.Fatalf("failed to seek to past last key: %v %v", k, v)
	}
}

// Ensure an engine containing cached values responds correctly to queries.
func TestEngine_QueryCache_Descending(t *testing.T) {
	// Generate temporary file.
	f, _ := ioutil.TempFile("", "tsm")
	f.Close()
	os.Remove(f.Name())
	walPath := filepath.Join(f.Name(), "wal")
	os.MkdirAll(walPath, 0777)
	defer os.RemoveAll(f.Name())

	// Create a few points.
	p1 := parsePoint("cpu,host=A value=1.1 1000000000")
	p2 := parsePoint("cpu,host=A value=1.2 2000000000")
	p3 := parsePoint("cpu,host=A value=1.3 3000000000")

	// Write those points to the engine.
	e := NewEngine(f.Name(), walPath, tsdb.NewEngineOptions())
	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}
	if err := e.WritePoints([]models.Point{p1, p2, p3}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	// Start a query transactions and get a cursor.
	tx := tx{engine: e.(*Engine)}
	descCursor := tx.Cursor("cpu,host=A", []string{"value"}, nil, false)

	k, v := descCursor.SeekTo(4000000000)
	if k != 3000000000 {
		t.Fatalf("failed to seek to before last key: %v %v", k, v)
	}

	k, v = descCursor.Next()
	if k != 2000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = descCursor.SeekTo(1)
	if k != -1 {
		t.Fatalf("failed to seek to after first key: %v %v", k, v)
	}
}

// Ensure an engine containing cached values responds correctly to queries.
func TestEngine_QueryTSM_Descending(t *testing.T) {
	fs := NewFileStore("")

	// Setup 3 files
	data := []keyValues{
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(1, 0), 1.0)}},
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(2, 0), 2.0)}},
		keyValues{"cpu,host=A#!~#value", []Value{NewValue(time.Unix(3, 0), 3.0)}},
	}

	files, err := newFiles(data...)
	if err != nil {
		t.Fatalf("unexpected error creating files: %v", err)
	}

	fs.Add(files...)

	// Start a query transactions and get a cursor.
	descCursor := devCursor{
		tsmKeyCursor: fs.KeyCursor("cpu,host=A#!~#value"),
		series:       "cpu,host=A",
		fields:       []string{"value"},
		ascending:    false,
	}

	k, v := descCursor.SeekTo(4000000000)
	if k != 3000000000 {
		t.Fatalf("failed to seek to before last key: %v %v", k, v)
	}

	k, v = descCursor.Next()
	if k != 2000000000 {
		t.Fatalf("failed to get next key: %v %v", k, v)
	}

	k, v = descCursor.SeekTo(1)
	if k != -1 {
		t.Fatalf("failed to seek to after first key: %v %v", k, v)
	}
}

func TestEngine_LoadMetadataIndex(t *testing.T) {
	// Generate temporary file.
	f, _ := ioutil.TempFile("", "tsm")
	f.Close()
	os.Remove(f.Name())
	walPath := filepath.Join(f.Name(), "wal")
	os.MkdirAll(walPath, 0777)
	defer os.RemoveAll(f.Name())

	// Create a few points.
	p1 := parsePoint("cpu,host=A value=1.1 1000000000")
	p2 := parsePoint("cpu,host=B value=1.2 2000000000")

	// Write those points to the engine.
	e := NewEngine(f.Name(), walPath, tsdb.NewEngineOptions()).(*Engine)
	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}
	if err := e.WritePoints([]models.Point{p1}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	// ensure we can close and load index from the WAL
	if err := e.Close(); err != nil {
		t.Fatalf("error closing: %s", err.Error())
	}
	if err := e.Open(); err != nil {
		t.Fatalf("error opening: %s", err.Error())
	}

	// Load metadata index.
	index := tsdb.NewDatabaseIndex()
	if err := e.LoadMetadataIndex(nil, index, make(map[string]*tsdb.MeasurementFields)); err != nil {
		t.Fatal(err)
	}

	// Verify index is correct.
	if m := index.Measurement("cpu"); m == nil {
		t.Fatal("measurement not found")
	} else if s := m.SeriesByID(1); s.Key != "cpu,host=A" || !reflect.DeepEqual(s.Tags, map[string]string{"host": "A"}) {
		t.Fatalf("unexpected series: %q / %#v", s.Key, s.Tags)
	}

	// write the snapshot, ensure we can close and load index from TSM
	if err := e.WriteSnapshot(); err != nil {
		t.Fatalf("error writing snapshot: %s", err.Error())
	}

	// ensure we can close and load index from the WAL
	if err := e.Close(); err != nil {
		t.Fatalf("error closing: %s", err.Error())
	}
	if err := e.Open(); err != nil {
		t.Fatalf("error opening: %s", err.Error())
	}

	// Load metadata index.
	index = tsdb.NewDatabaseIndex()
	if err := e.LoadMetadataIndex(nil, index, make(map[string]*tsdb.MeasurementFields)); err != nil {
		t.Fatal(err)
	}

	// Verify index is correct.
	if m := index.Measurement("cpu"); m == nil {
		t.Fatal("measurement not found")
	} else if s := m.SeriesByID(1); s.Key != "cpu,host=A" || !reflect.DeepEqual(s.Tags, map[string]string{"host": "A"}) {
		t.Fatalf("unexpected series: %q / %#v", s.Key, s.Tags)
	}

	// write a new point and ensure we can close and load index from TSM and WAL
	if err := e.WritePoints([]models.Point{p2}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	// ensure we can close and load index from the TSM and WAL
	if err := e.Close(); err != nil {
		t.Fatalf("error closing: %s", err.Error())
	}
	if err := e.Open(); err != nil {
		t.Fatalf("error opening: %s", err.Error())
	}

	// Load metadata index.
	index = tsdb.NewDatabaseIndex()
	if err := e.LoadMetadataIndex(nil, index, make(map[string]*tsdb.MeasurementFields)); err != nil {
		t.Fatal(err)
	}

	// Verify index is correct.
	if m := index.Measurement("cpu"); m == nil {
		t.Fatal("measurement not found")
	} else if s := m.SeriesByID(1); s.Key != "cpu,host=A" || !reflect.DeepEqual(s.Tags, map[string]string{"host": "A"}) {
		t.Fatalf("unexpected series: %q / %#v", s.Key, s.Tags)
	} else if s := m.SeriesByID(2); s.Key != "cpu,host=B" || !reflect.DeepEqual(s.Tags, map[string]string{"host": "B"}) {
		t.Fatalf("unexpected series: %q / %#v", s.Key, s.Tags)
	}
}

// Ensure that deletes only sent to the WAL will clear out the data from the cache on restart
func TestEngine_DeleteWALLoadMetadata(t *testing.T) {
	// Generate temporary file.
	f, _ := ioutil.TempFile("", "tsm")
	f.Close()
	os.Remove(f.Name())
	walPath := filepath.Join(f.Name(), "wal")
	os.MkdirAll(walPath, 0777)
	defer os.RemoveAll(f.Name())

	// Create a few points.
	p1 := parsePoint("cpu,host=A value=1.1 1000000000")
	p2 := parsePoint("cpu,host=B value=1.2 2000000000")

	// Write those points to the engine.
	e := NewEngine(f.Name(), walPath, tsdb.NewEngineOptions()).(*Engine)
	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}
	if err := e.WritePoints([]models.Point{p1, p2}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}
	if err := e.DeleteSeries([]string{"cpu,host=A"}); err != nil {
		t.Fatalf("failed to delete series: %s", err.Error())
	}

	// ensure we can close and load index from the WAL
	if err := e.Close(); err != nil {
		t.Fatalf("error closing: %s", err.Error())
	}

	e = NewEngine(f.Name(), walPath, tsdb.NewEngineOptions()).(*Engine)
	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}

	if exp, got := 0, len(e.Cache.Values(SeriesFieldKey("cpu,host=A", "value"))); exp != got {
		t.Fatalf("unexpected number of values: got: %d. exp: %d", got, exp)
	}

	if exp, got := 1, len(e.Cache.Values(SeriesFieldKey("cpu,host=B", "value"))); exp != got {
		t.Fatalf("unexpected number of values: got: %d. exp: %d", got, exp)
	}
}

// Ensure that the engine will backup any TSM files created since the passed in time
func TestEngine_Backup(t *testing.T) {
	// Generate temporary file.
	f, _ := ioutil.TempFile("", "tsm")
	f.Close()
	os.Remove(f.Name())
	walPath := filepath.Join(f.Name(), "wal")
	os.MkdirAll(walPath, 0777)
	defer os.RemoveAll(f.Name())

	// Create a few points.
	p1 := parsePoint("cpu,host=A value=1.1 1000000000")
	p2 := parsePoint("cpu,host=B value=1.2 2000000000")
	p3 := parsePoint("cpu,host=C value=1.3 3000000000")

	// Write those points to the engine.
	e := NewEngine(f.Name(), walPath, tsdb.NewEngineOptions()).(*Engine)

	// mock the planner so compactions don't run during the test
	e.CompactionPlan = &mockPlanner{}

	if err := e.Open(); err != nil {
		t.Fatalf("failed to open tsm1 engine: %s", err.Error())
	}

	if err := e.WritePoints([]models.Point{p1}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}
	if err := e.WriteSnapshot(); err != nil {
		t.Fatalf("failed to snapshot: %s", err.Error())
	}

	if err := e.WritePoints([]models.Point{p2}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	b := bytes.NewBuffer(nil)
	if err := e.Backup(b, "", time.Unix(0, 0)); err != nil {
		t.Fatalf("failed to backup: %s", err.Error())
	}

	tr := tar.NewReader(b)
	if len(e.FileStore.files) != 2 {
		t.Fatalf("file count wrong: exp: %d, got: %d", 2, len(e.FileStore.files))
	}

	for _, f := range e.FileStore.files {
		th, err := tr.Next()
		if err != nil {
			t.Fatalf("failed reading header: %s", err.Error())
		}
		if !strings.Contains(f.Path(), th.Name) || th.Name == "" {
			t.Fatalf("file name doesn't match:\n\tgot: %s\n\texp: %s", th.Name, f.Path())
		}
	}

	lastBackup := time.Now()

	// we have to sleep for a second because last modified times only have second level precision.
	// so this test won't work properly unless the file is at least a second past the last one
	time.Sleep(time.Second)

	if err := e.WritePoints([]models.Point{p3}, nil, nil); err != nil {
		t.Fatalf("failed to write points: %s", err.Error())
	}

	b = bytes.NewBuffer(nil)
	if err := e.Backup(b, "", lastBackup); err != nil {
		t.Fatalf("failed to backup: %s", err.Error())
	}

	tr = tar.NewReader(b)
	th, err := tr.Next()
	if err != nil {
		t.Fatalf("error getting next tar header: %s", err.Error())
	}

	mostRecentFile := e.FileStore.files[len(e.FileStore.files)-1].Path()
	if !strings.Contains(mostRecentFile, th.Name) || th.Name == "" {
		t.Fatalf("file name doesn't match:\n\tgot: %s\n\texp: %s", th.Name, mostRecentFile)
	}
}

func parsePoints(buf string) []models.Point {
	points, err := models.ParsePointsString(buf)
	if err != nil {
		panic(fmt.Sprintf("couldn't parse points: %s", err.Error()))
	}
	return points
}

func parsePoint(buf string) models.Point {
	return parsePoints(buf)[0]
}

func newFiles(values ...keyValues) ([]TSMFile, error) {
	var files []TSMFile

	for _, v := range values {
		var b bytes.Buffer
		w, err := NewTSMWriter(&b)
		if err != nil {
			return nil, err
		}

		if err := w.Write(v.key, v.values); err != nil {
			return nil, err
		}

		if err := w.WriteIndex(); err != nil {
			return nil, err
		}

		if err := w.Close(); err != nil {
			return nil, err
		}

		r, err := NewTSMReader(bytes.NewReader(b.Bytes()))
		if err != nil {
			return nil, err
		}
		files = append(files, r)
	}
	return files, nil
}

type keyValues struct {
	key    string
	values []Value
}

type mockPlanner struct{}

func (m *mockPlanner) Plan(lastWrite time.Time) []CompactionGroup { return nil }
func (m *mockPlanner) PlanLevel(level int) []CompactionGroup      { return nil }


text:
"use strict";
var utils = require('./utils.js');
var fs = require('fs');
var beautify = require('js-beautify').js_beautify;
var request = require('request').defaults({jar: true});
var iconvlite = require('iconv-lite');

var config = require('./config.js');
var beautify_options = require('./beautify_options.js');

var count = 0; // How many articles in the blog?
var pageSize = 10; // How many articles in each page?
var pages = 0; // How many pages are there in the blog?

var cookie = config.cookie;

if (!config.username) {
  console.error("Blog name must be passed.");
  return ;
}

// TODO : verification the blog name.
var userId;
var hostname = 'http://{username}.blog.163.com'.replace('{username}', config.username);
var apiURL = 'http://api.blog.163.com';
var apiGetBlogPath = '/{username}/dwr/call/plaincall/BlogBeanNew.getBlogs.dwr'.replace('{username}', config.username);
var overviewFile = './data/overview.json';
var authorFile = './data/author.json';

// Step 1: Get overview data.
var indexPageOption = {
  url: hostname + '/blog',
  encoding: null // The body is returned as a Buffer
};

if (cookie) {
  indexPageOption.headers = {
    'Cookie': cookie
  };
}
//console.log('indexPageOption:', indexPageOption);

request(indexPageOption, function(error, response, body) {
  if (!error && response.statusCode == 200) {
    var responseBody = iconvlite.decode(body, 'GBK'); // Convert from an encoded buffer to string.
    parseIndexPage(responseBody);
  } else {
    console.log('Error:', error);
  }
});

function parseIndexPage(body) {
  var overviewExp = /<textarea name="js">([^<]+)<\/textarea>/;
  var overviewMatch = body.match(overviewExp);
  // If the analytics data could not be found on the page, exit.
  // This may happens when you don't have permission to access the blog.
  if (!overviewMatch || !overviewMatch[1]) {
    console.warn("No overview data found. exit.");
    return;
  }
  var overviewObj = {};
  eval(overviewMatch[1].trim().replace("this.p", "overviewObj"));
  //console.log('overviewObj:', overviewObj);

  var authorObj = {};
  var authorExp = /UD\.host\s*=\s*({([^;])+)/;
  var authorMatch = body.match(authorExp);
  console.log("authorMatch:", authorMatch[1]);

  // If the author information could not be retrieved, exit.
  // This means there is something wrong on the page, or Netease had modified the page template.
  if (!authorMatch || !authorMatch[1]) {
    console.error("Could not get the author's information.");
    return;
  }
  eval("authorObj=" + authorMatch[1].trim());
  userId = authorObj.userId;

  count = overviewObj.a.map(function(category){
      return category.count;
    }).reduce(function(a, b) {
      return a + b;
  });
  console.log('Blog posts:', count);

  pages = Math.ceil(count / pageSize);

  // Save to overview.json
  fs.exists(overviewFile, function (exists) {
    if(!exists) {
      fs.writeFile(overviewFile, beautify(JSON.stringify(overviewObj), beautify_options));
    }
  });

  // Save to author.json
  fs.exists(authorFile, function (exists) {
    if(!exists) {
      fs.writeFile(authorFile, beautify(JSON.stringify(authorObj), beautify_options));
    }
  });

  var listPagePromises = [];
  for ( var i = 0; i < pages; i++) {
    listPagePromises.push(getListPagePromise(i));
  }

  //return false;//////////////////////////////////////////////

  Promise.all(listPagePromises).then(function(results) {
    // All list pages loaded.
    console.log('All list page promises done:', results);
    var postLinks = [];
    results.forEach(function(page) {
      postLinks = postLinks.concat(page);
    });

    console.log('All links:', postLinks.length);

    postLinks.forEach(function(postLink) {
      getArticleByLink(postLink);
    });
  }).catch(function(error) {
    console.error('list page error:', error);
  });

}

function getListPagePromise(pageIndex) {
  return new Promise(function(resolve, reject) {
    var postData = {
      callCount: 1,
      scriptSessionId: "${scriptSessionId}187",
      "c0-scriptName": "BlogBeanNew",
      "c0-methodName": "getBlogs",
      "c0-id": 0,
      "c0-param0": "number:" + userId,
      "c0-param1": "number:" + ((pageIndex > 0) ? (pageIndex + 1) * 10 : 0) ,
      "c0-param2": "number:" + (pageIndex > 0 ? 10 : 20),
      "batchId": 307850
    };
    var postDataArr = [];
    for (var prop in postData) {
      postDataArr.push(new String(prop) + '=' + postData[prop]);
    }
    var postDataStr = postDataArr.join('\n');

    var postOption = {
      url: hostname + apiGetBlogPath,
      form: postData,
      gzip: true,
      headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36',
        'Referer': 'http://api.blog.163.com/crossdomain.html?t=20100205',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2,es;q=0.2',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'DNT': '1',
        'Host': 'api.blog.163.com',
        'Origin': 'http://api.blog.163.com',
        'Pragma': 'no-cache',
        'Content-Type': 'text/plain'
        //'Content-Length': postDataStr.length
      }
    };

    if (cookie) {
      postOption.headers.Cookie = cookie;
    }

    request.post(postOption, function(err, httpResponse, body){
      if (err) {
        reject(err);
      } else {
        //let res = body.
        //console.log('body:', body)
        //return false;
        var pattern = /permalink\s*=\s*"blog\/static\/\d+";/g;
        var links =  body.match(pattern);
        if (!links) {
          console.warn("Links not found.", postData);
          resolve([]);
        } else {
          resolve(links);
        }
      }
    });
  });
}

function getArticleByLink(url) {
  var urlParts = url.match(/"(blog\/static\/\d+)";/);
  if (!urlParts || !urlParts[1]) {
    return ;
  }
  url = urlParts[1];
  var options = {
    url: hostname + '/' + url,
    //hostname: hostname,
    //path: '/' + url,
    //encoding: 'GBK',
    encoding: null,
    headers: {
      // The User-Agent header is required because the missing it will cause HTTP 403 Forbidden errors sometimes.
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'
    }
  };

  if (cookie) {
    options.headers.Cookie = cookie;
  }
  //console.log('url:', url);
  var blogId = url.split('/').pop();
  blogId = blogId.substring(0, blogId.length -2);
  //console.log('blogId:', blogId);

  request(options, function(error, response,  body) {
    let res = iconvlite.decode(body, 'GBK');
    var contentExp = /<div class="bct fc05 fc11 nbw-blog ztag">([\s\S]+?)<\/div>/; // Use the question mark(?) to avoid greediness.
    var contentMatch = res.match(contentExp);
    if (!contentMatch || !contentMatch[1]) {
      console.warn("Could not find the blog content. url:", url);
    }

    var articleObj = {};
    var t1 = res.split('<textarea name="js">')[1];
    if( !t1) {
      console.log('t1 undefined:', url);
      return;
    }
    var t2 = t1.split('</textarea>')[0].trim(),
        t3 = t2.substring(7);

    eval('articleObj = ' + t3);
    if (contentMatch && contentMatch[1]) {
      articleObj.blogContent = contentMatch[1];
    }
    var blogFile = './data/' + articleObj.publishTime + '.json';

    fs.writeFile(blogFile, beautify(JSON.stringify(articleObj), beautify_options), function(err) {
      if (err) throw err;
      //console.log('saved:' + blogFile);
    });
  }, function(e) {
    console.log('err:', e.message, ' url:', hostname + '/' + url);
  });
}


text:
from tlp.views.binders import ParameterBinderSelector

class PreferencesView:
    UI = 'preferences.ui'

    def __init__(self, loader, controller, factory):
        self.dialog = loader.get('preferences')
        self.model = controller
        loader.connect(self)

        self._set_view_behavior(loader)
        self._bind_parameters(loader)

    def show(self, parent):
        self.dialog.set_transient_for(parent.window)
        self._update_view()
        self.dialog.run()

        if self.model.changes.has_changes():
            self.model.save()

        self.dialog.hide()

    def _update_view(self):
        for param in self.model.parameters:
            param.notify_changes()

    def _set_view_behavior(self, loader):
        options = loader.get('TLP_OPTIONS')
        behavior = lambda switch, *a: options.set_sensitive(switch.get_active())
        loader.get('TLP_ENABLE').connect('notify::active', behavior)

    def _bind_parameters(self, loader):
        selector = ParameterBinderSelector()
        binders = [selector.get_from(param)
                   for param in self.model.parameters]

        for binder in binders:
            binder.bind(loader.get(binder.parameter.name))

        return binders


text:
package edu.learn.rest.utils;

public class CommonResponsesCodes {
    public static final int UNAUTHORIZED_CODE = 403;
    public static final int METHOD_NOT_ALLOWED = 405;
    public static final int BAD_RESPONSE_CODE = 400;
    public static final int GOOD_RESPONSE_CODE = 200;

    public static final String UNAUTHORIZED_MESSAGE = "Unauthorized access";
    public static final String METHOD_NOT_ALLOWED_MESSAGE = "Method not allowed";
    public static final String BAD_RESPONSE_MESSAGE = "Missing Information";
    public static final String GOOD_RESPONSE_MESSAGE = "OK";
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Akavache;
using GitHub.Api;
using GitHub.Caches;
using GitHub.Services;
using NSubstitute;
using Octokit;
using Xunit;

public class ModelServiceTests
{
    public class TheGetUserFromCacheMethod : TestBaseClass
    {
        [Fact]
        public async Task RetrievesUserFromCache()
        {
            var apiClient = Substitute.For<IApiClient>();
            var cache = new InMemoryBlobCache();
            await cache.InsertObject<AccountCacheItem>("user", new AccountCacheItem(CreateOctokitUser("octocat")));
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var user = await modelService.GetUserFromCache();

            Assert.Equal("octocat", user.Login);
        }
    }

    public class TheInsertUserMethod : TestBaseClass
    {
        [Fact]
        public async Task AddsUserToCache()
        {
            var apiClient = Substitute.For<IApiClient>();
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var user = await modelService.InsertUser(new AccountCacheItem(CreateOctokitUser("octocat")));

            var cached = await cache.GetObject<AccountCacheItem>("user");
            Assert.Equal("octocat", cached.Login);
        }
    }

    public class TheGetGitIgnoreTemplatesMethod : TestBaseClass
    {
        [Fact]
        public async Task CanRetrieveAndCacheGitIgnores()
        {
            var templates = new[] { "dotnet", "peanuts", "bloomcounty" };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetGitIgnoreTemplates().Returns(templates.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetGitIgnoreTemplates();

            Assert.Equal(4, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
            Assert.Equal("dotnet", fetched[1].Name);
            Assert.Equal("peanuts", fetched[2].Name);
            Assert.Equal("bloomcounty", fetched[3].Name);
            var cached = await cache.GetObject<IReadOnlyList<string>>("gitignores");
            Assert.Equal(3, cached.Count);
            Assert.Equal("dotnet", cached[0]);
            Assert.Equal("peanuts", cached[1]);
            Assert.Equal("bloomcounty", cached[2]);
        }

        [Fact]
        public async Task ReturnsCollectionOnlyContainingTheNoneOptionnWhenGitIgnoreEndpointNotFound()
        {
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetGitIgnoreTemplates()
                .Returns(Observable.Throw<string>(new NotFoundException("Not Found", HttpStatusCode.NotFound)));
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetGitIgnoreTemplates();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
        }

        [Fact]
        public async Task ReturnsCollectionOnlyContainingTheNoneOptionIfCacheReadFails()
        {
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetGitIgnoreTemplates()
                .Returns(Observable.Throw<string>(new NotFoundException("Not Found", HttpStatusCode.NotFound)));
            var cache = Substitute.For<IBlobCache>();
            cache.Get(Args.String)
                .Returns(Observable.Throw<byte[]>(new InvalidOperationException("Unknown")));
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetGitIgnoreTemplates();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
        }
    }

    public class TheGetLicensesMethod : TestBaseClass
    {
        [Fact]
        public async Task CanRetrieveAndCacheLicenses()
        {
            var licenses = new[]
            {
                new LicenseMetadata("mit", "MIT", new Uri("https://github.com/")),
                new LicenseMetadata("apache", "Apache", new Uri("https://github.com/"))
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetLicenses().Returns(licenses.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetLicenses();

            Assert.Equal(3, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
            Assert.Equal("MIT", fetched[1].Name);
            Assert.Equal("Apache", fetched[2].Name);
            var cached = await cache.GetObject<IReadOnlyList<ModelService.LicenseCacheItem>>("licenses");
            Assert.Equal(2, cached.Count);
            Assert.Equal("mit", cached[0].Key);
            Assert.Equal("apache", cached[1].Key);
        }

        [Fact]
        public async Task ReturnsCollectionOnlyContainingTheNoneOptionWhenLicenseApiNotFound()
        {
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetLicenses()
                .Returns(Observable.Throw<LicenseMetadata>(new NotFoundException("Not Found", HttpStatusCode.NotFound)));
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetLicenses();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
        }

        [Fact]
        public async Task ReturnsCollectionOnlyContainingTheNoneOptionIfCacheReadFails()
        {
            var apiClient = Substitute.For<IApiClient>();
            var cache = Substitute.For<IBlobCache>();
            cache.Get(Args.String)
                .Returns(Observable.Throw<byte[]>(new InvalidOperationException("Unknown")));
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetLicenses();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("None", fetched[0].Name);
        }
    }

    public class TheGetAccountsMethod : TestBaseClass
    {
        [Fact]
        public async Task CanRetrieveAndCacheUserAndAccounts()
        {
            var orgs = new[]
            {
                CreateOctokitOrganization("github"),
                CreateOctokitOrganization("fake")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetUser().Returns(Observable.Return(CreateOctokitUser("snoopy")));
            apiClient.GetOrganizations().Returns(orgs.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            await modelService.InsertUser(new AccountCacheItem { Login = "snoopy" });

            var fetched = await modelService.GetAccounts();

            Assert.Equal(3, fetched.Count);
            Assert.Equal("snoopy", fetched[0].Login);
            Assert.Equal("github", fetched[1].Login);
            Assert.Equal("fake", fetched[2].Login);
            var cachedOrgs = await cache.GetObject<IReadOnlyList<AccountCacheItem>>("snoopy|orgs");
            Assert.Equal(2, cachedOrgs.Count);
            Assert.Equal("github", cachedOrgs[0].Login);
            Assert.Equal("fake", cachedOrgs[1].Login);
            var cachedUser = await cache.GetObject<AccountCacheItem>("user");
            Assert.Equal("snoopy", cachedUser.Login);
        }

        [Fact]
        public async Task CanRetrieveUserFromCacheAndAccountsFromApi()
        {
            var orgs = new[]
            {
                CreateOctokitOrganization("github"),
                CreateOctokitOrganization("fake")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetOrganizations().Returns(orgs.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            await modelService.InsertUser(new AccountCacheItem(CreateOctokitUser("octocat")));

            var fetched = await modelService.GetAccounts();

            Assert.Equal(3, fetched.Count);
            Assert.Equal("octocat", fetched[0].Login);
            Assert.Equal("github", fetched[1].Login);
            Assert.Equal("fake", fetched[2].Login);
            var cachedOrgs = await cache.GetObject<IReadOnlyList<AccountCacheItem>>("octocat|orgs");
            Assert.Equal(2, cachedOrgs.Count);
            Assert.Equal("github", cachedOrgs[0].Login);
            Assert.Equal("fake", cachedOrgs[1].Login);
            var cachedUser = await cache.GetObject<AccountCacheItem>("user");
            Assert.Equal("octocat", cachedUser.Login);
        }

        [Fact]
        public async Task OnlyRetrievesOneUserEvenIfCacheOrApiReturnsMoreThanOne()
        {
            // This should be impossible, but let's pretend it does happen.
            var users = new[]
            {
                CreateOctokitUser("peppermintpatty"),
                CreateOctokitUser("peppermintpatty")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetUser().Returns(users.ToObservable());
            apiClient.GetOrganizations().Returns(Observable.Empty<Organization>());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            var fetched = await modelService.GetAccounts();

            Assert.Equal(1, fetched.Count);
            Assert.Equal("peppermintpatty", fetched[0].Login);
        }
    }

    public class TheGetRepositoriesMethod : TestBaseClass
    {
        [Fact]
        public async Task CanRetrieveAndCacheRepositoriesForUserAndOrganizations()
        {
            var orgs = new[]
            {
                CreateOctokitOrganization("github"),
                CreateOctokitOrganization("octokit")
            };
            var ownedRepos = new[]
            {
                CreateRepository("haacked", "seegit"),
                CreateRepository("haacked", "codehaacks")
            };
            var memberRepos = new[]
            {
                CreateRepository("mojombo", "semver"),
                CreateRepository("ninject", "ninject"),
                CreateRepository("jabbr", "jabbr"),
                CreateRepository("fody", "nullguard")
            };
            var githubRepos = new[]
            {
                CreateRepository("github", "visualstudio")
            };
            var octokitRepos = new[]
            {
                CreateRepository("octokit", "octokit.net"),
                CreateRepository("octokit", "octokit.rb"),
                CreateRepository("octokit", "octokit.objc")
            };
            var apiClient = Substitute.For<IApiClient>();
            apiClient.GetOrganizations().Returns(orgs.ToObservable());
            apiClient.GetUserRepositories(RepositoryType.Owner).Returns(ownedRepos.ToObservable());
            apiClient.GetUserRepositories(RepositoryType.Member).Returns(memberRepos.ToObservable());
            apiClient.GetRepositoriesForOrganization("github").Returns(githubRepos.ToObservable());
            apiClient.GetRepositoriesForOrganization("octokit").Returns(octokitRepos.ToObservable());
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            await modelService.InsertUser(new AccountCacheItem { Login = "opus" });

            var fetched = await modelService.GetRepositories().ToList();

            Assert.Equal(4, fetched.Count);
            Assert.Equal(2, fetched[0].Count);
            Assert.Equal(4, fetched[1].Count);
            Assert.Equal(1, fetched[2].Count);
            Assert.Equal(3, fetched[3].Count);
            Assert.Equal("seegit", fetched[0][0].Name);
            Assert.Equal("codehaacks", fetched[0][1].Name);
            Assert.Equal("semver", fetched[1][0].Name);
            Assert.Equal("ninject", fetched[1][1].Name);
            Assert.Equal("jabbr", fetched[1][2].Name);
            Assert.Equal("nullguard", fetched[1][3].Name);
            Assert.Equal("visualstudio", fetched[2][0].Name);
            Assert.Equal("octokit.net", fetched[3][0].Name);
            Assert.Equal("octokit.rb", fetched[3][1].Name);
            Assert.Equal("octokit.objc", fetched[3][2].Name);
            var cachedOwnerRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|Owner:repos");
            Assert.Equal(2, cachedOwnerRepositories.Count);
            Assert.Equal("seegit", cachedOwnerRepositories[0].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[0].Owner.Login);
            Assert.Equal("codehaacks", cachedOwnerRepositories[1].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[1].Owner.Login);
            var cachedMemberRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|Member:repos");
            Assert.Equal(4, cachedMemberRepositories.Count);
            Assert.Equal("semver", cachedMemberRepositories[0].Name);
            Assert.Equal("mojombo", cachedMemberRepositories[0].Owner.Login);
            Assert.Equal("ninject", cachedMemberRepositories[1].Name);
            Assert.Equal("ninject", cachedMemberRepositories[1].Owner.Login);
            Assert.Equal("jabbr", cachedMemberRepositories[2].Name);
            Assert.Equal("jabbr", cachedMemberRepositories[2].Owner.Login);
            Assert.Equal("nullguard", cachedMemberRepositories[3].Name);
            Assert.Equal("fody", cachedMemberRepositories[3].Owner.Login);
            var cachedGitHubRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|github|repos");
            Assert.Equal(1, cachedGitHubRepositories.Count);
            Assert.Equal("seegit", cachedOwnerRepositories[0].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[0].Owner.Login);
            Assert.Equal("codehaacks", cachedOwnerRepositories[1].Name);
            Assert.Equal("haacked", cachedOwnerRepositories[1].Owner.Login);
            var cachedOctokitRepositories = await cache.GetObject<IReadOnlyList<ModelService.RepositoryCacheItem>>("opus|octokit|repos");
            Assert.Equal("octokit.net", cachedOctokitRepositories[0].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[0].Owner.Login);
            Assert.Equal("octokit.rb", cachedOctokitRepositories[1].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[1].Owner.Login);
            Assert.Equal("octokit.objc", cachedOctokitRepositories[2].Name);
            Assert.Equal("octokit", cachedOctokitRepositories[2].Owner.Login);
        }

        [Fact]
        public async Task WhenNotLoggedInReturnsEmptyCollection()
        {
            var apiClient = Substitute.For<IApiClient>();
            var modelService = new ModelService(apiClient, new InMemoryBlobCache(), Substitute.For<IAvatarProvider>());

            var repos = await modelService.GetRepositories();

            Assert.Equal(0, repos.Count);
        }

        [Fact]
        public async Task WhenLoggedInDoesNotBlowUpOnUnexpectedNetworkProblems()
        {
            var apiClient = Substitute.For<IApiClient>();
            var modelService = new ModelService(apiClient, new InMemoryBlobCache(), Substitute.For<IAvatarProvider>());
            apiClient.GetOrganizations()
                .Returns(Observable.Throw<Organization>(new NotFoundException("Not Found", HttpStatusCode.NotFound)));

            var repos = await modelService.GetRepositories();

            Assert.Equal(0, repos.Count);
        }
    }

    public class TheInvalidateAllMethod : TestBaseClass
    {
        [Fact]
        public async Task InvalidatesTheCache()
        {
            var apiClient = Substitute.For<IApiClient>();
            var cache = new InMemoryBlobCache();
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());
            var user = await modelService.InsertUser(new AccountCacheItem(CreateOctokitUser("octocat")));
            Assert.Equal(1, (await cache.GetAllObjects<AccountCacheItem>()).Count());

            await modelService.InvalidateAll();

            Assert.Equal(0, (await cache.GetAllObjects<AccountCacheItem>()).Count());
        }

        [Fact]
        public async Task VaccumsTheCache()
        {
            var apiClient = Substitute.For<IApiClient>();
            var cache = Substitute.For<IBlobCache>();
            cache.InvalidateAll().Returns(Observable.Return(Unit.Default));
            var modelService = new ModelService(apiClient, cache, Substitute.For<IAvatarProvider>());

            await modelService.InvalidateAll();

            cache.Received().Vacuum();
        }
    }

    static User CreateOctokitUser(string login)
    {
        return new User("https://url", "", "", 1, "GitHub", DateTimeOffset.UtcNow, 0, "email", 100, 100, true, "http://url", 10, 42, "somewhere", login, "Who cares", 1, new Plan(), 1, 1, 1, "https://url", false);
    }

    static Organization CreateOctokitOrganization(string login)
    {
        return new Organization("https://url", "", "", 1, "GitHub", DateTimeOffset.UtcNow, 0, "email", 100, 100, true, "http://url", 10, 42, "somewhere", login, "Who cares", 1, new Plan(), 1, 1, 1, "https://url", "billing");
    }

    static Repository CreateRepository(string owner, string name)
    {
        return new Repository("https://url", "https://url", "https://url", "https://url", "https://url", "https://url", "https://url", 1, CreateOctokitUser(owner), name, "fullname", "description", "https://url", "c#", false, false, 0, 0, 0, "master", 0, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, new RepositoryPermissions(), null, null, null, true, false, false);
    }
}


text:
set -ex

echo =============================================================================
# go to project dir
SCRIPT_DIR=$(dirname $0)
cd $SCRIPT_DIR/../..

./node_modules/.bin/webdriver-manager update

function killServer () {
  kill $serverPid
}

./node_modules/.bin/gulp serve.js.prod&
serverPid=$!

./node_modules/.bin/gulp build.css.material&

trap killServer EXIT

# wait for server to come up!
sleep 10

# Let protractor use default browser unless one is specified.
OPTIONS="";
if [[ -n "$E2E_BROWSERS" ]]; then
  OPTIONS="--browsers=$E2E_BROWSERS";
fi

./node_modules/.bin/protractor protractor-js.conf.js $OPTIONS
./node_modules/.bin/protractor protractor-js.conf.js $OPTIONS --benchmark --dryrun
# TODO(tbosch): tests for benchpress on firefox are disabled
# as they are very flake. Enable once https://github.com/angular/angular/issues/5611
# is resolved.
# ./node_modules/.bin/protractor dist/js/cjs/benchpress/test/firefox_extension/conf.js


text:
import org.kender.simplenote.SNote;
import org.kender.simplenote.SimpleNote;
import org.kender.simplenote.exceptions.ConnectionFailed;

public class MoveToTrash {

    public static void main(String[] args) {
        if (args.length < 2) {
            System.out.println("You need more arguments");
            return;
        }

        String email = args[0];
        String password = args[1];

        SimpleNote sn = new SimpleNote(email, password);

        try {
            // Create a note first (or get it if we know the ID)
            SNote note = sn.addNote("This note will end up in the trash");

            note.trash(); // Flag it as "trashed"
            sn.updateNote(note); // Update the server
        } catch (ConnectionFailed e) {
            e.printStackTrace();
        }
    }
}


text:
Animation *AnimationFactory::Create(
        AnimationTypes::HideAnimation anim, int speed) {

    Animation *animation;

    switch (anim) {
    case AnimationTypes::Fade:
        animation = new FadeOut(speed);
        break;

    case AnimationTypes::None:
    default:
        animation = NULL;
    }

    return animation;
}


text:
var expect = require('chai').expect;

var components = require("../src/index.js");

describe("An asynchronous element", () => {
    it("blocks rendering until they complete", () => {
        var SlowElement = components.newElement();
        SlowElement.createdCallback = function () {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    this.textContent = "loaded!";
                    resolve();
                }, 1);
            });
        };
        components.registerElement("slow-element", { prototype: SlowElement });

        return components.renderFragment("<slow-element></slow-element>").then((output) => {
            expect(output).to.equal("<slow-element>loaded!</slow-element>");
        });
    });

    it("throw an async error if a component fails to render synchronously", () => {
        var FailingElement = components.newElement();
        FailingElement.createdCallback = () => { throw new Error(); };
        components.registerElement("failing-element", { prototype: FailingElement });

        return components.renderFragment(
            "<failing-element></failing-element>"
        ).then((output) => {
            throw new Error("Should not successfully render");
        }).catch(() => { /* All good. */ });
    });

    it("throw an async error if a component fails to render asynchronously", () => {
        var FailingElement = components.newElement();
        FailingElement.createdCallback = () => Promise.reject(new Error());
        components.registerElement("failing-element", { prototype: FailingElement });

        return components.renderFragment(
            "<failing-element></failing-element>"
        ).then((output) => {
            throw new Error("Should not successfully render");
        }).catch(() => { /* All good */ });
    });
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Registro de visitas en línea</title>
<link href="/styles/portada.css" rel="stylesheet" type="text/css">
<link href="/styles/apps.search.css" rel="stylesheet" type="text/css">

    	REGISTRO DE VISITAS EN LÍNEA

    	PERIODO 20/08/2015  al 20/08/2015

      <form name="form1" method="post" action="">

               SELECCIONE FECHAS

              Entre el
              <input name="desFecha" id="desFecha" style="text-align:center" size="12" class="txt-buscar-premio" value="20/08/2015" onChange="cargar();"/>
               y el
              <input name="desFechaF" id="desFechaF" style="text-align:center" size="12" class="txt-buscar-premio" value="20/08/2015" onChange="cargar();"/>

                  <input type="submit" name="buscar" id="buscar" value="Consultar" class="submit">

              dd/mm/aaaa

              dd/mm/aaaa

      </form>

        N°
        FECHA
      HORA DE

INGRESO
        NOMBRE DEL

VISITANTE
        TIPO DE

DOCUMENTO
        N° DE DOCUMENTO
        MOTIVO
        NOMBRE DEL

TRABAJOR
        DEPENDENCIA
        HORA DE

SALIDA

        1
        20/08/2015
        09:08:34
        MAGUIÑA  ROBLES, WILFREDO HERIBERTO
        DNI
        32824731
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        09:16:28

        2
        20/08/2015
        09:21:27
        MAGUIÑA  ROBLES, WILFREDO HERIBERTO
        DNI
        32824731
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        11:52:52

        3
        20/08/2015
        09:16:39
        REGALO  QUIJANO, WALTER  MANUEL
        DNI
        08182131
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        11:53:16

        4
        20/08/2015
        11:08:38
        VELIZ   ALVA, RAMON AMADEO  CARLOS
        DNI
        21801439
        ENTREVISTA
        BARRETO RAMIREZ, HILDA MARIA
        DESPACHO MINISTERIAL

        5
        20/08/2015
        09:57:58
        GIUDICE ALVA, ADRIANA CARMEN
        DNI
        07955057
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        11:52:41

        6
        20/08/2015
        11:56:27
        LETONA PEREYRA, MARI AURSULA INGRID
        DNI
        10771109
        ENTREVISTA
        BARRETO RAMIREZ, HILDA MARIA
        DESPACHO MINISTERIAL
        12:53:36

        7
        20/08/2015
        09:50:43
        PAZOS HAMM DE MUNAYLLA, MELVA ELIZABETH
        DNI
        06606713
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        12:06:33

        8
        20/08/2015
        09:28:26
        LOZANO ISIHUAYLAS, MERCEDES MILAGRO
        DNI
        09940174
        INFORMACION
        DE LA LAMA RIVERO, JULIO CARLOS ALFREDO
        OFICINA DE LOGISTICA
        09:40:23

        9
        20/08/2015
        12:26:40
        GALLEGOS PANIAGUA, HECTOR HUGO
        DNI
        07912682
        ENTREVISTA
        MERINO FELIX, LUIS PASCUAL
        DIRECCIÓN DE ACUICULTURA
        14:08:25

        10
        20/08/2015
        10:03:24
        PRADO RIOS, ANA LORENA
        DNI
        43802363
        ENTREVISTA
        SOTO SOTO, ZOILA LUZ
        DIRECCIÓN DE EXTRACCIÓN Y PRODUCCIÓN PESQUERA PARA CONSUMO HUMANO DIRECTO
        11:56:48

        11
        20/08/2015
        08:51:24
        HIDALGO SILVA, EDGAR
        DNI
        44999041
        ENTREVISTA
        CORONADO CAIRO, HURLEY
        OFICINA DE LOGISTICA
        09:09:20

        12
        20/08/2015
        09:08:39
        CHACON NIETO, GERMAN PABLO
        DNI
        10164878
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        09:16:33

        13
        20/08/2015
        09:21:35
        CHACON NIETO, GERMAN PABLO
        DNI
        10164878
        ENTREVISTA
        KASTNER URIBE, MONICA CARLOTA
        DESPACHO VICEMINISTERIAL DE PESQUERIA
        11:52:18

        14
        20/08/2015
        09:16:46
        MINAYA LEON, JUAN VICTOR
        DNI
        42215154
        ENTREVISTA
        MATSUURA GARRO, HUGO ALBERTO
        OFICINA DE TECNOLOGÍA DE LA INFORMACIÓN

        15
        20/08/2015
        11:17:10
        PEREZ LEANDRO, JAIME
        DNI
        07499613
        ENTREVISTA
        ABREGU BAEZ, MARIA DEL CARMEN
        DIRECCIÓN GENERAL DE EXTRACCIÓN Y PRODUCCIÓN PESQUERA PARA CONSUMO HUMANO INDIRECTO
        12:25:22

        16
        20/08/2015
        11:24:45
        LAJORA COLONIO, MARIA DEL ROSARIO
        DNI
        10169400
        ENTREVISTA
        SOTO SOTO, ZOILA LUZ
        DIRECCIÓN DE EXTRACCIÓN Y PRODUCCIÓN PESQUERA PARA CONSUMO HUMANO DIRECTO
        12:07:16

        17
        20/08/2015
        11:08:46
        DEL SOLAR, MARCO RAUL
        DNI
        07946248
        ENTREVISTA
        BARRETO RAMIREZ, HILDA MARIA
        DESPACHO MINISTERIAL

        18
        20/08/2015
        10:03:19
        CARMONA, MACARENA
        DNI
        70321170
        ENTREVISTA
        SOTO SOTO, ZOILA LUZ
        DIRECCIÓN DE EXTRACCIÓN Y PRODUCCIÓN PESQUERA PARA CONSUMO HUMANO DIRECTO
        11:56:39

        19
        20/08/2015
        11:08:51
        DUPUY ORTIZ DE ZEVALLOS, JAIME RICARDO
        DNI
        10542409
        ENTREVISTA
        BARRETO RAMIREZ, HILDA MARIA
        DESPACHO MINISTERIAL
        11:38:22

        20
        20/08/2015
        12:05:31
        CANCHAYA QUIJANO, ROLANDO PEDRO
        DNI
        07458265
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        12:28:47

        21
        20/08/2015
        11:08:56
        RUBIO CORDOVA, RAISA MARIA
        DNI
        70424649
        ENTREVISTA
        BARRETO RAMIREZ, HILDA MARIA
        DESPACHO MINISTERIAL
        12:25:06

        22
        20/08/2015
        10:05:44
        SANCHEZ CAMPOS, GILBERTO NOE
        DNI
        09155134
        ENTREVISTA
        GONZALEZ CAVA, DANIEL
        OFICINA DE LOGISTICA
        12:05:47

        23
        20/08/2015
        12:42:11
        ELGUERA RIOS, MARÍA ANGELICA
        DNI
        08884105
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        12:42:46

        24
        20/08/2015
        09:02:54
        DELGADO LINARES, RICARDO ALFONSO
        DNI
        70005187
        INFORMACION
        DE LA LAMA RIVERO, JULIO CARLOS ALFREDO
        OFICINA DE LOGISTICA
        09:09:27

        25
        20/08/2015
        09:50:39
        VALDEZ QUEZADA, CARMEN LUISA
        DNI
        40128896
        ENTREVISTA
        DE LA CRUZ MUCHOTRIGO, WALTER MANUEL
        OFICINA DE LOGISTICA
        10:03:41

        26
        20/08/2015
        10:16:34
        HUBNER TELLO, GUSTAVO ALEXANDER
        DNI
        45189217
        INFORMACION
        DE LA LAMA RIVERO, JULIO CARLOS ALFREDO
        OFICINA DE LOGISTICA
        10:17:20

        27
        20/08/2015
        10:50:50
        HUAMAN CAMACHO, VÍCTOR  MARTÍN
        DNI
        21887993
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        11:09:34

        28
        20/08/2015
        10:51:34
        RODRIGUEZ SEGURA, ALONSO HUMBERTO
        DNI
        44069491
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        10:51:54

        29
        20/08/2015
        11:56:17
        CORDOVA MARCHAN, SEGUNDO FLORENTINO
        DNI
        02644203
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        12:07:00

        30
        20/08/2015
        12:42:17
        ATENCIA ORTIZ , NINFA MAGDALENA
        DNI
        09380848
        INFORMACION
        DIOSES MORAN, MARIA TERESA
        OFICINA  DE ORIENTACIÓN Y ASESORÍA DEL PESCADOR
        12:42:25


text:
package chshare

import (
	"errors"
	"net"
	"net/http"
	"sync"
)

//HTTPServer extends net/http Server and
//adds graceful shutdowns
type HTTPServer struct {
	*http.Server
	listener  net.Listener
	running   chan error
	isRunning bool
	closer    sync.Once
}

//NewHTTPServer creates a new HTTPServer
func NewHTTPServer() *HTTPServer {
	return &HTTPServer{
		Server:   &http.Server{},
		listener: nil,
		running:  make(chan error, 1),
	}
}

func (h *HTTPServer) GoListenAndServe(addr string, handler http.Handler) error {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}
	h.isRunning = true
	h.Handler = handler
	h.listener = l
	go func() {
		h.closeWith(h.Serve(l))
	}()
	return nil
}

func (h *HTTPServer) closeWith(err error) {
	if !h.isRunning {
		return
	}
	h.isRunning = false
	h.running <- err
}

func (h *HTTPServer) Close() error {
	h.closeWith(nil)
	return h.listener.Close()
}

func (h *HTTPServer) Wait() error {
	if !h.isRunning {
		return errors.New("Already closed")
	}
	return <-h.running
}


text:
class SceneGraphTreeCtrl : public wxTreeCtrl
{
	DECLARE_DYNAMIC_CLASS(SceneGraphTreeCtrl)
	DECLARE_EVENT_TABLE()

public:
	/// Êîíñòðóêòîð êëàññà.
	SceneGraphTreeCtrl(void) { }

	/// Êîíñòðóêòîð êëàññà.
	/// <param name="parent">Óêàçàòåëü íà ðîäèòåëüñêîå îêíî.</param>
	/// <param name="id">Óíèêàëüíûé èäåíòèôèêàòîð äåðåâà.</param>
	SceneGraphTreeCtrl(wxWindow* parent, wxWindowID id = ID_TREECTRL);

	/// Äåñòðóêòîð êëàññà.
	~SceneGraphTreeCtrl(void);

	void OnSelChanged(wxTreeEvent& event);

	void AddChildSceneNode(const wxTreeItemId& parent, const wxString& name);

	void OnContextMenu(wxTreeEvent& event);

	void OnAddNodeChild(wxCommandEvent& event);

	void OnAddNodeSibling(wxCommandEvent& event);

	void OnDelNode(wxCommandEvent& event);

	void OnRename(wxCommandEvent& event);

	void OnItemActivated(wxTreeEvent& event);

	void OnBeginLabelEdit(wxTreeEvent& event);

	void OnEndLabelEdit(wxTreeEvent& event);

	Scene::ISceneNodeBase* GetSelectedItem(void);

private:
	SceneGraphTreeItemData* selectedItemData;
};

#endif // SCENEGRAPHTREECTRL_H


text:
package IOCDomain;

public interface IWebService
{
    IAuthenticator getAuthenticator();
    IStockQuote getStockQuote();
    void Execute();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 10(1): 23 (1918)

#### Original name
Astylospora cubensis Murrill

### Remarks
null


text:
<component name="libraryTable">
  <library name="support-vector-drawable-26.0.0-alpha1">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/9a9599e0ee74496f08b3005698e6f180a9a0ea0f/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/9a9599e0ee74496f08b3005698e6f180a9a0ea0f/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/support-vector-drawable/26.0.0-alpha1/support-vector-drawable-26.0.0-alpha1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
{-# LANGUAGE DeriveAnyClass    #-}
{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell   #-}

module Betfair.StreamingAPI.Types.OrderMarketChange
  ( OrderMarketChange(..)
  ) where

import Data.Aeson.TH                  (Options (omitNothingFields),
                                       defaultOptions, deriveJSON)
import Protolude
import Text.PrettyPrint.GenericPretty

--
import Betfair.StreamingAPI.Types.OrderRunnerChange (OrderRunnerChange)

data OrderMarketChange = OrderMarketChange
  { accountId :: Integer
  , orc       :: [OrderRunnerChange] -- Order Changes - a list of changes to orders on a selection
  , closed    :: Bool
  , id        :: Text -- Market Id - the id of the market the order is on
  } deriving (Eq, Read, Show, Generic, Pretty)

$(deriveJSON defaultOptions {omitNothingFields = True} ''OrderMarketChange)


text:
import * as React from "react";

export interface CellProps {
  showBorder: boolean;
}

const Cell: React.FC<CellProps> = ({ children, showBorder }) => (
  <div
    className={` w-7 h-7 md:w-14 md:h-14 mr-0.5 mb-0.5 border-dashed ${
      showBorder ? "border" : ""
    } border-white border-opacity-50 rounded`}
  >
    {children}
  </div>
);

export default Cell;


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape>
            <solid android:color="#ff74b2e0" />
        </shape>
    </item>
    <item
        android:bottom="1px"
        android:top="1px"
        android:left="1dp"
        android:right="1dp">
        <shape>
            <solid android:color="#ffffffff" />
        </shape>
    </item>

</layer-list>


text:
Alloy.Globals.fb.appid = Ti.App.Properties.getString('ti.facebook.appid');
Alloy.Globals.fb.permissions = ['publish_stream','email','user_birthday'];
Alloy.Globals.fb.forceDialogAuth = false;

Alloy.Globals.fb.addEventListener('login', function(e) {
  if (e.success) {

    Ti.App.Properties.setString('Cloud.sessionId', Alloy.Globals.fb.accessToken);
    Alloy.Globals.fb.requestWithGraphPath('me',{},"GET",function(e) {
      if (e.success) {
        var obj = JSON.parse(e.result),
            moment = require('alloy/moment'),
            token, user, email, birthday;

        email = obj.email;
        birthday = moment(obj.birthday, "MM/DD/YYYY");
        token = Alloy.Globals.fb.accessToken;
        Ti.API.info("Success: " +
                    "email" + email +
                    "birthday" + birthday +
                    "token" + token
                   );
        user = Alloy.createModel('social');
        user.fbLogin(token,email, birthday);
      }
      Alloy.Globals.TabGroup.setActiveTab(1);

      var chatRecords = Alloy.createCollection('chat');
      var _chat = Alloy.createModel('chat');
      _chat.show({
        success:function(response){
          Ti.API.info("chatRecords");
          Ti.API.info(response);
        },
        error:function(response){
        }
      });

    });

  } else if (e.error) {
    Ti.API.info(e.error);
  } else if (e.cancelled) {
    Ti.API.info("Canceled");
  }
});
Ti.API.info(Alloy.Globals);
Ti.API.info(Alloy.Globals.TabGroup);
$.login.open();
$.fbloginLabel.addEventListener('click', function(e) {
  Alloy.Globals.fb.authorize();
});


text:
package org.kie.workbench.common.dmn.webapp.kogito.common.client.services;

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

import javax.enterprise.context.ApplicationScoped;

import org.kie.workbench.common.dmn.api.editors.types.DMNSimpleTimeZone;
import org.uberfire.client.views.pfly.widgets.MomentTimeZone;

/**
 * Provides TimeZone details
 */
@ApplicationScoped
public class TimeZonesProvider {

    private final List<DMNSimpleTimeZone> TIME_ZONES = new ArrayList<>();

    public List<DMNSimpleTimeZone> getTimeZones() {
        if (TIME_ZONES.isEmpty()) {
            TIME_ZONES.addAll(buildTimeZones());
        }
        return TIME_ZONES;
    }

    private List<DMNSimpleTimeZone> buildTimeZones() {
        final List<DMNSimpleTimeZone> timeZones = new ArrayList<>();
        final String[] names = getNames();

        for (String name : names) {
            final double offset = getOffset(name);
            final String offsetString = getOffsetString(name);
            timeZones.add(new DMNSimpleTimeZone(name,
                                                offset,
                                                offsetString));
        }
        return timeZones;
    }

    protected String[] getNames() {
        return MomentTimeZone.Builder.tz().names();
    }

    protected double getOffset(final String timeZoneName) {
        return MomentTimeZone.Builder.tz(timeZoneName).utcOffset() / 60;
    }

    protected String getOffsetString(final String timeZoneName) {
        return MomentTimeZone.Builder.tz(timeZoneName).format("Z");
    }
}


text:
namespace help_utils_chromeos {

// Returns true if update over cellular networks is enabled.
bool IsUpdateOverCellularAllowed();

// Returns localized name for the connection |type|.
string16 GetConnectionTypeAsUTF16(const std::string& type);

}  // namespace help_utils_chromeos

#endif  // CHROME_BROWSER_UI_WEBUI_HELP_HELP_UTILS_CHROMEOS_H_