text:
namespace metrics {
  class UDPEndpoint {
   public:
    UDPEndpoint(const std::string& host, size_t port)
      : host(host), port(port) { }
    virtual ~UDPEndpoint() { }

    std::string string() const {
      std::ostringstream oss;
      oss << host << ":" << port;
      return oss.str();
    }

    bool operator==(const UDPEndpoint& other) const {
      return port == other.port && host == other.host;
    }

    const std::string host;
    const size_t port;
  };
}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from '@angular/core';
import { Http, Jsonp, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';

import { Observable } from "rxjs/Observable";
import { GLOBAL_URL } from "../model-data/GLOBAL";

import { ErrorsService } from "../service/errors.service";

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class IndexLiveService {
    public backPlayURL = GLOBAL_URL + '/app/1/index/playBack';

    constructor(
        public http: Http,
        public errors: ErrorsService,
    ) { }

    // 获取回放
    getBackPlay(page, pagesize): Observable<any> {
        let data = new URLSearchParams();
        data.append('page', page);
        data.append('pagesize', pagesize);
        return this.http.get(this.backPlayURL, {
            withCredentials: true,
            search: data
        })
            .map((res: Response) => res.json())
            .catch(this.errors.handleError);
    }

}


text:
#include "config.h"
#include <nc_tests.h>
#include "err_macros.h"

#define FILE_NAME_BASE "tst_formats"
#define HDF4_FILE "ref_contiguous.hdf4"
#define NDIM1 1
#define DIM_LEN 10
#define VAR_NAME "Copernicus_var"
#define DIM_NAME "Copernicus_dim"
#define NUM_FILL_WRITE_TESTS 2
#define NUM_FILL_WRITE_METHOD_TESTS 2

/* Determine how many formats are available, and what they are. */
void
determine_test_formats(int *num_formats, int *format)
{
    int ind = 0;
    int num;

    /* Check inputs. */
    assert(num_formats && format);

    /* We always have classic and 64-bit offset */
    num = 2;
    format[ind++] = NC_FORMAT_CLASSIC;
    format[ind++] = NC_FORMAT_64BIT_OFFSET;

    /* Do we have netCDF-4 and netCDF-4 classic? */
#ifdef USE_HDF5
    num += 2;
    format[ind++] = NC_FORMAT_NETCDF4;
    format[ind++] = NC_FORMAT_NETCDF4_CLASSIC;
#endif /* USE_HDF5 */

    /* Do we have CDF5? */
#ifdef ENABLE_CDF5
    num++;
    format[ind++] = NC_FORMAT_CDF5;
#endif /* ENABLE_CDF5 */

    *num_formats = num;
}

/* Function to test nc_inq_format(). */
int
check_inq_format(int ncid, int expected_format, int expected_extended_format, int expected_mode)
{
    int format;
    int extended_format;
    int mode;

    if (nc_inq_format(ncid + 66000, NULL) != NC_EBADID) ERR;
    if (nc_inq_format(ncid, NULL)) ERR;
    if (nc_inq_format(ncid, &format)) ERR;
    if (format != expected_format) {
        printf("format %d expected_format %d\n", format, expected_format);
        ERR;
    }
    if (nc_inq_format_extended(ncid + 66000, &extended_format, &mode) != NC_EBADID) ERR;
    {
        int mode;
        if (nc_inq_format_extended(ncid, NULL, &mode)) ERR;
        if (mode != expected_mode) {
            printf("expected_mode %x mode %x\n", expected_mode, mode);
            /*ERR;*/
        }
    }
    {
        int extended_format;
        if (nc_inq_format_extended(ncid, &extended_format, NULL)) ERR;
        if (extended_format != expected_extended_format) ERR;
    }

    if (nc_inq_format_extended(ncid, &extended_format, &mode)) ERR;
    if (mode != expected_mode) ERR;
    if (extended_format != expected_extended_format) ERR;

    /* Nothing to do with inq_format, but let's check the base_pe
     * functions. */
    if (nc_set_base_pe(ncid, 0)) ERR;
    if (nc_inq_base_pe(ncid, NULL)) ERR;

    return 0;
}

int
main(int argc, char **argv)
{
    printf("\n*** Testing netcdf format functions.\n");
    {
        int ncid;
        int f, d, a;
        int format[MAX_NUM_FORMATS];
        int num_formats;
        int ret;

        /* How many formats to be tested? */
        determine_test_formats(&num_formats, format);

        for (f = 0; f < num_formats; f++)
        {
            printf("*** testing nc_inq_format() and nc_inq_format_extended() with format %d...", format[f]);
            {
                char file_name[NC_MAX_NAME + 1];
                int expected_mode;
                int expected_extended_format;

                sprintf(file_name, "%s_%d.nc", FILE_NAME_BASE, format[f]);

                /* Set up test. */
                switch (format[f]) {
                case NC_FORMAT_CLASSIC:
                    expected_extended_format = NC_FORMATX_NC3;
                    expected_mode = 0;
                    break;
                case NC_FORMAT_64BIT_OFFSET:
                    expected_extended_format = NC_FORMATX_NC3;
                    expected_mode = NC_64BIT_OFFSET;
                    break;
                case NC_FORMAT_CDF5:
                    expected_extended_format = NC_FORMATX_NC3;
                    expected_mode = NC_CDF5;
                    break;
                case NC_FORMAT_NETCDF4:
                    expected_extended_format = NC_FORMATX_NC4;
                    expected_mode = NC_NETCDF4;
                    break;
                case NC_FORMAT_NETCDF4_CLASSIC:
                    expected_extended_format = NC_FORMATX_NC4;
                    expected_mode = NC_NETCDF4|NC_CLASSIC_MODEL;
                    break;
                }
                if (nc_set_default_format(format[f], NULL)) ERR;

                /* Create a file. */
                if (nc_create(file_name, 0, &ncid)) ERR;
                if (check_inq_format(ncid, format[f], expected_extended_format, expected_mode)) ERR;
                if (nc_close(ncid)) ERR;

                /* Re-open the file and check it again. */
                if (nc_open(file_name, 0, &ncid)) ERR;
                /* Classic flag is not set on mode in nc_open(). Not sure if
                 * this is a bug or not. */
                if (format[f] == NC_FORMAT_NETCDF4_CLASSIC)
                    expected_mode = NC_NETCDF4;
                if (check_inq_format(ncid, format[f], expected_extended_format, expected_mode)) ERR;
                if (nc_close(ncid)) ERR;
            }
            SUMMARIZE_ERR;
            /* Test without and with actual data write. */
            for (d = 0; d < NUM_FILL_WRITE_TESTS; d++)
            {
                /* Test setting _FillValue directly or calling nc_def_var_fill(). */
                for (a = 0; a < NUM_FILL_WRITE_METHOD_TESTS; a++)
                {
                    printf("*** testing late fill handling with format %d writing %d "
                           "using def_var_fill %d...", format[f], d, a);
                    char file_name[NC_MAX_NAME + 1];
                    int dimid, varid;
                    size_t index = {DIM_LEN - 1};
                    int data = TEST_VAL_42;
                    int data_in;
                    int fill_value = TEST_VAL_42 * 2;
                    int shuffle_in, deflate_in, deflate_level_in;
                    int options_mask_in, pixels_per_block_in;
                    int storage_in;

		    unsigned int filterid;
		    size_t nfilters;

                    /* Try to set fill mode after data have been written. */
                    sprintf(file_name, "%s_%d_%d_%d_elatefill.nc", FILE_NAME_BASE, format[f], d, a);
                    if (nc_set_default_format(format[f], NULL)) ERR;
                    if (nc_create(file_name, 0, &ncid)) ERR;
                    if (nc_def_dim(ncid, DIM_NAME, DIM_LEN, &dimid)) ERR;
                    if (nc_def_var(ncid, VAR_NAME, NC_INT, NDIM1, &dimid, &varid)) ERR;

                    /* There is no deflate on this var, and that is true in
                     * all formats. */
                    if (nc_inq_var_deflate(ncid, varid, &shuffle_in, &deflate_in,
                                           &deflate_level_in)) ERR;
                    if (shuffle_in || deflate_in || deflate_level_in) ERR;

                    /* There is no szip on this var, and that is true in
                     * all formats. */
                    if (nc_inq_var_szip(ncid, varid, &options_mask_in, &pixels_per_block_in)) ERR;
                    if (options_mask_in || pixels_per_block_in) ERR;

                    /* Since chunking is unset for netCDF-4 files, and
                     * unavailable for classic formats, this will tell us
                     * the var is contiguous. */
                    if (nc_inq_var_chunking(ncid, varid, &storage_in, NULL)) ERR;
                    if (storage_in != NC_CONTIGUOUS) ERR;

		    /* Since there are no filters defined, all of these
                       should succeed */
		    if (nc_inq_var_filter(ncid, varid, &filterid, NULL, NULL)) ERR;
		    filterid = H5Z_FILTER_DEFLATE;
		    if (nc_inq_var_filter_info(ncid, varid, filterid, NULL, NULL) != NC_ENOFILTER) ERR;
		    nfilters = 0;
		    if (nc_inq_var_filter_ids(ncid, varid, &nfilters, NULL)) ERR;
		    if(nfilters != 0) ERR;

                    if (nc_enddef(ncid)) ERR;
                    /* For netCDF-4, we don't actually have to write data to
                     * prevent future setting of the fill value. Once the user
                     * leaves calls enddef after defining a var, fill values
                     * can no longer be set. */
                    if (d)
                        if (nc_put_var1_int(ncid, varid, &index, &data)) ERR;
                    if (nc_redef(ncid)) ERR;
                    if (a)
                    {
                        ret = nc_def_var_fill(ncid, varid, NC_FILL, &fill_value);
                    }
                    else
                    {
                        ret = nc_put_att_int(ncid, varid, "_FillValue", NC_INT, 1,
                                             &fill_value);
                    }

                    /* Setting the fill value after data are written is
                     * allowed in classic formats, but not netcdf-4. */
                    if (format[f] == NC_FORMAT_CLASSIC || format[f] == NC_FORMAT_64BIT_OFFSET ||
                        format[f] == NC_FORMAT_CDF5)
                    {
                        if (ret) ERR;
                    }
                    else
                    {
                        if (ret != (a ? NC_ELATEDEF: NC_ELATEFILL)) ERR;
                    }
                    if (nc_enddef(ncid)) ERR;

                    /* There is (still!) no deflate on this var, and that
                     * is true in all formats. */
                    if (nc_inq_var_deflate(ncid, varid, &shuffle_in, &deflate_in,
                                           &deflate_level_in)) ERR;
                    if (shuffle_in || deflate_in || deflate_level_in) ERR;

                    /* There is (still!) no szip on this var, and that is
                     * true in all formats. */
                    if (nc_inq_var_szip(ncid, varid, &options_mask_in, &pixels_per_block_in)) ERR;
                    if (options_mask_in || pixels_per_block_in) ERR;

                    /* Storage is (still) contiguous. */
                    if (nc_inq_var_chunking(ncid, varid, &storage_in, NULL)) ERR;
                    if (storage_in != NC_CONTIGUOUS) ERR;

                    if (nc_close(ncid)) ERR;

                    /* Open the file and check data. */
                    if (nc_open(file_name, NC_NOWRITE, &ncid)) ERR;
                    if (nc_get_var1_int(ncid, varid, &index, &data_in)) ERR;
                    if (data_in != (d ? data : NC_FILL_INT)) ERR;
                    if (nc_close(ncid)) ERR;
                    SUMMARIZE_ERR;
                } /* next fill value method test */
            } /* next fill val write test */

#define NDIM2 2
#define DIM1_NAME "dim1"
#define DIM2_NAME "dim2"
#define NTYPE 6
#define DATA_LEN 4

            printf("*** testing handling of null strides with format %d... ",
                   format[f]);
            {
                char file_name[NC_MAX_NAME + 1];
                char var_name[NC_MAX_NAME + 1];
                int dimid[NDIM2];
                int xtype[NTYPE] = {NC_BYTE, NC_CHAR, NC_SHORT, NC_INT, NC_FLOAT, NC_DOUBLE};
                int type_size[NTYPE] = {1, 1, 2, 4, 4, 8};
                int varid[NTYPE];
                size_t start[NDIM2] = {0, 0};
                size_t count[NDIM2] = {2, 2};
                signed char data_byte[DATA_LEN] = {1, 2, 3, 4};
                unsigned char data_char[DATA_LEN] = {1, 2, 3, 4};
                short data_short[DATA_LEN] = {1, 2, 3, 4};
                int data_int[DATA_LEN] = {1, 2, 3, 4};
                float data_float[DATA_LEN] = {1, 2, 3, 4};
                double data_double[DATA_LEN] = {1, 2, 3, 4};
                void *data_ptr[NTYPE] = {data_byte, data_char, data_short, data_int, data_float, data_double};
                int t;

                /* Create the test file. */
                sprintf(file_name, "%s_%d_null_strides.nc", FILE_NAME_BASE, format[f]);
                if (nc_set_default_format(format[f], NULL)) ERR;
                if (nc_create(file_name, 0, &ncid)) ERR;
                if (nc_def_dim(ncid, DIM1_NAME, DIM_LEN, &dimid[0])) ERR;
                if (nc_def_dim(ncid, DIM2_NAME, DIM_LEN, &dimid[1])) ERR;
                for (t = 0; t < NTYPE; t++)
                {
                    sprintf(var_name, "var_%d", xtype[t]);
                    if (nc_def_var(ncid, var_name, xtype[t], NDIM2, dimid, &varid[t])) ERR;
                }
                if (nc_enddef(ncid)) ERR;

                /* Write some data. */
                for (t = 0; t < NTYPE; t++)
                {
                    if (nc_put_vars(ncid, varid[t], start, count, NULL, data_ptr[t])) ERR;
                }
                if (nc_close(ncid)) ERR;

                /* Open the file and check data. */
                {
                    int ndims, nvars, ngatts, unlimdimid;

                    if (nc_open(file_name, NC_NOWRITE, &ncid)) ERR;
                    if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
                    if (ndims != 2 || nvars != NTYPE || ngatts != 0 || unlimdimid != -1) ERR;
                    for (t = 0; t < NTYPE; t++)
                    {
                        nc_type my_type;
                        int var_ndims, natts;
                        int var_dimid[NDIM2];
                        void *data_in;

                        if (nc_inq_var(ncid, varid[t], NULL, &my_type, &var_ndims, var_dimid, &natts)) ERR;
                        if (my_type != xtype[t] || var_ndims != 2 || var_dimid[0] != dimid[0] ||
                            var_dimid[1] != dimid[1] || natts != 0) ERR;
                        if (!(data_in = malloc(DATA_LEN * type_size[t]))) ERR;
                        if (nc_get_vars(ncid, varid[t], start, count, NULL, data_in)) ERR;
                        if (memcmp(data_in, data_ptr[t], DATA_LEN * type_size[t])) ERR;
                        free(data_in);

                    }
                    if (nc_close(ncid)) ERR;
                }

            }
            SUMMARIZE_ERR;
            printf("*** testing bad name for nc_open/nc_create with format %d... ", format[f]);
            {
                int ncid;
                if (nc_set_default_format(format[f], NULL)) ERR;
                if (nc_create(NULL, 0, &ncid) != NC_EINVAL) ERR;
                if (nc_open(NULL, NC_NOWRITE, &ncid) != NC_EINVAL) ERR;
                if (nc_delete(NULL) != NC_EINVAL) ERR;
            }
            SUMMARIZE_ERR;
        } /* next format */
    }
    FINAL_RESULTS;
}


text:
export * from "./class21";
export * from "./class22";


text:
require "spec_helper"

describe Pliny::Log do
  before do
    @io = StringIO.new
    Pliny.stdout = @io
    stub(@io).print
  end

  after do
    Pliny.default_context = {}
  end

  it "logs in structured format" do
    mock(@io).print "foo=bar baz=42\n"
    Pliny.log(foo: "bar", baz: 42)
  end

  it "supports blocks to log stages and elapsed" do
    mock(@io).print "foo=bar at=start\n"
    mock(@io).print "foo=bar at=finish elapsed=0.000\n"
    Pliny.log(foo: "bar") do
    end
  end

  it "merges default context" do
    Pliny.default_context = { app: "pliny" }
    mock(@io).print "app=pliny foo=bar\n"
    Pliny.log(foo: "bar")
  end

  it "merges context from RequestStore" do
    Pliny::RequestStore.store[:log_context] = { app: "pliny" }
    mock(@io).print "app=pliny foo=bar\n"
    Pliny.log(foo: "bar")
  end

  it "supports a context" do
    mock(@io).print "app=pliny foo=bar\n"
    Pliny.context(app: "pliny") do
      Pliny.log(foo: "bar")
    end
  end

  it "local context does not overwrite default context" do
    Pliny.default_context = { app: "pliny" }
    mock(@io).print "app=not_pliny foo=bar\n"
    Pliny.log(app: 'not_pliny', foo: "bar")
    assert Pliny.default_context[:app] == "pliny"
  end

  it "local context does not overwrite request context" do
    Pliny::RequestStore.store[:log_context] = { app: "pliny" }
    mock(@io).print "app=not_pliny foo=bar\n"
    Pliny.context(app: "not_pliny") do
      Pliny.log(foo: "bar")
    end
    assert Pliny::RequestStore.store[:log_context][:app] == "pliny"
  end

  it "local context does not propagate outside" do
    Pliny::RequestStore.store[:log_context] = { app: "pliny" }
    mock(@io).print "app=pliny foo=bar\n"
    Pliny.context(app: "not_pliny", test: 123) do
    end
    Pliny.log(foo: "bar")
  end
end


text: Please clearly state the issue


text:
export let cache = {
	computeds: <ComputedObservable<any>[]>[]
};

export interface Subscribable<T> {
	subscribe(handler: (newValue: T, oldValue: T) => void): { notify(): void };
	unsubscribe(handler: (newValue: T, oldValue: T) => void): void;
}

export interface Observable<T> extends Function, Subscribable<T> {
	notifyAll(): void;
	data: {
		_subscribers: ((newValue: T, oldValue: T) => void)[]
		_value?: T;
	}
	extend(obj: {}): void;
}

export interface SimpleObservable<T> extends Observable<T> {

}

export interface ObservableArray<T> extends Observable<T> {
	push(value: T): void;

	subscribe(handler: (newValue: T, oldValue: T) => void): { notify(): void };
	subscribe(handler: (newItems: T[], oldItems: T[]) => void): { notify(): void };
}

export interface ComputedObservable<T> extends Observable<T> {

}


text:
from crypto.bls.bls_bft import BlsBft
from plenum.bls.bls_bft_factory import create_default_bls_bft_factory
from plenum.common.ledger_manager import LedgerManager
from plenum.server.batch_handlers.ts_store_batch_handler import TsStoreBatchHandler
from plenum.server.last_sent_pp_store_helper import LastSentPpStoreHelper
from plenum.server.ledgers_bootstrap import LedgersBootstrap
from plenum.server.request_handlers.get_txn_handler import GetTxnHandler

from plenum.common.constants import POOL_LEDGER_ID, DOMAIN_LEDGER_ID, CONFIG_LEDGER_ID, \
    BLS_PREFIX, TS_LABEL, SEQ_NO_DB_LABEL, NODE_STATUS_DB_LABEL, LAST_SENT_PP_STORE_LABEL
from plenum.server.pool_manager import TxnPoolManager
from stp_core.common.log import getlogger

logger = getlogger()

class NodeBootstrap(LedgersBootstrap):

    def __init__(self, node):
        super().__init__(
            write_req_manager=node.write_manager,
            read_req_manager=node.read_manager,
            action_req_manager=node.action_manager,
            name=node.name,
            config=node.config,
            ledger_ids=node.ledger_ids)
        self.set_data_location(node.dataLocation)
        self.set_genesis_location(node.genesis_dir)
        self.node = node

    def init_state_ts_db_storage(self):
        ts_storage = self.node._get_state_ts_db_storage()
        self.node.db_manager.register_new_store(TS_LABEL, ts_storage)

    def init_seq_no_db_storage(self):
        seq_no_db_storage = self.node.loadSeqNoDB()
        self.node.db_manager.register_new_store(SEQ_NO_DB_LABEL, seq_no_db_storage)

    def init_node_status_db_storage(self):
        node_status_db = self.node.loadNodeStatusDB()
        self.node.db_manager.register_new_store(NODE_STATUS_DB_LABEL, node_status_db)

    def init_last_sent_pp_store(self):
        last_sent_pp_store = LastSentPpStoreHelper(self.node)
        self.node.db_manager.register_new_store(LAST_SENT_PP_STORE_LABEL, last_sent_pp_store)

    def _init_storages(self, domain_storage):
        super()._init_storages(domain_storage)

        # StateTsDbStorage
        self.init_state_ts_db_storage()

        # seqNoDB storage
        self.init_seq_no_db_storage()

        # nodeStatusDB
        self.init_node_status_db_storage()

        # last_sent_pp_store
        self.init_last_sent_pp_store()

    def _init_bls_bft(self):
        super()._init_bls_bft()
        self.node.bls_bft = self.bls_bft

    def _create_bls_bft(self) -> BlsBft:
        bls_factory = create_default_bls_bft_factory(self.node)
        bls_bft = bls_factory.create_bls_bft()
        if bls_bft.can_sign_bls():
            logger.display("{}BLS Signatures will be used for Node {}".format(BLS_PREFIX, self.node.name))
        else:
            # TODO: for now we allow that BLS is optional, so that we don't require it
            logger.warning(
                '{}Transactions will not be BLS signed by this Node, since BLS keys were not found. '
                'Please make sure that a script to init BLS keys was called (init_bls_keys),'
                ' and NODE txn was sent with BLS public keys.'.format(BLS_PREFIX))
        return bls_bft

    def _update_txn_with_extra_data(self, txn):
        return self.node.update_txn_with_extra_data(txn)

    def _init_common_managers(self):
        # Pool manager init
        self.node.poolManager = TxnPoolManager(self.node,
                                               self.node.poolLedger,
                                               self.node.states[POOL_LEDGER_ID],
                                               self.node.write_manager,
                                               self.node.ha,
                                               self.node.cliname,
                                               self.node.cliha)

        # Ledger manager init
        ledger_sync_order = self.node.ledger_ids
        self.node.ledgerManager = LedgerManager(self.node,
                                                postAllLedgersCaughtUp=self.node.allLedgersCaughtUp,
                                                preCatchupClbk=self.node.preLedgerCatchUp,
                                                postCatchupClbk=self.node.postLedgerCatchUp,
                                                ledger_sync_order=ledger_sync_order,
                                                metrics=self.node.metrics)

    def register_ts_store_batch_handlers(self):
        ts_store_b_h = TsStoreBatchHandler(self.node.db_manager)
        for lid in [DOMAIN_LEDGER_ID, CONFIG_LEDGER_ID]:
            self.node.write_manager.register_batch_handler(ts_store_b_h, ledger_id=lid)

    def _register_common_handlers(self):
        get_txn_handler = GetTxnHandler(self.node, self.node.db_manager)
        for lid in self.node.ledger_ids:
            self.node.read_manager.register_req_handler(get_txn_handler, ledger_id=lid)
        self.register_ts_store_batch_handlers()


text:
package org.elasticsearch.rest.action.search;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.QuerySourceBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.exists.RestExistsAction;
import org.elasticsearch.rest.action.support.RestActions;
import org.elasticsearch.rest.action.support.RestStatusToXContentListener;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.source.FetchSourceContext;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.sort.SortOrder;

import static org.elasticsearch.common.unit.TimeValue.parseTimeValue;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.search.suggest.SuggestBuilders.termSuggestion;

/**
 *
 */
public class RestSearchAction extends BaseRestHandler {

    @Inject
    public RestSearchAction(Settings settings, RestController controller, Client client) {
        super(settings, controller, client);
        controller.registerHandler(GET, "/_search", this);
        controller.registerHandler(POST, "/_search", this);
        controller.registerHandler(GET, "/{index}/_search", this);
        controller.registerHandler(POST, "/{index}/_search", this);
        controller.registerHandler(GET, "/{index}/{type}/_search", this);
        controller.registerHandler(POST, "/{index}/{type}/_search", this);
        controller.registerHandler(GET, "/_search/template", this);
        controller.registerHandler(POST, "/_search/template", this);
        controller.registerHandler(GET, "/{index}/_search/template", this);
        controller.registerHandler(POST, "/{index}/_search/template", this);
        controller.registerHandler(GET, "/{index}/{type}/_search/template", this);
        controller.registerHandler(POST, "/{index}/{type}/_search/template", this);

        RestExistsAction restExistsAction = new RestExistsAction(settings, controller, client);
        controller.registerHandler(GET, "/_search/exists", restExistsAction);
        controller.registerHandler(POST, "/_search/exists", restExistsAction);
        controller.registerHandler(GET, "/{index}/_search/exists", restExistsAction);
        controller.registerHandler(POST, "/{index}/_search/exists", restExistsAction);
        controller.registerHandler(GET, "/{index}/{type}/_search/exists", restExistsAction);
        controller.registerHandler(POST, "/{index}/{type}/_search/exists", restExistsAction);
    }

    @Override
    public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
        SearchRequest searchRequest;
        searchRequest = RestSearchAction.parseSearchRequest(request);
        client.search(searchRequest, new RestStatusToXContentListener<SearchResponse>(channel));
    }

    public static SearchRequest parseSearchRequest(RestRequest request) {
        String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
        SearchRequest searchRequest = new SearchRequest(indices);
        // get the content, and put it in the body
        // add content/source as template if template flag is set
        boolean isTemplateRequest = request.path().endsWith("/template");
        if (RestActions.hasBodyContent(request)) {
            if (isTemplateRequest) {
                searchRequest.templateSource(RestActions.getRestContent(request));
            } else {
                searchRequest.source(RestActions.getRestContent(request));
            }
        }

        // do not allow 'query_and_fetch' or 'dfs_query_and_fetch' search types
        // from the REST layer. these modes are an internal optimization and should
        // not be specified explicitly by the user.
        String searchType = request.param("search_type");
        if (SearchType.fromString(searchType).equals(SearchType.QUERY_AND_FETCH) ||
                SearchType.fromString(searchType).equals(SearchType.DFS_QUERY_AND_FETCH)) {
            throw new IllegalArgumentException("Unsupported search type [" + searchType + "]");
        } else {
            searchRequest.searchType(searchType);
        }

        searchRequest.extraSource(parseSearchSource(request));
        searchRequest.queryCache(request.paramAsBoolean("query_cache", null));

        String scroll = request.param("scroll");
        if (scroll != null) {
            searchRequest.scroll(new Scroll(parseTimeValue(scroll, null)));
        }

        searchRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
        searchRequest.routing(request.param("routing"));
        searchRequest.preference(request.param("preference"));
        searchRequest.indicesOptions(IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));

        return searchRequest;
    }

    public static SearchSourceBuilder parseSearchSource(RestRequest request) {
        SearchSourceBuilder searchSourceBuilder = null;

        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            searchSourceBuilder = new SearchSourceBuilder();
            searchSourceBuilder.query(querySourceBuilder);
        }

        int from = request.paramAsInt("from", -1);
        if (from != -1) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.from(from);
        }
        int size = request.paramAsInt("size", -1);
        if (size != -1) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.size(size);
        }

        if (request.hasParam("explain")) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.explain(request.paramAsBoolean("explain", null));
        }
        if (request.hasParam("version")) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.version(request.paramAsBoolean("version", null));
        }
        if (request.hasParam("timeout")) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.timeout(request.paramAsTime("timeout", null));
        }
        if (request.hasParam("terminate_after")) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            int terminateAfter = request.paramAsInt("terminate_after",
                    SearchContext.DEFAULT_TERMINATE_AFTER);
            if (terminateAfter < 0) {
                throw new IllegalArgumentException("terminateAfter must be > 0");
            } else if (terminateAfter > 0) {
                searchSourceBuilder.terminateAfter(terminateAfter);
            }
        }

        String sField = request.param("fields");
        if (sField != null) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            if (!Strings.hasText(sField)) {
                searchSourceBuilder.noFields();
            } else {
                String[] sFields = Strings.splitStringByCommaToArray(sField);
                if (sFields != null) {
                    for (String field : sFields) {
                        searchSourceBuilder.field(field);
                    }
                }
            }
        }
        String sFieldDataFields = request.param("fielddata_fields");
        if (sFieldDataFields != null) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            if (Strings.hasText(sFieldDataFields)) {
                String[] sFields = Strings.splitStringByCommaToArray(sFieldDataFields);
                if (sFields != null) {
                    for (String field : sFields) {
                        searchSourceBuilder.fieldDataField(field);
                    }
                }
            }
        }
        FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
        if (fetchSourceContext != null) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.fetchSource(fetchSourceContext);
        }

        if (request.hasParam("track_scores")) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.trackScores(request.paramAsBoolean("track_scores", false));
        }

        String sSorts = request.param("sort");
        if (sSorts != null) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            String[] sorts = Strings.splitStringByCommaToArray(sSorts);
            for (String sort : sorts) {
                int delimiter = sort.lastIndexOf(":");
                if (delimiter != -1) {
                    String sortField = sort.substring(0, delimiter);
                    String reverse = sort.substring(delimiter + 1);
                    if ("asc".equals(reverse)) {
                        searchSourceBuilder.sort(sortField, SortOrder.ASC);
                    } else if ("desc".equals(reverse)) {
                        searchSourceBuilder.sort(sortField, SortOrder.DESC);
                    }
                } else {
                    searchSourceBuilder.sort(sort);
                }
            }
        }

        String sStats = request.param("stats");
        if (sStats != null) {
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            searchSourceBuilder.stats(Strings.splitStringByCommaToArray(sStats));
        }

        String suggestField = request.param("suggest_field");
        if (suggestField != null) {
            String suggestText = request.param("suggest_text", request.param("q"));
            int suggestSize = request.paramAsInt("suggest_size", 5);
            if (searchSourceBuilder == null) {
                searchSourceBuilder = new SearchSourceBuilder();
            }
            String suggestMode = request.param("suggest_mode");
            searchSourceBuilder.suggest().addSuggestion(
                    termSuggestion(suggestField).field(suggestField).text(suggestText).size(suggestSize)
                            .suggestMode(suggestMode)
            );
        }

        return searchSourceBuilder;
    }
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sign UP"
        android:id="@+id/sign_up_button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="onSignUpClicked"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/login_button"
        android:onClick="onLoginClicked"
        android:layout_alignTop="@+id/sign_up_button"
        android:layout_centerHorizontal="true"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:id="@+id/logout_button"
        android:onClick="onLogoutClicked"
        android:layout_alignTop="@+id/login_button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="CurrentUser"
        android:id="@+id/current_user_button"
        android:onClick="onCurrentUserClicked"
        android:layout_below="@+id/mail_signup_button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UserDelete"
        android:id="@+id/user_delete_button"
        android:onClick="onUserDeleteClicked"
        android:layout_alignTop="@+id/current_user_button"
        android:layout_alignLeft="@+id/mail_login_button"
        android:layout_alignStart="@+id/mail_login_button"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mail_SignUp"
        android:id="@+id/mail_signup_button"
        android:onClick="onMailSignUpClicked"
        android:layout_marginTop="42dp"
        android:layout_below="@+id/sign_up_button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mail_login"
        android:id="@+id/mail_login_button"
        android:layout_alignTop="@+id/mail_signup_button"
        android:layout_alignLeft="@+id/login_button"
        android:layout_alignStart="@+id/login_button"
        android:onClick="onMailLoginUpClicked"/>
