text:
"""
DXAnalysis Handler
++++++++++++++++++

Analyses are DNAnexus entities that capture an instantiation of a
running workflow. They can be created from
:func:`dxpy.bindings.dxworkflow.DXWorkflow.run` or from an
existing analysis ID.

"""

from __future__ import (print_function, unicode_literals)

import time
import dxpy
from dxpy.bindings import (DXObject, )
from dxpy.exceptions import DXJobFailureError

##############
# DXAnalysis #
##############

class DXAnalysis(DXObject):
    '''
    Remote analysis object handler.
    '''

    _class = "analysis"

    def __init__(self, dxid=None):
        self._test_harness_result = None
        DXObject.__init__(self, dxid=dxid)
        self.set_id(dxid)

    def describe(self, fields=None, **kwargs):
        """
        :param fields: dict where the keys are field names that should
            be returned, and values should be set to True (by default,
            all fields are returned)
        :type fields: dict
        :returns: Description of the analysis
        :rtype: dict

        Returns a hash with key-value pairs containing information
        about the analysis

        """
        describe_input = {}
        if fields is not None:
            describe_input['fields'] = fields
        self._desc = dxpy.api.analysis_describe(self._dxid, describe_input, **kwargs)
        return self._desc

    def add_tags(self, tags, **kwargs):
        """
        :param tags: Tags to add to the analysis
        :type tags: list of strings

        Adds each of the specified tags to the analysis. Takes no
        action for tags that are already listed for the analysis.

        """

        dxpy.api.analysis_add_tags(self._dxid, {"tags": tags}, **kwargs)

    def remove_tags(self, tags, **kwargs):
        """
        :param tags: Tags to remove from the analysis
        :type tags: list of strings

        Removes each of the specified tags from the analysis. Takes
        no action for tags that the analysis does not currently have.

        """

        dxpy.api.analysis_remove_tags(self._dxid, {"tags": tags}, **kwargs)

    def set_properties(self, properties, **kwargs):
        """
        :param properties: Property names and values given as key-value pairs of strings
        :type properties: dict

        Given key-value pairs in *properties* for property names and
        values, the properties are set on the analysis for the given
        property names. Any property with a value of :const:`None`
        indicates the property will be deleted.

        .. note:: Any existing properties not mentioned in *properties*
           are not modified by this method.

        """

        dxpy.api.analysis_set_properties(self._dxid, {"properties": properties}, **kwargs)

    def wait_on_done(self, interval=2, timeout=3600*24*7, **kwargs):
        '''
        :param interval: Number of seconds between queries to the analysis's state
        :type interval: integer
        :param timeout: Maximum amount of time to wait, in seconds, until the analysis is done (or at least partially failed)
        :type timeout: integer
        :raises: :exc:`~dxpy.exceptions.DXError` if the timeout is reached before the analysis has finished running, or :exc:`~dxpy.exceptions.DXJobFailureError` if some job in the analysis has failed

        Waits until the analysis has finished running.
        '''

        elapsed = 0
        while True:
            state = self._get_state(**kwargs)
            if state == "done":
                break
            if state in ["failed", "partially_failed"]:
                desc = self.describe(**kwargs)
                err_msg = "Analysis has failed because of {failureReason}: {failureMessage}".format(**desc)
                if desc.get("failureFrom") != None and desc["failureFrom"]["id"] != desc["id"]:
                    err_msg += " (failure from {id})".format(id=desc['failureFrom']['id'])
                raise DXJobFailureError(err_msg)
            if state == "terminated":
                raise DXJobFailureError("Analysis was terminated.")

            if elapsed >= timeout or elapsed < 0:
                raise DXJobFailureError("Reached timeout while waiting for the analysis to finish")

            time.sleep(interval)
            elapsed += interval

    def terminate(self, **kwargs):
        '''
        Terminates the associated analysis.
        '''
        dxpy.api.analysis_terminate(self._dxid, **kwargs)

    def get_output_ref(self, field, index=None, metadata=None):
        '''
        :param field: Output field name of this analysis
        :type field: string
        :param index: If the referenced field is an array, optionally specify an index (starting from 0) to indicate a particular member of the array
        :type index: int
        :param metadata: If the referenced field is of a data object class, a string indicating the metadata that should be read, e.g. "name", "properties.propkey", "details.refgenome"
        :type metadata: string

        Returns a dict containing a valid reference to an output of this analysis.
        '''

        link = {"$dnanexus_link": {"analysis": self._dxid, "field": field}}
        if index is not None:
            link["$dnanexus_link"]["index"] = index
        if metadata is not None:
            link["$dnanexus_link"]["metadata"] = metadata
        return link

    def _get_state(self, **kwargs):
        '''
        :returns: State of the remote object
        :rtype: string

        Queries the API server for the analysis's state.

        Note that this function is shorthand for:

            dxanalysis.describe(**kwargs)["state"]

        '''

        return self.describe(fields=dict(state=True), **kwargs)["state"]


text:
<?php

	$module_info['name'] = 'Admin GroupDocs Comparison';

	$module_info['desc'] = 'Sign Word, Exel, PDF, Images and other files using GroupDocs Embed Key and File ID';

	$module_info['version'] = 1.0;

?>

redpajama_set_name: RedPajamaGithub


text:
package com.google.iosched.input.fetcher;

import com.google.gson.JsonElement;

import java.io.IOException;
import java.util.Map;

/**
 * Generic interface for a fetcher that knows how to fetch Json elements.
 *
 */
public interface EntityFetcher {
  JsonElement fetch(Enum<?> entityType, Map<String, String> params)
      throws IOException;
}


text:
'use strict';
const os = require('os');
const BinBuild = require('bin-build');
const log = require('logalot');
const bin = require('.');

const cpuNum = os.cpus().length;

bin.run(['-version'], err => {
	if (err) {
		log.warn(err.message);
		log.warn('mozjpeg pre-build test failed');
		log.info('compiling from source');

		let cfgExtras = '';
		if (process.platform === 'darwin') {
			cfgExtras = 'libpng_LIBS=\'/usr/local/lib/libpng16.a -lz\' --enable-static';
		}

		const cfg = [
			`./configure --disable-shared --disable-dependency-tracking --with-jpeg8 ${cfgExtras}`,
			`--prefix="${bin.dest()}" --bindir="${bin.dest()}" --libdir="${bin.dest()}"`
		].join(' ');

		const builder = new BinBuild()
			.src('https://github.com/mozilla/mozjpeg/releases/download/v3.2/mozjpeg-3.2-release-source.tar.gz')
			.cmd('autoreconf -fiv')
			.cmd(cfg)
			.cmd(`make -j${cpuNum}`)
			.cmd(`make install -j${cpuNum}`);

		return builder.run(err => {
			if (err) {
				log.error(err.stack);
				return;
			}

			log.success('mozjpeg built successfully');
		});
	}

	log.success('mozjpeg pre-build test passed successfully');
});


text: require File.dirname(__FILE__) + '/lib/dynamic_active_resource'


text:
package org.dasein.cloud.digitalocean.models.rest;

public enum ActionType {
	DROPLET, KEY, IMAGE;

