text:
An image sprite is a collection of images put into a single image. A web page with many images can take a long time to load and generates multiple server requests. Using image sprites will reduce the number of server requests and save bandwidth.
This utility will help to create sprite image and related CSS file.

## How to use SpriteImages
It is console application, which takes source image directory as the input, and create sprite image and CSS file to the target directory provided. If no target directory provided, it will take the application executing path and creates an output folder and generates the files.

`C:\spriteimages.exe --source C:\Sample` - Generates sprite image and CSS files under C:\Output folder.

`C:\spriteimages.exe --source C:\Sample --target C:\Sample\Sprite` - Generates sprite image and CSS files under C:\Sample\Sprite folder.

`C:\spriteimages.exe --source C:\Sample --target C:\Sample\Sprite --useClass` - Generates sprite image and CSS files under C:\Sample\Sprite folder. The generated CSS element names will be with "." otherwise it will be with "#"


text:
using OpenStack.Serialization;

namespace OpenStack.Compute.v2_1.Serialization
{
    /// <summary>
    /// Server reboot type.
    /// </summary>
    /// <exclude />
    public class RebootType<T> : StringEnumeration
        where T : RebootType<T>, new()
    {
        /// <summary>
        /// A soft reboot is a graceful shutdown and restart of your server's operating system.
        /// </summary>
        public static readonly T Soft = new T {DisplayName = "SOFT"};

        /// <summary>
        /// A hard reboot power cycles your server, which performs an immediate shutdown and restart.
        /// </summary>
        public static readonly T Hard = new T {DisplayName = "HARD"};
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;

namespace DSL.POS.Report.Setup
{
    public class ReportSalesRegisterInfo
    {
        /// <summary>
        /// Get or set DateSet for Sales Register
        /// </summary>
        /// <param name="DemandStartdate">Demand Start Date</param>
        /// <param name="DemandEnddate">Demand End Date</param>
        /// <param name="branchPK">Branch Primary Key</param>
        /// <param name="productCategory">Product Category Primary Key</param>
        /// <param name="productSubCategory">Product SubCategory Primary Key</param>
        /// <param name="productBrand">Product Brand Primary Key</param>
        /// <param name="productPK">Product Primary Key</param>
        /// <returns>DataSet</returns>
        public DataSet GetSalesInfo(DateTime DemandStartdate, DateTime DemandEnddate, Guid branchPK, Guid productCategory, Guid productSubCategory, Guid productBrand, Guid productPK)
      {
          SqlConnection sc = new SqlConnection();
          sc.ConnectionString = ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString();

          SqlDataAdapter da = new SqlDataAdapter();
          SqlCommand cmd = new SqlCommand();

          Guid strConvartGuid = Guid.NewGuid();

          strConvartGuid = (Guid)TypeDescriptor.GetConverter(strConvartGuid).ConvertFromString("00000000-0000-0000-0000-000000000000");

          try
          {
              cmd.Connection = sc;
              cmd.CommandType = CommandType.StoredProcedure;
              cmd.CommandText = "ReptSalesRegisterInfo";
              cmd.Parameters.Add(new SqlParameter("@DemandStartdate", SqlDbType.DateTime));
              cmd.Parameters.Add(new SqlParameter("@DemandEnddate", SqlDbType.DateTime));
              cmd.Parameters.Add(new SqlParameter("@BR_PK", SqlDbType.UniqueIdentifier, 16));
              cmd.Parameters.Add(new SqlParameter("@PC_Pk", SqlDbType.UniqueIdentifier, 16));
              cmd.Parameters.Add(new SqlParameter("@PSC_PK", SqlDbType.UniqueIdentifier, 16));
              cmd.Parameters.Add(new SqlParameter("@PB_PK", SqlDbType.UniqueIdentifier, 16));
              cmd.Parameters.Add(new SqlParameter("@P_PK", SqlDbType.UniqueIdentifier, 16));

              if (DemandStartdate.ToString() == "00/00/0000")
              {
                  cmd.Parameters["@DemandStartdate"].Value = null;
              }
              else
              {
                  cmd.Parameters["@DemandStartdate"].Value = DemandStartdate;
              }
              if (DemandEnddate.ToString() == "00/00/0000")
              {
                  cmd.Parameters["@DemandEnddate"].Value = null;
              }
              else
              {
                  cmd.Parameters["@DemandEnddate"].Value = DemandEnddate;
              }
              if (branchPK.ToString() == "00000000-0000-0000-0000-000000000000")
              {
                  cmd.Parameters["@BR_PK"].Value = strConvartGuid;
              }
              else
              {
                  cmd.Parameters["@BR_PK"].Value = branchPK;
              }
              if (productCategory.ToString() == "00000000-0000-0000-0000-000000000000")
              {
                  cmd.Parameters["@PC_Pk"].Value = strConvartGuid;
              }
              else
              {
                  cmd.Parameters["@PC_Pk"].Value = productCategory;
              }
              if (productSubCategory.ToString() == "00000000-0000-0000-0000-000000000000")
              {
                  cmd.Parameters["@PSC_PK"].Value = strConvartGuid;
              }
              else
              {
                  cmd.Parameters["@PSC_PK"].Value = productSubCategory;
              }
              if (productBrand.ToString() == "00000000-0000-0000-0000-000000000000")
              {
                  cmd.Parameters["@PB_PK"].Value = strConvartGuid;
              }
              else
              {
                  cmd.Parameters["@PB_PK"].Value = productBrand;
              }
              if (productPK.ToString() == "00000000-0000-0000-0000-000000000000")
              {
                  cmd.Parameters["@P_PK"].Value = strConvartGuid;
              }
              else
              {
                  cmd.Parameters["@P_PK"].Value = productPK;
              }

              da.SelectCommand = cmd;

              sc.Open();

              DataSet ds = new DataSet();
              da.Fill(ds, "SalesRegisterInfo");

              return ds;
          }
          catch (Exception exp)
          {
              throw exp;
          }
          finally
          {
              sc.Close();
          }
      }
    }
}


text:
var Http = {};

Http.Errors = {};

Http.PromiseImplementation = window.Promise;


text:
import {
  fetch,
  normalize,
  extractHubURL,
  mercureSubscribe as subscribe
} from '../../utils/dataAccess';
import { success as deleteSuccess } from './delete';

export function error(error) {
  return { type: 'RECIPE_LIST_ERROR', error };
}

export function loading(loading) {
  return { type: 'RECIPE_LIST_LOADING', loading };
}

export function success(retrieved) {
  return { type: 'RECIPE_LIST_SUCCESS', retrieved };
}

export function list(page = 'recipes') {
  return dispatch => {
    dispatch(loading(true));
    dispatch(error(''));

    fetch(page)
      .then(response =>
        response
          .json()
          .then(retrieved => ({ retrieved, hubURL: extractHubURL(response) }))
      )
      .then(({ retrieved, hubURL }) => {
        retrieved = normalize(retrieved);

        dispatch(loading(false));
        dispatch(success(retrieved));

        if (hubURL && retrieved['hydra:member'].length)
          dispatch(
            mercureSubscribe(
              hubURL,
              retrieved['hydra:member'].map(i => i['@id'])
            )
          );
      })
      .catch(e => {
        dispatch(loading(false));
        dispatch(error(e.message));
      });
  };
}

export function reset(eventSource) {
  return dispatch => {
    if (eventSource) eventSource.close();

    dispatch({ type: 'RECIPE_LIST_RESET' });
    dispatch(deleteSuccess(null));
  };
}

export function mercureSubscribe(hubURL, topics) {
  return dispatch => {
    const eventSource = subscribe(hubURL, topics);
    dispatch(mercureOpen(eventSource));
    eventSource.addEventListener('message', event =>
      dispatch(mercureMessage(normalize(JSON.parse(event.data))))
    );
  };
}

export function mercureOpen(eventSource) {
  return { type: 'RECIPE_LIST_MERCURE_OPEN', eventSource };
}

export function mercureMessage(retrieved) {
  return dispatch => {
    if (1 === Object.keys(retrieved).length) {
      dispatch({ type: 'RECIPE_LIST_MERCURE_DELETED', retrieved });
      return;
    }

    dispatch({ type: 'RECIPE_LIST_MERCURE_MESSAGE', retrieved });
  };
}


text:
package org.axonframework.modelling.saga.repository;

import org.axonframework.common.caching.Cache;
import org.axonframework.modelling.saga.AssociationValue;
import org.axonframework.modelling.saga.AssociationValuesImpl;
import org.axonframework.modelling.saga.repository.inmemory.InMemorySagaStore;
import org.junit.jupiter.api.*;

import java.util.Collections;
import java.util.Set;

import static java.util.Collections.singleton;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * Abstract test class for validating the {@link CachingSagaStore}. Expects implementations to construct the type of
 * {@link Cache} used during testing.
 *
 * @author Allard Buijze
 */
public abstract class CachingSagaStoreTest {

    private SagaStore<StubSaga> delegate;
    private Cache sagaCache;
    private Cache associationsCache;

    private CachingSagaStore<StubSaga> testSubject;

    @SuppressWarnings("unchecked")
    @BeforeEach
    void setUp() {
        //noinspection rawtypes
        delegate = spy((SagaStore) new InMemorySagaStore());
        sagaCache = spy(sagaCache());
        associationsCache = spy(associationCache());

        testSubject = CachingSagaStore.<StubSaga>builder()
                                      .delegateSagaStore(delegate)
                                      .sagaCache(sagaCache)
                                      .associationsCache(associationsCache)
                                      .build();
    }

    /**
     * Retrieve the saga {@link Cache} used for testing.
     *
     * @return The saga {@link Cache} used for testing.
     */
    abstract Cache sagaCache();

    /**
     * Retrieve the association value entry {@link Cache} used for testing.
     *
     * @return The association value entry {@link Cache} used for testing.
     */
    abstract Cache associationCache();

    private void clearCaches() {
        sagaCache.removeAll();
        associationsCache.removeAll();
    }

    @Test
    void sagaAddedToCacheOnAdd() {
        testSubject.insertSaga(StubSaga.class, "123", new StubSaga(), singleton(new AssociationValue("key", "value")));

        verify(sagaCache).put(eq("123"), any());
        verify(associationsCache, never()).put(any(), any());
    }

    @Test
    void associationsAddedToCacheOnLoad() {
        testSubject.insertSaga(StubSaga.class, "id", new StubSaga(), singleton(new AssociationValue("key", "value")));

        verify(associationsCache, never()).put(any(), any());

        clearCaches();
        reset(sagaCache, associationsCache);

        final AssociationValue associationValue = new AssociationValue("key", "value");

        Set<String> actual = testSubject.findSagas(StubSaga.class, associationValue);
        assertEquals(singleton("id"), actual);
        verify(associationsCache, atLeast(1)).get("org.axonframework.modelling.saga.repository.StubSaga/key=value");
        verify(associationsCache).putIfAbsent("org.axonframework.modelling.saga.repository.StubSaga/key=value",
                                              Collections.singleton("id"));
    }

    @Test
    void sagaAddedToCacheOnLoad() {
        StubSaga saga = new StubSaga();
        testSubject.insertSaga(StubSaga.class, "id", saga, singleton(new AssociationValue("key", "value")));

        clearCaches();
        reset(sagaCache, associationsCache);

        SagaStore.Entry<StubSaga> actual = testSubject.loadSaga(StubSaga.class, "id");
        assertSame(saga, actual.saga());

        verify(sagaCache).get("id");
        verify(sagaCache).put(eq("id"), any());
        verify(associationsCache, never()).put(any(), any());
    }

    @Test
    void sagaNotAddedToCacheWhenLoadReturnsNull() {
        clearCaches();
        reset(sagaCache, associationsCache);

        SagaStore.Entry<StubSaga> actual = testSubject.loadSaga(StubSaga.class, "id");
        assertNull(actual);

        verify(sagaCache).get("id");
        verify(sagaCache, never()).put(eq("id"), any());
        verify(associationsCache, never()).put(any(), any());
    }

    @Test
    void commitDelegatedAfterAddingToCache() {
        StubSaga saga = new StubSaga();
        AssociationValue associationValue = new AssociationValue("key", "value");
        testSubject.insertSaga(StubSaga.class, "123", saga, singleton(associationValue));

        verify(associationsCache, never()).put(any(), any());
        verify(delegate).insertSaga(StubSaga.class, "123", saga, singleton(associationValue));
    }

    @Test
    void sagaAndAssociationsRemovedFromCacheOnDelete() {
        String testSagaId = "123";
        AssociationValue testAssociationValue = new AssociationValue("key", "value");
        AssociationValuesImpl testUpdatedAssociations = new AssociationValuesImpl();
        testUpdatedAssociations.add(testAssociationValue);
        String expectedAssociationKey = "org.axonframework.modelling.saga.repository.StubSaga/key=value";

        // Insert a Saga into the store, thus adding it to the cache.
        testSubject.insertSaga(StubSaga.class, testSagaId, new StubSaga(), singleton(testAssociationValue));
        assertTrue(sagaCache.containsKey(testSagaId));

        // Find the Saga, as this will set the association values in the cache.
        // Insert only adds association values to the cache, if they were already present.
        testSubject.findSagas(StubSaga.class, testAssociationValue);
        assertTrue(sagaCache.containsKey(testSagaId));
        assertTrue(associationsCache.containsKey(expectedAssociationKey));

        // Update the Saga instance, to ensure updating the Saga and adding "new" associations to the cache works.
        testSubject.updateSaga(StubSaga.class, testSagaId, new StubSaga(), testUpdatedAssociations);
        assertTrue(sagaCache.containsKey(testSagaId));
        assertTrue(associationsCache.containsKey(expectedAssociationKey));

        // Delete the Saga, to ensure it's removed from the cache.
        testSubject.deleteSaga(StubSaga.class, testSagaId, singleton(testAssociationValue));
        assertFalse(sagaCache.containsKey(testSagaId));
        assertFalse(associationsCache.containsKey(expectedAssociationKey));
    }
}


text:
Device::Device(){
  DeviceManager::registerDevice(this);
}

void Device::device_loop(Command cmd){

}

void Device::device_setup(){

}

void DeviceManager::registerDevice(Device *device){
  devices[device_count] = device;
  device_count++;
}

void DeviceManager::doDeviceLoops(Command cmd){
  for(int i=0;i<device_count;i++) {
    int stime = millis();
    devices[i]->device_loop(cmd);
    int delta = millis()-stime;
    if (delta > 0){
      DeviceManager:device_loop_ms[i]+=delta;
    }
  }
}

void DeviceManager::doDeviceSetups(){
  for(int i=0;i<device_count;i++) {
    devices[i]->device_setup();
  }
}

void OutputNavData(){
    Serial.print(F("hdgd:"));
    Serial.print(navdata::HDGD);
    Serial.print(';');
    Serial.print(F("deep:"));
    Serial.print(navdata::DEEP);
    Serial.print(';');
    Serial.print(F("pitc:"));
    Serial.print(navdata::PITC);
    Serial.print(';');
    Serial.print(F("roll:"));
    Serial.print(navdata::ROLL);
    Serial.print(';');
    Serial.print(F("yaw:"));
    Serial.print(navdata::YAW);
    Serial.print(';');
    Serial.print(F("fthr:"));
    Serial.print(navdata::FTHR);
    Serial.println(';');
}

void OutputSharedData(){

    Serial.print(F("motorAttached:"));
    Serial.print(thrusterdata::MATC);
    Serial.println(';');

    Serial.print(F("servo:"));
    Serial.print(cameraMountdata::CMNT);
    Serial.print(';');
    Serial.print(F("starg:"));
    Serial.print(cameraMountdata::CMTG);
    Serial.println(';');

    Serial.print(F("fmem:"));
    Serial.print(capedata::FMEM);
    Serial.print(';');
    Serial.print(F("vout:"));
    Serial.print(capedata::VOUT);
    Serial.print(';');
    Serial.print(F("iout:"));
    Serial.print(capedata::IOUT);
    Serial.print(';');
    Serial.print(F("atmp:"));
    Serial.print(capedata::ATMP);
    Serial.print(';');
    Serial.print(F("ver:"));
    Serial.print(F("CUSTOM_BUILD"));
    Serial.print(';');
    Serial.print(F("cmpd:"));
    Serial.print( F(__DATE__));
    Serial.print( F(", "));
    Serial.print( F(__TIME__));
    Serial.print( F(", "));
    Serial.println( F(__VERSION__));
    Serial.print(';');
    Serial.print(F("time:"));
    Serial.print(capedata::UTIM);
    Serial.println(';');

    Serial.print(F("pres:"));
    Serial.print(envdata::PRES);
    Serial.print(';');
    Serial.print(F("temp:"));
    Serial.print(envdata::TEMP);
    Serial.println(';');

    Serial.print(F("dlms:")); //device loop time in ms
    for(int i=0;i<DeviceManager::device_count;i++){
      Serial.print(i);
      Serial.print('|');
      Serial.print(DeviceManager::device_loop_ms[i]);
    }
    Serial.println(';');

}

int DeviceManager::device_count = 0;
Device *DeviceManager::devices[MAX_DEVICES];
unsigned DeviceManager::device_loop_ms[MAX_DEVICES];

// Initialize all of the shared data types
double navdata::HDGD = 0;
float navdata::DEEP = 0;
float navdata::PITC = 0;
float navdata::ROLL = 0;
float navdata::FTHR = 0;
float navdata::YAW = 0;

float envdata::PRES = 0;
float envdata::TEMP = 0;

double capedata::FMEM = 0;
double capedata::VOUT = 0;
double capedata::IOUT = 0;
double capedata::ATMP = 0;
String capedata::VER = "";
double capedata::UTIM = 0;

boolean thrusterdata::MATC = true;

int cameraMountdata::CMNT = MIDPOINT;
int cameraMountdata::CMTG = MIDPOINT;


text:
from __future__ import absolute_import

__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"

'''
Utility functions for celery.
'''

import sys
from timeit import itertools

from celery import current_app as app, states

from androlyze.analyze.distributed.exception import NetworkError
from androlyze.log.Log import log, clilog
from androlyze.storage.exception import DatabaseLoadException
from androlyze.util import Util

def write_analyze_task_results_to_fs(storage, group_result, chunked = False):
    '''
    Get successful task results and write them to disk if enabled.

    Parameters
    ----------
    storage: RedundantStorage
    group_result : GroupResult
    chunked : bool, optional (default is False)
        If work has been divided into chunks.

    Returns
    -------
    int
        Number of successful tasks
    '''
    if group_result is not None:
        results = get_successful_analyze_task_results(group_result, chunked = chunked)

        # no result writing to disk wanted
        if not storage.fs_storage_disabled():
            clilog.info("Fetching all analysis results for storage ...")
            if results:
                try:
                    storage.fetch_results_from_mongodb(results)
                except DatabaseLoadException as e:
                    log.exception(e)
            return len(results)

    return 0

def get_completed_tasks(group_result, total_cnt, tasks_per_chunk = 1):
    '''
    Get number of completed tasks from `group_result`.

    Parameters
    ----------
    group_result : GroupResult
    total_cnt : int
        Number of total tasks.
    tasks_per_chunk : int, optional (default is 1)
        Number of chunks the work is divided into.
    '''
    # not each chunk has the full number of tasks (last one doesn't)
    return min(total_cnt, group_result.completed_count() * tasks_per_chunk)

def get_successful_analyze_task_results(group_result, chunked = False):
    '''
    Get results for successful tasks from `group_result` (meaning their results) and ignore revoked ones.

    Parameters
    ----------
    group_result : GroupResult
    chunked : bool, optional (default is False)
        If work has been divided into chunks.

    Returns
    -------
    list< tuple<id, gridfs (bool)>>
    '''

    results = []

    def check_n_add(res):
        ''' Check if `res` is ready and has not been revoked etc. '''
        try:
            if res is not None:
                    result = res.get(propagate = False)
                    # if chunked, result is list of multiple tasks -> unpack results
                    if chunked:
                        result = Util.flatten(result)
                    # no result available if e.g. exception raised
                    if result is not None:
                        results.append(result)
        # TaskRevokedError
        except Exception:
            pass

    for res in group_result:
        check_n_add(res)

    # single result is of type list< tuple<id, gridfs (bool)>>
    # so flatten the result!
    return list(itertools.chain(*results))

def exp_backoff(task, _max = 64):
    '''
    Use exponential backoff for task retrying.

    wait_time = 2^1,..., 2^n limit by `_max`.

    Parameters
    ----------
    task : celery.app.task.Task
    _max : int, optional (default is 64)
        Maximum time to use.
    '''
    return min(2 ** task.request.retries, _max)

def get_registered_workers():
    ''' Get the registered celery workers '''
    ping_results = app.control.inspect().ping() or {}
    return ping_results.keys() or ("No workers available/pingable!", )

############################################################
#---Worker and network
############################################################

def get_workers_and_check_network():
    ''' Get the celery workers and check network.

    Returns
    -------
    str
        List of workers as str.

    Raises
    ------
    NetworkError
    '''
    try:
        reg_workers = get_registered_workers()
        return "Registered workers: %s" % ','.join(reg_workers)
    # network
    except IOError as e:
        raise NetworkError(caused_by = e, msg = "Network error or maybe invalid credentials? Have a look at log: /var/log/rabbitmq/<logfile> "), None, sys.exc_info()[2]

############################################################
#---Result fetching/callback
############################################################

def join_native(result_group, timeout=None, propagate=True,
                interval=0.5, callback=None):
    ''' Same as :py:method:`GroupResult.join_native` but delivers task meta too.
    Not just the result!
    '''
    from androlyze.celery import CeleryConstants

    order_index = None if callback else dict(
        (result.id, i) for i, result in enumerate(result_group.results)
    )
    acc = None if callback else [None for _ in range(len(result_group))]
    for task_id, meta in result_group.iter_native(timeout = timeout, interval = interval):
        value = meta
        if propagate and meta[CeleryConstants.CELERY_RESULT_BACKEND_KEY_STATUS] in states.PROPAGATE_STATES:
            raise value
        if callback:
            callback(task_id, value)
        else:
            acc[order_index[task_id]] = value
    return acc


text:
package org.stellar.base;

import org.stellar.base.xdr.AccountID;
import org.stellar.base.xdr.Int64;
import org.stellar.base.xdr.OperationType;
import org.stellar.base.xdr.PaymentOp;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Represents Payment operation.
 * @see List of Operations
 */
public class PaymentOperation extends Operation {

  private final KeyPair destination;
  private final Asset asset;
  private final String amount;

  private PaymentOperation(KeyPair destination, Asset asset, String amount) {
    this.destination = checkNotNull(destination, "destination cannot be null");
    this.asset = checkNotNull(asset, "asset cannot be null");
    this.amount = checkNotNull(amount, "amount cannot be null");
  }

  /**
   * Account that receives the payment.
   */
  public KeyPair getDestination() {
    return destination;
  }

  /**
   * Asset to send to the destination account.
   */
  public Asset getAsset() {
    return asset;
  }

  /**
   * Amount of the asset to send.
   */
  public String getAmount() {
    return amount;
  }

  @Override
  org.stellar.base.xdr.Operation.OperationBody toOperationBody() {
    PaymentOp op = new PaymentOp();

    // destination
    AccountID destination = new AccountID();
    destination.setAccountID(this.destination.getXdrPublicKey());
    op.setDestination(destination);
    // asset
    op.setAsset(asset.toXdr());
    // amount
    Int64 amount = new Int64();
    amount.setInt64(Operation.toXdrAmount(this.amount));
    op.setAmount(amount);

    org.stellar.base.xdr.Operation.OperationBody body = new org.stellar.base.xdr.Operation.OperationBody();
    body.setDiscriminant(OperationType.PAYMENT);
    body.setPaymentOp(op);
    return body;
  }

  /**
   * Builds Payment operation.
   * @see PathPaymentOperation
   */
  public static class Builder {
    private final KeyPair destination;
    private final Asset asset;
    private final String amount;

    private KeyPair mSourceAccount;

    /**
     * Construct a new PaymentOperation builder from a PaymentOp XDR.
     * @param op {@link PaymentOp}
     */
    Builder(PaymentOp op) {
      destination = KeyPair.fromXdrPublicKey(op.getDestination().getAccountID());
      asset = Asset.fromXdr(op.getAsset());
      amount = Operation.fromXdrAmount(op.getAmount().getInt64().longValue());
    }

    /**
     * Creates a new PaymentOperation builder.
     * @param destination The destination keypair (uses only the public key).
     * @param asset The asset to send.
     * @param amount The amount to send in lumens.
     * @throws ArithmeticException when amount has more than 7 decimal places.
     */
    public Builder(KeyPair destination, Asset asset, String amount) {
      this.destination = destination;
      this.asset = asset;
      this.amount = amount;
    }

    /**
     * Sets the source account for this operation.
     * @param account The operation's source account.
     * @return Builder object so you can chain methods.
     */
    public Builder setSourceAccount(KeyPair account) {
      mSourceAccount = account;
      return this;
    }

    /**
     * Builds an operation
     */
    public PaymentOperation build() {
      PaymentOperation operation = new PaymentOperation(destination, asset, amount);
      if (mSourceAccount != null) {
        operation.setSourceAccount(mSourceAccount);
      }
      return operation;
    }
  }
}


text:
NGSD is an acronym for the *next gen sequencing database*.
The NGSD manages samples, runs, variants, QC data and genes data for NGS sequencing.

This document describes the installation of the NGSD database.
The installation instructions are based on Ubuntu 18.04 LTS, but should work similarly on other Linux distributions.

These instructions assume that the installation is performed as root. If that is not the case, you have to prepend `sudo ` to all commands that need root privileges.

## MySQL database setup

The database backend of the NGSD is a MySQL database. To set it up, follow these instructions:

* If not available, install the MySQL package:

		> sudo apt-get install mysql-server

* Log into the server, e.g. with:

		> sudo mysql -u root

* Create the NGSD database:

		mysql> create database ngsd;
		mysql> grant all on ngsd.* to 'ngsduser'@'%' identified by '[mysql-password]';
		mysql> exit

## MySQL database optimization

In order to optimize the performance of MySQL for the NGSD, you can adapt/add the following settings in the `/etc/mysql/my.cnf` file:

		[mysqld]
		innodb_buffer_pool_instances = 2
		innodb_buffer_pool_size = 32G
		innodb_flush_log_at_trx_commit = 2
		innodb_lock_wait_timeout = 1000
		innodb_lru_scan_depth = 512
		join_buffer_size = 16M
		max_allowed_packet = 64M
		max_connections = 300
		max_heap_table_size = 256M
		query_cache_limit = 64M
		query_cache_size = 256M
		tmp_table_size = 256M
		wait_timeout = 108000

Restart the server:

		> sudo service mysql restart

## Initial import of data

The initial import of database content using ngs-bits.

* If missing, create `ngs-bits/bin/settings.ini` with:

		> cp ngs-bits/bin/settings.ini.example ngs-bits/bin/settings.ini

* Fill in the following NGSD credentials:
	* ngsd_host = `???`
	* ngsd_port = `???`
	* ngsd_name = ngsd
	* ngsd_user = ngsduser
	* ngsd_pass = `[mysql-password]`

* To set up the NGSD tables, use command:

		> ngs-bits/bin/NGSDInit -force [mysql-password]

* Finally, QC terms and gene information from several databases must be imported.
  Proceed accoding to the instructions of the following tools in the listed order:

		> ngs-bits/bin/NGSDImportQC --help
		> ngs-bits/bin/NGSDImportHGNC --help
		> ngs-bits/bin/NGSDImportEnsembl --help
		> ngs-bits/bin/NGSDImportHPO --help
		> ngs-bits/bin/NGSDImportGeneInfo --help
		> ngs-bits/bin/NGSDImportOMIM --help
		> ngs-bits/bin/NGSDImportORPHA --help

## Export NGSD annotation data

The NGSD variant counts for germline and somatic as well as the gene info can be exported to a VCF/BED file using NGSDExportAnnotationData.

* For germline small variants:

		> ngs-bits/bin/NGSDExportAnnotationData -variants [vcf_output_file] -genes [bed_file]

* For germline structural variants:

		> ngs-bits/bin/NGSDExportSV -out_folder [export_folder]

* For somatic small variants:

		> ngs-bits/bin/NGSDExportAnnotationData -variants [somatic_vcf_output_file] -mode somatic

The resulting VCF files have to be sorted (e.g. using `VcfStreamSort`) and then gzipped and indexed to be used as annotation source:

		> ngs-bits/bin/VcfStreamSort -in [unsorted_vcf] -out [sorted_vcf]
		> bgzip -c [sorted_vcf] > [sorted_vcf_gzip]
		> tabix -p vcf [sorted_vcf_gzip]

For variant annotation `VcfAnnotateFromVcf` and `VcfAnnotateFromBed` can be used.


text:
package umich.cse.yctung.libacousticsensing.Network;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.LinkedList;
import java.util.Queue;

import umich.cse.yctung.libacousticsensing.Audio.AudioSource;
import umich.cse.yctung.libacousticsensing.Constant;
import umich.cse.yctung.libacousticsensing.Log;
/**
 * Created by Yu-Chih Tung on 10/15/15.
 * NetworkController provides interface to talk to the matlab server
 * 2015/10/15: update to a common controller for all EchoTag/BumpFree/MicroButton projects
 * */

public class NetworkController {
//==================================================================================================
//	Constants
//==================================================================================================
	private static String LOG_TAG= Constant.LOG_TAG+"_NetworkController";
	// Types of actions (for packets sent from the server)
	private final static int ACTION_CONNECT = 1; 	// ACTION_CONNECT format: | ACTION_CONNECT | xxx parater setting
	private final static int ACTION_DATA 	= 2; 	// ACTION_DATA format: | ACTION_DATA | # of bytes to send | byte[] | -1
	private final static int ACTION_CLOSE 	= -1;	// ACTION_CLOSE format: | ACTION_CLOSE |
	private final static int ACTION_SET 	= 3;
	private final static int ACTION_INIT 	= 4;
	private final static int ACTION_SENSING_END = 5;
	private final static int ACTION_USER	= 6; 	// used for sending application's user-defined variables

	// Types of set actions (for packets sent to the server)
	public final static int SET_TYPE_BYTE_ARRAY 	= 1;
	public final static int SET_TYPE_STRING 		= 2;
	public final static int SET_TYPE_DOUBLE 		= 3;
	public final static int SET_TYPE_INT 			= 4;
	public final static int SET_TYPE_VALUE_STRING 	= 5; // sent value by string

	// Types of receving packets from server
	private final static int REACTION_SET_MEDIA 	= 1;
	private final static int REACTION_ASK_SENSING   = 2;
	private final static int REACTION_SET_RESULT 	= 3;
	private final static int REACTION_STOP_SENSING  = 4;
	private final static int REACTION_SERVER_CLOSED  = 5;

	// Server statuses
	private final static int SERVER_STATUS_DISABLED = -1; // default status of server
	private final static int SERVER_STATUS_ENABLED 	= 1;
	private final static int SERVER_STATUS_CONNECTED = 2;

	// Other control flags
	private final static boolean SAVE_LATEST_LOADED_AUDIO_TO_FILE = false;
	private final static int SOCKET_CONNECTION_CREATE_TIMEOUT = 500; // ms
	private final static int SOCKET_DATA_TRANSMIT_TIMEOUT = 0; // 0 means never timeout
	private final static int DATA_SENDING_THREAD_LOOP_DELAY = 1; //ms

//==================================================================================================
//	Internal status
//==================================================================================================
	int status;
	private Socket sc = null;
	private DataOutputStream dataOut = null;
	private DataInputStream dataIn = null;
	Queue<NetworkRequest> requestQueue;
	NetworkControllerListener listener;

//==================================================================================================
//	Public interface to open socket and send packets
//==================================================================================================
	public NetworkController(NetworkControllerListener listener) {
		this.listener=listener;
		status=SERVER_STATUS_DISABLED;
		requestQueue = new LinkedList();
	}

	// start connect to servers
	public void connectToServer(final String serverIp, final int serverPort){
		new Thread(){ // NOTE: networking processing can't be in the UI thread
			public void run() {
				try {
					InetAddress serverAddr = InetAddress.getByName(serverIp);
					Log.d(LOG_TAG,String.format("Trying to connect server at %s:%d", serverIp, serverPort));
					sc = new Socket(); // use a dummy socket initialization because the new timeout need to be set before connection
					sc.setSoTimeout(SOCKET_CONNECTION_CREATE_TIMEOUT);
					sc.connect(new InetSocketAddress(serverAddr, serverPort), SOCKET_CONNECTION_CREATE_TIMEOUT);
					sc.setSoTimeout(SOCKET_DATA_TRANSMIT_TIMEOUT); // update timeout back to normal timeout, e.g., no timeout

					dataOut = new DataOutputStream(sc.getOutputStream());
					dataIn = new DataInputStream(sc.getInputStream());

					Thread.sleep(1000); // intentionally wait to avoid packet lost (matlab bug)

					dataOut.write(ACTION_CONNECT);
					dataOut.flush();

					createThreadToReceiveAndBlockArrivePacket();

					status = SERVER_STATUS_CONNECTED;
					listener.isConnected(true, "Connected to server successfully");
				} catch (UnknownHostException e) {
					Log.e(LOG_TAG, "Can't connect socket : " + e.getMessage());
					e.printStackTrace();
					listener.isConnected(false, "UnknownHostException" + e.getMessage());
				} catch (IOException e) {
					Log.e(LOG_TAG, "Can't connect socket : " + e.getMessage());
					e.printStackTrace();
					listener.isConnected(false, "IOException" + e.getMessage());
				} catch (InterruptedException e) {
					e.printStackTrace();
					listener.isConnected(false, "InterruptedException" + e.getMessage());
				}
			}
		}.start();
	}

	public void sendInitAction() {
		NetworkRequest r = new NetworkRequest(ACTION_INIT, null, null, -1);
		requestQueue.add(r);
		sendPacketByAnotherThread();
	}

	// Note: the request here means the user study request
	boolean audioHasBeenUpdatedAfterRequestStartIsAsked = false;

	public void sendDataRequest(byte[] data) {
		NetworkRequest r = new NetworkRequest(ACTION_DATA, null, data, -1);
		requestQueue.add(r);
		sendPacketByAnotherThread();
	}

	public void sendSetAction(int setType, String name, byte[] data) {

		NetworkRequest r = new NetworkRequest(ACTION_SET, name, data, setType);
		requestQueue.add(r);
		sendPacketByAnotherThread();
	}

	public void sendUserAction(int stamp, String tag, int code, float arg0, float arg1, byte[] data) {
		// follow the previous ForcePhone's log setting format
		int TEMP_TYPE = 1; // TODO: support real types like float or int
		NetworkRequest r = new NetworkRequest(ACTION_USER, stamp, tag, code, arg0, arg1, data, TEMP_TYPE);
		requestQueue.add(r);
		sendPacketByAnotherThread();
	}

	public void sendSensingEndAction() {
		NetworkRequest r = new NetworkRequest(ACTION_SENSING_END, null, null, -1);
		requestQueue.add(r);
		sendPacketByAnotherThread();
	}
//==================================================================================================
//	Internal functions to handle the recevied packets
//==================================================================================================
	// Create a separate thread to pool packets
	private boolean keepRecvThreadRunning = false; // flag to mark it the receving thread is running or not
	private void createThreadToReceiveAndBlockArrivePacket (){
		if(!keepRecvThreadRunning){ // thread is already running, no need to run another thread
			keepRecvThreadRunning = true;
			class DataRecvingRunnable implements Runnable {
				public void run() {
					keepPacketRecving();
				}
			}
			new Thread(new DataRecvingRunnable(), "Data Recving Thread").start();
		}
	}

	//private short[] audioReceived = null;
	private void keepPacketRecving(){
		while(keepRecvThreadRunning) {
			try {
				byte reaction;
				reaction = dataIn.readByte();

				if(reaction == REACTION_ASK_SENSING) {
					listener.serverAskStartSensing();
					/*
					int type = dataIn.readInt();
					int rIdx = dataIn.readInt();
					int rCnt = dataIn.readInt();
					int answerSize = dataIn.readInt();
					byte[] answerBytes = new byte[answerSize];
					dataIn.readFully(answerBytes);
					String answerString = new String(answerBytes);

					float vol = dataIn.readFloat();
					boolean needToUpdateAudio = (dataIn.readInt()==1);
					boolean needToAutoPlay = (dataIn.readInt()==1);
					boolean needToCalibEnd = (dataIn.readInt()==1);

					if(needToUpdateAudio&&!audioHasBeenUpdatedAfterRequestStartIsAsked){
						Log.e(C.LOG_TAG, "[ERROR]: audio need to update but is not updated before the request is received");
						caller.error("[ERROR]: audio need to update but is not updated before the request is received");
					}

					latestReceviedUserStudyRequest = new UserStudyRequest(type, rIdx, rCnt, answerString, vol, needToUpdateAudio, needToAutoPlay, needToCalibEnd);

					byte check = dataIn.readByte();
					if(check != -1){
						Log.e(C.LOG_TAG, "[ERROR]: check is not -1 -> some packet might be dropped or there is a bug in matlab server");
						caller.error("Receive corrupted information from server (unstable network connection?) at reaction = "+reaction);
					}

					caller.requestReceivedFromServer(latestReceviedUserStudyRequest);
					*/
				} else if (reaction == REACTION_SERVER_CLOSED) {
					listener.serverClosed();
				} else if(reaction == REACTION_STOP_SENSING) {
					listener.serverAskStopSensing();
				} else if(reaction == REACTION_SET_MEDIA){ // This reaction sets audio based on the received payload
					int FS = dataIn.readInt(); // sample rate
					int chCnt = dataIn.readInt();
					int repeatCnt = dataIn.readInt(); // number of audio repetation played

					// read pilot
					int shortToRead = dataIn.readInt();
					int BYTE_OF_SHORT = 2;
					byte[] b = new byte[shortToRead*BYTE_OF_SHORT];
					int totalByteRead = 0;
					while(totalByteRead<shortToRead*BYTE_OF_SHORT) {
						//Log.d(Constant.LOG_TAG, "totalByteRead = "+totalByteRead+",validByteToRead = "+validByteToRead);
						int byteIsRead = dataIn.read(b, totalByteRead, shortToRead * BYTE_OF_SHORT - totalByteRead);
						totalByteRead += byteIsRead;
					}
					short[] pilot = new short[shortToRead];
					ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(pilot);

					// read signal
					shortToRead = dataIn.readInt();
					b = new byte[shortToRead*BYTE_OF_SHORT];
					totalByteRead = 0;
					while(totalByteRead<shortToRead*BYTE_OF_SHORT) {
						//Log.d(Constant.LOG_TAG, "totalByteRead = "+totalByteRead+",validByteToRead = "+validByteToRead);
						int byteIsRead = dataIn.read(b, totalByteRead, shortToRead * BYTE_OF_SHORT - totalByteRead);
						totalByteRead += byteIsRead;
					}
					short[] signal = new short[shortToRead];
					ByteBuffer.wrap(b).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(signal);
					byte check = dataIn.readByte();
					if(check != -1){
						Log.e(LOG_TAG, "Check is not -1 -> some packet might be dropped or there is a bug in matlab server");
						listener.updateDebugStatus(false, "signal loaded fails");
					}

					AudioSource audioSource = new AudioSource(pilot,signal,FS,chCnt,repeatCnt);

					Log.d(LOG_TAG, "Load audio from server with length="+shortToRead);
					listener.audioReceivedFromServer(audioSource);

					audioHasBeenUpdatedAfterRequestStartIsAsked = true;
					if(SAVE_LATEST_LOADED_AUDIO_TO_FILE){
						BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(Constant.libFolderPath + "audioFromServer.dat"));
						bos.write(b);
						bos.flush();
						bos.close();
					}
				} else if (reaction == REACTION_SET_RESULT) {
					// TODO: update result to user-app callbacks
					int audioSampleCnt = dataIn.readInt();
					int argInt = dataIn.readInt();
					// TODO: add write float
					byte check = dataIn.readByte();

					//Log.d(LOG_TAG, "received result sampleCnt = "+ audioSampleCnt +", argInt = "+argInt+", check = "+check);
					if(check != -1){
						Log.e(LOG_TAG, "Check is not -1 -> some packet might be dropped or there is a bug in matlab server");
						listener.updateDebugStatus(false, "result loaded fails (check != -1)");
					} else {
						listener.resultReceviedFromServer(audioSampleCnt, argInt);
					}

				}
			} catch (IOException e) {
				Log.w(LOG_TAG, "Read socket data timeout (need more data? or wait a while?)");
			}
		}
	}

	private boolean keepSendThreadRunning = false; // control outside the thread to make it work or not
	private boolean sendThreadIsStopped = true; // control inside the thread to make sure it run before the previous one has been stopped
	private void sendPacketByAnotherThread(){
		if(!keepSendThreadRunning){ // thread is not running anymore(or yet) -> need to run a new thread
			keepSendThreadRunning = true;
			class DataSendingRunnable implements Runnable {
				public void run() {
					// *** comment this line just for debugging ***
					keepPacketSending();
				}
			}
			new Thread(new DataSendingRunnable(), "Data Sending Thread").start();
		}
	}

	private void keepPacketSending(){
		boolean threadNeedInit = true;
		while(keepSendThreadRunning){
			if(threadNeedInit) {
				if (!sendThreadIsStopped) {
					Log.d(LOG_TAG, "Previous thread is not stopped yet when a new sending thread is created");
				} else {
					// indicate this thread is working
					sendThreadIsStopped = false;
					threadNeedInit = false;
				}
			} else {
				// send message to remote server
				try{
					while(!requestQueue.isEmpty()){
						NetworkRequest r = requestQueue.peek();
						switch (r.action){
							case ACTION_INIT:
								dataOut.write(ACTION_INIT);
								break;
							case ACTION_DATA:
								dataOut.write(ACTION_DATA);
								dataOut.writeInt(r.data.length);
								dataOut.write(r.data);
								dataOut.write(-1); // use as the sanity check of send message
								break;
							case ACTION_SET:
								dataOut.write(ACTION_SET);
								dataOut.writeInt(r.type);
								byte[] nameBytes = r.name.getBytes();
								dataOut.writeInt(nameBytes.length);
								dataOut.write(nameBytes);
								dataOut.write(-1); // use as the sanity check of send message
								dataOut.writeInt(r.data.length);
								dataOut.write(r.data);
								dataOut.write(-1); // use as the sanity check of send message
								break;
							case ACTION_USER:
								dataOut.write(ACTION_USER);
								dataOut.writeInt(r.stamp);

								byte[] tagBytes = r.name.getBytes();
								dataOut.writeInt(tagBytes.length);
								dataOut.write(tagBytes);
								dataOut.write(-1); // use as the sanity check of send message

								dataOut.writeInt(r.code);
								dataOut.writeFloat(r.arg0);
								dataOut.writeFloat(r.arg1);

								//dataOut.write(-1); // use as the sanity check of send message
							case ACTION_SENSING_END:
								dataOut.write(ACTION_SENSING_END);
								break;
							default:
								Log.e(LOG_TAG, "[ERROR]: undefined action = "+r.action);
						}
						requestQueue.poll();
					}
					dataOut.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(DATA_SENDING_THREAD_LOOP_DELAY);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		// end of sending thread (could be terminated by close socket)
		sendThreadIsStopped = true;
	}

	// this function open a new thread to close server if need
	public void closeServerIfServerIsAlive(){
		new Thread() {
			public void run() {
				// end the packet sending thread
				keepSendThreadRunning = false;
				keepRecvThreadRunning = false;
				// close server directly since the check alive function doesn't work
				closeServer();
			}
		}.start();
	}

	private void closeServer(){
		if(status != SERVER_STATUS_DISABLED){
			try {
				if(status == SERVER_STATUS_CONNECTED) {
					Log.d(LOG_TAG, "send disconnection messgae to socket for closing socket");
					dataOut.write(ACTION_CLOSE);
					dataOut.flush();
				}

				sc.close();
			} catch (IOException e) {
				Log.e(LOG_TAG, "ERROR: can't being closed : " + e.getMessage());
				e.printStackTrace();
			}
			status = SERVER_STATUS_DISABLED;
		} else {
			Log.w(LOG_TAG, "ERROR: server is not connected -> no need to close it");
		}
	}

	public boolean isConnected(){
		return status == SERVER_STATUS_CONNECTED;
	}

}


text:
package org.r4d5.teamcity.todo.agent;

import jetbrains.buildServer.agent.AgentBuildRunnerInfo;
import jetbrains.buildServer.agent.BuildAgentConfiguration;
import org.jetbrains.annotations.NotNull;
import org.r4d5.teamcity.todo.common.TodoBuildRunnerConstants;

public class TodoBuildRunnerInfo implements AgentBuildRunnerInfo {

    @NotNull
    public String getType() {
        return TodoBuildRunnerConstants.TODO_RUN_TYPE;
    }

    public boolean canRun(@NotNull BuildAgentConfiguration buildAgentConfiguration) {
        return true;
    }
}


text:
package clicolor_test

import cli "github.com/ivpusic/go-clicolor/clicolor"
import "testing"

type WriterFunc func([]byte) (int, error)

var ch chan string

func (f WriterFunc) Write(p []byte) (n int, err error) {
	return f(p)
}

func ExamplePrint_in() {
	cli.Print("this is green text").In("green")
	// prints: this is green text
}

func ExamplePrint_inFormat() {
	cli.Print("{red}Some text in red. {white}Some text in white. {default}Some text in default color.").InFormat()
	// prints: Some text in red. Some text in white. Some text in default color.
}

func Write(p []byte) (n int, err error) {
	str := string(p[:])
	ch <- str
	return 0, nil
}

func TestPrintIn(t *testing.T) {
	ch = make(chan string, 1)
	cli.Out = WriterFunc(Write)
	cli.Print("this is green text").In("green")
	str := <-ch

	expected := "\033[32mthis is green text\033[0m\n"
	if str != expected {
		t.Error("Expected", expected)
	}

	close(ch)
}

func TestPrintInFormat(t *testing.T) {
	ch = make(chan string, 1)
	cli.Out = WriterFunc(Write)
	cli.Print("{red}Some text in red. {white}Some text in white. {default}Some text in default color.").InFormat()
	str := <-ch

	expected := "\033[31mSome text in red. \033[0m\033[37mSome text in white. \033[0m\033[39mSome text in default color.\033[0m\n"
	if str != expected {
		t.Error("Expected", expected, "Got", str)
	}

	close(ch)
}


text:
__author__ = 'naveen'
from setuptools import setup

setup(
    name="MyLibrary",
    version="1.0",
    install_requires=[
        "oauth2client",
        "google-api-python-client",
    ],
    # ...
)


text:
package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	log "github.com/Sirupsen/logrus"
	"mime"
	"net/http"
	"strconv"
	"time"

	"github.com/backerman/evego"
	"github.com/zenazn/goji/web"
)

type queryItem struct {
	Quantity int    `json:"quantity"`
	ItemName string `json:"itemName"`
}

// priceFloat overrides the marshalling of our prices to JSON,
// ensuring we get 00000000000.00 rather than 0000e+00.
type priceFloat float64

func (p priceFloat) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("%.2f", p)), nil
}

type responseItem struct {
	// The EVE database ID of the item.
	ItemID int `json:"itemID"`
	// The name of the item.
	ItemName string `json:"itemName"`
	// The quantity of that item available for purchase in
	// the returned location.
	QuantityAvailable int `json:"quantityAvailable"`
	// The best buy price per unit found in the system/region.
	BestBuy priceFloat `json:"bestBuy"`
	// The best sell price per unit found in the system/region.
	BestSell priceFloat `json:"bestSell"`
	// Details of the best buy order
	BuyInfo orderInfo `json:"buyInfo"`
	// Details of the best sell order
	SellInfo orderInfo `json:"sellInfo"`
}

type orderInfo struct {
	// The quantity available to buy/sell on this order
	Quantity int `json:"quantity"`
	// This order's minimum quantity to buy (1 for sell)
	MinQuantity int `json:"minQuantity"`
	// Where the order is available
	Station station `json:"station"`
	// One of: station, system, region, or a number of jumps
	Within string `json:"within"`
}

func makeRangeString(order *evego.Order) string {
	var rangeStr string
	switch order.JumpRange {
	case evego.BuyRegion:
		rangeStr = "region"
	case evego.BuySystem:
		rangeStr = "system"
	case evego.BuyStation:
		rangeStr = "station"
	default:
		// fix upstream
		if order.NumJumps > 100 {
			rangeStr = "region"
		} else {
			rangeStr = fmt.Sprintf("%d jumps", order.NumJumps)
		}
	}
	return rangeStr
}

func makeOrderInfo(db evego.Database, order *evego.Order) orderInfo {
	return orderInfo{
		Quantity:    order.Quantity,
		MinQuantity: order.MinQuantity,
		// Cheat — it's an outpost if it has no reprocessing efficiency reported.
		Station: stationFromAPI(db, order.Station,
			order.Station.ReprocessingEfficiency == 0.0),
		Within: makeRangeString(order),
	}
}

// summarizeOrders takes as input the orders for a given type in a region/station
// and returns the corresponding responseItem struct filled out.
func summarizeOrders(db evego.Database, orders []evego.Order, dbItem *evego.Item) responseItem {
	var (
		quantity          int
		bestBuy, bestSell float64
		buyInfo, sellInfo orderInfo
	)

	for _, ord := range orders {
		if ord.Type == evego.Buy && ord.Price > bestBuy {
			bestBuy = ord.Price
			buyInfo = makeOrderInfo(db, &ord)
		} else if ord.Type == evego.Sell && (bestSell == 0 || ord.Price < bestSell) {
			bestSell = ord.Price
			sellInfo = makeOrderInfo(db, &ord)
		}
		if ord.Type == evego.Sell {
			quantity += ord.Quantity
		}
	}
	result := responseItem{
		ItemID:            dbItem.ID,
		ItemName:          dbItem.Name,
		QuantityAvailable: quantity,
		BestBuy:           priceFloat(bestBuy),
		BuyInfo:           buyInfo,
		BestSell:          priceFloat(bestSell),
		SellInfo:          sellInfo,
	}
	return result
}

func getItemPrices(
	db evego.Database,
	mkt evego.Market,
	req *[]queryItem,
	station *evego.Station,
	loc string) (*map[string]responseItem, error) {
	respItems := make(map[string]responseItem)
	for _, i := range *req {
		dbItem, err := db.ItemForName(i.ItemName)
		if err != nil {
			continue
		}
		var (
			item   responseItem
			orders *[]evego.Order
		)
		if station != nil {
			orders, err = mkt.OrdersInStation(dbItem, station)
		} else {
			orders, err = mkt.OrdersForItem(dbItem, loc, evego.AllOrders)
		}
		if err != nil {
			return nil, fmt.Errorf("Unable to retrieve order information for %v: %v", dbItem.Name, err)
		}
		item = summarizeOrders(db, *orders, dbItem)
		respItems[item.ItemName] = item
	}
	return &respItems, nil
}

// ItemsMarketValue returns a handler that takes as input a JSON
// array of items and their quantities, plus a specified station
// or region, and computes the items' value.
//
// FIXME: Should return all buy orders within range for the queried system.
func ItemsMarketValue(db evego.Database, mkt evego.Market, xmlAPI evego.XMLAPI) web.HandlerFunc {
	return func(c web.C, w http.ResponseWriter, r *http.Request) {
		contentType := r.Header.Get("Content-Type")
		contentType, _, err := mime.ParseMediaType(contentType)
		if err != nil {
			http.Error(w, `{"status": "Error", "error": "Bad request content type"}`,
				http.StatusBadRequest)
			return
		}
		if contentType != "application/json" {
			http.Error(w, `{"status": "Error", "error": "Request must be of type application/json"}`,
				http.StatusUnsupportedMediaType)
			return
		}
		reqBody, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, `{"status": "Error", "error": "Unable to process request body"}`,
				http.StatusBadRequest)
			return
		}
		var req []queryItem
		err = json.Unmarshal(reqBody, &req)
		if err != nil {
			http.Error(w, fmt.Sprintf("Unable to process request JSON: %v", err), http.StatusBadRequest)
			w.Write([]byte(`{"status": "Error"}`))
			return
		}
		loc := c.URLParams["location"]
		stationIDStr, isStation := c.URLParams["id"]
		var station *evego.Station
		if isStation {
			// Get station / outpost object.
			stationID, _ := strconv.Atoi(stationIDStr)
			station, err = db.StationForID(stationID)
			if err != nil {
				// Not a station; should be an outpost.
				station, err = xmlAPI.OutpostForID(stationID)
				if err != nil {
					http.Error(w, `{"status": "Error", "error": "Unable to identify location"}`,
						http.StatusBadRequest)
					return
				}
			}
		}
		respItems, err := getItemPrices(db, mkt, &req, station, loc)
		if err != nil {
			http.Error(w, `{"status": "Error", "error": "Unable to retrieve order information"}`,
				http.StatusBadRequest)
			return
		}
		respJSON, _ := json.Marshal(respItems)
		w.Write(respJSON)
	}
}