</RelativeLayout>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>
Ruleset: Basic JSP</title>

    <link rel="stylesheet" href="../../css/print.css" type="text/css" media="print" />
      <meta name="author" content="Tom Copeland" />
    <meta name="Date-Revision-yyyymmdd" content="20120501" />
    <meta http-equiv="Content-Language" content="en" />

        Last Published: 2012-05-01
                   | Version: 5.0.0
                          |                           SourceForge
        >
                          PMD
        >

Ruleset: Basic JSP

                    SourceForge.net Project Page
            |
                        Hosted by SourceForge

Overview

                          Download PMD 5.0.0

                          What's new in PMD 5.0.0

                          PMD in the news

                          PMD-related products and books

                          Best practices

                          Future directions

                          Similar projects

                          Credits

                          License

                          What does 'PMD' mean?

Usage

                          Installation

                          Command line usage

                          Ant task usage

                          Maven plugin usage

                          Mvn plugin usage

                          IDE plugin usage

                          Suppressing warnings

                          Finding duplicated code

                          JSP support

Customizing PMD

                          Compiling PMD

                          How to write a rule

                          Writing XPath rules

                          How to make a rule set

                          How it works

                          Rule guidelines

                          PMD developers information

                          PMD Release Process

For example

                          Run PMD on a Sourceforge project