	@Override
	public String toString() {
		switch(this) {
			case DROPLET:
				return "v2/droplets/%s/actions";
			case KEY:
				return "v2/account/keys/%s/actions";
            case IMAGE:
                return "v2/images/%s/actions";
			default:
				return "v2/????";
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_mediumAnimTime"
    android:toYDelta="0%p" />


text:
package me.hao0.session.redis;

import me.hao0.session.api.SessionManager;
import me.hao0.session.core.SessionFilter;
import java.io.IOException;

/**
 * Redis Session Filter
 */
public class RedisSessionFilter extends SessionFilter {

    /**
     * subclass create session manager
     * @return session manager
     */
    @Override
    protected SessionManager createSessionManager() throws IOException{
        return new RedisSessionManager();
    }
}


text: export { default } from 'ilios-common/components/save-button';


text: Just feel free to send PRs.


text:
package org.apache.pdfbox.preflight.process;

import java.util.List;

import org.apache.pdfbox.preflight.PreflightContext;
import org.apache.pdfbox.preflight.ValidationResult.ValidationError;

public abstract class AbstractProcess implements ValidationProcess
{

    protected void addValidationError(PreflightContext ctx, ValidationError error)
    {
        ctx.addValidationError(error);
    }

    protected void addValidationErrors(PreflightContext ctx, List<ValidationError> errors)
    {
        for (ValidationError error : errors)
        {
            addValidationError(ctx, error);
        }
    }
}


text:
Contributing to PETRARCH
========================

This page is still a bit of a work in progress.

Tutorial
--------

Walk through how to contribute some code/a function to PETRARCH. Explain how
the hooks work.

Tests
-----

Petrarch has a testing suite using pytest and TravisCI. This is run upon a
pull request to GitHub, and notfies us if your version passes. If you want
to test them yourself, just go into the main directory of Petrarch and run

    $ py.test

and the tests will be run. If it fails any tests, the PR will probably not
be accepted unless you provide a compelling reason.

Contributing Process
--------------------

You can check out the latest version of the Phoenix Pipeline by cloning this
repository using `git <http://git-scm.com/>`_.

::

    git clone https://github.com/openeventdata/petrarch.git

To contribute to the phoenix pipeline you should fork the repository,
create a branch, add to or edit code, push your new branch to your
fork of the phoenix pipeline on GitHub, and then issue a pull request.
See the example below:

::

    git clone https://github.com/YOUR_USERNAME/petrarch.git
    git checkout -b my_feature
    git add... # stage the files you modified or added
    git commit... # commit the modified or added files
    git push origin my_feature

Commit messages should first be a line, no longer than 80 characters,
that summarizes what the commit does. Then there should be a space,
followed by a longer description of the changes contained in the commit.
Since these comments are tied specifically to the code they refer to
(and cannot be out of date) please be detailed.

Note that ``origin`` (if you are cloning the forked the phoenix pipeline
repository to your local machine) refers to that fork on GitHub, *not*
the original (upstream) repository ``https://github.com/openeventdata/petrarch.git``.
If the upstream repository has changed since you forked and cloned it you can
set an upstream remote:

::

    git remote add upstream https://github.com/eventdata/phoenix_piepline.git

You can then pull changes from the upstream repository and rebasing
against the desired branch (in this example, development). You should
always issue pull requests against the development branch.

::

    git fetch upstream
    git rebase upstream/development

More detailed information on the use of git can be found in the `git
documentation <http://git-scm.com/documentation>`_.

Coding Guidelines
-----------------

The following are some guidelines on how new code should be written. Of
course, there are special cases and there will be exceptions to these
rules. However, following these rules when submitting new code makes the
review easier so new code can be integrated in less time.

Uniformly formatted code makes it easier to share code ownership. The
petrarch project tries to closely follow the official Python guidelines
detailed in `PEP8 <http://www.python.org/dev/peps/pep-0008/>`__ that
detail how code should be formatted and indented. Please read it and
follow it.

In addition, we add the following guidelines:

-  Use underscores to separate words in non-class names: n\_samples
   rather than nsamples.
-  Avoid multiple statements on one line. Prefer a line return after a
   control flow statement (if/for).
-  Use relative imports for references inside petrarch.
-  Please don't use ``import *``. It is considered harmful by the
   official Python recommendations. It makes the code harder to read as
   the origin of symbols is no longer explicitly referenced, but most
   important, it prevents using a static analysis tool like pyflakes to
   automatically find bugs in petrarch. Use the numpy docstring standard
   in all your docstrings.

These docs draw heavily on the contributing guidelines for
`scikit-learn <http://scikit-learn.org/>`_.


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

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

    <title>GPy.models.gp_heteroscedastic_regression — GPy  documentation</title>

    <link rel="stylesheet" href="../../../_static//default.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />

    <link rel="top" title="GPy  documentation" href="../../../index.html" />
    <link rel="up" title="GPy" href="../../GPy.html" />

Navigation

          index

          modules |

GPy  documentation »

Module code »

GPy »

Source code for GPy.models.gp_heteroscedastic_regression

# Copyright (c) 2012 - 2014 the GPy Austhors (see AUTHORS.txt)
# Licensed under the BSD 3-clause license (see LICENSE.txt)

import numpy as np
from ..core import GP
from .. import likelihoods
from .. import kern
from .. import util

[docs]class GPHeteroscedasticRegression(GP):
    """
    Gaussian Process model for heteroscedastic regression

    This is a thin wrapper around the models.GP class, with a set of sensible defaults

    :param X: input observations
    :param Y: observed values
    :param kernel: a GPy kernel, defaults to rbf
    """
    def __init__(self, X, Y, kernel=None, Y_metadata=None):

        Ny = Y.shape[0]

        if Y_metadata is None:
            Y_metadata = {'output_index':np.arange(Ny)[:,None]}
        else:
            assert Y_metadata['output_index'].shape[0] == Ny

        if kernel is None:
            kernel = kern.RBF(X.shape[1])

        #Likelihood
        #likelihoods_list = [likelihoods.Gaussian(name="Gaussian_noise_%s" %j) for j in range(Ny)]
        noise_terms = np.unique(Y_metadata['output_index'].flatten())
        likelihoods_list = [likelihoods.Gaussian(name="Gaussian_noise_%s" %j) for j in noise_terms]
        likelihood = likelihoods.MixedNoise(likelihoods_list=likelihoods_list)

        super(GPHeteroscedasticRegression, self).__init__(X,Y,kernel,likelihood, Y_metadata=Y_metadata)

[docs]    def plot(self,*args):
        return NotImplementedError

Quick search

    <form class="search" action="../../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

GPy  documentation »

Module code »

GPy »

        © Copyright 2013, Author.
      Created using Sphinx 1.3.1.


text:
title: Triangle of life
subtitle: Product Design
layout: default
modal-id: -desk
date: 2016-6-19
img: roundicons.png
thumbnail: earthquake-thumbnail.png
alt: image-alt
project-date: April 2014
client: Start Bootstrap
category: Web Development
description: Short-term Concept Product Design (2013)
link1: None

---

Triangle of Life is a student desk concept to provide a save space to hide in during earthquake.  When an earthquake happens, common students desks are not strong enough to serve as a protection from the building collapse. In many earthquake-prone regions, many teenagers died or injured because of the limited save space to hide. With Triangle of Life, once an earthquake strikes, students can quickly hide under the desks. Triangle of Life apples the structure of triangle which enhances stability. Having a handle inside, it is easy and convenient to be shut and create a stable triangular hollow space.
This three-day short design case was developed with three other team mates. My main contributions are concept development, product description and graphic design.


text: A HIDUsagePageTest is a test class for testing the behavior of HIDUsagePage


text:
import React from "react";
import { shallow } from "enzyme";
import { MarkedSlider, MarkedSliderProps } from "../marked_slider";
import { fakeImage } from "../../__test_support__/fake_state/resources";
import { MultiSlider, Slider } from "@blueprintjs/core";

describe("<MarkedSlider />", () => {
  const fakeProps = (): MarkedSliderProps => ({
    min: 0,
    max: 100,
    labelStepSize: 1,
    value: 10,
    images: [fakeImage(), fakeImage(), fakeImage()],
    onChange: jest.fn(),
    labelRenderer: jest.fn(),
    imageIndex: jest.fn(),
  });

  it("displays slider", () => {
    const p = fakeProps();
    const wrapper = shallow(<MarkedSlider {...p} />);
    expect(wrapper.find(Slider).length).toEqual(1);
    expect(wrapper.find(MultiSlider.Handle).length).toEqual(3);
  });
});


text:
var pluginstall = require('../pluginstall'),
    fs = require('fs'),
    et = require('elementtree'),
    configObj = {
        platform: 'android',
        projectPath: fs.realpathSync('test/project'),
        pluginPath: fs.realpathSync('test/plugin')
    };

exports['should exist'] = function (test) {
    test.equals(typeof pluginstall.parseXml, 'function');
    test.done();
}

exports['should return an object with an xmlDoc'] = function (test) {
    var dataObj = pluginstall.parseXml(configObj);

    test.equals(et.ElementTree, dataObj.xmlDoc.constructor);
    test.done();
}

exports['should return an object with the correct fields'] = function (test) {
    var dataObj = pluginstall.parseXml(configObj);

    test.equals('com.phonegap.plugins.childbrowser', dataObj._id);
    test.equals('0.6.0', dataObj.version);
    test.equals(2, dataObj.platforms.length);
    test.equals('android', dataObj.platforms[0]);

    test.done();
}


text:
/*
Problem 6. First larger than neighbours• Write a method that returns the index of the first element in array that is larger than its neighbours, or  -1 , if there's no such element.
• Use the method from the previous exercise.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class FirstLargerThanNeighbours
{
    static void Main()
    {
        Console.Write("Enter how many element will be in your array: ");
        int n = int.Parse(Console.ReadLine());
        int[] array = InputArray(n);
        int count = 0;
        for (int i = 0; i < array.Length; i++)
        {
            if (CkeckNeighbours(array, i))
            {
                Console.WriteLine("The index of the first element in array that is larger than its neighbours is: {0}", i);
                count++;
                return;
            }
        }

        if (count == 0) Console.WriteLine(-1);
    }
    static int[] InputArray(int length)
    {
        int[] array = new int[length];
        for (int i = 0; i < length; i++)
        {
            array[i] = int.Parse(Console.ReadLine());
        }
        return array;
    }
    static bool CkeckNeighbours(int[] array, int position)
    {
        bool result = false;
        if (position == 0)
        {
            return result = array[0] > array[1];
        }
        else if (position == array.Length - 1)
        {
            return result = array[position] > array[position - 1];
        }
        else
        {
            return result = (array[position] > array[position - 1] && array[position] > array[position + 1]);
        }
        return result;
    }

}


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

import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.spi.statistics.EmptyPlanStatisticsProvider;
import com.facebook.presto.spi.statistics.HistoryBasedPlanStatisticsProvider;
import com.facebook.presto.sql.planner.CachingPlanCanonicalInfoProvider;
import com.facebook.presto.sql.planner.PlanCanonicalInfoProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.inject.Inject;

import static java.util.Objects.requireNonNull;

public class HistoryBasedPlanStatisticsManager
{
    private final SessionPropertyManager sessionPropertyManager;
    private final PlanCanonicalInfoProvider planCanonicalInfoProvider;
    private final HistoryBasedOptimizationConfig config;

    private HistoryBasedPlanStatisticsProvider historyBasedPlanStatisticsProvider = EmptyPlanStatisticsProvider.getInstance();
    private boolean statisticsProviderAdded;

    @Inject
    public HistoryBasedPlanStatisticsManager(ObjectMapper objectMapper, SessionPropertyManager sessionPropertyManager, Metadata metadata, HistoryBasedOptimizationConfig config)
    {
        requireNonNull(objectMapper, "objectMapper is null");
        this.sessionPropertyManager = requireNonNull(sessionPropertyManager, "sessionPropertyManager is null");
        ObjectMapper newObjectMapper = objectMapper.copy().configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        this.planCanonicalInfoProvider = new CachingPlanCanonicalInfoProvider(newObjectMapper, metadata);
        this.config = requireNonNull(config, "config is null");
    }

    public void addHistoryBasedPlanStatisticsProviderFactory(HistoryBasedPlanStatisticsProvider historyBasedPlanStatisticsProvider)
    {
        if (statisticsProviderAdded) {
            throw new IllegalStateException("historyBasedPlanStatisticsProvider can only be set once");
        }
        this.historyBasedPlanStatisticsProvider = historyBasedPlanStatisticsProvider;
        statisticsProviderAdded = true;
    }

    public HistoryBasedPlanStatisticsCalculator getHistoryBasedPlanStatisticsCalculator(StatsCalculator delegate)
    {
        return new HistoryBasedPlanStatisticsCalculator(() -> historyBasedPlanStatisticsProvider, delegate, planCanonicalInfoProvider, config);
    }

    public HistoryBasedPlanStatisticsTracker getHistoryBasedPlanStatisticsTracker()
    {
        return new HistoryBasedPlanStatisticsTracker(() -> historyBasedPlanStatisticsProvider, sessionPropertyManager, config);
    }

    public PlanCanonicalInfoProvider getPlanCanonicalInfoProvider()
    {
        return planCanonicalInfoProvider;
    }
}


text:
"""
instances.py:
    Class to help manage the 'instances.json' file that has the data
    we'll use to determine cluster pricing.

    The thought here is that while the 'instances.json' file isn't
    _huge_, it's not small either, so I really don't want to fetch
    it more often than I have to. I'd rather fetch it at start time
    and cache it in memory, then refresh it at some interval.

    I could cache it to disk, but since this application runs more
    or less as a daemon, I think there's only minimal benefit of
    that (especially since while it is bigger than I'd like to
    continuously fetch from the internet, it's not too big to keep
    in memory). I could also use something like a Redis queue, and
    just munge the data to better fit that model (and it mostly fits
    out of the box), but then I'm taking on the overhead of running
    Redis, and I really don't think I'm getting any big gains from
    that.

    If you disagree, shoot me an e-mail!

Author: Corwin Brown <corwin@corwinbrown.com>
"""
from __future__ import print_function, absolute_import

import logging
from collections import defaultdict
from datetime import datetime, timedelta

import boto3
import requests

class AWSInstances(object):
    """
    Class for dealing with our 'instances.json' data.
    """

    def __init__(self, instances_json_url, cache_max_age):
        """
        Constructor.

        Args:
            instances_json_url (str):   The URL to use when fetching
                                            'instances.json'.
            cache_max_age (int):        The max age, in hours, of our
                                            cached instance data.
        """
        self.instances_json_url = instances_json_url
        self.cache_max_age = cache_max_age

        self._expire_time = None  # Track when our cached data expires.
        self._raw_data = None

        self.client = boto3.client('ec2')

        self._refresh_instances_json()

    @property
    def data(self):
        """
        Check if 'self.instances' is fresh enough, and then return
            the raw instance data.

        Returns:
          list
        """
        self._refresh_instances_json()

        return self._raw_data

    def get_instances(self, filter_instance_types=None):
        """
        Return all our instance data.

        Returns:
            dict
        """
        result = self.data
        if filter_instance_types:
            result = {k: v for k, v in result.iteritems()
                      if k in filter_instance_types}

        return self._json_wrapping(result=result)

    def get_instance_types(self,
                           filter_max_cpu=None,
                           filter_max_memory=None,
                           filter_max_storage=None):
        """
        Get all instance types. Filterable via CPU, Memory, and
            Storage requirements.

        Returns:
            dict
        """
        result = self.data
        if filter_max_cpu and result:
            result = {k: v for k, v in result.iteritems()
                      if v['vCPU'] <= int(filter_max_cpu)}
        if filter_max_memory and result:
            result = {k: v for k, v in result.iteritems()
                      if v['memory'] <= int(filter_max_memory)}
        if filter_max_storage and result:
            result = {k: v for k, v in result.iteritems()
                      if v['storage'] and v['storage']['size'] <= int(filter_max_storage)}

        return self._json_wrapping(result=result.keys())

    def get_instance_type(self, instance_type):
        """
        Return data on a single 'instance_type'.

        Args:
            instance_type (str):        The instance type to get data for.
        """

        return self._json_wrapping(result=self.data.get(instance_type))

    def get_prices(self, filter_instance_types=None):
        """
        Get pricing information for all instances. Filterable via
            instance type names.

        Args:
            filter_instance_types (list):   Instance type names to
                                                filter on.

        Returns:
            dict
        """
        result = self._get_pricing(instance_types=filter_instance_types)

        return self._json_wrapping(result=result)

    def get_price_instance_type(self, instance_type):
        """
        Get pricing data for a single instance type.

        Args:
            instance_type (str):    Name of the instance type to
                                        get pricing data for.

        Returns:
            dict
        """
        result = self._get_pricing(instance_types=[instance_type])

        return self._json_wrapping(result=result)

    def _get_pricing(self, instance_types=None):
        """
        Utility method to get pricing data via boto3. Really, this
            should live somewhere else since it's not really related
            to parsing our data file, but this will serve my
            purposes.

        ASSUMPTIONS:
            The purpose of this app is to generate data about a
                theoretical computer cluster in AWS. AWS only
                supports EMR on Linux. So I'm filtering down
                to only show Linux prices. In a traditonal project,
                this is when I'd ask for clarification, but this
                seems like a reasonable assumption. Also it allows
                me to format the data in a way that makes my life a
                little easier :)

        Args:
            instance_types (list):  List of instance types to filter
                                        on.

        Returns:
            dict
        """
        instance_types = instance_types or []
        raw_pricing_data = self.client.describe_spot_price_history(
            InstanceTypes=instance_types,
            ProductDescriptions=['Linux/UNIX'],
            StartTime=datetime.now() - timedelta(seconds=1),
            EndTime=datetime.now())

        spot_pricing_data = defaultdict(dict)
        for raw_price in raw_pricing_data.get('SpotPriceHistory', []):
            instance_type = raw_price['InstanceType']
            availability_zone = raw_price['AvailabilityZone']

            # I should only encounter each Availability Zone once....
            spot_pricing_data[instance_type][availability_zone] = {
                'spotPrice': raw_price['SpotPrice'],
                'timeStamp': raw_price['Timestamp'].strftime('%s')
            }

        return spot_pricing_data

    def _refresh_instances_json(self):
        """
        Check if 'self.instances' is fresh enough, and if not refresh
            it.
        """
        if self._expire_time and datetime.now() < self._expire_time:
            logging.debug('Refreshing instances cache...')
            return

        data = requests.get(self.instances_json_url).json()
        self._raw_data = self._clean_data(data)
        self._expire_time = (
            datetime.now() + timedelta(hours=self.cache_max_age))

    def _clean_data(self, data):
        """
        The data we're using has a boatload of information, and we
            really only need a little, so I'm going to clean it up
            a little bit. In a larger application, I'd use something
            like Marshmellow to marshall my data, but for this small
            usecase, I'm just going to prune the pricing data.

        The data is pruned for the following criteria:
            * We only really care about spot pricing, so we'll just
                pull out pricing data entirely, since it's a massive
                amount of data we don't need.

        I'm also performing exlusively reads, so let's reformat the
            data into a dict, so I can leverage lookups.

        Args:
            data (list):        The data to clean.

        Returns:
            list
        """
        data = {i.pop('instance_type'): i for i in data}

        result = {}
        for instance_type, attributes in data.iteritems():
            del attributes['pricing']
            result[instance_type] = attributes

        return data

    def _json_wrapping(self, **kwargs):
        """
        Return JSON friendly wrappings for our data.

        NOTE:
            'instances.json' uses both camelCase and snake_case, so
                I'm going to default to snake_case for no reason
                other than personal preference.

        Returns:
            dict
        """
        wrapping = {
            'expire_time': self._expire_time.strftime('%s'),
            'data_source': self.instances_json_url,
        }
        wrapping.update(kwargs)

        return wrapping


text:
/*
 * Decompiled with CFR 0_119.
 */
package systemCalls.image;

import java.awt.image.BufferedImage;
import script.InternalScriptError;
import script.Script;
import script.dataObjects.DataObject;
import script.dataObjects.IntObject;
import script.systemCalls.Trap;

public class Trap_GetPixelA
extends Trap {
    public Trap_GetPixelA(Script s) {
        super(s, "getPixelA");
    }

    @Override
    public DataObject apply() throws InternalScriptError {
        Object o = this.getObjParam(0, true);
        int x = this.getIntParam(1, true);
        int y = this.getIntParam(2, true);
        if (!(o instanceof BufferedImage)) {
            throw new InternalScriptError("Trap error: The first parameter handed to rescaleImage is no valid image!");
        }
        BufferedImage in = (BufferedImage)o;
        return new IntObject((in.getRGB(x, y) & -16777216) >> 24);
    }
}


text:
<?php

namespace Krillzip\Diatheke;

/**
 * Description of Exception
 *
 * @author krillzip
 */
class Exception extends \Exception{
    const NOT_INSTALLED = 1;
    const QUERY_BUILDER = 2;
    const REFERENCE_ERROR = 3;
    const CONFIGURATION_ERROR = 4;
    const DIATHEKE_ERROR = 5;
}


text:
<?php

/**
 * Style directive string value representation
 *
 * @package Document
 * @access private
 * @version //autogen//
 */
class ezcDocumentPcssStyleStringValue extends ezcDocumentPcssStyleValue
{
    /**
     * Parse value string representation
     *
     * Parse the string representation of the value into a usable
     * representation.
     *
     * @param string $value
     * @return void
     */
    public function parse( $value )
    {
        $this->value = (string) $value;

        return $this;
    }

    /**
     * Get regular expression matching the value
     *
     * Return a regular sub expression, which matches all possible values of
     * this value type. The regular expression should NOT contain any named
     * sub-patterns, since it might be repeatedly embedded in some box parser.
     *
     * @return string
     */
    public function getRegularExpression()
    {
        return '\S+';
    }

    /**
     * Convert value to string
     *
     * @return string
     */
    public function __toString()
    {
        return $this->value;
    }
}
?>


text:
require 'sinatra'
require 'sinatra/activerecord'
require 'pony'
require 'debugger'
require 'json'
require 'timezone'
require 'rack-flash'
require 'bcrypt'
require './env'

require_relative './helpers/helpers'
require_relative './controllers/user_controller'
require_relative './controllers/circle_controller'
require_relative './controllers/task_controller'
require_relative './controllers/alert_controller'

require_relative './models/task'


text:
XwalkExistingImpl::XwalkExistingImpl(
    scoped_ptr<DevToolsHttpClient> client,
    ScopedVector<DevToolsEventListener>& devtools_event_listeners)
    : XwalkImpl(client.Pass(),
                 devtools_event_listeners,
                 scoped_ptr<PortReservation>()) {}

XwalkExistingImpl::~XwalkExistingImpl() {}

std::string XwalkExistingImpl::GetOperatingSystemName() {
  return std::string();
}

Status XwalkExistingImpl::QuitImpl() {
  return Status(kOk);
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_char_07.cpp
Label Definition File: CWE415_Double_Free__new_delete.label.xml
Template File: sources-sinks-07.tmpl.cpp
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using new and Deallocae data using delete
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using delete
 * Flow Variant: 07 Control flow: if(staticFive==5) and if(staticFive!=5)
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

/* The variable below is not declared "const", but is never assigned
   any other value so a tool should be able to identify that reads of
   this will always give its initialized value. */
static int staticFive = 5;

namespace CWE415_Double_Free__new_delete_char_07
{

#ifndef OMITBAD

void bad()
{
    char * data;
    /* Initialize data */
    data = NULL;
    if(staticFive==5)
    {
        data = new char;
        /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */
        delete data;
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Possibly deleting memory twice */
        delete data;
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G1() - use badsource and goodsink by changing the second staticFive==5 to staticFive!=5 */
static void goodB2G1()
{
    char * data;
    /* Initialize data */
    data = NULL;
    if(staticFive==5)
    {
        data = new char;
        /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */
        delete data;
    }
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* do nothing */
        /* FIX: Don't attempt to delete the memory */
        ; /* empty statement needed for some flow variants */
    }
}

/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
    char * data;
    /* Initialize data */
    data = NULL;
    if(staticFive==5)
    {
        data = new char;
        /* POTENTIAL FLAW: delete data in the source - the bad sink deletes data as well */
        delete data;
    }
    if(staticFive==5)
    {
        /* do nothing */
        /* FIX: Don't attempt to delete the memory */
        ; /* empty statement needed for some flow variants */
    }
}

/* goodG2B1() - use goodsource and badsink by changing the first staticFive==5 to staticFive!=5 */
static void goodG2B1()
{
    char * data;
    /* Initialize data */
    data = NULL;
    if(staticFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        data = new char;
        /* FIX: Do NOT delete data in the source - the bad sink deletes data */
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Possibly deleting memory twice */
        delete data;
    }
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
    char * data;
    /* Initialize data */
    data = NULL;
    if(staticFive==5)
    {
        data = new char;
        /* FIX: Do NOT delete data in the source - the bad sink deletes data */
    }
    if(staticFive==5)
    {
        /* POTENTIAL FLAW: Possibly deleting memory twice */
        delete data;
    }
}

void good()
{
    goodB2G1();
    goodB2G2();
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE415_Double_Free__new_delete_char_07; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
define([
    'underscore',
    'contrail-model',
    'config/rbac/common/ui/js/models/rbacRulesModel',
    'config/rbac/common/ui/js/rbacUtils'
], function (_, ContrailModel, RBACRulesModel, RBACUtils) {
    var rbacUtils = new RBACUtils();
    var rbacModel = RBACRulesModel.extend({
        configRBAC: function (callbackObj, options) {
            return rbacUtils.configAllRBAC(this, callbackObj, options);
        },

        deleteRBAC: function(callbackObj, options) {
            return rbacUtils.deleteAllRBAC(callbackObj, options);
        }
    });
    return rbacModel;
});


text:
<?php

namespace Google\AdsApi\AdWords\v201809\o;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
abstract class Attribute
{

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

    /**
     * @var array $parameterMap
     */
    private $parameterMap = ['Attribute.Type' => 'AttributeType'];

    /**
     * @param string $AttributeType
     */
    public function __construct($AttributeType = null)
    {
      $this->AttributeType = $AttributeType;
    }

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

    /**
     * @param string $AttributeType
     * @return \Google\AdsApi\AdWords\v201809\o\Attribute
     */
    public function setAttributeType($AttributeType)
    {
      $this->AttributeType = $AttributeType;
      return $this;
    }

    /**
     * Getter for a non PHP standard named variables.
     *
     * @param string $var variable name to get
     * @return string variable value
     */
    public function __get($var)
    {
      if (!array_key_exists($var, $this->parameterMap)) {
        return null;
      }
      return $this->{$this->parameterMap[$var]};
    }

    /**
     * Setter for a non PHP standard named variables.
     *
     * @param string $var variable name
     * @param mixed $value variable value to set
     * @return \Google\AdsApi\AdWords\v201809\o\Attribute
     */
    public function __set($var, $value)
    {
      $this->{$this->parameterMap[$var]} = $value;
    }

}


text:
require 'sinatra'
#require 'sinatra/activerecord'
#require './config/environments' #database configuration
#require './models/model'        #Model class
require 'json'
require 'set'

$connections = {}
$conlist = []

def tuple(params)
  users,video = params["users"].sort,params["video"]
  return "#{params["users"].join(",")} => #{params["video"]}"
end

def validate_json(data)
  data && data['users'] && !data['users'].empty? && data['video']
end

def json_error(msg)
  return {Error: msg}.to_json
end

get '/' do
  'Noone should see this'
end

def mintime(hash)
  return hash.values.min
end

#This method checks if everyone is ok with stuff playing
post '/keepalive' do
  content_type :json
  user = @data['user']
  tnew = @data['time']
  conn = $conlist[@data['c_id'].to_i]
  time = conn[:time][user]
  puts ">>>>#{conn[:time][user]}"
  conn[:time][user] = time < tnew ? tnew : time
  #if conn[:seeking]
  return {skip: conn[:rdy].empty? , time: mintime(conn[:time])}.to_json
  #else
  #  return conn[:rdy].empty? ? 200 : 406
end

get '/redirect/:c_cid/:uid' do
end

get '/caguei/:c_id' do
  cid = params[:c_id].to_i
  $connections.delete($conlist[cid][:state])
  $conlist[cid] = nil
end

before do
  request.body.rewind
  body = request.body.read
  @data= JSON.parse body unless body.empty?
end

#=> Post:
#users: Arr(Str)    List of users IDs
#video: Int         Video id to be watched
#=> Return:
#session_id : Int   Session id for the watch
post '/start' do
  content_type :json
  return json_error("empty data")  unless validate_json(@data)
  state = tuple(@data)
  users = @data["users"]
  puts ">>>>>>#{users.inspect}"
  return json_error("duplicate video")  if $connections[state]
  num = ($conlist <<
         ($connections[state] =
          { rdy: Set.new(users),
            time:Hash[users.zip([0]*users.size)],
            state: state})).size
  return {session_id: num-1}.to_json
end

#This method signals that the user is ready and waiting for the others
#=> Post:
#c_id: Int          Connection ID for the session
#user: Int          User ID
#=> Return
#ack: Bool          Everything is OK
post '/play' do
  id,user = ["c_id","user"].map{|x| @data[x]}
  return json_error("missing user") unless user
  return json_error("video not registered") unless id && $conlist[id]
  $conlist[id][:rdy].delete(user)
  ncon = $conlist[id][:rdy]
  return {ok: $conlist[id][:rdy].to_a}.to_json
end

#The user stopped the player
#=> Post:
#c_id: Int          Connection ID for the session
#user: Int          User ID
#=> Return
#ack: Bool          Everything is OK
post '/stop' do
  id,user = ["c_id","user"].map{|x| @data[x]}
  return json_error("missing user") unless user
  return json_error("video not registered") unless id && $conlist[id]
  $conlist[id][:rdy].add(user)
  ncon = $conlist[id][:rdy]
  return {ok: ncon.empty?}.to_json
end

post '/seek' do
  id,user,time = ["c_id",'user',"time"].map{|x| @data[x]}
  puts $conlist.inspect
  con = $conlist[id]
  con[:time].each do |k,v|
    con[:time][k] = time.to_i
  end
  con[:rdy] = Set.new(con[:time].keys.select{|x| x != user})
end

post '/seek-ack' do
  id,user= ["c_id","user"].map{|x| @data[x]}
  $conlist[id][:rdy].delete(user)
end

options '/*' do
  response.headers["Access-Control-Allow-Origin"] = "*"
  response.headers["Access-Control-Allow-Methods"] = "POST, GET"
  response.headers["Access-Control-Allow-Headers"] = "origin, content-type, accept"
end

after do
  response['Access-Control-Allow-Origin'] = "*"
end


text:
import { observable, action } from 'mobx';

class ReservedTokenStore {

  @observable tokens;

  constructor(tokens = []) {
    this.tokens = tokens;
  }

  @action addToken = (token) => {
    this.tokens.push(token);
  }

  @action setTokenProperty = (index, property, value) => {
    let newToken = {...this.tokens[index]};
    newToken[property] = value;
    this.tokens[index] = newToken;
  }

  @action removeToken = (index) => {
    this.tokens.splice(index,1);
  }

  findToken(inputToken) {
    return this.tokens.find((token) => {
      if (inputToken['dim'] === token['dim'] && inputToken['addr'] === token['addr'] && inputToken['val'] === token['val']) {
        return true;
      }

      return false;
    });
  }
}

const reservedTokenStore = new ReservedTokenStore();

export default reservedTokenStore;
export { ReservedTokenStore };


text:
C++ spell check

spell [-v] [-x] [-d <dct>]... [-w <dict_ext>]... [-e <text_ext>]... <input>...

spell reads words from text files and checks them against words in dictionary files.

The following arguments may be provided:

  -d <dictionary_name> : add a dictionary name or directory to search
     for directory names. If a directory name is entered files with
     extensions defined by -w arguments will be loaded. Dictonary names
     may also be defined using the SPELL_DICTIONARIES environment variable.

  -w <dictonary_extension> : Specify an extension for dictionary files.
     You may specify multiple -w arguments. This is used when a directory
     name is specified by a -d argument. If no extensions are provided
     the default dictionary extension is "dict".

  -e <text_extension> : specify an extension for text files.
     You may specify multiple -e arguments. This is used when a directory
     name is specified as an input file argument. If no extensions are provided
     the default text file extension is "txt".

  -v : verbose mode - show dictionaries and filenames as they are processed.

  -x : no run - show which dictionary and input files will be processed.

  -c : no env - do not load dictionaries from SPELL_DICTIONARIES

  -t : do not show lines containing mispelled words - no text

  -n : Show near matches - words that are similar but not exactly in a dirctionary.

  -h or -?: show this help

  input : All arguments following flags are taken as input files to process.

The SPELL_DICTIONARIES environment variable can be used to specify which
dictionary files to read. Dictionary files and directories are separated by
colon characters.

The current value of SPELL_DICTIONARIES is "/Users/daniel/dictionaries"

Words must start with a letter and may only contain letters or the following
other characters: _'

-------

A dictionary file is a newline-separated list of words. The spell program will allow
variations, such as words with different case or words that have s or 's following the
dictionary word.

This has a simple makefile. No configure or install.

English word lists can be found at: http://wordlist.sourceforge.net/

Put these into your dictionaries directory.

This spell program will look for a list of text files in a directory tree for
each directory specified by a -d argument, or as listed in the SPELL_DICTIONARIES
environment variable.

All text files with the required extension in the directory tree rooted at the current
directory.

See examples/runme


text:
#ifndef RBX_BUILTIN_DATA_HPP
#define RBX_BUILTIN_DATA_HPP

#include "builtin/object.hpp"
#include "type_info.hpp"

namespace rubinius {
  // Copied from here because you can't include capi/include/ruby.h into
  // our C++ files.
  struct RDataShadow {
    void (*dmark)(void*);
    void (*dfree)(void*);
    void *data;
  };

  class Data : public Object {
  public:
    const static object_type type = DataType;

  public:   /* Types */
    /** The signature for the mark function. */
    typedef   void (*MarkFunctor)(void*);

    /** The signature for the free function. */
    typedef   void (*FreeFunctor)(void*);

  private:
    void (*dmark_)(void*);
    void (*dfree_)(void*);
    void *data_;

  public:   /* Interface */

    /**  Register class with the VM. */
    static void   init(STATE);

    /** New Data instance. */
    static Data*  create(STATE, void* data, MarkFunctor mark, FreeFunctor free);

    static void finalize(STATE, Data* data);

    RDataShadow* rdata(STATE);
    void* data(STATE);
    FreeFunctor free(STATE);
    MarkFunctor mark(STATE);

  public:   /* TypeInfo */

    class Info : public TypeInfo {
    public:
      Info(object_type type) : TypeInfo(type) { }
      virtual void mark(Object* t, ObjectMark& mark);
      virtual void auto_mark(Object* obj, ObjectMark& mark) {}
    };
  };

}

#endif


text:
package server.entity;

import io.vertx.core.json.JsonObject;
import io.vertx.rxjava.core.Future;
import io.vertx.rxjava.ext.web.Cookie;
import io.vertx.rxjava.ext.web.RoutingContext;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.stream.Stream;

import static io.vertx.rxjava.core.Future.succeededFuture;

/**
 * Handles getting strings from ResourceBundles.
 */
public enum Language {
    ENGLISH(Locale.UK),
    ESTONIAN(new Locale.Builder().setLanguage("et").setScript("Latn").setRegion("EE").build()),
    GERMAN(new Locale.Builder().setLanguage("de").setScript("Latn").setRegion("GR").build());

    public static final String LANGUAGE = "lang";
    private final Locale locale;
    private final ResourceBundle bundle;

    Language(Locale locale) {
        this.locale = locale;
        this.bundle = ResourceBundle.getBundle("messages", locale, new UTF8Control());
    }

    public static String getString(String key, String lang) {
        return key == null ? null : getLanguageOrDefault(lang).getString(key);
    }

    public static String getString(String key, RoutingContext ctx) {
        Cookie lang = ctx.getCookie(LANGUAGE);
        return getString(key, lang != null ? lang.getValue() : null);
    }

    public static Future<JsonObject> getJsonTranslations(String lang) {
        ResourceBundle bundle = getLanguageOrDefault(lang).getBundle();
        return succeededFuture(bundle.keySet().stream()
                .collect(JsonObject::new, (json, key) -> json.put(key, bundle.getString(key)), JsonObject::mergeIn));
    }

    public static String validate(String lang) {
        return getLanguageOrDefault(lang).getLocale().getLanguage();
    }

    private static Language getLanguageOrDefault(String lang) {
        return Stream.of(values())
                     .filter(language -> language.getLocale().getLanguage().equals(lang))
                     .findAny()
                     .orElse(ENGLISH);
    }

    public Locale getLocale() {
        return locale;
    }

    public ResourceBundle getBundle() {
        return bundle;
    }

    public String getString(String key) {
        return bundle.getString(key);
    }

    /**
     * Implementation of reading a ResourceBundle in UTF-8 format.
     */
    private static class UTF8Control extends ResourceBundle.Control {
        @Override
        public ResourceBundle newBundle(String baseName, Locale locale, String format,
                                        ClassLoader loader, boolean reload) throws IOException {
            String bundleName = toBundleName(baseName, locale);
            String resourceName = toResourceName(bundleName, "properties");
            ResourceBundle bundle = null;
            InputStream stream = null;
            if (reload) {
                URL url = loader.getResource(resourceName);
                if (url != null) {
                    URLConnection connection = url.openConnection();
                    if (connection != null) {
                        connection.setUseCaches(false);
                        stream = connection.getInputStream();
                    }
                }
            } else {
                stream = loader.getResourceAsStream(resourceName);
            }
            if (stream != null) {
                try {
                    bundle = new PropertyResourceBundle(new InputStreamReader(stream, StandardCharsets.UTF_8));
                } finally {
                    stream.close();
                }
            }
            return bundle;
        }
    }
}


text:
<?php

/**
 * Includes
 */
require_once 'CouchDBCommand.php';

/**
 * Get Attachment Command
 *
 * @package Commands
 * @author Adam Venturella
 */
class GetAttachment implements CouchDBCommand
{
	private $database;
	private $name;
	private $document;

	/**
	 * undocumented function
	 *
	 * @param string $database
	 * @param string $document
	 * @param string $name
	 * @author Adam Venturella
	 */
	public function __construct($database, $document, $name)
	{
		$this->database     = $database;
		$this->document     = $document;
		$this->name         = $name;
	}

	public function request()
	{
		 return <<<REQUEST
GET /$this->database/$this->document/$this->name HTTP/1.0
Connection: close
{authorization}

REQUEST;
	}

	public function __toString()
	{
		return 'GetAttachment';
	}
}
?>


text:
/**
 * Utilities for WindGate DMDL.
 */
package com.asakusafw.dmdl.windgate.util;


text:
layout: page
subheadline: "Tech"
title: 'Hiver Canadien: Check'
date: 2014-04-14 00:00:34+00:00
teaser: "Le printemps est enfin de retour après un rude hiver Canadien... "
header:
    image_fullwidth: "blog/2014/04/canada-winter-niagara.jpg"
    caption: Image by Dawn Armfield
    caption_url: "http://darmfield.com/photos"
image:
    thumb:  blog/2014/04/canada-winter-niagara_150x150.jpg
    homepage: blog/2014/04/canada-winter-niagara.jpg
categories:
    - tech
comments: false
show_meta: true
redirect_from:
    - /en/2014/04/14/hiver-canadien-check/
    - /fr/2014/04/14/hiver-canadien-check/
    - /2014/04/14/hiver-canadien-check/
---

Plusieurs tempêtes de neiges, des températures si fraiches que l'aéroport de Toronto a été [immobilisé pendant plusieurs heures](http://www.huffingtonpost.ca/2013/12/23/ice-storm-flight-cancellations_n_4492279.html).

Pendant ce temps, nos Webcampak ont continué à fonctionner normalement et à capturer leurs clichés comme prévu.

Bien que les composants intégrés au sein du Webcampak soient annoncés pour des températures "extrêmes", bien que nos Webcampak aient rencontré par le passé des températures très fraiches (jusque -15 C en France) il subsistait une très légère incertitude quand à la capacité du Webcampak à fonctionner à la limite (voir au delà) de ses spécifications techniques.

Et ce fut chose faite cet hiver.

A Montreal, en Janvier 2014, la température moyenne était de -10.2 C et est descendue jusque[ -27.3 C](http://montreal.weatherstats.ca/metrics/temperature.html) sous abri.

[![]({{ site.urlimg }}blog/2014/04/Webcampak-Montreal-JAN2014.png)]({{ site.urlimg }}blog/2014/04/Webcampak-Montreal-JAN2014.png)

**Températures au sein d'un Webcampak, à Montréal, le 8 Janvier 2014**

Le dispositif de chauffage et de dégivrage intégrés ont très bien rempli leurs rôles, avec de très rares incursions en dessous de 0 C au sein du Webcampak.

Si vous avez un projet dans le grand nord, nous sommes prêts à relever le défi !


text:
* Design: https://github.com/ArialBlack/Decl.in.ua
* Form to digitize scanned declarations: https://github.com/dimanech/form
* Our crowdsourcing framework that'll be used to crowdsource digitization process: https://github.com/mrgambal/vulyk
* Assorted scripts to cleanup data: https://github.com/dchaplinsky/open-declaration

#### R pre-requisites to generate analytics
First of all install ```R 3.1``` or newer

then run ```R``` and install following packages:
* ```install.packages('knitrBootstrap')```
* ```install.packages('ggplot2')```
* ```install.packages('dplyr')```
* ```install.packages('xtable')```
* ```install.packages('scales')```
* ```install.packages('doBy')```


text:
A Clojure durable queue implementation on top of postgresql using
postgresql's advisory locks to provide non-blocking take,
such that concurrent workers do not block each other.

## Installation

[Leiningen](https://github.com/technomancy/leiningen) dependency information:

```clj
[com.layerware/pgqueue "0.5.1"]
```

## Recent Changes

 - 0.5.1 dependency updates
 - 0.5.0 is the same API as 0.4.1, but has dependency version bumps with potentially-breaking changes:
   - `clojure.java.jdbc 0.6.x` Ensure that your app is otherwise
     compatible with `clojure.java.jdbc 0.6.x` breaking changes. See
     the
     [CHANGELOG](https://github.com/clojure/java.jdbc/blob/master/CHANGES.md).
   - `nippy` encoding updates require that you remove/empty your
     pgqueue queues before upgrading and re-queue these items after
     upgrading.  If you do not need to save your current queues, you
     can simple delete the pgqueues table for the same effect.
 - 0.4.1 fix (harmless) warning about rollback w/ autocommit on
 - 0.4.0 `pgqueue` namespace moved to `pgqueue.core` per [Clojure style guidelines](https://github.com/bbatsov/clojure-style-guide#no-single-segment-namespaces)
 - 0.3.4 Fixes reconnect bug
 - 0.3.3 Added `:analyze-threshold` option to `pgqueue.core/queue`

## Usage

```clj
(require '[pgqueue.core :as pgq])

; Define a queue config
(def q-config {:db {:subprotocol "postgresql"
                    :subname "//127.0.0.1:5432/pgtest"
                    :user "pgtest"
                    :password "pgtest"}})

;; Create a queue with a name and config
(def q (pgq/queue :my-queue q-config))

;; Put items on the queue
(pgq/put q :a) ;=> true
(pgq/put q :b) ;=> true

;; Put nil is a no-op
(pgq/put q nil) ;=> nil

;; How many?
(pgq/count q) ;=> 2

;; Take items off the queue
(pgq/take q) ;=> :a
(pgq/take q) ;=> :b
(pgq/take q) ;=> nil

;; Safely take item from queue using pgqueue/take-with.
;; If the work in the body crashes, the item is
;; unlocked for other workers to take it instead.

;; Successful case
(pgq/put q :success)
(pgq/take-with [item q]
  ; item is locked
  ; do work here
  (Thread/sleep 20))
  ; item is unlocked/deleted

;; Failure case
(pgq/put q :failme)
(pgq/take-with [item q]
  ; item is locked
  (throw (ex-info "FAIL!" {}))) ;=> ExceptionInfo FAIL!

;; it's OK, item is safe for the next taker:
(pgq/take q) ;=> :failme

;; pgqueue is also a priority queue
;; For put with arity of 2, a default priority of 100 is used.
;;   (see pgqueue/queue docs to set a default priority for a queue)
;; For put with arity of 3, the second argument is a priority integer
;; where a lower value = higher priority; negative integers are ok
(pgq/put q 500 "least")
(pgq/put q 200 "low")
(pgq/put q 100 "medium")
(pgq/put q 1   "high")
(pgq/put q -10 "urgent")

(pgq/take q) ;=> "urgent"
(pgq/take q) ;=> "high"
(pgq/take q) ;=> "medium"
(pgq/take q) ;=> "low"
(pgq/take q) ;=> "least"

;; Put a batch
(pgq/put-batch q [1 2 3]) ;=> true

;; Take a batch
(pgq/take-batch q 3) ;=> [1 2 3]

```

## Documentation

[API Docs] (http://layerware.github.io/pgqueue)

## Why use pgqueue?

pgqueue is a middle-ground queueing solution between file-based
durable queues and larger queue/messaging servers.

If you are already using postgresql for your database and don't
need a heavy-load queueing solution, pgqueue might be the right fit.

Benefits of pgqueue include:
 - concurrent, non-blocking take across multiple processes
   and across multiple JVM threads
 - safely take an item for work (pgqueue/take-with) and
   ensure that item is unlocked in the event of a crash/exception
 - backing up your postgresql database backs up your queues, too!

## Performance

Obviously, a queue implementation on a relational database is going
to perform more slowly than a dedicated queuing server.  That said,
pgqueue's use of postgresql's advisory locks is likely faster than
a strategy that locks a row for update.

See the perf project in this repository to run a performance test
on your hardware.

Here are the results from a Linode 2048
  (2GB RAM, SSD, 2 x Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz)
using the following JVM options in project.clj:
```
jvm-opts ^:replace ["-Xmx1g" "-Xms1g" "-server"]
```

```
PGQUEUE_CONFIG=./perf.config.edn lein run -m pgqueue.perf
pgqueue perf test

       put     100 integers...    483ms duration   0.207/ms (   207/s) avg rate
      take     100 integers...    495ms duration   0.202/ms (   202/s) avg rate
 put-batch     100 integers...     51ms duration   1.961/ms (  1961/s) avg rate
take-batch     100 integers...    192ms duration   0.521/ms (   521/s) avg rate

       put    1000 integers...   1265ms duration   0.791/ms (   791/s) avg rate
      take    1000 integers...   3171ms duration   0.315/ms (   315/s) avg rate
 put-batch    1000 integers...    428ms duration   2.336/ms (  2336/s) avg rate
take-batch    1000 integers...   1779ms duration   0.562/ms (   562/s) avg rate

       put   10000 integers...   9312ms duration   1.074/ms (  1074/s) avg rate
      take   10000 integers...  33683ms duration   0.297/ms (   297/s) avg rate
 put-batch   10000 integers...   2419ms duration   4.134/ms (  4134/s) avg rate
take-batch   10000 integers...  20792ms duration   0.481/ms (   481/s) avg rate
```

## License

Copyright © 2018 Layerware, Inc.

Distributed under the [Apache License, Version 2.0] (http://www.apache.org/licenses/LICENSE-2.0.html)


text:
package com.facebook.cache.disk;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/** Test for the score-based eviction comparator. */
@RunWith(PowerMockRunner.class)
@PrepareForTest({System.class})
public class ScoreBasedEvictionComparatorSupplierTest {

  private static final long RANDOM_SEED = 42;

  private List<DiskStorage.Entry> entries;

  @Before
  public void setUp() {
    Random random = new Random(RANDOM_SEED);

    PowerMockito.mockStatic(System.class);
    when(System.currentTimeMillis()).thenAnswer((Answer<Long>) invocation -> 0L);

    entries = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
      DiskStorage.Entry entry = mock(DiskStorage.Entry.class);
      when(entry.getTimestamp()).thenReturn(random.nextLong());
      when(entry.getSize()).thenReturn(random.nextLong());
      entries.add(entry);
    }
  }

  @Test
  public void testTimestampOnlyOrder() {
    doTest(1f, 0f);
    for (int i = 0; i < entries.size() - 1; i++) {
      assertTrue(entries.get(i).getTimestamp() < entries.get(i + 1).getTimestamp());
    }
  }

  @Test
  public void testSizeOnlyOrder() {
    doTest(0f, 1f);
    for (int i = 0; i < entries.size() - 1; i++) {
      assertTrue(entries.get(i).getSize() > entries.get(i + 1).getSize());
    }
  }

  @Test
  public void testEqualOrder() {
    doTest(1f, 1f);
  }

  @Test
  public void testWeightedOrder() {
    doTest(2f, 3f);
  }

  private void doTest(float ageWeight, float sizeWeight) {
    ScoreBasedEvictionComparatorSupplier supplier =
        new ScoreBasedEvictionComparatorSupplier(ageWeight, sizeWeight);
    Collections.sort(entries, supplier.get());

    for (int i = 0; i < entries.size() - 1; i++) {
      assertTrue(
          supplier.calculateScore(entries.get(i), 0)
              > supplier.calculateScore(entries.get(i + 1), 0));
    }
  }
}


text:
package br.com.ceducarneiro.exerciciofinal.controller;

public interface SyncListener {

    void onSyncSuccess();
    void onSyncError();

}


text:
/**
 * This file is generated by Sencha Cmd and should NOT be edited.  It will
 * redirect to the most recently built example css file for the application to
 * support capture of theme background, frame, and corner images for non-CSS3
 * browsers.
 */
@import '../../build/production/resources/Muleview-example.css';


text:
This example implements five layered images and three independent containers
running the PostgreSQL database.

The images are build on top of the other in this order:
_base_ ⇒ _common_ ⇒ _server_ ⇒ _database_ ⇒ _buildtime_.

The containers run three different database implementations:

1. Plain clean database ([`database.shed`](database.shed)).

1. Database with data inserted at image build time ([`buildtime.shed`](buildtime.shed)).

1. Database with data inserted at container start time ([`starttime.shed`](starttime.shed)).

Also is provided the interactive client container ([`client.shed`](client.shed)) for the build time database.

How to test:

1. Create images and containers:

        shed-hub build      # 'shed-hub build --remove' to start again

2. Test **postgres_database** container. First start database:

        shed-container start postgres_database

    And then connect with password from `pwfile.txt` file:

        psql -h 127.0.0.1 -U postgres

    or without password

        shed-container exec -it postgres_database psql

    or

        shed-container exec -it postgres_database sh
        sh-4.2$ psql    # inside the container

3. Test **postgres_buildtime** container.

        shed-container start postgres_buildtime
        psql -h 127.0.0.2 -U postgres
        shed-container start -ai postgres_client

4. Test **postgres_starttime** container.

        shed-container start postgres_starttime
        shed-container logs postgres_starttime
        psql -h 127.0.0.3 -U postgres

5. Verify all three databases are running simultaneously:

        shed-container ps


text:
<?php

namespace Mpwar\CoreDomain\Exam;

use Mpwar\CoreDomain\Exam\ExamId;
use Mpwar\CoreDomain\Exam\Exam;

interface ExamRepository
{
    /**
     * @param Exam $Exam
     *
     * @return void
     */
    public function add(Exam $exam);

    /**
     * @param Exam $Exam
     *
     * @return void
     */
    public function update(Exam $exam);

    /**
     * @return Array|null
     */
    public function search();

    /**
     * @return Exam|null
     */
    public function findById($id);

    /**
     * @param Exam $Exam
     *
     * @return void
     */
    public function delete(Exam $exam);
}


text:
<script>
const scriptURL = 'worklet_script_fetch.js';

// Test AudioWorklet.
const audioContext = new OfflineAudioContext(2,44100*40,44100);
const audioWorkletPromise = audioContext.audioWorklet.addModule(scriptURL);

// Test PaintWorklet.
const paintWorkletPromise = CSS.paintWorklet.addModule(scriptURL);

// TODO(https://crbug.com/1011208): Test AnimationWorklet and LayoutWorklet.

const promises = [audioWorkletPromise, paintWorkletPromise];
Promise.allSettled(promises)
  .then(results => {
    // The subresource filter should pass or block them all.
    const numOfSuccess = results.filter(r => r.status === 'fulfilled').length;
    if (numOfSuccess === promises.length)
      document.title = 'FetchSucceeded';
    else if (numOfSuccess === 0)
      document.title = 'FetchFailed';
    else
      document.title = 'FetchPartiallyFailed';
  });
</script>


text:
class AutocompleteProvider;
class Profile;
class TemplateURL;

namespace base {
class Time;
}  // namespace base

// AutocompleteMatch ----------------------------------------------------------

// A single result line with classified spans.  The autocomplete popup displays
// the 'contents' and the 'description' (the description is optional) in the
// autocomplete dropdown, and fills in 'fill_into_edit' into the textbox when
// that line is selected.  fill_into_edit may be the same as 'description' for
// things like URLs, but may be different for searches or other providers.  For
// example, a search result may say "Search for asdf" as the description, but
// "asdf" should appear in the box.
struct AutocompleteMatch {
  // Autocomplete matches contain strings that are classified according to a
  // separate vector of styles.  This vector associates flags with particular
  // string segments, and must be in sorted order.  All text must be associated
  // with some kind of classification.  Even if a match has no distinct
  // segments, its vector should contain an entry at offset 0 with no flags.
  //
  // Example: The user typed "goog"
  //   http://www.google.com/        Google
  //   ^          ^   ^              ^   ^
  //   0,         |   15,            |   4,
  //              11,match           0,match
  //
  // This structure holds the classification information for each span.
  struct ACMatchClassification {
    // The values in here are not mutually exclusive -- use them like a
    // bitfield.  This also means we use "int" instead of this enum type when
    // passing the values around, so the compiler doesn't complain.
    enum Style {
      NONE  = 0,
      URL   = 1 << 0,  // A URL
      MATCH = 1 << 1,  // A match for the user's search term
      DIM   = 1 << 2,  // "Helper text"
    };

    ACMatchClassification(size_t offset, int style)
        : offset(offset),
          style(style) {
    }

    // Offset within the string that this classification starts
    size_t offset;

    int style;
  };

  typedef std::vector<ACMatchClassification> ACMatchClassifications;

  // Type used by providers to attach additional, optional information to
  // an AutocompleteMatch.
  typedef std::map<std::string, std::string> AdditionalInfo;

  // The type of this match.
  enum Type {
    URL_WHAT_YOU_TYPED = 0,  // The input as a URL.
    HISTORY_URL,             // A past page whose URL contains the input.
    HISTORY_TITLE,           // A past page whose title contains the input.
    HISTORY_BODY,            // A past page whose body contains the input.
    HISTORY_KEYWORD,         // A past page whose keyword contains the input.
    NAVSUGGEST,              // A suggested URL.
    SEARCH_WHAT_YOU_TYPED,   // The input as a search query (with the default
                             // engine).
    SEARCH_HISTORY,          // A past search (with the default engine)
                             // containing the input.
    SEARCH_SUGGEST,          // A suggested search (with the default engine).
    SEARCH_OTHER_ENGINE,     // A search with a non-default engine.
    EXTENSION_APP,           // An Extension App with a title/url that contains
                             // the input.
    NUM_TYPES,
  };

  // Null-terminated array of characters that are not valid within |contents|
  // and |description| strings.
  static const char16 kInvalidChars[];

  AutocompleteMatch();
  AutocompleteMatch(AutocompleteProvider* provider,
                    int relevance,
                    bool deletable,
                    Type type);
  AutocompleteMatch(const AutocompleteMatch& match);
  ~AutocompleteMatch();

  // Converts |type| to a string representation.  Used in logging and debugging.
  AutocompleteMatch& operator=(const AutocompleteMatch& match);

  // Converts |type| to a string representation.  Used in logging.
  static std::string TypeToString(Type type);

  // Converts |type| to a resource identifier for the appropriate icon for this
  // type.
  static int TypeToIcon(Type type);

  // Comparison function for determining when one match is better than another.
  static bool MoreRelevant(const AutocompleteMatch& elem1,
                           const AutocompleteMatch& elem2);

  // Comparison functions for removing matches with duplicate destinations.
  // Destinations are compared using |stripped_destination_url|.
  static bool DestinationSortFunc(const AutocompleteMatch& elem1,
                                  const AutocompleteMatch& elem2);
  static bool DestinationsEqual(const AutocompleteMatch& elem1,
                                const AutocompleteMatch& elem2);

  // Helper functions for classes creating matches:
  // Fills in the classifications for |text|, using |style| as the base style
  // and marking the first instance of |find_text| as a match.  (This match
  // will also not be dimmed, if |style| has DIM set.)
  static void ClassifyMatchInString(const string16& find_text,
                                    const string16& text,
                                    int style,
                                    ACMatchClassifications* classifications);

  // Similar to ClassifyMatchInString(), but for cases where the range to mark
  // as matching is already known (avoids calling find()).  This can be helpful
  // when find() would be misleading (e.g. you want to mark the second match in
  // a string instead of the first).
  static void ClassifyLocationInString(size_t match_location,
                                       size_t match_length,
                                       size_t overall_length,
                                       int style,
                                       ACMatchClassifications* classifications);

  // Converts classifications to and from a serialized string representation
  // (using comma-separated integers to sequentially list positions and styles).
  static std::string ClassificationsToString(
      const ACMatchClassifications& classifications);
  static ACMatchClassifications ClassificationsFromString(
      const std::string& serialized_classifications);

  // Adds a classification to the end of |classifications| iff its style is
  // different from the last existing classification.  |offset| must be larger
  // than the offset of the last classification in |classifications|.
  static void AddLastClassificationIfNecessary(
      ACMatchClassifications* classifications,
      size_t offset,
      int style);

  // Removes invalid characters from |text|. Should be called on strings coming
  // from external sources (such as extensions) before assigning to |contents|
  // or |description|.
  static string16 SanitizeString(const string16& text);

  // Copies the destination_url with "www." stripped off to
  // |stripped_destination_url|.  This method is invoked internally by the
  // AutocompleteController and does not normally need to be invoked.
  void ComputeStrippedDestinationURL();

  // Gets data relevant to whether there should be any special keyword-related
  // UI shown for this match.  If this match represents a selected keyword, i.e.
  // the UI should be "in keyword mode", |keyword| will be set to the keyword
  // and |is_keyword_hint| will be set to false.  If this match has a non-NULL
  // |associated_keyword|, i.e. we should show a "Press [tab] to search ___"
  // hint and allow the user to toggle into keyword mode, |keyword| will be set
  // to the associated keyword and |is_keyword_hint| will be set to true.  Note
  // that only one of these states can be in effect at once.  In all other
  // cases, |keyword| will be cleared, even when our member variable |keyword|
  // is non-empty -- such as with non-substituting keywords or matches that
  // represent searches using the default search engine.  See also
  // GetSubstitutingExplicitlyInvokedKeyword().
  void GetKeywordUIState(Profile* profile,
                         string16* keyword,
                         bool* is_keyword_hint) const;

  // Returns |keyword|, but only if it represents a substituting keyword that
  // the user has explicitly invoked.  If for example this match represents a
  // search with the default search engine (and the user didn't explicitly
  // invoke its keyword), this returns the empty string.  The result is that
  // this function returns a non-empty string in the same cases as when the UI
  // should show up as being "in keyword mode".
  string16 GetSubstitutingExplicitlyInvokedKeyword(Profile* profile) const;

  // Returns the TemplateURL associated with this match.  This may be NULL if
  // the match has no keyword OR if the keyword no longer corresponds to a valid
  // TemplateURL.  See comments on |keyword| below.
  TemplateURL* GetTemplateURL(Profile* profile) const;

  // Adds optional information to the |additional_info| dictionary.
  void RecordAdditionalInfo(const std::string& property,
                            const std::string& value);
  void RecordAdditionalInfo(const std::string& property, int value);
  void RecordAdditionalInfo(const std::string& property,
                            const base::Time& value);

  // The provider of this match, used to remember which provider the user had
  // selected when the input changes. This may be NULL, in which case there is
  // no provider (or memory of the user's selection).
  AutocompleteProvider* provider;

  // The relevance of this match. See table in autocomplete.h for scores
  // returned by various providers. This is used to rank matches among all
  // responding providers, so different providers must be carefully tuned to
  // supply matches with appropriate relevance.
  //
  // TODO(pkasting): http://b/1111299 This should be calculated algorithmically,
  // rather than being a fairly fixed value defined by the table above.
  int relevance;

  // How many times this result was typed in / selected from the omnibox.
  // Only set for some providers and result_types.  If it is not set,
  // its value is -1.  At the time of writing this comment, it is only
  // set for matches from HistoryURL and HistoryQuickProvider.
  int typed_count;

  // True if the user should be able to delete this match.
  bool deletable;

  // This string is loaded into the location bar when the item is selected
  // by pressing the arrow keys. This may be different than a URL, for example,
  // for search suggestions, this would just be the search terms.
  string16 fill_into_edit;

  // The position within fill_into_edit from which we'll display the inline
  // autocomplete string.  This will be string16::npos if this match should
  // not be inline autocompleted.
  size_t inline_autocomplete_offset;

  // The URL to actually load when the autocomplete item is selected. This URL
  // should be canonical so we can compare URLs with strcmp to avoid dupes.
  // It may be empty if there is no possible navigation.
  GURL destination_url;

  // The destination URL with "www." stripped off for better dupe finding.
  GURL stripped_destination_url;

  // The main text displayed in the address bar dropdown.
  string16 contents;
  ACMatchClassifications contents_class;

  // Additional helper text for each entry, such as a title or description.
  string16 description;
  ACMatchClassifications description_class;

  // The transition type to use when the user opens this match.  By default
  // this is TYPED.  Providers whose matches do not look like URLs should set
  // it to GENERATED.
  content::PageTransition transition;

  // True when this match is the "what you typed" match from the history
  // system.
  bool is_history_what_you_typed_match;

  // Type of this match.
  Type type;

  // Set with a keyword provider match if this match can show a keyword hint.
  // For example, if this is a SearchProvider match for "www.amazon.com",
  // |associated_keyword| could be a KeywordProvider match for "amazon.com".
  scoped_ptr<AutocompleteMatch> associated_keyword;

  // The keyword of the TemplateURL the match originated from.  This is nonempty
  // for both explicit "keyword mode" matches as well as matches for the default
  // search provider (so, any match for which we're doing substitution); it
  // doesn't imply (alone) that the UI is going to show a keyword hint or
  // keyword mode.  For that, see GetKeywordUIState() or
  // GetSubstitutingExplicitlyInvokedKeyword().
  //
  // CAUTION: The TemplateURL associated with this keyword may be deleted or
  // modified while the AutocompleteMatch is alive.  This means anyone who
  // accesses it must perform any necessary sanity checks before blindly using
  // it!
  string16 keyword;

  // True if the user has starred the destination URL.
  bool starred;

  // True if this match is from a previous result.
  bool from_previous;

  // Optional search terms args.  If present,
  // AutocompleteController::UpdateAssistedQueryStats() will incorporate this
  // data with additional data it calculates and pass the completed struct to
  // TemplateURLRef::ReplaceSearchTerms() to reset the match's |destination_url|
  // after the complete set of matches in the AutocompleteResult has been chosen
  // and sorted.  Most providers will leave this as NULL, which will cause the
  // AutocompleteController to do no additional transformations.
  scoped_ptr<TemplateURLRef::SearchTermsArgs> search_terms_args;

  // Information dictionary into which each provider can optionally record a
  // property and associated value and which is presented in chrome://omnibox.
  AdditionalInfo additional_info;

#ifndef NDEBUG
  // Does a data integrity check on this match.
  void Validate() const;

  // Checks one text/classifications pair for valid values.
  void ValidateClassifications(
      const string16& text,
      const ACMatchClassifications& classifications) const;
#endif
};

typedef AutocompleteMatch::ACMatchClassification ACMatchClassification;
typedef std::vector<ACMatchClassification> ACMatchClassifications;
typedef std::vector<AutocompleteMatch> ACMatches;

#endif  // CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_MATCH_H_


text:
module ViolentRuby
  # Unix Password Cracker provides a friendly interface to
  # crack unix passwords. Because all hackers totes do this.
  # @author Kent 'picat' Gruber
  #
  # @example Basic Usage
  #   config = { file: "/etc/passwd", dictionary: "dictionary.txt" }
  #
  #   upc = ViolentRuby::UnixPasswordCracker.new(config)
  #
  #   upc.crack do |result|
  #     next unless result[:cracked]
  #     puts "Cracked #{result[:username]}'s password: #{result[:plaintext_password]}"
  #   end
  #
  class UnixPasswordCracker
    # @!attribute file
    #   @return [String] Path to the /etc/passwd file.
    attr_accessor :file

    # @!attribute dictionary
    #   @return [String] Path to dictionary file.
    attr_accessor :dictionary

    alias etc file

    # Create a new Unix Password Cracker.
    #
    # @param  args [Hash]   The options to create a new Unix Password Cracker.
    # @option args [String] :file       The path to an /etc/passwd file.
    # @option args [String] :dictionary The path to a dictionry of passwords.
    #
    # @return [UnixPasswordCracker]
    def initialize(args = {})
      @file       = args[:file]       if args[:file]
      @dictionary = args[:dictionary] if args[:dictionary]
    end

    # Parse a unix /etc/passwd file into a more mangeable form.
    #
    # @example Basic Usage
    #   upc = ViolentRuby::UnixPasswordCracker.new
    #   upc.parse_etc_file(file: 'passwords.txt')
    #   # {"victim" => "HX9LLTdc/jiDE", "root" => "DFNFxgW7C05fo"}
    #
    # @example Super Advanced Usage
    #   ViolentRuby::UnixPasswordCracker.new.parse_etc_file(file: 'passwords.txt') do |user, pass|
    #     puts user + ' ' + pass
    #   end
    #   # victim HX9LLTdc/jiDE
    #   # root DFNFxgW7C05fo
    #
    # @param  args [Hash]    The options when parsing the file.
    # @option args [String]  :file      The path to an /etc/passwd file.
    # @option args [Boolean] :users     Specify that only users should be returned ( default: +false+ ).
    # @option args [Boolean] :passwords Specify that only passwords should be returned ( default: +false+ ).
    #
    # @return [Hash]
    def parse_etc_file(args = {})
      # Readlines from /etc/passwd file.
      lines = File.readlines(args[:file]).collect do |line|
        line unless line.split(':').first.chars.first.include?('#')
      end

      # Collect the users and passwords from the lines.
      users     = lines.collect { |x| x.split(':')[0] }.map(&:strip)
      passwords = lines.collect { |x| x.split(':')[1] }.map(&:strip)

      # Friendly behavior to return just users or passwords.
      return users     if args[:users]
      return passwords if args[:passwords]

      # Zip'm together into a hash.
      users_passwords = Hash[users.zip(passwords)]

      # Yield each pair when a block is given, or return all at once.
      if block_given?
        users_passwords.each do |user, password|
          yield user, password
        end
      else
        users_passwords
      end
    end

    # Crack unix passwords.
    #
    # @example Basic Usage
    #   ViolentRuby::UnixPasswordCracker.new(file: "passwords.txt", dictionary: "dictionary.txt").crack_passwords do |result|
    #     next unless result[:cracked]
    #     puts "Cracked #{result[:username]}'s password: #{result[:plaintext_password]}"
    #   end
    #
    # @param  args [Hash]   The options when crack'n some passwords.
    # @option args [String] :file       The path to an /etc/passwd file.
    # @option args [String] :dictionary The path to a dictionry of passwords.
    #
    # @yield [Hash]
    def crack_passwords(args = {})
      # Use the file and dictionry instance variables or the arguments.
      file = args[:file]       || @file
      dict = args[:dictionary] || @dictionary
      # Parse the given /etc/passwd file and compare with the dictionary.
      parse_etc_file(file: file) do |user, password|
        File.readlines(dict).map(&:strip).each do |word|
          if cracked?(password, word)
            yield format_result(user, password, word)
            break
          else
            yield format_result(user, password)
          end
        end
      end
    end

    alias crack crack_passwords

    alias crack! crack_passwords

    alias get_crackn crack_passwords

    alias release_the_kraken crack_passwords

    # Check if a given encrypted password matches a given plaintext
    # word when the same crytographic operation is performed on it.
    #
    # @example Basic Usage
    #   ViolentRuby::UnixPasswordCracker.new.check_password('HX9LLTdc/jiDE', 'egg')
    #   # true
    #
    # @example Advanced Usage
    #   ViolentRuby::UnixPasswordCracker.new.check_password('HXA82SzTqypHA', 'egg ')
    #   # false
    #
    #   ViolentRuby::UnixPasswordCracker.new.check_password('HXA82SzTqypHA', 'egg ', false)
    #   # true
    #
    # @param encrypted_password [String] The encrypted password to check against.
    # @param plaintext_password [String] The plaintext password to check against.
    # @param strip              [Boolean] Strip trailing spaces and newlines from word ( default: +true+ )
    #
    # @return [Boolean]
    def check_password(encrypted_password, plaintext_password, strip = true)
      plaintext_password.strip! if strip # sometimes passwords have trailing spaces
      if plaintext_password.crypt(encrypted_password[0, 2]) == encrypted_password
        true
      else
        false
      end
    end

    alias cracked? check_password

    private

    # @api private
    # Format the results for the password crack'n.
    #
    # @param user           [String]
    # @param encrypted_pass [String]
    # @param plaintext_pass [String]
    #
    # @return [Hash]
    def format_result(user, encrypted_pass, plaintext_pass = false)
      result = {}
      if plaintext_pass
        result[:cracked] = true
      else
        result[:cracked] = false
      end
      result[:username]           = user
      result[:encrypted_password] = encrypted_pass
      result[:plaintext_password] = plaintext_pass if plaintext_pass
      result
    end
  end
end


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
null

#### Original name
Tussilago albicans Sw.

### Remarks
null


text:
import subprocess
import os
import signal

from calabar.tunnels import (
    TUN_TYPE_STR,
    ExecutableNotFound,
    TunnelTypeDoesNotMatch,
    is_really_running,
)

class TunnelBase(object):
    """The base Tunnel clase for encapsulating a specific type of tunnel.

    Create a tunnel that's opened using the given command and executable.

    ``cmd`` is a list of command arguments with the first argument being the
    display name that the tunnel process should use eg ``calabar_vpnc``
    ``executable`` is a path to the executable file that will be used to
    create the tunnel eg. ``/usr/sbin/vpnc``
    ``name`` will be this tunnels string identifier.
    ``tun_type`` if given, must match :attr:`TunnelBase.TYPE` or a
    :exc:`TunnelTypeDoesNotMatch` exception will be raised.

    To implement other tunnels, you can extend this class (as :class:`calabar.tunnels.vpnc.VpncTunnel`
    does) or if the tunnel process is simple enough to only need command line
    options, you can simply pass in the appropriate ``cmd`` array and
    path to the required ``executable``.
    """

    TUNNEL_TYPE = 'base'

    def __init__(self, cmd, executable, name='default', tunnel_type=None):
        self.cmd = cmd
        self.executable = executable
        self.proc = None
        self.name = name
        if tunnel_type and tunnel_type != TunnelBase.TUNNEL_TYPE:
            raise TunnelTypeDoesNotMatch(
                'Tunnel type <%s> does not match expected <%s>' % (tunnel_type, TunnelBase.TUNNEL_TYPE))
        self.closing = False # Are we currently trying to close this tunnel
        self.opening = False # Not currently trying to open this tunnel

    def open(self):
        """
        Open the tunnel.
        """
        if not which(self.executable):
            raise ExecutableNotFound("The executable <%s> in invalid. Not found or not marked executable." % repr(self.executable))

        self.closing = False
        self.opening = True
        self.proc = self._open(self.cmd, self.executable)

        return self.proc

    def _open(self, cmd, executable):
        """
        Perform the actual process launch using the command and executable
        configured for this tunnel.
        """
        proc = subprocess.Popen(cmd, executable=executable)

        return proc

    def is_running(self):
        if self.proc:
            return is_really_running(self)
        else:
            return False

    def close(self, wait=True, force=False):
        """
        Close this tunnel if currently running and waits for it to finish closing.

        If ``force`` is given as True, close using :mod:signal.SIGKILL to force a close.
        """
        self.closing = True
        self.opening = False
        if self.is_running():
            sig = signal.SIGTERM
            if force:
                sig = signal.SIGKILL

            os.kill(self.proc.pid, sig)
            if wait:
                self.proc.wait()

    def handle_closed(self, exit_status):
        """
        Handle the tunnel process having closed externally. There was probably
        some sort of error.
        """
        self.closing = False
        self.opening = False
        self.proc = None

    @staticmethod
    def parse_configuration(config, section_name):
        """
        Parse out the required tunnel information from the given
        :mod:ConfigParser.ConfigParser instance, with this tunnel being
        represented by the tunnel at ``section_name``.

        Returns a dictionary with options corresponding to those taken by
        :member:`__init__`
        """
        tun_conf_d = {}
        tun_conf_d[TUN_TYPE_STR] = TunnelBase.TUNNEL_TYPE
        cmd = config.get(section_name, 'cmd')
        tun_conf_d['cmd'] = cmd.split()
        tun_conf_d['executable'] = config.get(section_name, 'executable')

        return tun_conf_d

def which(program):
    """
    Determine where the given executable exists on the path (if it exists). Mimics
    the behavior of the gnu ``which`` command.

    Returns ``None`` if the executable is not found.

    Taken from: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
    """
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file


text:
'use strict';

var gulp = require('gulp');
var exec = require('child_process').execSync;
var browsersync = require('browser-sync');
var changed = require('gulp-changed');

gulp.task('js', function () {
  if (process.env.NODE_ENV === 'production') {
    exec('npm run buildjs', function (err, stdout, stderr) {
      console.log(stdout)
      console.log(stderr)
      return err
    });
    return gulp.src([global.path.src + '/js/worker/*.js'], {
        base: global.path.src
      })
      .pipe(changed(global.path.dist))
      .pipe(gulp.dest(global.path.dist));
  } else {
    gulp.src([global.path.src + '/js/**/*.*', global.path.src + '/config.js'], {
        base: global.path.src
      })
      .pipe(changed(global.path.dist))
      .pipe(gulp.dest(global.path.dist))
      .pipe(browsersync.reload({
        stream: true
      }));
  }
});


text:
<?php namespace Kevindierkx\Elicit\Query\Processors;

use Kevindierkx\Elicit\Query\Builder;

class Processor
{
    /**
     * Process the results of an API request.
     *
     * @param  \Kevindierkx\Elicit\Query\Builder  $query
     * @param  array  $results
     * @return array
     */
    protected function processRequest(Builder $query, $results)
    {
        // Here we validate the results being returned to be associative.
        // When they are not we wrap them in an array making it easier for
        // elicit to them parse as a model.
        if (array_keys($results) !== range(0, count($results) - 1)) {
            return [$results];
        }

        // Here we return the results directly, assuming the items in
        // the array are a collection.
        return $results;
    }

    /**
     * Process the results of both an "Index" and "Show" API request
     *
     * @param  \Kevindierkx\Elicit\Query\Builder  $query
     * @param  array  $results
     * @return array
     */
    public function processShowRequest(Builder $query, $results)
    {
        return $this->processRequest($query, $results);
    }

    /**
     * Process the results of an "Create" API request
     *
     * @param  \Kevindierkx\Elicit\Query\Builder  $query
     * @param  array  $results
     * @return array
     */
    public function processCreateRequest(Builder $query, $results)
    {
        return $this->processRequest($query, $results);
    }

    /**
     * Process the result of an "Update" API request
     *
     * @param  \Kevindierkx\Elicit\Query\Builder  $query
     * @param  array  $results
     * @return array
     */
    public function processUpdateRequest(Builder $query, $results)
    {
        return $this->processRequest($query, $results);
    }

    /**
     * Process the result of an "Delete" API request
     *
     * @param  \Kevindierkx\Elicit\Query\Builder  $query
     * @param  array  $results
     * @return boolean
     */
    public function processDeleteRequest(Builder $query, $results)
    {
        // We assume that there isn't any response on
        // a successful delete operation (204 No Content)
        return ( count($results) != 0 );
    }
}


text:
var net    = require('net'),
    test   = require('tape'),
    argosy = require('..'),
    match  = require('argosy-pattern/match')

var service = argosy()
var client = argosy()
client.pipe(service).pipe(client)

service.accept({ square: match.number }).process(function (msg, cb) {
    client.invoke({ multiply: [msg.square, msg.square] }, cb)
})
service.accept({ multiply: match.array }).process(function (msg, cb) {
    cb(null, msg.multiply.reduce(function (a, b) {
        return a * b
    }))
})

var server = net.createServer(function (c) {
    c.pipe(service).pipe(c)
})

test('start server', function (t) {
    server.listen(0, t.end.bind(t))
})

test('invoke square over net with sub-invocations', function (t) {
    t.plan(1)
    t.timeoutAfter(2000)

    var myclient = argosy()
    var socket = net.createConnection(server.address(), function () {
        myclient.pipe(socket).pipe(myclient)

        myclient.invoke({ square: 4 }).then(function (result) {
            t.equals(result, 16, 'tells us square of 4 is 16')
            setTimeout(socket.end.bind(socket), 200)
        }).catch(t.error.bind(t))
    })
})

test('stop server', function (t) {
    server.close(t.end.bind(t))
})