text:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

from landlab import load_params
from landlab.plot import imshow_grid
from landlab.components import (PrecipitationDistribution, Radiation,
                                PotentialEvapotranspiration, SoilMoisture,
                                Vegetation, VegCA)

GRASS = 0
SHRUB = 1
TREE = 2
BARE = 3
SHRUBSEEDLING = 4
TREESEEDLING = 5

def compose_veg_grid(grid, percent_bare=0.4, percent_grass=0.2,
                     percent_shrub=0.2, percent_tree=0.2):
    """Compose spatially distribute PFT."""
    no_cells = grid.number_of_cells
    shrub_point = int(percent_bare * no_cells)
    tree_point = int((percent_bare + percent_shrub) * no_cells)
    grass_point = int((1 - percent_grass) * no_cells)

    veg_grid = np.full(grid.number_of_cells, BARE, dtype=int)
    veg_grid[shrub_point:tree_point] = SHRUB
    veg_grid[tree_point:grass_point] = TREE
    veg_grid[grass_point:] = GRASS

    np.random.shuffle(veg_grid)
    return veg_grid

def initialize(data, grid, grid1):
    """Initialize random plant type field.

    Plant types are defined as the following:

    *  GRASS = 0
    *  SHRUB = 1
    *  TREE = 2
    *  BARE = 3
    *  SHRUBSEEDLING = 4
    *  TREESEEDLING = 5
    """
    grid1.at_cell['vegetation__plant_functional_type'] = compose_veg_grid(
        grid1, percent_bare=data['percent_bare_initial'],
        percent_grass=data['percent_grass_initial'],
        percent_shrub=data['percent_shrub_initial'],
        percent_tree=data['percent_tree_initial'])

    # Assign plant type for representative ecohydrologic simulations
    grid.at_cell['vegetation__plant_functional_type'] = np.arange(6)
    grid1.at_node['topographic__elevation'] = np.full(grid1.number_of_nodes,
                                                      1700.)
    grid.at_node['topographic__elevation'] = np.full(grid.number_of_nodes,
                                                     1700.)
    precip_dry = PrecipitationDistribution(
        mean_storm_duration=data['mean_storm_dry'],
        mean_interstorm_duration=data['mean_interstorm_dry'],
        mean_storm_depth=data['mean_storm_depth_dry'])
    precip_wet = PrecipitationDistribution(
        mean_storm_duration=data['mean_storm_wet'],
        mean_interstorm_duration=data['mean_interstorm_wet'],
        mean_storm_depth=data['mean_storm_depth_wet'])

    radiation = Radiation(grid)
    pet_tree = PotentialEvapotranspiration(grid, method=data['PET_method'],
                                           MeanTmaxF=data['MeanTmaxF_tree'],
                                           delta_d=data['DeltaD'])
    pet_shrub = PotentialEvapotranspiration(grid, method=data['PET_method'],
                                            MeanTmaxF=data['MeanTmaxF_shrub'],
                                            delta_d=data['DeltaD'])
    pet_grass = PotentialEvapotranspiration(grid, method=data['PET_method'],
                                            MeanTmaxF=data['MeanTmaxF_grass'],
                                            delta_d=data['DeltaD'])
    soil_moisture = SoilMoisture(grid, **data) # Soil Moisture object
    vegetation = Vegetation(grid, **data) # Vegetation object
    vegca = VegCA(grid1, **data) # Cellular automaton object

    # Initializing inputs for Soil Moisture object
    grid.at_cell['vegetation__live_leaf_area_index'] = (
        1.6 * np.ones(grid.number_of_cells))
    grid.at_cell['soil_moisture__initial_saturation_fraction'] = (
        0.59 * np.ones(grid.number_of_cells))

    return (precip_dry, precip_wet, radiation, pet_tree, pet_shrub,
            pet_grass, soil_moisture, vegetation, vegca)

def empty_arrays(n, grid, grid1):
    precip = np.empty(n) # Record precipitation
    inter_storm_dt = np.empty(n) # Record inter storm duration
    storm_dt = np.empty(n) # Record storm duration
    time_elapsed = np.empty(n) # To record time elapsed from the start of simulation

    # Cumulative Water Stress
    veg_type = np.empty([n / 55, grid1.number_of_cells], dtype=int)
    daily_pet = np.zeros([365, grid.number_of_cells])
    rad_factor = np.empty([365, grid.number_of_cells])
    EP30 = np.empty([365, grid.number_of_cells])

    # 30 day average PET to determine season
    pet_threshold = 0  # Initializing pet_threshold to ETThresholddown
    return (precip, inter_storm_dt, storm_dt, time_elapsed, veg_type,
            daily_pet, rad_factor, EP30, pet_threshold)

def create_pet_lookup(radiation, pet_tree, pet_shrub, pet_grass, daily_pet,
                      rad_factor, EP30, grid):
    for i in range(0, 365):
        pet_tree.update(float(i) / 365.25)
        pet_shrub.update(float(i) / 365.25)
        pet_grass.update(float(i) / 365.25)
        daily_pet[i] = [pet_grass._PET_value, pet_shrub._PET_value,
                   pet_tree._PET_value, 0., pet_shrub._PET_value,
                   pet_tree._PET_value]
        radiation.update(float(i) / 365.25)
        rad_factor[i] = grid.at_cell['radiation__ratio_to_flat_surface']

        if i < 30:
            if i == 0:
                EP30[0] = daily_pet[0]
            else:
                EP30[i] = np.mean(daily_pet[:i], axis=0)
        else:
            EP30[i] = np.mean(daily_pet[i - 30:i], axis=0)

def save(sim, inter_storm_dt, storm_dt, precip, veg_type, yrs,
         walltime, time_elapsed):
    np.save(sim + '_Tb', inter_storm_dt)
    np.save(sim + '_Tr', storm_dt)
    np.save(sim + '_P', precip)
    np.save(sim + '_VegType', veg_type)
    np.save(sim + '_Years', yrs)
    np.save(sim + '_Time_Consumed_minutes', walltime)
    np.save(sim + '_CurrentTime', time_elapsed)