Rule Sets

                          jsp

                          Basic JSF

            Basic JSP

                          xsl

                          XPath in XSL

                          java

                          Design

                          Coupling

                          Jakarta Commons Logging

                          Basic

                          Strict Exceptions

                          Security Code Guidelines

                          Java Logging

                          Android

                          Controversial

                          Comments

                          Type Resolution

                          Empty Code

                          String and StringBuffer

                          Code Size

                          Braces

                          Unused Code

                          Unnecessary

                          J2EE

                          JavaBeans

                          Migration

                          Import Statements

                          JUnit

                          Naming

                          Finalizer

                          Optimization

                          Clone Implementation

                          ecmascript

                          Basic Ecmascript

                          Unnecessary

                          Braces

                          xml

                          Basic XML

Project Documentation

                          Project Information

                          Project Reports

Basic JSP

	Rules concerning basic JSP guidelines.

NoLongScripts

Since: PMD 3.6

Scripts should be part of Tag Libraries, rather than part of JSP pages.

// Element [ upper-case(@Name)="SCRIPT" and (@EndLine - @BeginLine > 10) ]

Example(s):

<HTML>
<BODY>
<!--Java Script-->
<SCRIPT language="JavaScript" type="text/javascript">
<!--
function calcDays(){
  var date1 = document.getElementById('d1').lastChild.data;
  var date2 = document.getElementById('d2').lastChild.data;
  date1 = date1.split("-");
  date2 = date2.split("-");
  var sDate = new Date(date1[0]+"/"+date1[1]+"/"+date1[2]);
  var eDate = new Date(date2[0]+"/"+date2[1]+"/"+date2[2]);
  var daysApart = Math.abs(Math.round((sDate-eDate)/86400000));
  document.getElementById('diffDays').lastChild.data = daysApart;
}