// Go only provides a float min, so do our own for ints.
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

const reprocessCacheKey = "reprocess-output-values"
const reprocessCacheTTL = time.Hour

// ReprocessOutputValues returns a web handler function that generates a list of
// possible output from reprocessing, along with the Jita sell and buy price of each.
func ReprocessOutputValues(db evego.Database, mkt evego.Market, xmlAPI evego.XMLAPI, cache evego.Cache) web.HandlerFunc {
	tickerboard := []queryItem{
		{Quantity: 1, ItemName: "Tritanium"},
		{Quantity: 1, ItemName: "Pyerite"},
		{Quantity: 1, ItemName: "Mexallon"},
		{Quantity: 1, ItemName: "Isogen"},
		{Quantity: 1, ItemName: "Nocxium"},
		{Quantity: 1, ItemName: "Megacyte"},
		{Quantity: 1, ItemName: "Zydrine"},
		{Quantity: 1, ItemName: "Megacyte"},
	}
	return func(c web.C, w http.ResponseWriter, r *http.Request) {
		// Check cached and use that instead if it's available.
		cached, found := cache.Get(reprocessCacheKey)
		if found {
			w.Write(cached)
			return
		}
		jita, err := db.StationForID(60003760) // Jita IV - Moon 4 - Caldari Navy Assembly Plant
		if err != nil {
			http.Error(w, `{"status": "Error", "error": "Unable to retrieve ticker prices"}`,
				http.StatusInternalServerError)
			log.Printf("Error looking up Jita station info (???): %v", err)
			return
		}
		results, err := getItemPrices(db, mkt, &tickerboard, jita, "")
		if err != nil {
			http.Error(w, `{"status": "Error", "error": "Unable to retrieve ticker prices"}`,
				http.StatusInternalServerError)
			log.Printf("Error getting Jita item prices: %v", err)
			return
		}

		resultsJSON, err := json.Marshal(results)
		// Write output to cache as well.
		cache.Put(reprocessCacheKey, resultsJSON, time.Now().Add(reprocessCacheTTL))
		w.Write(resultsJSON)
	}
}