def plot(sim, grid, veg_type, yrs, yr_step=10):
    pic = 0
    years = range(0, yrs)
    cmap = mpl.colors.ListedColormap(
        ['green', 'red', 'black', 'white', 'red', 'black'])
    bounds = [-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
    print 'Plotting cellular field of Plant Functional Type'
    print 'Green - Grass; Red - Shrubs; Black - Trees; White - Bare'

    # Plot images to make gif.
    for year in range(0, yrs, yr_step):
        filename = 'year_' + "%05d" % year
        pic += 1
        plt.figure(pic, figsize=(10, 8))
        imshow_grid(grid, veg_type[year], values_at='cell', cmap=cmap,
                    grid_units=('m', 'm'), norm=norm, limits=[0, 5],
                    allow_colorbar=False)
        plt.title(filename, weight='bold', fontsize=22)
        plt.xlabel('X (m)', weight='bold', fontsize=18)
        plt.ylabel('Y (m)', weight='bold', fontsize=18)
        plt.xticks(fontsize=14, weight='bold')
        plt.yticks(fontsize=14, weight='bold')
        plt.savefig(sim + '_' + filename)

    grass_cov = np.empty(yrs)
    shrub_cov = np.empty(yrs)
    tree_cov = np.empty(yrs)
    grid_size = float(veg_type.shape[1])

    for x in range(0, yrs):
        grass_cov[x] = (veg_type[x][veg_type[x] == GRASS].size / grid_size) * 100
        shrub_cov[x] = ((veg_type[x][veg_type[x] == SHRUB].size / grid_size) *
                        100 + (veg_type[x][veg_type[x] == SHRUBSEEDLING].size /
                        grid_size) * 100)
        tree_cov[x] = ((veg_type[x][veg_type[x] == TREE].size / grid_size) *
                       100 + (veg_type[x][veg_type[x] == TREESEEDLING].size /
                       grid_size) * 100)

    pic += 1
    plt.figure(pic, figsize=(10, 8))
    plt.plot(years, grass_cov, '-g', label='Grass', linewidth=4)
    plt.hold(True)
    plt.plot(years, shrub_cov, '-r', label='Shrub', linewidth=4)
    plt.hold(True)
    plt.plot(years, tree_cov, '-k', label='Tree', linewidth=4)
    plt.ylabel('% Area Covered by Plant Type', weight='bold', fontsize=18)
    plt.xlabel('Time in years', weight='bold', fontsize=18)
    plt.xticks(fontsize=12, weight='bold')
    plt.yticks(fontsize=12, weight='bold')
    plt.legend(loc=0, prop={'size': 16, 'weight': 'bold'})
    plt.savefig(sim + '_percent_cover')


text:
        <link
            href="../../../../syntax_highlighter/styles/shCore.css" rel="stylesheet"
            type="text/css"
        />
        <link
            href="../../../../syntax_highlighter/styles/shCoreEclipse.css"
            rel="stylesheet" type="text/css"
        />
        <link
            href="../../../../syntax_highlighter/styles/shThemeWordpress.css"
            rel="stylesheet" type="text/css"
        />

<?php

/**
 * @see Zend_Gdata_App_Extension
 */
require_once 'Zend/Gdata/App/Extension.php';

/**
 * Represents the media:restriction element
 *
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Media
 * @copyright  Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Gdata_Media_Extension_MediaRestriction extends Zend_Gdata_Extension
{

    protected $_rootElement = 'restriction';
    protected $_rootNamespace = 'media';

    /**
     * @var string
     */
    protected $_relationship = null;

    /**
     * @var string
     */
    protected $_type = null;

    /**
     * Constructs a new MediaRestriction element
     *
     * @param string $text
     * @param string $relationship
     * @param string $type
     */
    public function __construct($text = null, $relationship = null,  $type = null)
    {
        $this->registerAllNamespaces(Zend_Gdata_Media::$namespaces);
        parent::__construct();
        $this->_text = $text;
        $this->_relationship = $relationship;
        $this->_type = $type;
    }

    /**
     * Retrieves a DOMElement which corresponds to this element and all
     * child properties.  This is used to build an entry back into a DOM
     * and eventually XML text for sending to the server upon updates, or
     * for application storage/persistence.
     *
     * @param DOMDocument $doc The DOMDocument used to construct DOMElements
     * @return DOMElement The DOMElement representing this element and all
     * child properties.
     */
    public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
    {
        $element = parent::getDOM($doc, $majorVersion, $minorVersion);
        if ($this->_relationship !== null) {
            $element->setAttribute('relationship', $this->_relationship);
        }
        if ($this->_type !== null) {
            $element->setAttribute('type', $this->_type);
        }
        return $element;
    }

    /**
     * Given a DOMNode representing an attribute, tries to map the data into
     * instance members.  If no mapping is defined, the name and value are
     * stored in an array.
     *
     * @param DOMNode $attribute The DOMNode attribute needed to be handled
     */
    protected function takeAttributeFromDOM($attribute)
    {
        switch ($attribute->localName) {
        case 'relationship':
            $this->_relationship = $attribute->nodeValue;
            break;
        case 'type':
            $this->_type = $attribute->nodeValue;
            break;
        default:
            parent::takeAttributeFromDOM($attribute);
        }
    }

    /**
     * @return string
     */
    public function getRelationship()
    {
        return $this->_relationship;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface
     */
    public function setRelationship($value)
    {
        $this->_relationship = $value;
        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }

    /**
     * @param string $value
     * @return Zend_Gdata_Media_Extension_MediaRestriction Provides a fluent interface
     */
    public function setType($value)
    {
        $this->_type = $value;
        return $this;
    }

}

redpajama_set_name: RedPajamaGithub


text:
using namespace Jass;

#define LUA_PUSHDWORD(L, v) \
	lua_pushlightuserdata(L, reinterpret_cast<void*>(v))
#define LUA_TODWORD(L, index) \
	reinterpret_cast<DWORD>(lua_touserdata(L, index))

namespace PortedJassNatives {
#include "JassLuaNativesData.h.inc"
#include "JassLuaNatives.impl.inc"
}


text: {{ cms:partial:shared/checklist:find_a_location }}


text:
<?xml version="1.0"?>
<PluginConfig>
	<SupportURL>https://github.com/mlamoure/</SupportURL>

			<Field type="menu" id="ddlLoginMethod" defaultValue="email">
				Login Method:
				<List>
					<Option value="email">Email</Option>
					<Option value="phone">Phone</Option>
				</List>
			</Field>

			<Field id="loginDescription"
			            type="label">
			        Your login will either be your email address or phone number.  Phone numbers should use the "+" symbol with country code designation followed by the phone number without spaces or dashes.  e.g. +12223334444.  It seems that with August accounts, the email or phone number are interchangable, so either will work fine to log in.
			</Field>

	    <Field id="txtLogin"
	            type="textfield">
	        August Login:
	    </Field>
			<Field id="txtPassword"
	            type="textfield" secure="true">
	        August Password:
	    </Field>

			<Field id="verifyDescription" type="label">
			        Due to the way the August API works, you will need to verify your email/phone in order to register a new "deviceID" with August.  Click the button below to test your credentials.  If the plugin is able to sucessfully log in, it will then verify the new DeviceID with August.  You will recieve a code via email or SMS to your login method to enter below.
			</Field>

			<Field id="verifyButton"
				            type="button"
				            tooltip="Check credentials and verify">

				        <Title>Check credentials and verify</Title>
				        <CallbackMethod>checkCredentialsAndVerify</CallbackMethod>
			</Field>

			<Field id="verifyStatusDescription" type="label">
			        Account Status:
			</Field>

			<Field hidden="true" defaultValue="true" type="checkbox" id="chkStatusUnknown"><Description></Description></Field>
			<Field id="verifyStatusUnknown" type="label" fontColor="red" visibleBindingId="chkStatusUnknown" visibleBindingValue="true">
			        Not set
			</Field>

			<Field hidden="true" type="checkbox" id="chkNotVerified"><Description></Description></Field>
			<Field id="verifyStatusNotVerified" type="label" fontColor="red" visibleBindingId="chkNotVerified" visibleBindingValue="true">
			        Not Verified (scroll down to enter/send the code)
			</Field>

			<Field hidden="true" type="checkbox" id="chkAllGood"><Description></Description></Field>
			<Field id="verifyAllGood" type="label" fontColor="green" visibleBindingId="chkAllGood" visibleBindingValue="true">
			        All Good
			</Field>

			<Field hidden="true" type="checkbox" id="checkboxValidationSent" defaultValue="false"><Description></Description></Field>

			<Field id="code"
	            type="textfield"
	            readonly="NO"
	            visibleBindingId="checkboxValidationSent"
	            visibleBindingValue="true">
	        	Verification Code:
	    	</Field>

			<Field id="sendVerification"
				            type="button"
				            tooltip="Check credentials and verify"
				            visibleBindingId="checkboxValidationSent"
				            visibleBindingValue="true">

				        <Title>Verify</Title>
				        <CallbackMethod>sendVerification</CallbackMethod>
			</Field>

			<Field type="menu" id="pollingInterval" defaultValue="60">
				Polling Interval:
				<List>
					<Option value="10">10 Seconds</Option>
					<Option value="15">15 Seconds</Option>
					<Option value="30">30 Seconds</Option>
					<Option value="45">45 Seconds</Option>
					<Option value="60">60 Seconds</Option>
					<Option value="90">90 Seconds</Option>
				</List>
			</Field>

		    <Field id="indigoVariablesFolderName" type="textfield" defaultValue="august_locks">
		        Variable folder name:
		    </Field>

			<Field hidden="false" type="checkbox" id="chkDebug">Debug (will produce a lot of log data)<Description></Description></Field>
			<Field hidden="false" type="checkbox" id="chkDebug_L2">Level 2 - Variable Output Debug<Description></Description></Field>

</PluginConfig>


text:
/**
 * XML normaliser (requires UTF-8 input)
 *
 * - Sorts attributes alphabetically
 * - Ensures numeric entities all have the same style of representation
 *   (decimal Ӓ or hex 覫)
 */

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <ctype.h>

#include <expat.h>
#include <libxml/xmlwriter.h>
#include "xml.c"
#include "string.c"

typedef xmlChar lxml_ch;
typedef XML_Char expat_ch;

enum n_err {
    N_OK = 0,
    N_ERR = 1,
    N_ERR_ENCODING = 10,
    N_ERR_PARSE_FAIL = 11,
    N_ERR_PARSE_STOPPED = 12,
};

enum ent_num_mode {
    ENT_NUM_LEAVE = 0,
    ENT_NUM_DEC = 1,
    ENT_NUM_HEX = 2,
};

enum state {
    IN_NONE = 0,
    IN_DOC = 0,
    IN_ELEM = 1,
    IN_DTD = 2,
    IN_CDATA = 3,
};

bool debug = false;

struct attr {
    const char *name;
    const char *value;
};

struct ctx {
    xmlTextWriterPtr writer;
    XML_Parser parser;

    enum state *stack;
    ssize_t stack_cap;
    ssize_t stack_depth;

    enum ent_num_mode ent_num_mode;
    char *error;
    int error_code;
    void (*error_free)(void *p);

    bool self_close;
    struct attr *attrs;
    size_t attrs_cap;
};

void ctx_push(struct ctx *ctx, enum state state) {
    if (ctx->stack_depth + 1 >= ctx->stack_cap) {
        ctx->stack_cap = ctx->stack_cap > 0 ? ctx->stack_cap * 2 : 32;
        ctx->stack = realloc(ctx->stack, ctx->stack_cap * sizeof(enum state));
    }
    ctx->stack_depth++;
    ctx->stack[ctx->stack_depth] = state;
}

int ctx_pop(struct ctx *ctx, enum state state) {
    if (ctx->stack_depth < 0) {
        return IN_NONE;
    }
    enum state ret = ctx->stack[ctx->stack_depth];
    if (ret != state) {
        return 1;
    }
    ctx->stack_depth--;
    return 0;
}

static int ctx_errf(struct ctx *ctx, int code, char *fmt, ...) {
    if (ctx->error != NULL && ctx->error_free != NULL) {
        ctx->error_free(ctx->error);
    }
    va_list args;
    va_start(args, fmt);
    ctx->error_code = code;
    ctx->error_free = free;
    vasprintf(&ctx->error, fmt, args);
    va_end(args);
    return code;
}

int ctx_err(struct ctx *ctx, int code, char *error) {
    if (ctx->error != NULL && ctx->error_free != NULL) {
        ctx->error_free(ctx->error);
    }
    ctx->error_code = code;
    ctx->error = error;
    return code;
}

void ctx_deinit(struct ctx *ctx) {
    if (ctx->error != NULL && ctx->error_free != NULL) {
        ctx->error_free(ctx->error);
    }
    free(ctx->stack);
    free(ctx->attrs);
}

bool str_has_prefix(const char *str, const char *pre)
{
    return strncmp(pre, str, strlen(pre)) == 0;
}

int attr_comp(const void *a, const void *b) {
    const struct attr *aa = a;
    const struct attr *bb = b;
    return strcmp(aa->name, bb->name);
}

void xml_elem_end(void *user_data, const expat_ch *name) {
    (void)name;
    struct ctx *ctx = user_data;
    if (ctx->self_close) {
        xmlTextWriterEndElement(ctx->writer);
    } else {
        xmlTextWriterFullEndElement(ctx->writer);
    }
    ctx->self_close = false;
}

void xml_elem_start(void *user_data, const expat_ch *name, const expat_ch **atts) {
    struct ctx *ctx = user_data;
    ctx->self_close = true;

    xmlTextWriterStartElement(ctx->writer, (lxml_ch*)name);
    if (atts == NULL || *atts == NULL) {
        return;
    }

    size_t attlen = 0;
    for (size_t i = 0; atts[i]; i+=2) {
        attlen++;
    }

    if (attlen > ctx->attrs_cap) {
        while (ctx->attrs_cap < attlen) {
            ctx->attrs_cap *= 2;
            ctx->attrs = realloc(ctx->attrs, sizeof(struct attr) * ctx->attrs_cap);
        }
    }

    for (size_t i = 0, j = 0; atts[i]; j+=1, i+=2) {
        ctx->attrs[j].name = atts[i];
        ctx->attrs[j].value = atts[i+1];
    }

    qsort(ctx->attrs, attlen, sizeof(struct attr), attr_comp);
}

void xml_default(void *user_data, const expat_ch *s, int len) {
    struct ctx *ctx = user_data;
    ctx->self_close = false;
    lxml_ch *copy;

    // expat seems to deserialise entities in discrete chunks, i.e.  not as
    // part of the character data stream. so we can (hopefully) assume that the
    // default handler gets them complete as a single unit.
    // FIXME: it doesn't apear to do this inside entities, i.e.
    //   <!ENTITY pathpart "([\w_@.%*?+-]|\\ )">
    if (ctx->ent_num_mode != ENT_NUM_LEAVE && len > 4 && s[0] == '&' && s[1] == '#' && s[len-1] == ';') {
        int base = 10;
        const char *start = s + 2;
        if (s[2] == 'x') {
            base = 16;
            start++;
        }
        if (base == 16 && ctx->ent_num_mode == ENT_NUM_HEX) {
            goto std;
        } else if (base == 10 && ctx->ent_num_mode == ENT_NUM_DEC) {
            goto std;
        }

        char *end;
        long ent = strtoul(start, &end, base);
        if (*end != *(s + len-1)) {
            // if it doesn't parse up to the semicolon, just handle it like normal.
            goto std;
        }

        // cheat! just allocate double the memory rather than waste time
        // working out how to calculate hex to dec sizes
        copy = xmlMalloc(len * 2);
        sprintf((char *)copy, (ctx->ent_num_mode == ENT_NUM_DEC ? "&#%ld;" : "&#x%lx;"), ent);
        goto print;
    }

std:;
    copy = xmlCharStrndup(s, len);
print:;
    xmlTextWriterWriteRaw(ctx->writer, copy);
    free(copy);
}

int xml_unknown_encoding(void *encoding_handler_data, const expat_ch *name, XML_Encoding *info) {
    (void)name;
    (void)info;
    struct ctx *ctx = encoding_handler_data;
    ctx_err(ctx, N_ERR_ENCODING, "unknown encoding");
    return XML_STATUS_ERROR;
}

int main() {
    int rc = 0;
    xmlTextWriterPtr writer = xmlNewTextWriterFilename("/dev/stdout", 0);

    XML_Parser parser = XML_ParserCreate(NULL);

    struct ctx ctx = {
        .writer = writer,
        .parser = parser,
        .attrs = calloc(sizeof(struct attr), 32),
        .attrs_cap = 32,
        .ent_num_mode = ENT_NUM_HEX,
    };
    XML_SetUserData(parser, &ctx);

    XML_SetElementHandler(parser, xml_elem_start, xml_elem_end);
    XML_SetDefaultHandler(parser, xml_default);
    XML_SetUnknownEncodingHandler(parser, xml_unknown_encoding, &ctx);

    {
        #define READ_SIZE 8192
        char buffer[READ_SIZE];
        bool done = false;
        size_t read = 0;
        while (!done) {
            size_t len = fread(&buffer, sizeof(char), READ_SIZE, stdin);
            if (len < READ_SIZE) {
                done = true;
            }
            read += len;
            enum XML_Status status = XML_Parse(parser, buffer, len, done);

            XML_Index idx = XML_GetCurrentByteIndex(parser);
            if (idx < 0 || status != XML_STATUS_OK) {
                enum XML_Error err = XML_GetErrorCode(parser);

                ctx_errf(&ctx, N_ERR_PARSE_FAIL,
                    "expat error %s(%d) before completion %ld != %zu, byte %zu\n",
                    expat_errors[err], err, idx, len, read);
                goto cleanup;
            }

            size_t idx_sz = (size_t) idx;
            if (done) {
                if (idx_sz != read) {
                    enum XML_Error err = XML_GetErrorCode(parser);
                    ctx_errf(&ctx, N_ERR_PARSE_STOPPED,
                        "expat stopped %s(%d) before completion %ld != %zu, byte %zu\n",
                        expat_errors[err], err, idx, len, read);
                    goto cleanup;
                }
            }
        }
    }

    xmlTextWriterFlush(writer);

cleanup:
    if (ctx.error_code > 0) {
        rc = ctx.error_code;
        if (ctx.error != NULL) {
            fprintf(stderr, "%s\n", ctx.error);
        } else {
            fprintf(stderr, "parsing failed with unknown error %d\n", ctx.error_code);
        }
    }

    ctx_deinit(&ctx);
    XML_ParserFree(parser);
    xmlFreeTextWriter(writer);

    return rc;
}


text:
from oslo_config import cfg
from testtools import matchers

from vitrage.common.constants import EntityCategory
from vitrage.common.constants import VertexProperties as VProps
from vitrage.datasources.nagios import NAGIOS_DATASOURCE
from vitrage.datasources.nagios.properties import NagiosTestStatus
from vitrage.datasources import NOVA_HOST_DATASOURCE
from vitrage.datasources import NOVA_INSTANCE_DATASOURCE
from vitrage.datasources import NOVA_ZONE_DATASOURCE
from vitrage.tests.functional.datasources.base import \
    TestDataSourcesBase
from vitrage.tests.mocks import mock_driver

class TestNagios(TestDataSourcesBase):

    DATASOURCES_OPTS = [
        cfg.ListOpt('types',
                    default=[NAGIOS_DATASOURCE,
                             NOVA_HOST_DATASOURCE,
                             NOVA_INSTANCE_DATASOURCE,
                             NOVA_ZONE_DATASOURCE],
                    help='Names of supported driver data sources'),

        cfg.ListOpt('path',
                    default=['vitrage.datasources'],
                    help='base path for data sources')
    ]

    def setUp(self):
        super(TestNagios, self).setUp()
        self.cfg_fixture.config(group='datasources',
                                types=[
                                    NAGIOS_DATASOURCE,
                                    NOVA_HOST_DATASOURCE,
                                    NOVA_INSTANCE_DATASOURCE,
                                    NOVA_ZONE_DATASOURCE
                                ])
        self.load_datasources()

    def test_nagios_validity(self):
        # Setup
        processor = self._create_processor_with_graph()
        self.assertThat(processor.entity_graph,
                        matchers.HasLength(
                            self._num_total_expected_vertices())
                        )

        spec_list = mock_driver.simple_nagios_alarm_generators(
            host_num=1,
            events_num=1)
        static_events = mock_driver.generate_random_events_list(spec_list)
        nagios_event = static_events[0]
        nagios_event['resource_name'] = \
            self._find_entity_id_by_type(processor.entity_graph,
                                         NOVA_HOST_DATASOURCE)
        nagios_event['status'] = NagiosTestStatus.CRITICAL

        # Action
        processor.process_event(nagios_event)

        # Test assertions
        self.assertThat(processor.entity_graph,
                        matchers.HasLength(
                            self._num_total_expected_vertices() + 1)
                        )

        nagios_vertices = processor.entity_graph.get_vertices(
            vertex_attr_filter={
                VProps.VITRAGE_CATEGORY: EntityCategory.ALARM,
                VProps.VITRAGE_TYPE: NAGIOS_DATASOURCE
            })
        self.assertThat(nagios_vertices, matchers.HasLength(1))

        nagios_neighbors = processor.entity_graph.neighbors(
            nagios_vertices[0].vertex_id)
        self.assertThat(nagios_neighbors, matchers.HasLength(1))

        self.assertEqual(NOVA_HOST_DATASOURCE,
                         nagios_neighbors[0][VProps.VITRAGE_TYPE])


text:
package org.nd4j.aeron.ipc.response;

import io.aeron.Aeron;
import io.aeron.driver.MediaDriver;
import io.aeron.driver.ThreadingMode;
import lombok.extern.slf4j.Slf4j;
import org.agrona.CloseHelper;
import org.agrona.concurrent.BusySpinIdleStrategy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.nd4j.common.tests.BaseND4JTest;
import org.nd4j.aeron.ipc.*;
import org.nd4j.common.tests.tags.NativeTag;
import org.nd4j.common.tests.tags.TagNames;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;

import javax.annotation.concurrent.NotThreadSafe;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;

@Slf4j
@NotThreadSafe
@Disabled("Tests are too flaky")
@Tag(TagNames.FILE_IO)
@Tag(TagNames.DIST_SYSTEMS)
@NativeTag
public class AeronNDArrayResponseTest extends BaseND4JTest {
    private MediaDriver mediaDriver;

    @Override
    public long getTimeoutMilliseconds() {
        return 180000L;
    }

    @BeforeEach
    public void before() {
        if(isIntegrationTests()) {
            final MediaDriver.Context ctx =
                    new MediaDriver.Context().threadingMode(ThreadingMode.SHARED).dirDeleteOnShutdown(true)
                            .dirDeleteOnStart(true)
                            .termBufferSparseFile(false).conductorIdleStrategy(new BusySpinIdleStrategy())
                            .receiverIdleStrategy(new BusySpinIdleStrategy())
                            .senderIdleStrategy(new BusySpinIdleStrategy());
            mediaDriver = MediaDriver.launchEmbedded(ctx);
            System.out.println("Using media driver directory " + mediaDriver.aeronDirectoryName());
            System.out.println("Launched media driver");
        }
    }

    @Test
    public void testResponse() throws Exception {
        skipUnlessIntegrationTests();   //Long-running test - don't run as part of unit tests by default

        int streamId = 10;
        int responderStreamId = 11;
        String host = "127.0.0.1";
        Aeron.Context ctx = new Aeron.Context().driverTimeoutMs(100000)
                        .availableImageHandler(AeronUtil::printAvailableImage)
                        .unavailableImageHandler(AeronUtil::printUnavailableImage)
                        .aeronDirectoryName(mediaDriver.aeronDirectoryName()).keepAliveIntervalNs(100000)
                        .errorHandler(e -> log.error(e.toString(), e));

        int baseSubscriberPort = 40123 + new java.util.Random().nextInt(1000);

        Aeron aeron = Aeron.connect(ctx);
        AeronNDArrayResponder responder =
                        AeronNDArrayResponder.startSubscriber(aeron, host, baseSubscriberPort + 1, new NDArrayHolder() {
                            /**
                             * Set the ndarray
                             *
                             * @param arr the ndarray for this holder
                             *            to use
                             */
                            @Override
                            public void setArray(INDArray arr) {

                        }

                            /**
                            * The number of updates
                            * that have been sent to this older.
                            *
                            * @return
                            */
                            @Override
                            public int totalUpdates() {
                                return 1;
                            }

                            /**
                             * Retrieve an ndarray
                             *
                             * @return
                             */
                            @Override
                            public INDArray get() {
                                return Nd4j.scalar(1.0);
                            }

                            /**
                             * Retrieve a partial view of the ndarray.
                             * This method uses tensor along dimension internally
                             * Note this will call dup()
                             *
                             * @param idx        the index of the tad to get
                             * @param dimensions the dimensions to use
                             * @return the tensor along dimension based on the index and dimensions
                             * from the master array.
                             */
                            @Override
                            public INDArray getTad(int idx, int... dimensions) {
                                return Nd4j.scalar(1.0);
                            }
                        }

                                        , responderStreamId);

        AtomicInteger count = new AtomicInteger(0);
        AtomicBoolean running = new AtomicBoolean(true);
        AeronNDArraySubscriber subscriber =
                        AeronNDArraySubscriber.startSubscriber(aeron, host, baseSubscriberPort, new NDArrayCallback() {
                            /**
                             * A listener for ndarray message
                             *
                             * @param message the message for the callback
                             */
                            @Override
                            public void onNDArrayMessage(NDArrayMessage message) {
                                count.incrementAndGet();

                            }

                            @Override
                            public void onNDArrayPartial(INDArray arr, long idx, int... dimensions) {
                                count.incrementAndGet();
                            }

                            @Override
                            public void onNDArray(INDArray arr) {
                                count.incrementAndGet();
                            }
                        }, streamId, running);

        int expectedResponses = 10;
        HostPortPublisher publisher = HostPortPublisher.builder().aeron(aeron)
                        .uriToSend(host + String.format(":%d:", baseSubscriberPort) + streamId)
                        .channel(AeronUtil.aeronChannel(host, baseSubscriberPort + 1)).streamId(responderStreamId)
                        .build();

        for (int i = 0; i < expectedResponses; i++) {
            publisher.send();
        }

        Thread.sleep(60000);

        assertEquals(expectedResponses, count.get());

        System.out.println("After");

        CloseHelper.close(responder);
        CloseHelper.close(subscriber);
        CloseHelper.close(publisher);
        CloseHelper.close(aeron);

    }

}


text:
@class IDEKeyboardShortcut, IDESourceEditorExtension, NSString;

@interface IDESourceEditorExtensionCommand : NSObject
{
    IDESourceEditorExtension *_extension;
    NSString *_name;
    NSString *_identifier;
    IDEKeyboardShortcut *_keyboardShortcut;
}

+ (double)cancellationDelay;
+ (void)initialize;
- (void).cxx_destruct;
@property(retain) IDEKeyboardShortcut *keyboardShortcut; // @synthesize keyboardShortcut=_keyboardShortcut;
@property(readonly, copy) NSString *identifier; // @synthesize identifier=_identifier;
@property(readonly, copy) NSString *name; // @synthesize name=_name;
@property(readonly) __weak IDESourceEditorExtension *extension; // @synthesize extension=_extension;
- (void)_updateCommandMenuItem:(id)arg1;
- (id)menuItemWithAction:(SEL)arg1;
- (id)identifierForAccessibility;
@property(readonly, copy) NSString *identifierForKeyBinding;
- (id)extensionIdentifier;
- (id)performCommandWithParameters:(id)arg1 completionBlock:(CDUnknownBlockType)arg2;
- (id)description;
- (id)initWithCommandDefinition:(id)arg1 inExtension:(id)arg2;

@end


text:
const commonjs = require('rollup-plugin-commonjs');
const replace = require('rollup-plugin-replace');
const resolve = require('rollup-plugin-node-resolve');
const typescript = require('rollup-plugin-typescript');

export default {
  entry: './src/index.ts',
  dest: './dest/bundle.js',
  format: 'cjs',
  plugins: [
    typescript({
      typescript: require('typescript'),
    }),
    commonjs({
      namedExports: {}
    }),
    resolve(),
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
  ],
}


text:
<?php

namespace DevGroup\ExtensionsManager\tests;

use DevGroup\ExtensionsManager\helpers\ExtensionsHelper;
use testsHelper\TestConfigCleaner;
use Yii;
use yii\web\Application;

class ExtensionsHelperTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        TestConfigCleaner::cleanExtensions();
        $config = include __DIR__ . '/../../testapp/config/console.php';
        new Application($config);
        Yii::$app->cache->flush();
        Yii::setAlias('@vendor', __DIR__ . '/../../testapp/vendor');
        parent::setUp();
    }

    public function tearDown()
    {
        parent::tearDown();
        if (Yii::$app && Yii::$app->has('session', true)) {
            Yii::$app->session->close();
        }
        Yii::$app = null;
        TestConfigCleaner::cleanExtensions();
        TestConfigCleaner::cleanTestConfigs();
    }

    public function testGetAllConfigurables()
    {
        $this->assertEquals(4, count(ExtensionsHelper::getConfigurables()));
    }

    public function testGetOnlyActive()
    {
        $this->assertEquals(1, count(ExtensionsHelper::getConfigurables(true)));
    }
}