onload=calcDays;
//-->
</SCRIPT>
</BODY>
</HTML>

NoScriptlets

Since: PMD 3.6

Scriptlets should be factored into Tag Libraries or JSP	declarations, rather than being part of JSP pages.

					//JspScriptlet
					|
					//Element[ upper-case(@Name)="JSP:SCRIPTLET" ]

Example(s):

<HTML>
<HEAD>
<%
response.setHeader("Pragma", "No-cache");
%>
</HEAD>
	<BODY>
		<jsp:scriptlet>String title = "Hello world!";</jsp:scriptlet>
	</BODY>
</HTML>

NoInlineStyleInformation

Since: PMD 3.6

Style information should be put in CSS files, not in JSPs. Therefore, don't use <B> or <FONT> tags, or attributes like "align='center'".

This rule is defined by the following Java class:net.sourceforge.pmd.lang.jsp.rule.basic.NoInlineStyleInformationRule

Example(s):

<html><body><p align='center'><b>text</b></p></body></html>

NoClassAttribute

Since: PMD 3.6

Do not use an attribute called 'class'. Use "styleclass" for CSS styles.

					 //Attribute[ upper-case(@Name)="CLASS" ]

Example(s):

<HTML> <BODY>
<P class="MajorHeading">Some text</P>
</BODY> </HTML>

NoJspForward

Since: PMD 3.6

Do not do a forward from within a JSP file.

					 //Element[ @Name="jsp:forward" ]

Example(s):

<jsp:forward page='UnderConstruction.jsp'/>

IframeMissingSrcAttribute

Since: PMD 3.6

IFrames which are missing a src element can cause security information popups in IE if you are accessing the page
through SSL. See http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q261188

	//Element[upper-case(@Name)="IFRAME"][count(Attribute[upper-case(@Name)="SRC" ]) = 0]

Example(s):

<HTML><title>bad example><BODY>
<iframe></iframe>
</BODY> </HTML>

<HTML><title>good example><BODY>
<iframe src="foo"></iframe>
</BODY> </HTML>

NoHtmlComments

Since: PMD 3.6

			In a production system, HTML comments increase the payload
			between the application server to the client, and serve
			little other purpose. Consider switching to JSP comments.

	//CommentTag

Example(s):

<HTML><title>bad example><BODY>
<!-- HTML comment -->
</BODY> </HTML>

<HTML><title>good example><BODY>
<%-- JSP comment --%>
</BODY> </HTML>

DuplicateJspImports

Since: PMD 3.7

Avoid duplicate import statements inside JSP's.

This rule is defined by the following Java class:net.sourceforge.pmd.lang.jsp.rule.basic.DuplicateJspImportsRule

Example(s):

<%@ page import=\"com.foo.MyClass,com.foo.MyClass\"%><html><body><b><img src=\"<%=Some.get()%>/foo\">xx</img>text</b></body></html>

JspEncoding

Since: PMD

A missing 'meta' tag or page directive will trigger this rule, as well as a non-UTF-8 charset.

//Content[
not(Element[@Name="meta"][
   Attribute[@Name="content"]/AttributeValue[contains(lower-case(@Image),"charset=utf-8")]
])
and
    not(JspDirective[@Name='page']/JspDirectiveAttribute[@Name='contentType'][contains(lower-case(@Value),"charset=utf-8")])
]

Example(s):

                Most browsers should be able to interpret the following headers:

                <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

                <meta http-equiv="Content-Type"  content="text/html; charset=UTF-8" />

NoInlineScript

Since: PMD

Avoid inlining HTML script content.  Consider externalizing the HTML script using the 'src' attribute on the <script> element.
Externalized script could be reused between pages.  Browsers can also cache the script, reducing overall download bandwidth.

//HtmlScript[@Image != '']

Example(s):

                Most browsers should be able to interpret the following headers:

                <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

                <meta http-equiv="Content-Type"  content="text/html; charset=UTF-8" />

              Copyright ©                    2002-2012
                        InfoEther.
            All Rights Reserved.


text:
define(function() {

  var FavoriteView = Backbone.Marionette.ItemView.extend({
    initialize: function(options) {
      this.options = options
    },

    template: Handlebars.templates['query/dropdowns/favorite_layout'],

    className: 'favorite-child',

    bindings: {

    },

    events: {
      'click': 'setCurrentQuery'
    },

    setCurrentQuery: function(e) {
      e.stopPropagation()
      this.model.trigger('setCurrentQuery', this.model.get("query"))
    },

    onDestroy: function() {
      this.options = null
    },

    render: function() {
      this.unstickit()
      Backbone.Marionette.ItemView.prototype.render.call(this)
      this.stickit()
    }
  })

  return FavoriteView
})


text:
namespace MassTransit.Monitoring.Performance
{
    using System;
    using System.Threading.Tasks;
    using Util;

    /// <summary>
    /// An observer that updates the performance counters using the bus events
    /// generated.
    /// </summary>
    public class PerformanceCounterReceiveObserver :
        IReceiveObserver
    {
        readonly ICounterFactory _factory;

        public PerformanceCounterReceiveObserver(ICounterFactory factory)
        {
            _factory = factory;
        }

        Task IReceiveObserver.PreReceive(ReceiveContext context)
        {
            return Task.CompletedTask;
        }

        Task IReceiveObserver.PostReceive(ReceiveContext context)
        {
            return Task.CompletedTask;
        }

        Task IReceiveObserver.PostConsume<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType)
        {
            ConsumerPerformanceCounterCache.GetCounter(_factory, consumerType).Consumed(duration);
            MessagePerformanceCounterCache<T>.Counter(_factory).Consumed(duration);
            return Task.CompletedTask;
        }