text:
/*
* JavaScript to updade the database when seen or want to see buttons are clicked.
* -vkolova
*/

(function($) {

  $( "#have_seen" ).live( "click", function() {
    $( "#have_seen" ).empty().append(' запазване...');

    $.ajax({
				url: vk_select_params.vk_ajax_url,
				data: {
          'action': 'update_seen',
          'security': vk_select_params.ajax_nonce,
          'user_id': $( '#user_id' ).val(),
          'play_id': $( '#play_id' ).val()
        },
				type: 'POST',
        success: function( response ) {
          switch ( response ) {
          	case '0':
          		$( ".btn-group" ).empty().append( '<button type="button" class="btn btn-default" data-toggle="dropdown" id="want_to_see">			  Искам да я гледам		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Гледах я

' );
          		break;
          	case '1':
              $( ".btn-group" ).empty().append( '	  <button type="button" class="btn btn-default" data-toggle="dropdown" id="have_seen">			  Гледах я		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Искам да я гледам

' );
          		break;
          	default:
            	$( ".btn-group" ).empty().append( '<button type="button" class="btn btn-success" data-toggle="dropdown" id="want_to_see">			Искам да я гледам		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Гледах я

' );
          }
        }
			});
    });

    $( "#want_to_see" ).live( "click", function() {
      $( "#want_to_see" ).empty().append(' запазване...');

      $.ajax({
					url: vk_select_params.vk_ajax_url,
					data: {
            'action': 'want_to_see',
            'security': vk_select_params.ajax_nonce,
            'user_id': $( '#user_id' ).val(),
            'play_id': $( '#play_id' ).val()
          },
					type: 'POST',
					success: function( response ) {
            switch ( response ) {
            	case '0':
            		$( ".btn-group" ).empty().append( '<button type="button" class="btn btn-default" data-toggle="dropdown" id="want_to_see">			  Искам да я гледам		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Гледах я

' );
            		break;
            	case '1':
                $( ".btn-group" ).empty().append( '	  <button type="button" class="btn btn-default" data-toggle="dropdown" id="have_seen">			  Гледах я		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Искам да я гледам

' );
            		break;
            	default:
              	$( ".btn-group" ).empty().append( '<button type="button" class="btn btn-success" data-toggle="dropdown" id="want_to_see">			Искам да я гледам		</button>	  <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">	    	    Toggle Dropdown	  </button>

Гледах я

' );
            }
					}
				});
      });
})(jQuery);


text:
extern "C" IMAGE_DOS_HEADER __ImageBase;
#endif

MetricsLog::MetricsLog(const std::string& client_id, int session_id)
    : MetricsLogBase(client_id, session_id, MetricsLog::GetVersionString()) {}

MetricsLog::~MetricsLog() {}

// static
void MetricsLog::RegisterPrefs(PrefService* local_state) {
  local_state->RegisterListPref(prefs::kStabilityPluginStats);
}

int64 MetricsLog::GetIncrementalUptime(PrefService* pref) {
  base::TimeTicks now = base::TimeTicks::Now();
  static base::TimeTicks last_updated_time(now);
  int64 incremental_time = (now - last_updated_time).InSeconds();
  last_updated_time = now;

  if (incremental_time > 0) {
    int64 metrics_uptime = pref->GetInt64(prefs::kUninstallMetricsUptimeSec);
    metrics_uptime += incremental_time;
    pref->SetInt64(prefs::kUninstallMetricsUptimeSec, metrics_uptime);
  }

  return incremental_time;
}

std::string MetricsLog::GetInstallDate() const {
  PrefService* pref = g_browser_process->local_state();
  if (pref) {
    return pref->GetString(prefs::kMetricsClientIDTimestamp);
  } else {
    NOTREACHED();
    return "0";
  }
}

// static
std::string MetricsLog::GetVersionString() {
  chrome::VersionInfo version_info;
  if (!version_info.is_valid()) {
    NOTREACHED() << "Unable to retrieve version info.";
    return std::string();
  }

  std::string version = version_info.Version();
  if (!version_extension_.empty())
    version += version_extension_;
  if (!version_info.IsOfficialBuild())
    version.append("-devel");
  return version;
}

MetricsLog* MetricsLog::AsMetricsLog() {
  return this;
}

void MetricsLog::RecordIncrementalStabilityElements() {
  DCHECK(!locked_);

  PrefService* pref = g_browser_process->local_state();
  DCHECK(pref);

  OPEN_ELEMENT_FOR_SCOPE("profile");
  WriteCommonEventAttributes();

  WriteInstallElement();

  {
    OPEN_ELEMENT_FOR_SCOPE("stability");  // Minimal set of stability elements.
    WriteRequiredStabilityAttributes(pref);
    WriteRealtimeStabilityAttributes(pref);

    WritePluginStabilityElements(pref);
  }
}

void MetricsLog::WriteStabilityElement(PrefService* pref) {
  DCHECK(!locked_);

  DCHECK(pref);

  // Get stability attributes out of Local State, zeroing out stored values.
  // NOTE: This could lead to some data loss if this report isn't successfully
  //       sent, but that's true for all the metrics.

  OPEN_ELEMENT_FOR_SCOPE("stability");
  WriteRequiredStabilityAttributes(pref);
  WriteRealtimeStabilityAttributes(pref);

  // TODO(jar): The following are all optional, so we *could* optimize them for
  // values of zero (and not include them).
  WriteIntAttribute("incompleteshutdowncount",
                    pref->GetInteger(
                        prefs::kStabilityIncompleteSessionEndCount));
  pref->SetInteger(prefs::kStabilityIncompleteSessionEndCount, 0);

  WriteIntAttribute("breakpadregistrationok",
      pref->GetInteger(prefs::kStabilityBreakpadRegistrationSuccess));
  pref->SetInteger(prefs::kStabilityBreakpadRegistrationSuccess, 0);
  WriteIntAttribute("breakpadregistrationfail",
      pref->GetInteger(prefs::kStabilityBreakpadRegistrationFail));
  pref->SetInteger(prefs::kStabilityBreakpadRegistrationFail, 0);
  WriteIntAttribute("debuggerpresent",
                   pref->GetInteger(prefs::kStabilityDebuggerPresent));
  pref->SetInteger(prefs::kStabilityDebuggerPresent, 0);
  WriteIntAttribute("debuggernotpresent",
                   pref->GetInteger(prefs::kStabilityDebuggerNotPresent));
  pref->SetInteger(prefs::kStabilityDebuggerNotPresent, 0);

  WritePluginStabilityElements(pref);
}

void MetricsLog::WritePluginStabilityElements(PrefService* pref) {
  // Now log plugin stability info.
  const ListValue* plugin_stats_list = pref->GetList(
      prefs::kStabilityPluginStats);
  if (plugin_stats_list) {
    OPEN_ELEMENT_FOR_SCOPE("plugins");
    for (ListValue::const_iterator iter = plugin_stats_list->begin();
         iter != plugin_stats_list->end(); ++iter) {
      if (!(*iter)->IsType(Value::TYPE_DICTIONARY)) {
        NOTREACHED();
        continue;
      }
      DictionaryValue* plugin_dict = static_cast<DictionaryValue*>(*iter);

      std::string plugin_name;
      plugin_dict->GetString(prefs::kStabilityPluginName, &plugin_name);

      OPEN_ELEMENT_FOR_SCOPE("pluginstability");
      // Use "filename" instead of "name", otherwise we need to update the
      // UMA servers.
      WriteAttribute("filename", CreateBase64Hash(plugin_name));

      int launches = 0;
      plugin_dict->GetInteger(prefs::kStabilityPluginLaunches, &launches);
      WriteIntAttribute("launchcount", launches);

      int instances = 0;
      plugin_dict->GetInteger(prefs::kStabilityPluginInstances, &instances);
      WriteIntAttribute("instancecount", instances);

      int crashes = 0;
      plugin_dict->GetInteger(prefs::kStabilityPluginCrashes, &crashes);
      WriteIntAttribute("crashcount", crashes);
    }

    pref->ClearPref(prefs::kStabilityPluginStats);
  }
}

void MetricsLog::WriteRequiredStabilityAttributes(PrefService* pref) {
  // The server refuses data that doesn't have certain values.  crashcount and
  // launchcount are currently "required" in the "stability" group.
  WriteIntAttribute("launchcount",
                    pref->GetInteger(prefs::kStabilityLaunchCount));
  pref->SetInteger(prefs::kStabilityLaunchCount, 0);
  WriteIntAttribute("crashcount",
                    pref->GetInteger(prefs::kStabilityCrashCount));
  pref->SetInteger(prefs::kStabilityCrashCount, 0);
}

void MetricsLog::WriteRealtimeStabilityAttributes(PrefService* pref) {
  // Update the stats which are critical for real-time stability monitoring.
  // Since these are "optional," only list ones that are non-zero, as the counts
  // are aggergated (summed) server side.

  int count = pref->GetInteger(prefs::kStabilityPageLoadCount);
  if (count) {
    WriteIntAttribute("pageloadcount", count);
    pref->SetInteger(prefs::kStabilityPageLoadCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilityRendererCrashCount);
  if (count) {
    WriteIntAttribute("renderercrashcount", count);
    pref->SetInteger(prefs::kStabilityRendererCrashCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilityExtensionRendererCrashCount);
  if (count) {
    WriteIntAttribute("extensionrenderercrashcount", count);
    pref->SetInteger(prefs::kStabilityExtensionRendererCrashCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilityRendererHangCount);
  if (count) {
    WriteIntAttribute("rendererhangcount", count);
    pref->SetInteger(prefs::kStabilityRendererHangCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilityChildProcessCrashCount);
  if (count) {
    WriteIntAttribute("childprocesscrashcount", count);
    pref->SetInteger(prefs::kStabilityChildProcessCrashCount, 0);
  }

#if defined(OS_CHROMEOS)
  count = pref->GetInteger(prefs::kStabilityOtherUserCrashCount);
  if (count) {
    // TODO(kmixter): Write attribute once log server supports it
    // and remove warning log.
    // WriteIntAttribute("otherusercrashcount", count);
    LOG(WARNING) << "Not yet able to send otherusercrashcount="
                 << count;
    pref->SetInteger(prefs::kStabilityOtherUserCrashCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilityKernelCrashCount);
  if (count) {
    // TODO(kmixter): Write attribute once log server supports it
    // and remove warning log.
    // WriteIntAttribute("kernelcrashcount", count);
    LOG(WARNING) << "Not yet able to send kernelcrashcount="
                 << count;
    pref->SetInteger(prefs::kStabilityKernelCrashCount, 0);
  }

  count = pref->GetInteger(prefs::kStabilitySystemUncleanShutdownCount);
  if (count) {
    // TODO(kmixter): Write attribute once log server supports it
    // and remove warning log.
    // WriteIntAttribute("systemuncleanshutdowns", count);
    LOG(WARNING) << "Not yet able to send systemuncleanshutdowns="
                 << count;
    pref->SetInteger(prefs::kStabilitySystemUncleanShutdownCount, 0);
  }
#endif  // OS_CHROMEOS

  int64 recent_duration = GetIncrementalUptime(pref);
  if (recent_duration)
    WriteInt64Attribute("uptimesec", recent_duration);
}

void MetricsLog::WritePluginList(
    const std::vector<webkit::npapi::WebPluginInfo>& plugin_list) {
  DCHECK(!locked_);

  OPEN_ELEMENT_FOR_SCOPE("plugins");

  for (std::vector<webkit::npapi::WebPluginInfo>::const_iterator iter =
           plugin_list.begin();
       iter != plugin_list.end(); ++iter) {
    OPEN_ELEMENT_FOR_SCOPE("plugin");

    // Plugin name and filename are hashed for the privacy of those
    // testing unreleased new extensions.
    WriteAttribute("name", CreateBase64Hash(UTF16ToUTF8(iter->name)));
    std::string filename_bytes =
#if defined(OS_WIN)
        UTF16ToUTF8(iter->path.BaseName().value());
#else
        iter->path.BaseName().value();
#endif
    WriteAttribute("filename", CreateBase64Hash(filename_bytes));
    WriteAttribute("version", UTF16ToUTF8(iter->version));
  }
}

void MetricsLog::WriteInstallElement() {
  OPEN_ELEMENT_FOR_SCOPE("install");
  WriteAttribute("installdate", GetInstallDate());
  WriteIntAttribute("buildid", 0);  // We're using appversion instead.
}

void MetricsLog::RecordEnvironment(
         const std::vector<webkit::npapi::WebPluginInfo>& plugin_list,
         const DictionaryValue* profile_metrics) {
  DCHECK(!locked_);

  PrefService* pref = g_browser_process->local_state();

  OPEN_ELEMENT_FOR_SCOPE("profile");
  WriteCommonEventAttributes();

  WriteInstallElement();

  WritePluginList(plugin_list);

  WriteStabilityElement(pref);

  {
    OPEN_ELEMENT_FOR_SCOPE("cpu");
    WriteAttribute("arch", base::SysInfo::CPUArchitecture());
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("memory");
    WriteIntAttribute("mb", base::SysInfo::AmountOfPhysicalMemoryMB());
#if defined(OS_WIN)
    WriteIntAttribute("dllbase", reinterpret_cast<int>(&__ImageBase));
#endif
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("os");
    WriteAttribute("name",
                   base::SysInfo::OperatingSystemName());
    WriteAttribute("version",
                   base::SysInfo::OperatingSystemVersion());
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("gpu");
    GpuDataManager* gpu_data_manager = GpuDataManager::GetInstance();
    if (gpu_data_manager) {
      WriteIntAttribute("vendorid", gpu_data_manager->gpu_info().vendor_id);
      WriteIntAttribute("deviceid", gpu_data_manager->gpu_info().device_id);
    }
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("display");
    int width = 0;
    int height = 0;
    base::SysInfo::GetPrimaryDisplayDimensions(&width, &height);
    WriteIntAttribute("xsize", width);
    WriteIntAttribute("ysize", height);
    WriteIntAttribute("screens", base::SysInfo::DisplayCount());
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("bookmarks");
    int num_bookmarks_on_bookmark_bar =
        pref->GetInteger(prefs::kNumBookmarksOnBookmarkBar);
    int num_folders_on_bookmark_bar =
        pref->GetInteger(prefs::kNumFoldersOnBookmarkBar);
    int num_bookmarks_in_other_bookmarks_folder =
        pref->GetInteger(prefs::kNumBookmarksInOtherBookmarkFolder);
    int num_folders_in_other_bookmarks_folder =
        pref->GetInteger(prefs::kNumFoldersInOtherBookmarkFolder);
    {
      OPEN_ELEMENT_FOR_SCOPE("bookmarklocation");
      WriteAttribute("name", "full-tree");
      WriteIntAttribute("foldercount",
          num_folders_on_bookmark_bar + num_folders_in_other_bookmarks_folder);
      WriteIntAttribute("itemcount",
          num_bookmarks_on_bookmark_bar +
          num_bookmarks_in_other_bookmarks_folder);
    }
    {
      OPEN_ELEMENT_FOR_SCOPE("bookmarklocation");
      WriteAttribute("name", "toolbar");
      WriteIntAttribute("foldercount", num_folders_on_bookmark_bar);
      WriteIntAttribute("itemcount", num_bookmarks_on_bookmark_bar);
    }
  }

  {
    OPEN_ELEMENT_FOR_SCOPE("keywords");
    WriteIntAttribute("count", pref->GetInteger(prefs::kNumKeywords));
  }

  if (profile_metrics)
    WriteAllProfilesMetrics(*profile_metrics);
}

void MetricsLog::WriteAllProfilesMetrics(
    const DictionaryValue& all_profiles_metrics) {
  const std::string profile_prefix(prefs::kProfilePrefix);
  for (DictionaryValue::key_iterator i = all_profiles_metrics.begin_keys();
       i != all_profiles_metrics.end_keys(); ++i) {
    const std::string& key_name = *i;
    if (key_name.compare(0, profile_prefix.size(), profile_prefix) == 0) {
      DictionaryValue* profile;
      if (all_profiles_metrics.GetDictionaryWithoutPathExpansion(key_name,
                                                                 &profile))
        WriteProfileMetrics(key_name.substr(profile_prefix.size()), *profile);
    }
  }
}

void MetricsLog::WriteProfileMetrics(const std::string& profileidhash,
                                     const DictionaryValue& profile_metrics) {
  OPEN_ELEMENT_FOR_SCOPE("userprofile");
  WriteAttribute("profileidhash", profileidhash);
  for (DictionaryValue::key_iterator i = profile_metrics.begin_keys();
       i != profile_metrics.end_keys(); ++i) {
    Value* value;
    if (profile_metrics.GetWithoutPathExpansion(*i, &value)) {
      DCHECK(*i != "id");
      switch (value->GetType()) {
        case Value::TYPE_STRING: {
          std::string string_value;
          if (value->GetAsString(&string_value)) {
            OPEN_ELEMENT_FOR_SCOPE("profileparam");
            WriteAttribute("name", *i);
            WriteAttribute("value", string_value);
          }
          break;
        }

        case Value::TYPE_BOOLEAN: {
          bool bool_value;
          if (value->GetAsBoolean(&bool_value)) {
            OPEN_ELEMENT_FOR_SCOPE("profileparam");
            WriteAttribute("name", *i);
            WriteIntAttribute("value", bool_value ? 1 : 0);
          }
          break;
        }

        case Value::TYPE_INTEGER: {
          int int_value;
          if (value->GetAsInteger(&int_value)) {
            OPEN_ELEMENT_FOR_SCOPE("profileparam");
            WriteAttribute("name", *i);
            WriteIntAttribute("value", int_value);
          }
          break;
        }

        default:
          NOTREACHED();
          break;
      }
    }
  }
}

void MetricsLog::RecordOmniboxOpenedURL(const AutocompleteLog& log) {
  DCHECK(!locked_);

  OPEN_ELEMENT_FOR_SCOPE("uielement");
  WriteAttribute("action", "autocomplete");
  WriteAttribute("targetidhash", "");
  // TODO(kochi): Properly track windows.
  WriteIntAttribute("window", 0);
  WriteCommonEventAttributes();

  {
    OPEN_ELEMENT_FOR_SCOPE("autocomplete");

    WriteIntAttribute("typedlength", static_cast<int>(log.text.length()));
    WriteIntAttribute("selectedindex", static_cast<int>(log.selected_index));
    WriteIntAttribute("completedlength",
                      static_cast<int>(log.inline_autocompleted_length));
    const std::string input_type(
        AutocompleteInput::TypeToString(log.input_type));
    if (!input_type.empty())
      WriteAttribute("inputtype", input_type);

    for (AutocompleteResult::const_iterator i(log.result.begin());
         i != log.result.end(); ++i) {
      OPEN_ELEMENT_FOR_SCOPE("autocompleteitem");
      if (i->provider)
        WriteAttribute("provider", i->provider->name());
      const std::string result_type(AutocompleteMatch::TypeToString(i->type));
      if (!result_type.empty())
        WriteAttribute("resulttype", result_type);
      WriteIntAttribute("relevance", i->relevance);
      WriteIntAttribute("isstarred", i->starred ? 1 : 0);
    }
  }

  ++num_events_;
}


text:
<?php

final class PhabricatorPhurlURLSearchConduitAPIMethod
  extends PhabricatorSearchEngineAPIMethod {

  public function getAPIMethodName() {
    return 'phurls.search';
  }

  public function newSearchEngine() {
    return new PhabricatorPhurlURLSearchEngine();
  }

  public function getMethodSummary() {
    return pht('Read information about Phurl URLS.');
  }

}


text:
Android Client for Indicative's REST API

This REST client creates a JSON representation of your event and posts it to Indicative's Event endpoint.

Features:

+ No external dependencies, so you'll never have library conflicts.
+ Asynchronous, designed to never slow down or break your app.
+ Fault tolerent: if network connectivity is lost, events are queued and retried.

Sample usage:

    // Our Android library is available on Maven Central as an AAR artifact.
    // If your project uses Gradle, you can integrate by adding the following dependency:

    repositories {
        mavenCentral()
    }

    dependencies {
        compile 'com.indicative.client.android:Indicative-Android:1.10.0'
    }

    // In the onCreate() method of your Application class, call the launch()
    // method, passing in the application context and your project's API key.
    // You can find yours by logging in at indicative.com and navigating to
    // the Project Settings page.
    @Override
	public void onCreate() {
	    Indicative.launch(getApplicationContext(), "Your-API-Key-Goes-Here");
	}

    // Then start tracking events with the recordEvent() method
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("Age", 23);
    properties.put("Gender", "Female");
    Indicative.recordEvent("Registration", "user47", properties);

We've added common properties and cached unique identifiers!

A common property is a property that gets recorded for all events. Common properties are stored in SharedPreferences and appended to each event's properties when the event is recorded.

You can also set a unique identifier to be recorded for all events. This value will be stored in SharedPreferences as well, and will be set for all events that don't otherwise have a unique identifier specified.  If you haven't set a unique identifier, Indicative will generate a UUID during initialization and and treat that UUID as the default unique identifier for all events. To set a different unique identifier for a specific event, simply call the `recordEvent()` method and pass in a different `uniqueId` value.

Our API -- all are static methods:

         Method Name
         Method Description

         launch(Context context, String apiKey)
         Initializes the static Indicative instance with the project's API Key, using the application context.  This method will generate and store a UUID unique identifier if one isn't already stored.

         recordEvent(String eventName, String uniqueId, Map<String, Object> properties)
         Queues an event to be processed with the given event name, uniqueness identifier, and properties (common properties will be appended to this event). NOTE: the objects stored as property values should be String, numeric, or boolean objects.

         recordEvent(String eventName)
         Queues an event to be processed with the given event name, uniqueness identifier stored previously by initialization or explicitly set by setUniqueID(), and any common properties previously stored.

         recordEvent(String eventName, String uniqueId)
         Queues an event to be processed with the given event name, uniqueness identifier, and any common properties previously stored.

         recordEvent(String eventName,  Map<String, Object> properties)
         Queues an event to be processed with the given event name, uniqueness identifier generated by the app or cached previously, and properties (common properties will be appended to this event). NOTE: the objects stored as property values should be String, numeric, or boolean objects.

         setUniqueID(String uniqueID)
         Stores (in SharedPreferences) a unique identifier to be used for all `recordEvent()` calls that don't provide a `uniqueId`.

         clearUniqueID()
         Clears the unique identifier stored using `setUniqueID()`. All events, if not provided a unique identifier, will default to the UUID generated on first initialization.

         addProperty(String name, String value)
         Stores a common property in SharedPreferences with the given name and value.

         addProperty(String name, int value)
         Stores a common property in SharedPreferences with the given name and value.

         addProperty(String name, boolean value)
         Stores a common property in SharedPreferences with the given name and value.

         addProperties(Map<String, Object> properties)
         Stores all common properties in SharedPreferences with the given name and value.  NOTE: we only accept type String, boolean, and int within this Map.

         removeProperty(String name)
         Removes a single common property from storage with given name (key).

         clearProperties()
         Removes all common properties from storage.

         reset()
         Removes all state from the Indicative SDK and regenerates the anonymous ID. This should be called in your application on logout.

You should modify and extend this class to your heart's content.  If you make any changes please send a pull request!

As a best practice, consider adding a method that takes as a parameter the object representing your user, and adds certain default properties based on that user's characteristics (e.g., gender, age, etc.).

For more details, see our documentation at: http://app.indicative.com/docs/integration.html


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class com.hazelcast.config.ExecutorConfig (Hazelcast API - 2.5)
</TITLE>

<META NAME="date" CONTENT="2013-01-15">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.hazelcast.config.ExecutorConfig

Packages that use ExecutorConfig

com.hazelcast.config

Uses of ExecutorConfig in com.hazelcast.config

Methods in com.hazelcast.config that return ExecutorConfig

 ExecutorConfig
Config.getExecutorConfig()

          Deprecated. use getExecutorConfig (name) instead

 ExecutorConfig
Config.getExecutorConfig(String name)

          Returns the ExecutorConfig for the given name

 ExecutorConfig
ExecutorConfig.setCorePoolSize(int corePoolSize)

 ExecutorConfig
ExecutorConfig.setKeepAliveSeconds(int keepAliveSeconds)

 ExecutorConfig
ExecutorConfig.setMaxPoolSize(int maxPoolSize)

 ExecutorConfig
ExecutorConfig.setName(String name)

Methods in com.hazelcast.config that return types with arguments of type ExecutorConfig

 Map<String,ExecutorConfig>
Config.getExecutorConfigMap()

 Collection<ExecutorConfig>
Config.getExecutorConfigs()

          Returns the collection of executor configs.

Methods in com.hazelcast.config with parameters of type ExecutorConfig

 Config
Config.addExecutorConfig(ExecutorConfig executorConfig)

          Adds a new ExecutorConfig by name

 Config
Config.setExecutorConfig(ExecutorConfig executorConfig)

          Deprecated. use addExecutorConfig instead

Method parameters in com.hazelcast.config with type arguments of type ExecutorConfig

 Config
Config.setExecutorConfigMap(Map<String,ExecutorConfig> mapExecutors)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2008-2012 Hazelcast, Inc. All Rights Reserved.