text:
General Guidelines
------------------

* **Code style.** Please follow local code style. Ask if you're unsure.
* **No warnings.** All generated code must compile without warnings.
* **Android version support.** The library should support versions of Android that have more than 5% distribution, as measured by [Google's dashboard](https://developer.android.com/about/dashboards/index.html). No versions should be dropped without good reason.
* **Architecture support.** Scanning should support ARMv7a, with and without NEON vector instruction support. Other architectures may be added.
* **Testing.** Test both with the `buffalo` demo app, and with the included `SampleApp`. Test at least on one physical device and report the device model & OS tested on.


text:
package org.pomo.fast.file;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Serializable;

import org.pomo.fast.file.listener.FileWriteListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 本地文件IO操作
 *
 * @author Mr.Po
 *
 */
public class FastFile {

	private final static Logger LOG = LoggerFactory.getLogger(FastFile.class);

	public static final char separatorChar = File.separatorChar;
	public static final char unseparatorChar = (char) (139 - File.separatorChar);

	public static final String separator = String.valueOf(separatorChar);
	public static final String unseparator = String
			.valueOf((char) (139 - File.separatorChar));

	/**
	 * 文件写入流速
	 */
	private static int RADIX = 4;

	/**
	 * 删除文件夹及其文件
	 *
	 * @param folderPath
	 *            文件夹路径
	 */
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			LOG.info("删除失败!", e);
		}
	}

	/**
	 * 删除文件夹下所有文件(不包括该文件夹)
	 *
	 * @param path
	 *            文件夹路径
	 * @return
	 */
	public static boolean delAllFile(String path) {

		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {// 判断文件是否存在,若不存在即已删除成功
			LOG.debug("path:" + path + ",找不到!");
			return true;
		}
		if (!file.isDirectory()) {// File是否为一个文件夹
			LOG.error("path:" + path + ",不是一个有效的目录!");
			return false;
		}
		String[] tempList = file.list();
		File temp = null;

		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件夹
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 复制文件
	 *
	 * @param sourceFile
	 *            源文件
	 * @param destinationFile
	 *            目标文件
	 * @return 目标文件File(由调用方判断是否为空,和文件是否存在)
	 * @throws IOException
	 */
	public static File copyFile(File sourceFile, File destinationFile)
			throws IOException {
		writeFile(sourceFile, sourceFile.length(), new FileInputStream(
				sourceFile), new FileOutputStream(destinationFile), null);
		return destinationFile;
	}

	/**
	 * 复制文件
	 *
	 * @param source
	 *            原始文件路径
	 * @param destination
	 *            目标文件路径
	 * @return 目标文件File(由调用方判断是否为空,和文件是否存在)
	 * @throws IOException
	 */
	public static File copyFile(String source, String destination)
			throws IOException {
		return copyFile(new File(source), createFile(destination));
	}

	/**
	 * 复制文件
	 *
	 * @param sourceFile
	 *            源文件
	 * @param destination
	 *            目标文件路径
	 * @return 目标文件File(由调用方判断是否为空,和文件是否存在)
	 * @throws IOException
	 */
	public static File copyFile(File sourceFile, String destination)
			throws IOException {
		return copyFile(sourceFile, createFile(destination));
	}

	/**
	 * 上传文件,并且自动重命名
	 *
	 * @param sourceFile
	 *            源文件
	 * @param path
	 *            文件本地路径
	 * @param fileName
	 *            文件原始名称(包含后缀,重命名后会在前追加时间戳)
	 * @return 目标文件File(由调用方判断是否为空,和文件是否存在)
	 * @throws IOException
	 */
	public static File uploadFile(File sourceFile, String path, String fileName)
			throws IOException {
		return copyFile(sourceFile,
				path + File.separatorChar + System.currentTimeMillis() + "_"
						+ fileName);
	}

	/**
	 * 判断该路径是否为一个文件

	 * 若文件存在,则调用File方法判断 若文件不存在,则判断路径是否是以 separatorChar或 unseparatorChar 结尾
	 *
	 * @param path
	 *            路径
	 * @return
	 */
	public static boolean isFile(String path) {

		File file = new File(path);

		if (file.exists()) {

			return file.isFile();

		} else {

			char end = path.charAt(path.length() - 1);
			return !(end == separatorChar || end == unseparatorChar);

		}

	}

	/**
	 * 判断该路径是否为一个目录

	 * 若文件存在,则调用File方法判断 若文件不存在,则判断路径是否是以 separatorChar或 unseparatorChar 结尾
	 *
	 * @param path
	 *            路径
	 * @return
	 */
	public static boolean isDirectory(String path) {

		File file = new File(path);

		if (file.exists()) {

			return file.isDirectory();

		} else {

			char end = path.charAt(path.length() - 1);
			return end == separatorChar || end == unseparatorChar;

		}

	}

	/**
	 * 得到File的name,当File为文件时,不包含后缀
	 *
	 * @param file
	 * @return
	 */
	public static String getFileNameNoSuffix(File file) {

		String name = file.getName();
		int len = name.lastIndexOf('.');
		if (len != -1) {
			name = name.substring(0, len);
		}
		return name;
	}

	/**
	 * 创建指定文件的父级文件夹
	 *
	 * @param file
	 *            指定文件
	 */
	public static void createParentDirectory(File file) {

		File directory = file.getParentFile();

		if (!directory.exists()) {
			directory.mkdirs();
		}

	}

	/**
	 * 创建指定目录,当指定目录存在时跳过
	 *
	 * @param path
	 */
	public static void createDirectory(String path) {
		File directory = new File(path);
		if (!directory.exists()) {
			directory.mkdirs();
		}
	}

	/**
	 * 创建文件
	 *
	 * @param file
	 *            待创建文件
	 * @return 文件
	 * @throws IOException
	 */
	public static File createFile(File file) throws IOException {

		createParentDirectory(file);

		file.createNewFile();

		return file;

	}

	/**
	 * 创建文件
	 *
	 * @param pathFileName
	 *            完整路径(包括后缀名)
	 * @return
	 * @throws IOException
	 */
	public static File createFile(String pathFileName) throws IOException {

		LOG.debug("--->文件路径:" + pathFileName);

		File file = new File(pathFileName);

		// 如果该文件存在
		if (file.exists()) {
			return file;
		}

		return createFile(file);
	}

	/**
	 * 将InputStream中的数据通过OutputStream保存到硬盘
	 *
	 * @param length
	 *            文件总长度
	 * @param inputStream
	 *            输入流
	 * @param outputStream
	 *            输出流
	 * @param listener
	 *            下载文件转换时的监听
	 * @return 是否写入成功
	 * @throws IOException
	 */
	public static void writeFile(File file, long length,
			InputStream inputStream, OutputStream outputStream,
			FileWriteListener listener) throws IOException {

		if (listener != null
				&& listener.beforeExecute(file, length, inputStream,
						outputStream)) {

			// inputStream.close();
			// outputStream.close();

			listener.afterExecute(file, null);

			return;
		}

		int len = 0, count = 0;
		byte[] writeBuffer = new byte[RADIX * 1024];

		IOException err = null;

		try {

			while ((len = inputStream.read(writeBuffer)) != -1) {// 一边读一边写

				if (listener != null) {
					count += len;
					if (listener.executeing(file, length, count))
						return;
				}

				outputStream.write(writeBuffer, 0, len);
			}

		} catch (IOException e) {

			LOG.error("--->写入文件失败!", e);
			err = e;

		} finally {
			// inputStream.close();
			// outputStream.close();

			if (listener != null)
				listener.afterExecute(file, err);
		}
	}

	/**
	 * 将InputStream中的数据保存到硬盘
	 *
	 * @param path
	 *            文件在本地的路径
	 * @param fileName
	 *            文件在本地名称
	 * @param length
	 *            文件总长度
	 * @param inputStream
	 *            文件输入流
	 * @param listener
	 *            文件写入监听
	 * @return 写入的文件
	 * @throws IOException
	 */
	public static File writeFile(File file, int length,
			InputStream inputStream, FileWriteListener listener)
			throws IOException {

		writeFile(file, length, inputStream, new FileOutputStream(file),
				listener);

		LOG.info("文件创建成功!");
		return file;
	}

	/**
	 * 将一个内存对象保存至硬盘(String文件会被保存为文本文件,其他可序列化文件会以二进制方式保存)
	 *
	 * @param serializable
	 *            内存对象(可序列化对象)
	 * @param path
	 *            文件所在路径
	 * @param fileName
	 *            文件名
	 * @return 写入文件(可能为null,或不存在)
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static File writeFile(Serializable serializable, String charset,
			String path, String fileName) throws FileNotFoundException,
			IOException {

		FileOutputStream fileOutputStream = new FileOutputStream(
				createFile(path + fileName));
		ObjectOutputStream objectOutputStream = null;

		try {

			if (serializable instanceof String) {// 普通文件
				fileOutputStream.write(((String) serializable)
						.getBytes(charset));

			} else {// 对象文件,需要序列化
				objectOutputStream = new ObjectOutputStream(fileOutputStream);
				objectOutputStream.writeObject(serializable);
			}

			return new File(path + fileName);

		} catch (IOException e) {
			LOG.error("向" + path + fileName + "写入文件失败!", e);
			throw e;
		} finally {
			fileOutputStream.close();
			if (objectOutputStream != null)
				objectOutputStream.close();
		}
	}

	/**
	 * 从输入流中读取其文本
	 *
	 * @param inputStream
	 *            输入流
	 * @param charset
	 *            编码方式
	 * @return 文本内容
	 * @throws IOException
	 */
	public static String readText(InputStream inputStream, String charset)
			throws IOException {

		StringBuilder content = new StringBuilder();
		BufferedReader buff = null;
		try {
			char[] c = new char[RADIX];
			int len;
			buff = new BufferedReader(new InputStreamReader(inputStream,
					charset));
			while ((len = buff.read(c)) != -1)
				content.append(c,0,len);

			LOG.debug("文件读取成功!");
		} catch (Exception e) {
			LOG.error("文件读取失败!", e);
		} finally {
			buff.close();
			inputStream.close();
		}
		return content.toString();

	}

	/**
	 * 从本地读取文件
	 *
	 * @param t
	 *            文件类型(String或可序列化文件)
	 * @param pathFileName
	 *            文件完整路径(包含后缀名)
	 * @return 实例对象
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T readFile(Class<T> clazz, String pathFileName,
			String charset) throws IOException, ClassNotFoundException {

		Object obj = null;

		FileInputStream fileInputStream = new FileInputStream(pathFileName);

		if (clazz.equals(String.class)) {// 该对象为文本类型

			obj = (T) readText(fileInputStream, charset);

		} else {
			ObjectInputStream objectInputStream = null;
			try {
				objectInputStream = new ObjectInputStream(fileInputStream);
				obj = (T) objectInputStream.readObject();

			} catch (ClassNotFoundException e) {
				LOG.error("--->" + pathFileName + ",对象转换失败,可能是序列化版本不一致!", e);
				throw e;
			} catch (IOException e) {
				LOG.error("--->读取文件: " + pathFileName + " 失败!", e);
				throw e;
			} finally {
				objectInputStream.close();
			}
		}

		fileInputStream.close();

		return (T) obj;
	}

	/**
	 * 读取文件最后一行文本,当最后一行内容不是很长时此方法适用
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static String readLastLine(File file) throws IOException {

		RandomAccessFile raf = null;
		String lastLine = "";
		try {
			raf = new RandomAccessFile(file, "r");
			long len = raf.length();

	        if (len != 0L) {
	          long pos = len - 1;
	          while (pos > 0) {
	            pos--;
	            raf.seek(pos);
	            if (raf.readByte() == '\n') {
	              lastLine = raf.readLine();
	              break;
	            }
	          }
	        }
		} catch (FileNotFoundException e) {
			LOG.error("没有找到文件",e);
			throw e;
		} catch (IOException e) {
			LOG.error("文件读取失败",e);
			throw e;
		}finally{
			raf.close();
		}

		return lastLine;
	}

	/**
	 * 追加指定内容到指定文件末尾
	 * @param file			指定文件
	 * @param content		内容
	 * @throws IOException
	 */
	public static void append(File file,byte[] b) throws IOException {
		RandomAccessFile raf = null;
        try {
        	// 打开一个随机访问文件流,按读写方式
			raf = new RandomAccessFile(file, "rw");
			// 将写文件指针移到文件尾。
	        raf.seek(raf.length());

	        raf.write(b);
		} catch (IOException e) {
			LOG.error("追加内容失败! \n file:"+file,e);
			throw e;
		}finally{
			raf.close();
		}
	}

	/**
	 * 得到一个字节输入流
	 *
	 * @param filePath
	 *            完整路径(包括后缀名)
	 * @return 字节输入流
	 * @throws IOException
	 *             文件不能找到,文件被锁定等
	 */
	public static ByteArrayInputStream getInputStream(String pathFileName)
			throws IOException {
		FileInputStream fileInputStream = new FileInputStream(pathFileName);
		byte[] b = new byte[fileInputStream.available()];
		fileInputStream.read(b);
		fileInputStream.close();
		return new ByteArrayInputStream(b);
	}

	public static int getRADIX() {
		return RADIX;
	}

	public static void setRADIX(int rADIX) {
		RADIX = rADIX;
	}

}