        Task IReceiveObserver.ConsumeFault<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType, Exception exception)
        {
            ConsumerPerformanceCounterCache.GetCounter(_factory, consumerType).Faulted();
            MessagePerformanceCounterCache<T>.Counter(_factory).ConsumeFaulted(duration);
            return Task.CompletedTask;
        }

        Task IReceiveObserver.ReceiveFault(ReceiveContext context, Exception exception)
        {
            return Task.CompletedTask;
        }
    }
}


text:
'use strict'

var util = require('util')
var EventEmitter = require('events').EventEmitter
var once = require('once')
var httpHeaders = require('http-headers')
var Request = require('./request')
var utils = require('./utils')

var StatsEmitter = module.exports = function () {
  EventEmitter.call(this)
}
util.inherits(StatsEmitter, EventEmitter)

StatsEmitter.prototype._server = function (server, onStats) {
  this._attach(onStats)
  server.on('request', this._request.bind(this))
}

StatsEmitter.prototype._request = function (req, res, onStats) {
  var that = this
  var start = process.hrtime()

  this.emit('request', new Request(req, res))
  this._attach(onStats)

  var emit = once(function (ok) {
    var bytesReadPreviously = req.connection._requestStats ? req.connection._requestStats.bytesRead : 0
    var bytesWrittenPreviously = req.connection._requestStats ? req.connection._requestStats.bytesWritten : 0
    var bytesReadDelta = req.connection.bytesRead - bytesReadPreviously
    var bytesWrittenDelta = req.connection.bytesWritten - bytesWrittenPreviously
    var ip = getIp(req)

    req.connection._requestStats = {
      bytesRead: req.connection.bytesRead,
      bytesWritten: req.connection.bytesWritten
    }

    that.emit('complete', {
      ok: ok,
      time: utils.toMilliseconds(process.hrtime(start)),
      req: {
        bytes: bytesReadDelta,
        headers: req.headers,
        method: req.method,
        path: req.url,
        ip: ip,
        raw: req
      },
      res: {
        bytes: bytesWrittenDelta,
        headers: httpHeaders(res, true),
        status: res.statusCode,
        raw: res
      }
    })
  })

  res.once('finish', emit.bind(null, true))
  res.once('close', emit.bind(null, false))
}

function getIp (req) {
  var ip = req.headers['x-forwarded-for']
  if (!ip) {
    ip = req.connection && req.connection.remoteAddress
    if (!ip && req.socket) {
      ip = req.socket.remoteAddress || (req.socket.connection && req.socket.connection.remoteAddress)
    }
  }
  return ip
}

StatsEmitter.prototype._attach = function (listener) {
  if (typeof listener === 'function') this.on('complete', listener)
}


text:
import swgpy
from swgpy.object import *
from swgpy.attributes import *
from attributes.AttributeHelpers import SetOptionalAttribute
class DeedAttributeTemplate(BaseAttributeTemplate):
	def buildAttributeTemplate(self, object):
		attribute_list_message = AttributeListMessage()
		attribute_list_message.object_id = object.id
		attributes = AttributeList()
		if len(object.custom_name) > 0:
			attributes.append("@obj_attr_n:original_name", "@" + object.stf_file + ":" + object.stf_name)
		attributes.extend([
			Attribute("@obj_attr_n:volume", str(object.volume))
		])
		SetOptionalAttribute(attributes, '@obj_attr_n:crafter', 'crafter', object, False)
		SetOptionalAttribute(attributes, '@obj_attr_n:serial_number', 'serial_number', object, False)
		scenes = object.getStringAttribute('examine_scene').split(',')
		for scene in scenes:
			attributes.append(Attribute('@obj_attr_n:examine_scene', scene))
		attribute_list_message.attributes = attributes
		return attribute_list_message


text:
require 'dumbo/task/base'

module Dumbo
  module Task
    class IndexHadoop < Base
      def initialize(topic, interval, source, inputSpec, granularitySpec = nil)
        @topic = topic
        @source = source
        @inputSpec = inputSpec
        @granularitySpec = {
          segmentGranularity: "hour",
          queryGranularity: "minute",
          intervals: [interval],
        }.merge(granularitySpec || {})
      end

      def as_json(options = {})
        {
          type: 'index_hadoop',
          spec: {
            dataSchema: {
              dataSource: @topic,
              parser: {
                parseSpec: {
                  format: "json",
                  timestampSpec: {
                    column: ((@source['timestamp'] || {})['column'] || "ts"),
                    format: ((@source['timestamp'] || {})['format'] || "iso"),
                  },
                  dimensionsSpec: {
                    dimensions: (@source['dimensions'] || []),
                    spatialDimensions: (@source['spacialDimensions'] || []),
                  }
                }
              },
              metricsSpec: (@source['aggregators'] || {}).map do |name, aggregator|
                { type: aggregator, name: name, fieldName: name }
              end + [{ type: "count", name: "events" }],
              granularitySpec: @granularitySpec,
            },
            ioConfig: {
              type: 'hadoop',
              inputSpec: @inputSpec,
            },
            tuningConfig: {
              type: "hadoop",
              overwriteFiles: true,
              useCombiner: true,
              partitionsSpec: {
                type: "hashed",
                targetPartitionSize: 5000000,
              },
              jobProperties: {
                "mapreduce.job.classloader" => true,
                "mapreduce.map.memory.mb" => 2048,
                "mapreduce.map.java.opts" => "-server -Xmx1536m -Duser.timezone=UTC -Dfile.encoding=UTF-8",
                "mapreduce.reduce.memory.mb" => 6144,
                "mapreduce.reduce.java.opts" =>"-server -Xmx2560m -Duser.timezone=UTC -Dfile.encoding=UTF-8",
                "mapreduce.job.reduces" => 21,
                "mapreduce.job.jvm.numtasks" => 20,
                "mapreduce.reduce.shuffle.parallelcopies" => 50,
                "mapreduce.reduce.shuffle.input.buffer.percent" => 0.5,
                "mapreduce.task.io.sort.mb"  => 250,
                "mapreduce.task.io.sort.factor" => 100,
                "mapreduce.jobtracker.handler.count" => 64,
                "mapreduce.tasktracker.http.threads" => 20,
                "mapreduce.output.fileoutputformat.compress" => false,
                "mapreduce.output.fileoutputformat.compress.type" => "BLOCK",
                "mapreduce.output.fileoutputformat.compress.codec" => "org.apache.hadoop.io.compress.GzipCodec",
                "mapreduce.map.output.compress" => true,
                "mapreduce.map.output.compress.codec" => "org.apache.hadoop.io.compress.Lz4Codec",
                "mapreduce.map.speculative" => false,
                "mapreduce.reduce.speculative" => false,
                "mapreduce.task.timeout" => 1800000
              },
            },
          },
        }
      end
    end
  end
end


text:
'use strict';

/**
 * Path description for the application package in the image store specified
 * during the prior copy operation.
 *
 */
class ApplicationTypeImageStorePath {
  /**
   * Create a ApplicationTypeImageStorePath.
   * @member {string} applicationTypeBuildPath The relative image store path to
   * the application package.
   */
  constructor() {
  }

  /**
   * Defines the metadata of ApplicationTypeImageStorePath
   *
   * @returns {object} metadata of ApplicationTypeImageStorePath
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ApplicationTypeImageStorePath',
      type: {
        name: 'Composite',
        className: 'ApplicationTypeImageStorePath',
        modelProperties: {
          applicationTypeBuildPath: {
            required: true,
            serializedName: 'ApplicationTypeBuildPath',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ApplicationTypeImageStorePath;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>tesseract: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

tesseract
    4.00.00dev

tesseract::DocumentCache Member List

This is the complete list of members for tesseract::DocumentCache, including all inherited members.

AddToCache(DocumentData *data)	tesseract::DocumentCache

Clear()	tesseract::DocumentCache	inline

DocumentCache(inT64 max_memory)	tesseract::DocumentCache	explicit

documents() const	tesseract::DocumentCache	inline

FindDocument(const STRING &document_name) const	tesseract::DocumentCache

GetPageBySerial(int serial)	tesseract::DocumentCache	inline

LoadDocuments(const GenericVector< STRING > &filenames, CachingStrategy cache_strategy, FileReader reader)	tesseract::DocumentCache

TotalPages()	tesseract::DocumentCache

~DocumentCache()	tesseract::DocumentCache

Generated on Wed Mar 28 2018 19:53:46 for tesseract by

     1.8.13


text:
namespace Helios.Tenants.Dashboard.Dto
{
    public enum SalesSummaryDatePeriod
    {
        Daily = 1,
        Weekly = 2,
        Monthly = 3
    }
}


text:
package com.google.template.soy.bididirectives;

import com.google.common.collect.ImmutableList;
import com.google.template.soy.data.restricted.StringData;
import com.google.template.soy.javasrc.restricted.JavaExpr;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.shared.AbstractSoyPrintDirectiveTestCase;
import com.google.template.soy.shared.restricted.SharedRestrictedTestUtils;

/**
 * Unit tests for BidiSpanWrapDirective.
 *
 * @author Kai Huang
 */
public class BidiSpanWrapDirectiveTest extends AbstractSoyPrintDirectiveTestCase {

  private static final BidiSpanWrapDirective BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR =
      new BidiSpanWrapDirective(SharedRestrictedTestUtils.BIDI_GLOBAL_DIR_FOR_STATIC_LTR_PROVIDER);

  private static final BidiSpanWrapDirective BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL =
      new BidiSpanWrapDirective(SharedRestrictedTestUtils.BIDI_GLOBAL_DIR_FOR_STATIC_RTL_PROVIDER);

  private static final BidiSpanWrapDirective BIDI_SPAN_WRAP_DIRECTIVE_FOR_ISRTL_CODE_SNIPPET =
      new BidiSpanWrapDirective(
          SharedRestrictedTestUtils.BIDI_GLOBAL_DIR_FOR_ISRTL_CODE_SNIPPET_PROVIDER);

  public void testApplyForTofu() {

    assertTofuOutput("", "", BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR);
    assertTofuOutput("blah", "blah", BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR);
    assertTofuOutput("\u05E0\u200E", "\u05E0",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR);

    assertTofuOutput("", "", BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL);
    assertTofuOutput("blah\u200F", "blah",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL);
    assertTofuOutput("\u05E0", "\u05E0", BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL);
  }

  public void testApplyForJsSrc() {

    JsExpr dataRef = new JsExpr("opt_data.myKey", Integer.MAX_VALUE);
    assertEquals(
        "soy.$$bidiSpanWrap(1, opt_data.myKey)",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR.applyForJsSrc(
            dataRef, ImmutableList.<JsExpr>of()).getText());
    assertEquals(
        "soy.$$bidiSpanWrap(-1, opt_data.myKey)",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL.applyForJsSrc(
            dataRef, ImmutableList.<JsExpr>of()).getText());
    assertEquals(
        "soy.$$bidiSpanWrap(IS_RTL?-1:1, opt_data.myKey)",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_ISRTL_CODE_SNIPPET.applyForJsSrc(
            dataRef, ImmutableList.<JsExpr>of()).getText());
  }

  public void testApplyForJavaSrc() {

    JavaExpr dataRef = new JavaExpr("stringValue", StringData.class, Integer.MAX_VALUE);
    assertEquals(
        "com.google.template.soy.data.restricted.StringData.forValue(" +
            "com.google.template.soy.internal.i18n.SoyBidiUtils.getBidiFormatter(" +
            "1).spanWrap(stringValue.toString(), true))",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_LTR.applyForJavaSrc(
            dataRef, ImmutableList.<JavaExpr>of()).getText());
    assertEquals(
        "com.google.template.soy.data.restricted.StringData.forValue(" +
            "com.google.template.soy.internal.i18n.SoyBidiUtils.getBidiFormatter(" +
            "-1).spanWrap(stringValue.toString(), true))",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_STATIC_RTL.applyForJavaSrc(
            dataRef, ImmutableList.<JavaExpr>of()).getText());
    assertEquals(
        "com.google.template.soy.data.restricted.StringData.forValue(" +
            "com.google.template.soy.internal.i18n.SoyBidiUtils.getBidiFormatter(" +
            "IS_RTL?-1:1).spanWrap(stringValue.toString(), true))",
        BIDI_SPAN_WRAP_DIRECTIVE_FOR_ISRTL_CODE_SNIPPET.applyForJavaSrc(
            dataRef, ImmutableList.<JavaExpr>of()).getText());
  }

}


text:
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import login_required

from assignment.models import Assignment
from student.models import Student
from submission.models import Submission

from django.utils import timezone
from django.template import RequestContext, Context, loader
from mailer.mail_settings import DEFAULT_SENDER, DEFAULT_RECEIVERS

collections = [0, 1, 2]

def assignments(request):
    assignments = Assignment.objects.all()
    student_count = Student.objects.count()
    return render_to_response('assignments.html',
            dict(
            student_count=student_count,
            title="assignments",
            assignments=assignments))

@login_required
def assignment(request, seq):
    assignment = get_object_or_404(Assignment, sequence=seq)
    cs = []
    for c in collections:
        students = Student.objects.filter(collection=c).order_by('student_num').values()
        s_count = len(students)
        sub_count = 0
        for student in students:
            submissions = Submission.objects.filter(
                    student=student['id'],
                    assignment=assignment).values()
            if submissions:
                student['submission'] = submissions[0]
                sub_count += 1

        cs.append((students, sub_count, s_count))

    return render_to_response('assignment.html',
            dict(
                assignment=assignment,
                title=assignment.title,
                collections=cs,
                ))

@login_required
def report(request, seq):
    assignment = get_object_or_404(Assignment, sequence=seq)
    cs = []
    all_sum = 0
    sub_sum = 0
    for c in collections:
        students = Student.objects.filter(collection=c).order_by('student_num').values()
        s_count = len(students)
        sub_count = 0
        zeros = []
        for student in students:
            submissions = Submission.objects.filter(
                    student=student['id'],
                    assignment=assignment).values()
            if submissions:
                sub_count += 1
            else:
                zeros.append(student)
        all_sum += s_count
        sub_sum += sub_count
        cs.append((zeros, s_count, sub_count, s_count-sub_count))

    zero_sum = all_sum - sub_sum
    now = timezone.now()
    to = None

    if request.POST and request.POST.has_key('to'):
        from mailer.process_mail import _mail_sender
        import re
        to = request.POST['to']
        to = set(re.split(r'[\s,;]+', to))
        to.add(DEFAULT_SENDER)
        to.discard('')
        t = loader.get_template('mails/report.html')
        receivers = to | set(DEFAULT_RECEIVERS)
        context = Context({
            'title':assignment.title,
            'collections':cs,
            'now':now,
            'all_sum':all_sum,
            'sub_sum':sub_sum,
            'zero_sum':zero_sum,
            'to':to,
            'receivers':receivers,
            })
        message = t.render(context)
        sender = _mail_sender()
        subject = "数据结构 %s 提交情况报告".decode('utf8')% assignment.title
        print "sending mails to %d address:" % len(to)
        print '-'*40
        for i, toaddr in enumerate(to):
            print "%d.  %s" % (i, toaddr)
        print '-'*40
        sender.send_mail(subject, None, DEFAULT_SENDER, set(to), html_message=message)

    return render_to_response('report.html',
            {   'title':assignment.title,
                'collections':cs,
                'now':now,
                'all_sum':all_sum,
                'sub_sum':sub_sum,
                'zero_sum':zero_sum,
                'to':to,
                'receivers':DEFAULT_RECEIVERS,
                }, context_instance=RequestContext(request))


text:
use clippy_utils::diagnostics::span_lint;
use clippy_utils::return_ty;
use clippy_utils::ty::{contains_adt_constructor, contains_ty};
use rustc_hir::{Impl, ImplItem, ImplItemKind, ItemKind, Node};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};

declare_clippy_lint! {
    /// ### What it does
    /// Warns when constructors have the same name as their types.
    ///
    /// ### Why is this bad?
    /// Repeating the name of the type is redundant.
    ///
    /// ### Example
    /// ```rust,ignore
    /// struct Foo {}
    ///
    /// impl Foo {
    ///     pub fn foo() -> Foo {
    ///         Foo {}
    ///     }
    /// }
    /// ```
    /// Use instead:
    /// ```rust,ignore
    /// struct Foo {}
    ///
    /// impl Foo {
    ///     pub fn new() -> Foo {
    ///         Foo {}
    ///     }
    /// }
    /// ```
    pub SELF_NAMED_CONSTRUCTORS,
    style,
    "method should not have the same name as the type it is implemented for"
}

declare_lint_pass!(SelfNamedConstructors => [SELF_NAMED_CONSTRUCTORS]);

impl<'tcx> LateLintPass<'tcx> for SelfNamedConstructors {
    fn check_impl_item(&mut self, cx: &LateContext<'tcx>, impl_item: &'tcx ImplItem<'_>) {
        match impl_item.kind {
            ImplItemKind::Fn(ref sig, _) => {
                if sig.decl.implicit_self.has_implicit_self() {
                    return;
                }
            },
            _ => return,
        }

        let parent = cx.tcx.hir().get_parent_did(impl_item.hir_id());
        let item = cx.tcx.hir().expect_item(parent);
        let self_ty = cx.tcx.type_of(item.def_id);
        let ret_ty = return_ty(cx, impl_item.hir_id());

        // Do not check trait impls
        if matches!(item.kind, ItemKind::Impl(Impl { of_trait: Some(_), .. })) {
            return;
        }

        // Ensure method is constructor-like
        if let Some(self_adt) = self_ty.ty_adt_def() {
            if !contains_adt_constructor(cx.tcx, ret_ty, self_adt) {
                return;
            }
        } else if !contains_ty(cx.tcx, ret_ty, self_ty) {
            return;
        }

        if_chain! {
            if let Some(self_def) = self_ty.ty_adt_def();
            if let Some(self_local_did) = self_def.did.as_local();
            let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did);
            if let Some(Node::Item(x)) = cx.tcx.hir().find(self_id);
            let type_name = x.ident.name.as_str().to_lowercase();
            if impl_item.ident.name.as_str() == type_name || impl_item.ident.name.as_str().replace("_", "") == type_name;

            then {
                span_lint(
                    cx,
                    SELF_NAMED_CONSTRUCTORS,
                    impl_item.span,
                    &format!("constructor `{}` has the same name as the type", impl_item.ident.name),
                );
            }
        }
    }
}


text:
namespace AspectSharp.Lang.Steps
{
	using System;

	/// <summary>
	/// Summary description for StepChainBuilder.
	/// </summary>
	public class StepChainBuilder
	{
		private IStep _head;
		private IStep _tail;

		public void AddStep( IStep step )
		{
			if (_head == null)
			{
				_head = step;
				_tail = _head;
			}
			else
			{
				_tail.Next = step;
				_tail = step;
			}
		}

		public IStep Build()
		{
			return _head;
		}
	}
}


text: public enum Test {}


text:
require 'fog/openstack/common'
require 'fog/openstack/identity'