text:
package com.popdeem.sdk.uikit.utils;

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.popdeem.sdk.core.utils.PDLocaleUtils;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.text.DecimalFormat;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * Created by mikenolan on 19/02/16.
 */
public class PDUIUtils {

    public static final String PD_DATE_FORMAT = "EEE dd MMM kk:mm";

    private static final DecimalFormat DF_TWO_PLACES = new DecimalFormat(".##");

    /**
     * Method to calculate the time until (Needs refactoring)
     *
     * @param expiryTimeInSeconds {@link Long} value for expiry time in seconds
     * @param nonClaimedReward    {@link Boolean}
     * @param isSweepstakes       {@link Boolean}
     * @return {@link String} value for time until
     */
    public static String timeUntil(long expiryTimeInSeconds, boolean nonClaimedReward, boolean isSweepstakes) {
        final DateTime now = DateTime.now();
        final DateTime expiry = new DateTime(expiryTimeInSeconds * 1000);

        // Check if reward has expired
        if (expiry.isBefore(now)) {
            return "Reward has expired";
        }

        // Days
        int days = Days.daysBetween(now, expiry).getDays();
        if (days == 1) {
            if (isSweepstakes) {
                return "1 day";
            } else {
                return nonClaimedReward ? "1 day remaining" : "Expires in 1 day";
            }
        }
        if (days > 1) {
            if (isSweepstakes) {
                return days + " days";
            } else {
                return nonClaimedReward ? days + " days remaining" : "Expires in " + days + " days";
            }
        }

        // Hours
        int hours = Hours.hoursBetween(now, expiry).getHours();
        if (hours == 1) {
            if (isSweepstakes) {
                return "1 hour";
            } else {
                return nonClaimedReward ? "1 hour remaining" : "Expires in 1 hour";
            }
        }
        if (hours > 1) {
            if (isSweepstakes) {
                return hours + " hours";
            } else {
                return nonClaimedReward ? hours + " hours remaining" : "Expires in " + hours + " hours";
            }
        }

        // Minutes
        int minutes = Minutes.minutesBetween(now, expiry).getMinutes();
        if (minutes == 1) {
            if (isSweepstakes) {
                return "1 minute";
            } else {
                return nonClaimedReward ? "1 minute remaining" : "Expires in 1 minute";
            }
        }

        if (isSweepstakes) {
            return minutes + " minutes";
        } else
            return nonClaimedReward ? minutes + " minutes remaining" : "Expires in " + minutes + " minutes";
    }