module Fog
  module Identity
    class OpenStack
      class V2 < Fog::Service

        requires :openstack_auth_url
        recognizes :openstack_auth_token, :openstack_management_url,
                   :persistent, :openstack_service_type, :openstack_service_name,
                   :openstack_tenant, :openstack_tenant_id,
                   :openstack_api_key, :openstack_username, :openstack_identity_endpoint,
                   :current_user, :current_tenant, :openstack_region,
                   :openstack_endpoint_type, :openstack_cache_ttl,
                   :openstack_project_name, :openstack_project_id,
                   :openstack_project_domain, :openstack_user_domain, :openstack_domain_name,
                   :openstack_project_domain_id, :openstack_user_domain_id, :openstack_domain_id,
                   :openstack_identity_prefix, :openstack_endpoint_path_matches

        model_path 'fog/openstack/models/identity_v2'
        model :tenant
        collection :tenants
        model :user
        collection :users
        model :role
        collection :roles
        model :ec2_credential
        collection :ec2_credentials

        request_path 'fog/openstack/requests/identity_v2'

        request :check_token
        request :validate_token

        request :list_tenants
        request :create_tenant
        request :get_tenant
        request :get_tenants_by_id
        request :get_tenants_by_name
        request :update_tenant
        request :delete_tenant

        request :list_users
        request :create_user
        request :update_user
        request :delete_user
        request :get_user_by_id
        request :get_user_by_name
        request :add_user_to_tenant
        request :remove_user_from_tenant

        request :list_endpoints_for_token
        request :list_roles_for_user_on_tenant
        request :list_user_global_roles

        request :create_role
        request :delete_role
        request :delete_user_role
        request :create_user_role
        request :get_role
        request :list_roles

        request :set_tenant

        request :create_ec2_credential
        request :delete_ec2_credential
        request :get_ec2_credential
        request :list_ec2_credentials

        class Mock
          attr_reader :auth_token
          attr_reader :auth_token_expiration
          attr_reader :current_user
          attr_reader :current_tenant
          attr_reader :unscoped_token

          def self.data
            @users ||= {}
            @roles ||= {}
            @tenants ||= {}
            @ec2_credentials ||= Hash.new { |hash, key| hash[key] = {} }
            @user_tenant_membership ||= {}

            @data ||= Hash.new do |hash, key|
              hash[key] = {
                  :users => @users,
                  :roles => @roles,
                  :tenants => @tenants,
                  :ec2_credentials => @ec2_credentials,
                  :user_tenant_membership => @user_tenant_membership
              }
            end
          end

          def self.reset!
            @data = nil
            @users = nil
            @roles = nil
            @tenants = nil
            @ec2_credentials = nil
          end

          def initialize(options={})
            @openstack_username = options[:openstack_username] || 'admin'
            @openstack_tenant = options[:openstack_tenant] || 'admin'
            @openstack_auth_uri = URI.parse(options[:openstack_auth_url])
            @openstack_management_url = @openstack_auth_uri.to_s

            @auth_token = Fog::Mock.random_base64(64)
            @auth_token_expiration = (Time.now.utc + 86400).iso8601

            @admin_tenant = self.data[:tenants].values.find do |u|
              u['name'] == 'admin'
            end

            if @openstack_tenant
              @current_tenant = self.data[:tenants].values.find do |u|
                u['name'] == @openstack_tenant
              end

              unless @current_tenant
                @current_tenant_id = Fog::Mock.random_hex(32)
                @current_tenant = self.data[:tenants][@current_tenant_id] = {
                    'id' => @current_tenant_id,
                    'name' => @openstack_tenant
                }
              else
                @current_tenant_id = @current_tenant['id']
              end
            else
              @current_tenant = @admin_tenant
            end

            @current_user = self.data[:users].values.find do |u|
              u['name'] == @openstack_username
            end
            @current_tenant_id = Fog::Mock.random_hex(32)

            unless @current_user
              @current_user_id = Fog::Mock.random_hex(32)
              @current_user = self.data[:users][@current_user_id] = {
                  'id' => @current_user_id,
                  'name' => @openstack_username,
                  'email' => "#{@openstack_username}@mock.com",
                  'tenantId' => Fog::Mock.random_numbers(6).to_s,
                  'enabled' => true
              }
            else
              @current_user_id = @current_user['id']
            end
          end

          def data
            self.class.data[@openstack_username]
          end

          def reset_data
            self.class.data.delete(@openstack_username)
          end

          def credentials
            {:provider => 'openstack',
             :openstack_auth_url => @openstack_auth_uri.to_s,
             :openstack_auth_token => @auth_token,
             :openstack_management_url => @openstack_management_url,
             :openstack_current_user_id => @openstack_current_user_id,
             :current_user => @current_user,
             :current_tenant => @current_tenant}
          end
        end

        class Real < Fog::Identity::OpenStack::Real
          private

          def default_service_type(_)
            DEFAULT_SERVICE_TYPE
          end
        end
      end
    end
  end
end


text:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />

    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="@color/customNavy"/>
</android.support.v4.widget.DrawerLayout>


text:
'''
Set the config variable.
'''

import ConfigParser as cp
import json

config = cp.RawConfigParser()
config.read('../data/config/config.cfg')

min_wdw_sz = json.loads(config.get("hog","min_wdw_sz"))
step_size = json.loads(config.get("hog", "step_size"))
orientations = config.getint("hog", "orientations")
pixels_per_cell = json.loads(config.get("hog", "pixels_per_cell"))
cells_per_block = json.loads(config.get("hog", "cells_per_block"))
visualize = config.getboolean("hog", "visualize")
normalize = config.getboolean("hog", "normalize")
pos_feat_ph = config.get("paths", "pos_feat_ph")
neg_feat_ph = config.get("paths", "neg_feat_ph")
model_path = config.get("paths", "model_path")
threshold = config.getfloat("nms", "threshold")


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/seal_bg"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45.5dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/btn_list_item_bg"
        android:clickable="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="14dp"
            android:text="@string/new_message"
            android:textColor="@color/text_color"
            android:textSize="16sp" />

        <cn.rongcloud.im.ui.widget.switchbutton.SwitchButton
            android:id="@+id/remind_switch"
            style="@style/SwitchButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:padding="8dp"
            app:kswAnimationDuration="300"
            app:kswBackDrawable="@drawable/ios_back_drawable"
            app:kswBackMeasureRatio="1.4"
            app:kswThumbDrawable="@drawable/ios_thumb"
            app:kswThumbMarginBottom="-8dp"
            app:kswThumbMarginLeft="-5dp"
            app:kswThumbMarginRight="-5dp"
            app:kswThumbMarginTop="-2.5dp" />

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.25dp"
        android:layout_marginLeft="14dp"
        android:layout_marginRight="14dp"
        android:background="#dfdfdd" />

    <RelativeLayout
        android:id="@+id/seal_notice"
        android:layout_width="match_parent"
        android:layout_height="45.5dp"
        android:background="@drawable/btn_list_item_bg"
        android:clickable="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="14dp"
            android:text="@string/message_notice"
            android:textColor="@color/text_color"
            android:textSize="16sp" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45.5dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/btn_list_item_bg"
        android:clickable="true"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="14dp"
            android:text="@string/message_show_details"
            android:textColor="@color/text_color"
            android:textSize="16sp" />

        <cn.rongcloud.im.ui.widget.switchbutton.SwitchButton
            style="@style/SwitchButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:padding="8dp"
            app:kswAnimationDuration="300"
            app:kswBackDrawable="@drawable/ios_back_drawable"
            app:kswBackMeasureRatio="1.4"
            app:kswThumbDrawable="@drawable/ios_thumb"
            app:kswThumbMarginBottom="-8dp"
            app:kswThumbMarginLeft="-5dp"
            app:kswThumbMarginRight="-5dp"
            app:kswThumbMarginTop="-2.5dp" />

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45.5dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/btn_list_item_bg"
        android:clickable="true"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="14dp"
            android:text="@string/new_message_voice"
            android:textColor="@color/text_color"
            android:textSize="16sp" />

        <cn.rongcloud.im.ui.widget.switchbutton.SwitchButton
            style="@style/SwitchButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:padding="8dp"
            app:kswAnimationDuration="300"
            app:kswBackDrawable="@drawable/ios_back_drawable"
            app:kswBackMeasureRatio="1.4"
            app:kswThumbDrawable="@drawable/ios_thumb"
            app:kswThumbMarginBottom="-8dp"
            app:kswThumbMarginLeft="-5dp"
            app:kswThumbMarginRight="-5dp"
            app:kswThumbMarginTop="-2.5dp" />

    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.25dp"
        android:layout_marginLeft="14dp"
        android:layout_marginRight="14dp"
        android:background="#dfdfdd" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="45.5dp"
        android:background="@drawable/btn_list_item_bg"
        android:clickable="true"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="14dp"
            android:text="@string/new_message_vibration"
            android:textColor="@color/text_color"
            android:textSize="16sp" />

        <cn.rongcloud.im.ui.widget.switchbutton.SwitchButton
            style="@style/SwitchButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:padding="8dp"
            app:kswAnimationDuration="300"
            app:kswBackDrawable="@drawable/ios_back_drawable"
            app:kswBackMeasureRatio="1.4"
            app:kswThumbDrawable="@drawable/ios_thumb"
            app:kswThumbMarginBottom="-8dp"
            app:kswThumbMarginLeft="-5dp"
            app:kswThumbMarginRight="-5dp"
            app:kswThumbMarginTop="-2.5dp" />

    </RelativeLayout>

    <!--  <RelativeLayout
          android:id="@+id/re_notice"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content">

          <TextView
              style="@style/DemoTextStyleBigBlack"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerVertical="true"
              android:layout_marginBottom="16dp"
              android:layout_marginLeft="24dp"
              android:layout_marginTop="18dp"
              android:text="@string/new_message_notice" />

          <CheckBox
              android:id="@+id/new_message_notice_check"
              android:layout_width="90dp"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              android:layout_marginBottom="12dp"
              android:layout_marginTop="13dp"
              android:visibility="gone"
              android:button="@drawable/rc_switch_btn" />

      </RelativeLayout>

      <include layout="@layout/de_merge_view" />

      <RelativeLayout
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:visibility="gone">

          <TextView
              style="@style/DemoTextStyleBigBlack"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerVertical="true"
              android:layout_marginBottom="16dp"
              android:layout_marginLeft="24dp"
              android:layout_marginTop="18dp"
              android:text="@string/new_message_show" />

          <CheckBox
              android:id="@+id/new_message_show_check"
              android:layout_width="90dp"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              android:layout_marginBottom="12dp"
              android:layout_marginRight="18dp"
              android:layout_marginTop="13dp"
              android:button="@drawable/rc_switch_btn" />

      </RelativeLayout>

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

          <TextView

              style="@style/DemoTextStyleBigBlack"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerVertical="true"
              android:layout_marginBottom="16dp"
              android:layout_marginLeft="24dp"
              android:layout_marginTop="18dp"
              android:text="@string/new_message_voice" />

          <CheckBox
              android:id="@+id/voice_check"
              android:layout_width="90dp"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              android:layout_marginBottom="12dp"
              android:layout_marginTop="13dp"
              android:button="@drawable/de_switch_privacy_btn" />

      </RelativeLayout>

      <include layout="@layout/de_merge_view" />

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

          <TextView
              style="@style/DemoTextStyleBigBlack"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerVertical="true"
              android:layout_marginBottom="16dp"
              android:layout_marginLeft="24dp"
              android:layout_marginTop="18dp"
              android:text="@string/new_message_vibration" />

          <CheckBox
              android:id="@+id/vibration_check"
              android:layout_width="90dp"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              android:layout_marginBottom="12dp"
              android:layout_marginTop="13dp"
              android:button="@drawable/de_switch_privacy_btn" />

      </RelativeLayout>

      <include layout="@layout/de_merge_view" />

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

          <TextView
              style="@style/DemoTextStyleBigBlack"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerVertical="true"
              android:layout_marginBottom="16dp"
              android:layout_marginLeft="24dp"
              android:layout_marginTop="18dp"
              android:text="@string/new_message_prompt_voice" />

          <TextView
              style="@style/DemoTextStyleMiddle"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_alignParentRight="true"
              android:layout_centerVertical="true"
              android:layout_marginRight="18dp"
              android:text="@string/new_message_follow_system" />

      </RelativeLayout>

      <include layout="@layout/de_merge_view" />-->