    public static String convertTimeToDayAndMonth(long expiryTimeInSeconds) {
        if (expiryTimeInSeconds <= 0) {
            return "";
        }

        return convertUnixTimeToDate(expiryTimeInSeconds, "d MMM");
    }

    /**
     * Get a time in milliseconds in Timer format
     *
     * @param millis Time in milliseconds
     * @return String in timer format
     */
    public static String millisecondsToTimer(long millis) {
        return String.format(Locale.getDefault(), "%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millis),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
    }

    public static String millisecondsToMinutes(long millis) {
        return String.valueOf(TimeUnit.MILLISECONDS.toMinutes(millis));
    }

    /**
     * Format a Unix Time stamp for the given format
     *
     * @param date   Unix Time stamp in seconds
     * @param format Format to use when converting.
     * @return Formatted date String
     */
    public static String convertUnixTimeToDate(long date, String format) {
        DateTime dateTime = new DateTime(date * 1000);
        DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
        return formatter.print(dateTime);
    }

    /**
     * Hide UI Keyboard
     *
     * @param context Application Context
     * @param view    View
     */
    public static void hideKeyboard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public static String formatDistance(float distanceInMeters) {
        if (PDLocaleUtils.useMetricSystem()) {
            double distanceInKm = distanceInMeters / 1000;
            return String.format(Locale.getDefault(), "%1skm", DF_TWO_PLACES.format(distanceInKm));
        } else {
            double miles = distanceInMeters / 1609.344;
            return String.format(Locale.getDefault(), "%1smiles", DF_TWO_PLACES.format(miles));
        }
    }

}


text:
package com.twitter.finatra.http

import com.twitter.finatra.http.response._
import com.twitter.inject.Logging
import javax.inject.Inject

abstract class Controller extends RouteDSL with Logging {
  /*
   * NOTE: Using constructor-injection for the following fields would add boilerplate to all
   * controllers, so instead we use vars to allow setter injection after object creation
   */
  @Inject private var responseBuilder: ResponseBuilder = _

  /* Protected */
  protected def response = responseBuilder
}


text:
var w = window.innerWidth * window.devicePixelRatio,
    h = window.innerHeight * window.devicePixelRatio;

/*
For Fullscreen put this code:

var w = window.innerWidth * window.devicePixelRatio,
    h = window.innerHeight * window.devicePixelRatio;
*/

var game = new Phaser.Game(w, h, Phaser.AUTO, 'gameContainer');

game.state.add('boot', bootState);
game.state.add('load', loadState);
game.state.add('start', startState);
game.state.add('play', playState);

game.state.start('boot');


text:
namespace Personal.Bondora.Configuration
{
    public static partial class Config
    {
        public static class Communication
        {
            public static string NamedPipeName
            {
                get { return _settings.GetSetting("communication/namedPipeName"); }
            }

            public static string SingleProcessMutexName
            {
                get { return _settings.GetSetting("communication/singleProcessMutexName"); }
            }
        }
    }
}


text:
using System;
using Net.Sf.Pkcs11.Wrapper;
namespace Net.Sf.Pkcs11.Objects
{
    /// <summary>
    /// Description of PublicKey.
    /// </summary>
    public abstract class PublicKey : Key
    {
        public PublicKey()
        {
            Class.ObjectType = CKO.PUBLIC_KEY;
        }
        public PublicKey(Session session, uint hObj)
            : base(session, hObj)
        {
        }

        public static new P11Object GetInstance(Session session, uint hObj)
        {
            KeyTypeAttribute keyType = ReadAttribute(session, hObj, new KeyTypeAttribute());

            switch (keyType.KeyType)
            {
                case CKK.RSA:
                    return RSAPublicKey.GetInstance(session, hObj);
                case CKK.GOST:
                    return GostPublicKey.GetInstance(session, hObj);
                default:
                    return null;
            }

        }

        ByteArrayAttribute subject = new ByteArrayAttribute(CKA.SUBJECT);
        BooleanAttribute encrypt = new BooleanAttribute(CKA.ENCRYPT),
        verify = new BooleanAttribute(CKA.VERIFY),
        verifyRecover = new BooleanAttribute(CKA.VERIFY_RECOVER),
        wrap = new BooleanAttribute(CKA.WRAP),
        trusted = new BooleanAttribute(CKA.TRUSTED);

        public ByteArrayAttribute Subject
        {
            get { return subject; }
        }

        public BooleanAttribute Encrypt
        {
            get { return encrypt; }
        }

        public BooleanAttribute Verify
        {
            get { return verify; }
        }

        public BooleanAttribute VerifyRecover
        {
            get { return verifyRecover; }
        }

        public BooleanAttribute Wrap
        {
            get { return wrap; }
        }

        public BooleanAttribute Trusted
        {
            get { return trusted; }
        }