</LinearLayout>


text:
package net.unikernel.bummel.project_model.api;

import java.awt.Point;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.*;

/**
 *
 * @author uko, mcangel
 */
public abstract class BasicElement implements Element
{
	public static final String PROP_STATE = "state";
	public static final String PROP_LBL = "label";
	public static final String PROP_COORDS = "coordinates";

	private String label;
	private int state;
	private Point coords;
	private ArrayList<String> availablePorts;
	private PropertyChangeSupport pcs;

	public BasicElement(String[] availablePorts)
	{
		this.availablePorts = new ArrayList<>(Arrays.asList(availablePorts));
		this.pcs = new PropertyChangeSupport(this);
	}

	@Override
	public String getLabel()
	{
		return label;
	}
	@Override
	public void setLabel(String label)
	{
		String old = this.label;
		this.label = label;
		this.pcs.firePropertyChange(PROP_LBL, old, this.label);
	}
	@Override
	public int getState()
	{
		return state;
	}
	@Override
	public void setState(int state)
	{
		int old = this.state;
		this.state = state;
		this.pcs.firePropertyChange(PROP_STATE, old, this.state);
	}
	@Override
	public Point getCoords()
	{
		return coords;
	}
	@Override
	public void setCoords(Point point)
	{
		Point old = this.coords;
		this.coords = point;
		this.pcs.firePropertyChange(PROP_COORDS, old, this.coords);
	}
	@Override
	public List<String> getPorts()
	{
		return Collections.unmodifiableList(availablePorts);
	}
	/**
	 * Return the port's name by port position
	 * @param port port's position in the list
	 * @return port's name
	 */
	@Override
	public String getPort(int port)
	{
		return getPorts().get(port);
	}

	/**
	 * Changes all null values on the port to 0s
	 * @param valuesOnPorts map of port -> value
	 * @return map of port -> value free of null values e.i. will all available ports.
	 */
	@Override
	public Map<String, Double> nullFreePortsOf(Map<String, Double> valuesOnPorts)
	{
		for(String port : getPorts())
			if(valuesOnPorts.get(port) == null) valuesOnPorts.put(port, new Double(0));
		return valuesOnPorts;
	}

	@Override
	public synchronized void addPropertyChangeListener(PropertyChangeListener listener)
	{
		this.pcs.addPropertyChangeListener(listener);
	}
	@Override
	public synchronized void removePropertyChangeListener(PropertyChangeListener listener)
	{
		this.pcs.removePropertyChangeListener(listener);
	}
}


text:
<?php
	include_once("includes/config.inc.php");
	include_once("includes/functions.php");

	$keyword = isset($_REQUEST["keyword"])?$_REQUEST["keyword"]: (isset($_REQUEST["symbol"])? $_REQUEST["symbol"] : "Nasdaq");
	$name = isset($_REQUEST["name"])?$_REQUEST["name"]: $keyword;
	$type = isset($_REQUEST["type"])?$_REQUEST["type"]:"Market";

	$arrData = getData($keyword, $type);
        if($arrData!="No data available"){
            $arrResult = getResults($arrData);
        }
	$arrData1 = array();
	$arrResult1 = array();
	$type1 = $keyword1 = "";

?>

<link href="<?php echo $basedir ?>includes/styles.css" rel="stylesheet" type="text/css" />
<link href="<?php echo $basedir ?>includes/menus.css" rel="stylesheet" type="text/css" />

<?php
if(isset($_REQUEST["win"])==1){
?>

<?php
}
?>

<?php if(SHOW_LEFT_AD == 1){ ?>

<?php } ?>

<?php if(SHOW_SPONSOR_AD == 1){ ?>
	    <img alt="" src="<?php echo $basedir ?>images/american_express.gif" />
<?php } ?>

		<?php echo $keyword;?>
		<?php echo round($arrResult["BasicData"], 2);?>

		<?php echo round($arrResult["RateValue"], 2);?>
		(<?php echo $arrResult["RatePerc"];?>%)

<?php

//if($arrData!="No data available" && $keyword!=""){
if(true){
?>

        <?php include_once("graphs.inc.php"); ?>

            	        	        <?php if(SHOW_COMPARISON == 1){ ?>
                <input type="button" class="hierarchal_menu" title="Expand/Collaps" value="" onclick="open_menu('menu');" />

                <?php
					foreach($arrTypesData as $key=>$arr){
				?>

 <?php echo $key;?>

							<?php
                                foreach($arr as $k => $val){
                            ?>
                                    <li class="<?php echo $key;?>_list"><?php echo $val;?>

                            <?php
                                }
                            ?>

                                <input type="text" id="<?php echo $key;?>_list" class="submit" />

             <?php
				 }
			 ?>

 None

    		            				<?php } ?>

<?php echo $arrResult["HistYears"];?> Years

1 Year

                    <?php
						foreach($arrDurations as $val){
					?>

<?php echo $val;?>

                    <?php
						}
					?>

Updated <?php echo convertDateTime($arrResult["UpdateDate"]);?>

        <?php if(SHOW_BOTTOM_AD == 1){ ?>

 <img alt="" src="<?php echo $basedir ?>images/bottom_ad_img.gif" />

		<?php } ?>

<?php
}else{
?>

Prototype

            No data available

        <?php if(SHOW_BOTTOM_AD == 1){ ?>

 <img alt="" src="<?php echo $basedir ?>images/bottom_ad_img.gif" />

		<?php } ?>

<?php
}
?>

<input type="hidden" name="type" id="type" value="<?php echo $type;?>" />
<input type="hidden" name="type1" id="type1" value="<?php echo $type1;?>" />
<input type="hidden" name="keyword1" id="keyword1" value="<?php echo $keyword1;?>" />


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

import com.github.pires.obd.commands.ObdCommand;
import com.github.pires.obd.enums.AvailableCommandNames;

/**
 * Displays the current engine revolutions per minute (RPM).
 *
 */
public class RPMCommand extends ObdCommand {

    private int rpm = -1;

    /**
     * Default ctor.
     */
    public RPMCommand() {
        super("01 0C");
    }

    /**
     * Copy ctor.
     *
     * @param other a {@link com.github.pires.obd.commands.engine.RPMCommand} object.
     */
    public RPMCommand(RPMCommand other) {
        super(other);
    }

    /** {@inheritDoc} */
    @Override
    protected void performCalculations() {
        // ignore first two bytes [41 0C] of the response((A*256)+B)/4
        rpm = (buffer.get(2) * 256 + buffer.get(3)) / 4;
    }

    /** {@inheritDoc} */
    @Override
    public String getFormattedResult() {
        return String.format("%d%s", rpm, getResultUnit());
    }

    /** {@inheritDoc} */
    @Override
    public String getCalculatedResult() {
        return String.valueOf(rpm);
    }

    /** {@inheritDoc} */
    @Override
    public String getResultUnit() {
        return "RPM";
    }

    /** {@inheritDoc} */
    @Override
    public String getName() {
        return AvailableCommandNames.ENGINE_RPM.getValue();
    }

    /**
     *
getRPM.

     *
     * @return a int.
     */
    public int getRPM() {
        return rpm;
    }

}


text:
"""
Demonstration of how to print using the HTML class.
"""
from prompt_toolkit import HTML, print_formatted_text

print = print_formatted_text

def title(text):
    print(HTML("\n{}").format(text))

def main():
    title("Special formatting")
    print(HTML("    Bold"))
    print(HTML("    <blink>Blink</blink>"))
    print(HTML("    Italic"))
    print(HTML("    <reverse>Reverse</reverse>"))
    print(HTML("    Underline"))
    print(HTML("    <hidden>Hidden</hidden> (hidden)"))

    # Ansi colors.
    title("ANSI colors")

    print(HTML("    <ansired>ANSI Red</ansired>"))
    print(HTML("    <ansiblue>ANSI Blue</ansiblue>"))

    # Other named colors.
    title("Named colors")

    print(HTML("    <orange>orange</orange>"))
    print(HTML("    <purple>purple</purple>"))

    # Background colors.
    title("Background colors")

    print(HTML('    '))
    print(HTML('    '))

    # Interpolation.
    title("HTML interpolation (see source)")

    print(HTML("    {}").format("<test>"))
    print(HTML("    {text}").format(text="<test>"))
    print(HTML("    %s") % ("<text>",))

    print()

if __name__ == "__main__":
    main()