        public override void ReadAttributes(Session session)
        {
            base.ReadAttributes(session);

            subject = ReadAttribute(session, HObj, new ByteArrayAttribute(CKA.SUBJECT));
            encrypt = ReadAttribute(session, HObj, new BooleanAttribute(CKA.ENCRYPT));
            verify = ReadAttribute(session, HObj, new BooleanAttribute(CKA.VERIFY));
            verifyRecover = ReadAttribute(session, HObj, new BooleanAttribute(CKA.VERIFY_RECOVER));
            wrap = ReadAttribute(session, HObj, new BooleanAttribute(CKA.WRAP));
            trusted = ReadAttribute(session, HObj, new BooleanAttribute(CKA.TRUSTED));

        }

    }
}


text:
/*
 * args.c - argument processing.
 */

#include <sys/utsname.h>
#include <vncviewer.h>

#define FLASHPORT  (5400)    /* Offset to listen for `flash' commands */
#define CLIENTPORT (5500)    /* Offset to listen for reverse connections */
#define SERVERPORT (5900)    /* Offset to server for regular connections */

char *programName;

char hostname[256];
int port;

Bool listenSpecified = False;
int listenPort = 0, flashPort = 0;

char *displayname = NULL;

Bool shareDesktop = False;
Bool viewOnly = False;

CARD32 explicitEncodings[MAX_ENCODINGS];
int nExplicitEncodings = 0;
Bool addCopyRect = True;
Bool addRRE = True;
Bool addCoRRE = True;
Bool addHextile = True;

Bool useBGR233 = False;
Bool forceOwnCmap = False;
Bool forceTruecolour = False;
int requestedDepth = 0;

char *geometry = NULL;

int wmDecorationWidth = 4;
int wmDecorationHeight = 24;

char *passwdFile = NULL;

int updateRequestPeriodms = 0;

int updateRequestX = 0;
int updateRequestY = 0;
int updateRequestW = 0;
int updateRequestH = 0;

int rawDelay = 0;
int copyRectDelay = 0;

Bool debug = False;

void
usage()
{
    fprintf(stderr,"\n"
	    "usage: %s [<options>] <host>:<display#>\n"
	    "       %s [<options>] -listen [<display#>]\n"
	    "\n"
	    "<options> are:\n"
	    "              [-display <display>] [-shared] [-viewonly]\n"
	    "              [-raw] [-copyrect] [-rre] [-corre] [-hextile]\n"
	    "              [-nocopyrect] [-norre] [-nocorre] [-nohextile]\n"
	    "              [-bgr233] [-owncmap] [-truecolour] [-depth <d>]\n"
	    "              [-geometry <geom>]\n"
	    "              [-wmdecoration <width>x<height>]\n"
	    "              [-passwd <passwd-file>]\n"
	    "              [-period <ms>]\n"
	    "              [-region <x> <y> <width> <height>]\n"
	    "              [-rawdelay <ms>] [-copyrectdelay <ms>] [-debug]\n\n"
	    ,programName,programName);
    exit(1);
}

void
processArgs(int argc, char **argv)
{
    int i;
    Bool argumentSpecified = False;

    programName = argv[0];

    for (i = 1; i < argc; i++) {

	if (strcmp(argv[i],"-display") == 0) {

	    if (++i >= argc) usage();
	    displayname = argv[i];

	} else if (strcmp(argv[i],"-shared") == 0) {

	    shareDesktop = True;

	} else if (strcmp(argv[i],"-viewonly") == 0) {

	    viewOnly = True;

	} else if (strcmp(argv[i],"-rre") == 0) {

	    explicitEncodings[nExplicitEncodings++] = rfbEncodingRRE;
	    addRRE = False;

	} else if (strcmp(argv[i],"-corre") == 0) {

	    explicitEncodings[nExplicitEncodings++] = rfbEncodingCoRRE;
	    addCoRRE = False;

	} else if (strcmp(argv[i],"-hextile") == 0) {

	    explicitEncodings[nExplicitEncodings++] = rfbEncodingHextile;
	    addHextile = False;

	} else if (strcmp(argv[i],"-copyrect") == 0) {

	    explicitEncodings[nExplicitEncodings++] = rfbEncodingCopyRect;
	    addCopyRect = False;

	} else if (strcmp(argv[i],"-raw") == 0) {

	    explicitEncodings[nExplicitEncodings++] = rfbEncodingRaw;

	} else if (strcmp(argv[i],"-norre") == 0) {

	    addRRE = False;

	} else if (strcmp(argv[i],"-nocorre") == 0) {

	    addCoRRE = False;

	} else if (strcmp(argv[i],"-nohextile") == 0) {

	    addHextile = False;

	} else if (strcmp(argv[i],"-nocopyrect") == 0) {

	    addCopyRect = False;

	} else if (strcmp(argv[i],"-bgr233") == 0) {

	    useBGR233 = True;

	} else if (strcmp(argv[i],"-owncmap") == 0) {

	    forceOwnCmap = True;

	} else if (strcmp(argv[i],"-truecolour") == 0) {

	    forceTruecolour = True;

	} else if (strcmp(argv[i],"-depth") == 0) {

	    if (++i >= argc) usage();
	    requestedDepth = atoi(argv[i]);

	} else if (strcmp(argv[i],"-geometry") == 0) {

	    if (++i >= argc) usage();
	    geometry = argv[i];

	} else if (strcmp(argv[i],"-wmdecoration") == 0) {

	    if (++i >= argc) usage();
	    if (sscanf(argv[i], "%dx%d",
		       &wmDecorationWidth, &wmDecorationHeight) != 2) usage();

	} else if (strcmp(argv[i],"-passwd") == 0) {

	    if (++i >= argc) usage();
	    passwdFile = argv[i];

	} else if (strcmp(argv[i],"-period") == 0) {

	    if (++i >= argc) usage();
	    updateRequestPeriodms = atoi(argv[i]);

	} else if (strcmp(argv[i],"-region") == 0) {

	    if ((i+4) >= argc) usage();
	    updateRequestX = atoi(argv[i+1]);
	    updateRequestY = atoi(argv[i+2]);
	    updateRequestW = atoi(argv[i+3]);
	    updateRequestH = atoi(argv[i+4]);
	    if ((updateRequestX < 0) || (updateRequestY < 0) ||
		(updateRequestW < 0) || (updateRequestH < 0))
		usage();
	    i += 4;

	} else if (strcmp(argv[i],"-rawdelay") == 0) {

	    if (++i >= argc) usage();
	    rawDelay = atoi(argv[i]);

	} else if (strcmp(argv[i],"-copyrectdelay") == 0) {

	    if (++i >= argc) usage();
	    copyRectDelay = atoi(argv[i]);

	} else if (strcmp(argv[i],"-debug") == 0) {

	    debug = True;

	} else if (strcmp(argv[i],"-listen") == 0) {

	    if (argumentSpecified) usage();

	    listenSpecified = True;
	    if (++i < argc) {
		listenPort = CLIENTPORT+atoi(argv[i]);
		flashPort = FLASHPORT+atoi(argv[i]);
	    }

	} else if (argv[i][0] != '-') {

	    if (argumentSpecified || listenSpecified) usage();

	    argumentSpecified = True;

	    if (sscanf(argv[i], "%[^:]:%d", hostname, &port) != 2) usage();

	    if (port < 100)
		port += SERVERPORT;

	} else {

	    usage();

	}
    }

    if (listenSpecified) {
	if (listenPort == 0) {
	    char *display;
	    char *colonPos;
	    struct utsname hostinfo;

	    display = XDisplayName(displayname);
	    colonPos = strchr(display, ':');

	    uname(&hostinfo);

	    if (colonPos && ((colonPos == display) ||
			     (strncmp(hostinfo.nodename, display,
				      strlen(hostinfo.nodename)) == 0))) {

		listenPort = CLIENTPORT+atoi(colonPos+1);
		flashPort = FLASHPORT+atoi(colonPos+1);

	    } else {
		fprintf(stderr,"%s: cannot work out which display number to "
			"listen on.\n", programName);
		fprintf(stderr,
			"Please specify explicitly with -listen <num>\n");
		exit(1);
	    }
	}

    } else if (!argumentSpecified) {

	usage();

    }
}


text:
package top.ningg.java.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class JavaIO {

	public static void main(String[] args) throws IOException {
		String fileName = "D:/test.log";
		InputStream inputStream = new FileInputStream(fileName);

		inputStream.read();

		Socket socket = new Socket();

	}
}


text:
..
    :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
    :license: See LICENSE.txt.

.. _assembly:

********
Assembly
********

.. module:: clique

As seen in the :ref:`tutorial`, Clique provides the high-level
:py:func:`assemble` function to support automatically assembling items into
relevant :ref:`collections <collection>` based on a common changing
numerical component::

    >>> import clique
    >>> collections, remainder = clique.assemble([
    ...     'file.0001.jpg', 'file.0002.jpg', 'file.0003.jpg',
    ...     'file.0001.dpx', 'file.0002.dpx', 'file.0003.dpx'
    ... ])
    >>> print collections
    [<Collection "file.%04d.dpx [1-3]">, <Collection "file.%04d.jpg [1-3]">]

.. note::

    Any items that are not members of a returned collection can be found in
    the *remainder* list.

However, as mentioned in the :ref:`introduction`, Clique has no understanding
of what a numerical component represents. Therefore, it takes a conservative
approach and considers **all** collections with a common changing numerical
component as valid. This can lead to surprising results at first::

    >>> collections, remainder = clique.assemble([
    ...     'file_v1.0001.jpg', 'file_v1.0002.jpg', 'file_v1.0003.jpg',
    ...     'file_v2.0001.jpg', 'file_v2.0002.jpg', 'file_v2.0003.jpg'
    ... ])
    >>> print collections
    [<Collection "file_v1.%04d.jpg [1-3]">,
     <Collection "file_v2.%04d.jpg [1-3]">,
     <Collection "file_v%d.0001.jpg [1-2]">,
     <Collection "file_v%d.0002.jpg [1-2]">,
     <Collection "file_v%d.0003.jpg [1-2]">]

Here, Clique returned more collections than might have been expected, but, as
can be seen, they are all valid collections. This is an important feature of
Clique - it doesn't attempt to guess. Instead, it is designed to be wrapped
easily with domain specific logic to get the results desired.

There are a couple of ways to influence the returned result from the
:py:func:`~assemble` function:

    * Pass a *minimum_items* argument.
    * Pass custom *patterns*.

Minimum Items
=============

By default, Clique will filter out any collection from the returned result of
:py:func:`~assemble` that has less than two items. This value can be customised
per :py:func:`~assemble` call by passing *minimum_items* as a keyword::

    >>> print clique.assemble(['file.0001.jpg'])[0]
    []
    >>> print clique.assemble(['file.0001.jpg'], minimum_items=1)[0]
    [<Collection "file.%04d.jpg [1]">]

Patterns
========

By default, Clique finds all groups of numbers in each item and creates
collections that have common :term:`head`, :term:`tail` and :term:`padding`
values.

Custom patterns can be used to tailor the process. Pass them as a list of
regular expressions (either strings or :py:class:`re.RegexObject` instances)::

    >>> items = [
    ...     'file.0001.jpg', 'file.0002.jpg', 'file.0003.jpg',
    ...     'file.0001.dpx', 'file.0002.dpx', 'file.0003.dpx'
    ... ])
    >>> print clique.assemble(items, patterns=[
    ...     '\.(?P<index>(?P<padding>0*)\d+)\.\D+\d?$'
    ... ])[0]
    [<Collection "file_v1.%04d.jpg [1-3]">,
     <Collection "file_v2.%04d.jpg [1-3]">]

.. note::

    Each custom expression **must** contain the expression from
    :py:data:`DIGITS_PATTERN` exactly once. An easy way to do this is using
    Python's string formatting.

    So, instead of::

        '\.(?P<index>(?P<padding>0*)\d+)\.\D+\d?$'

    use::

        '\.{0}\.\D+\d?$'.format(clique.DIGITS_PATTERN)

Some common expressions are predefined in the :py:data:`~clique.PATTERNS`
dictionary (contributions welcome!)::

    >>> print clique.assemble(items, patterns=[clique.PATTERNS['frames']])[0]
    [<Collection "file_v1.%04d.jpg [1-3]">,
     <Collection "file_v2.%04d.jpg [1-3]">]

.. _assembly/case_sensitivity:

Case Sensitivity
================

When assembling collections, it is sometimes useful to be able to specify
whether the case of the items should be important or not. For example,
"file.0001.jpg" and "FILE.0002.jpg" could be identified as part of the same
collection or not.

By default the assembly is case sensitive, but this can be controlled by setting
the *case_sensitive* argument::

    >>> items = ['file.0001.jpg', 'FILE.0002.jpg', 'file.0003.jpg']
    >>> print clique.assemble(items, case_sensitive=False)
    [<Collection "file.%04d.jpg [1-3]">], []
    >>> print clique.assemble(items, case_sensitive=True)
    [<Collection "file.%04d.jpg [1, 3]">], ['FILE.0002.jpg']

A common use case might be to ignore case sensitivity when on a Windows or Mac
machine::

    >>> import sys
    >>> clique.assemble(
    ...     items, case_sensitive=sys.platform not in ('win32', 'darwin')
    ... )


text:
MIME-Version: 1.0
Server: CERN/3.0
Date: Sunday, 01-Dec-96 20:18:05 GMT
Content-Type: text/html
Content-Length: 1759
Last-Modified: Wednesday, 12-Jul-95 16:11:32 GMT

<title>Kristen Summers -- Logical Structure Types</title>

Toward a Taxonomy of Logical Document Structures

In Electronic Publishing and the Information Superhighway:
Proceedings of the Dartmouth Institute for Advanced Graduate Studies
(<!WA0><!WA0><!WA0><!WA0>DAGS '95),
pages 124 - 133, Boston, May 1995.

Abstract

The automated discovery of logical structure in text documents
is an important problem that has recently received a good deal of
attention; it can enable the creation of
flexible and sophisticated document manipulation tools that will
greatly increase the impact of electronic documents.  This paper
addresses aspects of the nature of these logical structures,
in order to develop categories of structures that reflect
the variance in requirements for discovery and the variance
in significance for applications.  A complete taxonomy is not
developed, but relevant attributes are identified in three
forms of categorization:  fundamental, based on structure definitions;
discovery, based on required observables to find structures; and
usage, based on roles structures play in applications.
The attributes themselves are independent of the choice
of particular logical structures to consider in a given
application, and their direct
implications are discussed.

You can view the <!WA1><!WA1><!WA1><!WA1>full postscript file,
view an
<!WA2><!WA2><!WA2><!WA2>
html version at the
<!WA3><!WA3><!WA3><!WA3>conference
papers site,
or return to <!WA4><!WA4><!WA4><!WA4>my home page.


text:
package com.sumologic.sumobot.core.aws

import com.amazonaws.auth.{AWSCredentials, BasicAWSCredentials}
import com.sumologic.sumobot.core.config.ListOfConfigs
import com.typesafe.config.Config

object AWSAccounts {
  def load(config: Config): Map[String, AWSCredentials] = {
    ListOfConfigs.parse(config, "aws") {
      (name, accountConfig) =>
        val key = accountConfig.getString(s"key.id")
        val secret = accountConfig.getString(s"key.secret")
        new BasicAWSCredentials(key, secret)
    }
  }
}


text:
namespace net.openstack.Providers.Rackspace.Objects.Response
{
    using net.openstack.Core.Domain;
    using Newtonsoft.Json;

    /// <summary>
    /// This models the JSON response used for the Get Metadata Item request.
    /// </summary>
    /// <seealso href="http://docs.openstack.org/api/openstack-compute/2/content/Get_Metadata_Item-d1e5507.html">Get Metadata Item (OpenStack Compute API v2 and Extensions Reference)</seealso>
    /// <threadsafety static="true" instance="false"/>
    [JsonObject(MemberSerialization.OptIn)]
    internal class MetadataItemResponse
    {
        /// <summary>
        /// Gets information about the metadata item. The returned <see cref="Metadata"/> object
        /// will only have one item, containing the key and value for the metadata item.
        /// </summary>
        [JsonProperty("meta")]
        public Metadata Metadata { get; private set; }
    }
}


text:
<?php

namespace AcmeGroup\LaboBundle\Entity;

// use AcmeGroup\LaboBundle\Entity\baseRepository;
use labo\Bundle\TestmanuBundle\Entity\fournisseurRepository as fournisseurBaseRepo;

/**
 * fournisseurRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class fournisseurRepository extends fournisseurBaseRepo {

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">
    <title>Imagery Search</title>

    <link rel="stylesheet" href="http://10.104.6.45:8080/static/built/girder_lib.min.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-slider.min.css">
    <link rel="stylesheet" href="css/font-awesome.min.css">

    <link rel="stylesheet" href="css/main.css">

Updating heatmap...

          <button id="heatmap-hide">Hide Heatmap Layer</button>

            <button class="btn btn-link" id="login" href="#">Login</button>

            <button class="btn btn-link hidden" id="logout" href="#">Logout</button>

Search in...

        <button id="rectangle" class="lastused">Rectangle</button>
        <button id="polygon">Polygon</button>
        <button id="point">Point + Radius</button>

Left-click points in the polygon.  Double click, right click, or click the starting point to close the polygon.

Left to create a point.

        <select class="form-control" id="query-type">
          <option value="within">Within</option>
          <option value="intersects">Intersects</option>
        </select>
        Min. Distance (meters)
        <input type="number" class="form-control radius-input" id="min-dist-field" name="min-dist" value="0"></input>
        Max. Distance (meters)
        <input type="number" class="form-control radius-input" id="max-dist-field" name="max-dist" value="5000"></input>

      <button class="btn btn-default" style="" id="showjumpto">Jump to Coordinates...</button>

        Lat.
        <input type="number" class="form-control" id="lat-field" name="lat" value="39.7815"></input>
        Lon.
        <input type="number" class="form-control" id="lon-field" name="lon" value="-84.0636"></input>
        <button class="btn btn-default" id="jumpto">Jump</button>

        <button class="btn btn-default" id="search">Search</button>

      <button class="btn btn-default" style="margin-left: 10px; position: fixed;" id="slide-button"></button>
      <button class="btn btn-default" style="margin-left: 10px; position: fixed;" id="" data-toggle="modal" data-target="#change-heatmap-fields">Edit Filter Fields</button>

            <button type="btn" class="close" data-dismiss="modal" aria-label="Close">×</button>

Results

            <button class="btn btn-default" style="margin-left: 10px; position: fixed;" id="slide-button"></button>
            <button class="btn btn-default" style="margin-left: 10px; position: fixed;" id="edit-filter-fields-button" data-toggle="modal" data-target="#change-fields">Edit Filter Fields</button>
            <button class="btn btn-default" style="float:right;" id="next-page">Next Page</button>
            <button class="btn btn-default" style="float:right; margin-right: 50px;" id="prev-page">Previous Page</button>

                      Image
                      Modality
                      Date
                      View

            <button type="btn" class="btn btn-default" id="download-all">Download All</button>

            <button type="btn" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Metadata Fields

        <input id="field-search" placeholder="Search"></input>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Metadata Fields

        <input id="field-search" placeholder="Search"></input>


text:
namespace forecast_io
{

// Forward declarations
namespace factories
{
	class SynchronicDataPointFactory;
}
namespace listeners
{

}

namespace parsers
{

class SynchronicDataPointFactoryParser : public forecast_io::parsers::NotifyingSynchronicDataPointParser
{
public:
	SynchronicDataPointFactoryParser(factories::SynchronicDataPointFactory* pFactory) noexcept;

	virtual void parse(json_object* const & pJsonObj);

private:
	factories::SynchronicDataPointFactory& factory;

};

}

}

#endif // SYNCHRONICDATAPOINTFACTORYPARSER_HPP


text:
<?php

namespace Application\Sonata\MediaBundle\PHPCR;

use Sonata\MediaBundle\PHPCR\BaseMedia as BaseMedia;

/**
 * @author Nicolas Bastien <nbastien@prestaconcept.net>
 */
class Media extends BaseMedia
{
    /**
     * @var integer $id
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }
}


text:
// Copyright (C) 2011 The Android Open Source Project
//
// 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.google.gerrit.server.account;

import com.google.gerrit.common.data.GroupList;
import com.google.gerrit.common.data.GroupReference;
import com.google.gerrit.common.errors.NoSuchGroupException;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.project.ProjectControl;
import com.google.inject.Inject;
import com.google.inject.Provider;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class VisibleGroups {

  public interface Factory {
    VisibleGroups create();
  }

  private final Provider<IdentifiedUser> identifiedUser;
  private final GroupCache groupCache;
  private final GroupControl.Factory groupControlFactory;

  private boolean onlyVisibleToAll;
  private AccountGroup.Type groupType;

  @Inject
  VisibleGroups(final Provider<IdentifiedUser> currentUser,
      final GroupCache groupCache,
      final GroupControl.Factory groupControlFactory) {
    this.identifiedUser = currentUser;
    this.groupCache = groupCache;
    this.groupControlFactory = groupControlFactory;
  }

  public void setOnlyVisibleToAll(final boolean onlyVisibleToAll) {
    this.onlyVisibleToAll = onlyVisibleToAll;
  }

  public void setGroupType(final AccountGroup.Type groupType) {
    this.groupType = groupType;
  }

  public GroupList get() {
    return createGroupList(filterGroups(groupCache.all()));
  }

  public GroupList get(final Collection<ProjectControl> projects)
      throws NoSuchGroupException {
    final Set<AccountGroup> groups =
        new TreeSet<AccountGroup>(new GroupComparator());
    for (final ProjectControl projectControl : projects) {
      final Set<GroupReference> groupsRefs = projectControl.getAllGroups();
      for (final GroupReference groupRef : groupsRefs) {
        final AccountGroup group = groupCache.get(groupRef.getUUID());
        if (group == null) {
          throw new NoSuchGroupException(groupRef.getUUID());
        }
        groups.add(group);
      }
    }
    return createGroupList(filterGroups(groups));
  }

  /**
   * Returns visible list of known groups for the user. Depending on the group
   * membership realms supported, this may only return a subset of the effective
   * groups.
   * @See GroupMembership#getKnownGroups()
   */
  public GroupList get(final IdentifiedUser user) throws NoSuchGroupException {
    if (identifiedUser.get().getAccountId().equals(user.getAccountId())
        || identifiedUser.get().getCapabilities().canAdministrateServer()) {
      final Set<AccountGroup.UUID> effective =
          user.getEffectiveGroups().getKnownGroups();
      final Set<AccountGroup> groups =
          new TreeSet<AccountGroup>(new GroupComparator());
      for (final AccountGroup.UUID groupId : effective) {
        AccountGroup group = groupCache.get(groupId);
        if (group != null) {
          groups.add(group);
        }
      }
      return createGroupList(filterGroups(groups));
    } else {
      throw new NoSuchGroupException("Groups of user '" + user.getAccountId()
          + "' are not visible.");
    }
  }

  private List<AccountGroup> filterGroups(final Iterable<AccountGroup> groups) {
    final List<AccountGroup> filteredGroups = new LinkedList<AccountGroup>();
    final boolean isAdmin =
        identifiedUser.get().getCapabilities().canAdministrateServer();
    for (final AccountGroup group : groups) {
      if (!isAdmin) {
        final GroupControl c = groupControlFactory.controlFor(group);
        if (!c.isVisible()) {
          continue;
        }
      }
      if ((onlyVisibleToAll && !group.isVisibleToAll())
          || (groupType != null && !groupType.equals(group.getType()))) {
        continue;
      }
      filteredGroups.add(group);
    }
    return filteredGroups;
  }

  private GroupList createGroupList(final List<AccountGroup> groups) {
    return new GroupList(groups, identifiedUser.get()
        .getCapabilities().canCreateGroup());
  }
}


text:
use std::u32;
use std::char;
use std::ascii::AsciiExt;

// Bootstring parameters for Punycode
static BASE: u32 = 36;
static T_MIN: u32 = 1;
static T_MAX: u32 = 26;
static SKEW: u32 = 38;
static DAMP: u32 = 700;
static INITIAL_BIAS: u32 = 72;
static INITIAL_N: u32 = 0x80;
static DELIMITER: char = '-';

#[inline]
fn adapt(mut delta: u32, num_points: u32, first_time: bool) -> u32 {
    delta /= if first_time { DAMP } else { 2 };
    delta += delta / num_points;
    let mut k = 0;
    while delta > ((BASE - T_MIN) * T_MAX) / 2 {
        delta /= BASE - T_MIN;
        k += BASE;
    }
    k + (((BASE - T_MIN + 1) * delta) / (delta + SKEW))
}

/// Convert Punycode to an Unicode `String`.
///
/// This is a convenience wrapper around `decode`.
#[inline]
pub fn decode_to_string(input: &str) -> Option<String> {
    decode(input).map(|chars| chars.into_iter().collect())
}

/// Convert Punycode to Unicode.
///
/// Return None on malformed input or overflow.
/// Overflow can only happen on inputs that take more than
/// 63 encoded bytes, the DNS limit on domain name labels.
pub fn decode(input: &str) -> Option<Vec<char>> {
    // Handle "basic" (ASCII) code points.
    // They are encoded as-is befor the last delimiter, if any.
    let (mut output, input) = match input.rfind(DELIMITER) {
        None => (Vec::new(), input),
        Some(position) => (
            input[..position].chars().collect(),
            if position > 0 { &input[position + 1..] } else { input }
        )
    };
    let mut code_point = INITIAL_N;
    let mut bias = INITIAL_BIAS;
    let mut i = 0;
    let mut iter = input.bytes();
    loop {
        let previous_i = i;
        let mut weight = 1;
        let mut k = BASE;
        let mut byte = match iter.next() {
            None => break,
            Some(byte) => byte,
        };
        // Decode a generalized variable-length integer into delta,
        // which gets added to i.
        loop {
            let digit = match byte {
                byte @ b'0' ... b'9' => byte - b'0' + 26,
                byte @ b'A' ... b'Z' => byte - b'A',
                byte @ b'a' ... b'z' => byte - b'a',
                _ => return None
            } as u32;
            if digit > (u32::MAX - i) / weight {
                return None  // Overflow
            }
            i += digit * weight;
            let t = if k <= bias { T_MIN }
                    else if k >= bias + T_MAX { T_MAX }
                    else { k - bias };
            if digit < t {
                break
            }
            if weight > u32::MAX / (BASE - t) {
                return None  // Overflow
            }
            weight *= BASE - t;
            k += BASE;
            byte = match iter.next() {
                None => return None,  // End of input before the end of this delta
                Some(byte) => byte,
            };
        }
        let length = output.len() as u32;
        bias = adapt(i - previous_i, length + 1, previous_i == 0);
        if i / (length + 1) > u32::MAX - code_point {
            return None  // Overflow
        }
        // i was supposed to wrap around from length+1 to 0,
        // incrementing code_point each time.
        code_point += i / (length + 1);
        i %= length + 1;
        let c = match char::from_u32(code_point) {
            Some(c) => c,
            None => return None
        };
        output.insert(i as usize, c);
        i += 1;
    }
    Some(output)
}

/// Convert an Unicode `str` to Punycode.
///
/// This is a convenience wrapper around `encode`.
#[inline]
pub fn encode_str(input: &str) -> Option<String> {
    encode(&input.chars().collect::<Vec<char>>())
}

/// Convert Unicode to Punycode.
///
/// Return None on overflow, which can only happen on inputs that would take more than
/// 63 encoded bytes, the DNS limit on domain name labels.
pub fn encode(input: &[char]) -> Option<String> {
    // Handle "basic" (ASCII) code points. They are encoded as-is.
    let output_bytes = input.iter().filter_map(|&c|
        if c.is_ascii() { Some(c as u8) } else { None }
    ).collect();
    let mut output = unsafe { String::from_utf8_unchecked(output_bytes) };
    let basic_length = output.len() as u32;
    if basic_length > 0 {
        output.push_str("-")
    }
    let mut code_point = INITIAL_N;
    let mut delta = 0;
    let mut bias = INITIAL_BIAS;
    let mut processed = basic_length;
    let input_length = input.len() as u32;
    while processed < input_length {
        // All code points < code_point have been handled already.
        // Find the next larger one.
        let min_code_point = input.iter().map(|&c| c as u32)
                                  .filter(|&c| c >= code_point).min().unwrap();
        if min_code_point - code_point > (u32::MAX - delta) / (processed + 1) {
            return None  // Overflow
        }
        // Increase delta to advance the decoder's <code_point,i> state to <min_code_point,0>
        delta += (min_code_point - code_point) * (processed + 1);
        code_point = min_code_point;
        for &c in input.iter() {
            let c = c as u32;
            if c < code_point {
                delta += 1;
                if delta == 0 {
                    return None  // Overflow
                }
            }
            if c == code_point {
                // Represent delta as a generalized variable-length integer:
                let mut q = delta;
                let mut k = BASE;
                loop {
                    let t = if k <= bias { T_MIN }
                            else if k >= bias + T_MAX { T_MAX }
                            else { k - bias };
                    if q < t {
                        break
                    }
                    let value = t + ((q - t) % (BASE - t));
                    value_to_digit(value, &mut output);
                    q = (q - t) / (BASE - t);
                    k += BASE;
                }
                value_to_digit(q, &mut output);
                bias = adapt(delta, processed + 1, processed == basic_length);
                delta = 0;
                processed += 1;
            }
        }
        delta += 1;
        code_point += 1;
    }
    Some(output)
}

#[inline]
fn value_to_digit(value: u32, output: &mut String) {
    let code_point = match value {
        0 ... 25 => value + 0x61,  // a..z
        26 ... 35 => value - 26 + 0x30,  // 0..9
        _ => panic!()
    };
    unsafe { output.as_mut_vec().push(code_point as u8) }
}

#[cfg(test)]
mod tests {
    use super::{decode, encode_str};
    use rustc_serialize::json::{Json, Object};

    fn one_test(description: &str, decoded: &str, encoded: &str) {
        match decode(encoded) {
            None => panic!("Decoding {} failed.", encoded),
            Some(result) => {
                let result = result.into_iter().collect::<String>();
                assert!(result == decoded,
                        format!("Incorrect decoding of {}:\n   {}\n!= {}\n{}",
                                encoded, result, decoded, description))
            }
        }

        match encode_str(decoded) {
            None => panic!("Encoding {} failed.", decoded),
            Some(result) => {
                assert!(result == encoded,
                        format!("Incorrect encoding of {}:\n   {}\n!= {}\n{}",
                                decoded, result, encoded, description))
            }
        }
    }

    fn get_string<'a>(map: &'a Object, key: &str) -> &'a str {
        match map.get(&key.to_string()) {
            Some(&Json::String(ref s)) => s,
            None => "",
            _ => panic!(),
        }
    }

    #[test]
    fn test_punycode() {

        match Json::from_str(include_str!("punycode_tests.json")) {
            Ok(Json::Array(tests)) => for test in tests.iter() {
                match test {
                    &Json::Object(ref o) => one_test(
                        get_string(o, "description"),
                        get_string(o, "decoded"),
                        get_string(o, "encoded")
                    ),
                    _ => panic!(),
                }
            },
            other => panic!("{:?}", other)
        }
    }
}


text:
package sampleclean.activeml

import org.apache.spark.mllib.linalg.Vector
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.rdd.RDD

/**
  * Parameters for the hardcoded label getter.
  * @param hardcodedLabeledData already labeled data.
  */
case class HardcodedLabelGetterParameters(hardcodedLabeledData: RDD[(String, LabeledPoint)])

/** Unused context for labeling points. */
case class HardcodedLabelGetterPointContext()

/** Unused shared context for labeling groups of points. */
case class HardcodedLabelGetterGroupContext()

/**
  * Dummy label getter that is initialized with labeled data and simply returns the labels when queried.
  * @constructor stores the already-labeled data for later retrieval.
  * @param parameters parameters for the label getter including the pre-labeled data.
  */
class HardCodedLabelGetter(parameters: HardcodedLabelGetterParameters)
  extends LabelGetter[HardcodedLabelGetterPointContext, HardcodedLabelGetterGroupContext, HardcodedLabelGetterParameters](parameters) {
  private val labelMap = Map(parameters.hardcodedLabeledData.map(p => p._1 -> p._2.label).collect() : _*)

  /**
    * Add previously-provided labels to an RDD of unlabeled points
    * @param points an RDD of unlabeled points (id, feature vector, point context).
    * @param groupContext group labeling context shared by all points.
    * @return an RDD of labeled points (id, feature vector)
    */
  override def addLabels(points: RDD[(String, Vector, HardcodedLabelGetterPointContext)], groupContext:HardcodedLabelGetterGroupContext): RDD[(String, LabeledPoint)] = {
    points.map(p => p._1 -> new LabeledPoint(labelMap(p._1), p._2))
  }

  /** do any necessary cleanup once the labelGetter is done being used. */
  override def cleanUp(): Unit = {}
}


text:
This is a site where you can practice chess openings. You select an opening from the list and then attempt to play it on the board. You are supposed to always respond with the most commonly played continuation. If you do not the move will be taken back and you try again. See the site here: http://cabanachess.com/

## Prep

First download the latest version of KingBase in PGN ZIP format here: http://www.kingbase-chess.net/

Unzip the file and rename the folder as KingBase/ in the project directory. Then run `prep/treeify_games.py`. If successful it should generate a games/ directory.

Next download the opening name PGN file from here: http://www.chessfiles.com/download-openings.html

Copy the file ecoe.pgn to the project directory and run `prep/build_openings.py`. If successful it should generate an openings.json file.

Finally, run `prep/logo.py` to create the logo and favicon.

## Running

Install node modules: `npm install`

Install forever: `npm install -g forever`

Then run: `forever start app.js`

By default the site will be accessible at http://localhost:3000/