text:
The google-cloud-ruby integration tests are end-to-end tests that validate library functionality on real Google Cloud Platform hosting environments. The integration process deploys several Rack-based applications to Google Cloud Platform one by one, then validates google-cloud-ruby code by making requests to these test applications.

All integration tests require [Cloud SDK](https://cloud.google.com/sdk/) for deployment. Following the instructions in [Authentication guide](../AUTHENTICATION.md) for installation and authentication.

### Configuration
First, make sure a Google Cloud Platform project is setup that satisfies the following requirements:
1. Enable the [Stackdriver Error Reporting API](https://console.cloud.google.com/apis/api/clouderrorreporting.googleapis.com/overview).
2. Make sure a [Google Container Engine Cluster](https://cloud.google.com/container-engine/docs/clusters/operations) with permissions to access all the GCP services this library implements is properly setup and ready to use. It's easier to create the Cluster through [Cloud Platform Console](https://console.cloud.google.com/kubernetes/list). Keep in mind once the Cluster is created, the service permissions cannot be updated.

Once Google Cloud SDK is installed and authenticated, make sure the following items are also configured properly:
1. Set Project ID:
```sh
$ gcloud config set project PROJECT_ID
```
2. Set Container Cluster name:
```sh
$ gcloud config set container/cluster CLUSTER_NAME
```
3. Extend Cloud Build timeout to an hour:
```sh
$ gcloud config set container/build_timeout 3600
```
In addition to Cloud SDK, Google Container Engine requires [Docker](https://www.docker.com/) for building Docker images, and the [Kubernetes commandline tool](http://kubernetes.io/docs/user-guide/kubectl-overview/) for image deployment.

Follow the [Docker website](https://www.docker.com/products/docker) for Docker installation instructions.

The Kubernetes commandline tool can be installed through Cloud SDK:
```sh
$ gcloud components install kubectl
```

### Usage
To kick off the full integration test suite:
```sh
$ rake integration
```

### Integration tests on Google App Engine
To run the integration tests just on Google App Engine:
```sh
$ rake integration:gae
```
This rake task automates the Google App Engine deployment by deploying the google-cloud-ruby libraries with sample applications using the `gcloud app deploy` shell command. Each of the sample applications contains an app.yaml.example file that defines specific deployment procedure for that application. For example, the [Rails 5 app.yaml.example](rails5_app/app.yaml.example) file defines a custom entrypoint that allows bundler to install the sample application's dependencies and launch the application.

After a successful deployment, each google-cloud-ruby libraries can then run its integration tests against the deployed sample application. For example, the [google-cloud-logging tests](../google-cloud-logging/integration/) send HTTP requests to redefined routes on the sample application to trigger logs being generated. Then it's able to verify the result logs through Cloud SDK.

### Integration tests on Google Container Engine
To run the integration tests on Google Container Engine:
```sh
$ rake integration:gke
```
Similar to the workflow of `integration:gae` task, the `integration:gke` task uses the `Dockerfile.example` file from each sample application as the template to build a Docker image, deploy it to Google Container Registry, and deploy Google Container pods to launch the application. In the case of GKE pods configuration, all sample application shares a same configuration defined in [integration_rc.yaml.example](integration_rc.yaml.example) file.

After the integration tests finish run against the deployed GKE sample application, the `integration:gke` application is also able to clean up all the resources created during the deployment. These resources include local test Docker image, GCR test Docker image, GKE ReplicationController, and GKE pods.

### Integration tests on Google Compute Engine
We're currently not supporting automated tests on Google Compute Engine environment for the following reasons:
* Major functionalities such as metadata service accisibility, application default authentication are, operating system, and API accessibility are already covered by other automated tests.
* Both GAE and GKE are currently hosted on GCE VMs.
* It's harder to automate deployment on GCE environment than GAE or GKE, due to GCE's IaaS nature.

### Write tests

Each google-cloud-ruby libraries should define its own set of integration tests. It it doesn't already, make sure a corresponding `integration:gae` or `integration:gke` task exists at the package level. These tasks will be invoked by top level `integration` task when deployment is finished. Otherwise these package level tasks can also be invoked independently assume deployment already happened.

Common test cases defined in `google-cloud-*/integration/` directory will be run on both GAE and GKE environments. Environment specific test cases can be defined in `google-cloud-*/integration/gae/` or `google-cloud-*/integration/gke/` directories. Such test cases will only be run against the corresponding environment.


text:
using Amazon.DynamoDBv2;
using Amazon.Internal;
using Amazon.KeyManagementService;
using Narochno.Credstash;

namespace HumbleConfig.Credstash
{
    public static class CredstashExtensions
    {
        public static IConfigurationSourceConfigurator AddCredstash(this IConfigurationConfigurator configuration, CredstashOptions options, IAmazonKeyManagementService amazonKeyManagementService, IAmazonDynamoDB amazonDynamoDb)
        {
            var credstash = new Narochno.Credstash.Credstash(options, amazonKeyManagementService, amazonDynamoDb);

            return configuration.AddConfigurationSource(new CredstashSource(credstash));

        }

        public static IConfigurationSourceConfigurator AddCredstash(this IConfigurationConfigurator configuration, Amazon.RegionEndpoint region, string table)
        {
            var credstashOptions = new CredstashOptions()
            {
                Region = region,
                Table = table
            };

            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient(region);
            var amazonDynamoDbClient = new AmazonDynamoDBClient(region);

            return AddCredstash(configuration, credstashOptions, amazonKeyManagementServiceClient, amazonDynamoDbClient);
        }

        public static IConfigurationSourceConfigurator AddCredstash(this IConfigurationConfigurator configuration, Amazon.RegionEndpoint region)
        {
            var credstashOptions = new CredstashOptions()
            {
                Region = region
            };

            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient(region);
            var amazonDynamoDbClient = new AmazonDynamoDBClient(region);

            return AddCredstash(configuration, credstashOptions, amazonKeyManagementServiceClient, amazonDynamoDbClient);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace DesignPatterns\Behavioral\Mediator\Subsystem;

use DesignPatterns\Behavioral\Mediator\Colleague;

/**
 * Server serves responses.
 */
class Server extends Colleague
{
    /**
     * process on server.
     */
    public function process()
    {
        $data = $this->getMediator()->queryDb();
        $this->getMediator()->sendResponse("Hello $data");
    }
}


text:
local copas = require "copas"
local http = require "webmeet.wraphttp"

local function create_request_thread(req)
    return coroutine.create(function()
	while not req.done do
	    copas.sleep(-1)
	    local success, code, headers = http.request(req)
	    if not success then
		return
	    end
	end
    end)
end

local function adapt_request(post_request)
    if type(post_request) == "string" then
	local u = post_request
	post_request = {
	    url = u,
	    method = "POST",
	    headers = {
		["Connection"] = "keep-alive",
		["Transfer-Encoding"] = "chunked",
	    }
	}
    end
    return post_request
end

-- Create a source that sends http POST request.
-- Return function to add new chunks to the POST body.
local function construct(post_request)
    local chunk = nil
    local me = nil
    local notify = nil

    post_request = adapt_request(post_request)
    post_request.source = function()
	-- No active chunk?
	if not chunk then
	    if notify then
		copas.wakeup(notify)
		notify = nil
	    end
	    copas.sleep(60)
	end
	local result = chunk
	if result == nil and notify then
	    copas.wakeup(notify)
	    notify = nil
	    post_request.done = true
	end
	chunk = nil
	return result
    end

    return function(set_chunk)
	if set_chunk == "" then
	    return
	end

	-- Wake up poster thread
	chunk = set_chunk
	if me == nil or coroutine.status(me) == "dead" then
	    -- Not connected to HTTP server, reconnect.
	    me = copas.addthread(create_request_thread(post_request))
	end
	copas.wakeup(me)
	notify = coroutine.running()
	if notify then
	    copas.sleep(-1)
	end
	return true
    end
end

return construct


text:
SpriteSheet::SpriteSheet()
: Texture()
{
#ifdef _DEBUG
    std::cout << "Creating the SpriteSheet" <<  std::endl;
#endif
}

SpriteSheet::~SpriteSheet()
{
    m_sprites.clear();
#ifdef _DEBUG
    std::cout << "Destroying the SpriteSheet" <<  std::endl;
#endif
}

void SpriteSheet::AddSprite(const std::string &name, uint32_t x, uint32_t y, uint32_t w, uint32_t h)
{
    Sprite sprite;
    sprite.x = x;
    sprite.y = y;
    sprite.w = w;
    sprite.h = h;

    SpriteMap::iterator lb = m_sprites.lower_bound(name);

    // efficient add or update (Effective STL - Item 24)
    if(lb != m_sprites.end() && !(m_sprites.key_comp()(name, lb->first)))
    {
        lb->second = sprite;
    }
    else
    {
        m_sprites.insert(lb, SpriteMap::value_type(name, sprite));
    }
}

Sprite SpriteSheet::GetSprite(const std::string &name)
{
    if(!m_sprites.empty())
    {
        SpriteMap::iterator it;
        it = m_sprites.find(name);
        if(it != m_sprites.end())
        {
            return it->second;
        }
    }

    Sprite sprite;
    sprite.x = 0;
    sprite.y = 0;
    sprite.w = 0;
    sprite.h = 0;

    return sprite;
}

bool SpriteSheet::LoadSpritesFromXML(const std::string &filename)
{
    try
    {
        std::unique_ptr<TextureAtlas> textureAtlas (TextureAtlas_(filename,
                xml_schema::flags::dont_validate));

        std::string texAtlasImgPath = static_cast<std::string>(textureAtlas->imagePath());
        //int texAtlasWidth = textureAtlas->width();
        //int textAtlasHeight = textureAtlas->height();

        TextureAtlas::sprite_sequence& ss(textureAtlas->sprite());

        for (auto spriteIt = ss.begin(); spriteIt != ss.end(); ++spriteIt)
        {
            std::string name = static_cast<std::string>(spriteIt->n());
            int x = spriteIt->x();
            int y = spriteIt->y();
            int w = spriteIt->w();
            int h = spriteIt->h();
            AddSprite(name, x, y, w, h);
        }
    }
    catch (const xml_schema::exception& e)
    {
        std::cerr << e << std::endl;
        return false;
    }
    return true;
}

std::size_t SpriteSheet::Size() const
{
    return m_sprites.size();
}


text:
from openerp.osv import fields
from openerp.osv import osv

class product_product(osv.osv):
    _name = 'product.product'
    _inherit = 'product.product'

    def compute_price(self, cr, uid, ids, recursive=False, test=False, real_time_accounting = False, context=None):
        '''
        Will return test dict when the test = False
        Multiple ids at once?
        testdict is used to inform the user about the changes to be made
        '''
        testdict = {}
        for prod_id in ids:
            bom_obj = self.pool.get('mrp.bom')
            bom_id = bom_obj._bom_find(cr, uid, product_id = prod_id, context=context)
            if bom_id:
                # In recursive mode, it will first compute the prices of child boms
                if recursive:
                    #Search the products that are components of this bom of prod_id
                    bom = bom_obj.browse(cr, uid, bom_id, context=context)

                    #Call compute_price on these subproducts
                    prod_set = set([x.product_id.id for x in bom.bom_line_ids])
                    res = self.compute_price(cr, uid, list(prod_set), recursive=recursive, test=test, real_time_accounting = real_time_accounting, context=context)
                    if test:
                        testdict.update(res)
                #Use calc price to calculate and put the price on the product of the BoM if necessary
                price = self._calc_price(cr, uid, bom_obj.browse(cr, uid, bom_id, context=context), test=test, real_time_accounting = real_time_accounting, context=context)
                if test:
                    testdict.update({prod_id : price})
        if test:
            return testdict
        else:
            return True

    def _calc_price(self, cr, uid, bom, test = False, real_time_accounting=False, context=None):
        if context is None:
            context={}
        price = 0
        uom_obj = self.pool.get("product.uom")
        tmpl_obj = self.pool.get('product.template')
        for sbom in bom.bom_line_ids:
            my_qty = sbom.product_qty
            price += uom_obj._compute_price(cr, uid, sbom.product_id.uom_id.id, sbom.product_id.standard_price, sbom.product_uom.id) * my_qty

        if bom.routing_id:
            for wline in bom.routing_id.workcenter_lines:
                wc = wline.workcenter_id
                cycle = wline.cycle_nbr
                hour = (wc.time_start + wc.time_stop + cycle * wc.time_cycle) *  (wc.time_efficiency or 1.0)
                price += wc.costs_cycle * cycle + wc.costs_hour * hour
                price = self.pool.get('product.uom')._compute_price(cr,uid,bom.product_uom.id, price, bom.product_id.uom_id.id)

        #Convert on product UoM quantities
        if price > 0:
            price = uom_obj._compute_price(cr, uid, bom.product_uom.id, price / bom.product_qty, bom.product_id.uom_id.id)

        product = tmpl_obj.browse(cr, uid, bom.product_tmpl_id.id, context=context)
        if not test:
            if (product.valuation != "real_time" or not real_time_accounting):
                tmpl_obj.write(cr, uid, [product.id], {'standard_price' : price}, context=context)
            else:
                #Call wizard function here
                wizard_obj = self.pool.get("stock.change.standard.price")
                ctx = context.copy()
                ctx.update({'active_id': product.id, 'active_model': 'product.template'})
                wiz_id = wizard_obj.create(cr, uid, {'new_price': price}, context=ctx)
                wizard_obj.change_price(cr, uid, [wiz_id], context=ctx)
        return price

product_product()

class product_bom(osv.osv):
    _inherit = 'mrp.bom'

    _columns = {
        'standard_price': fields.related('product_tmpl_id','standard_price',type="float",relation="product.product",string="Standard Price",store=False)
    }

product_bom()
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N953.html">

Redirecting to type.N953.html...


text:
class Moom < Cask
  version :latest
  sha256 :no_check

  url 'http://manytricks.com/download/moom'
  appcast 'http://manytricks.com/moom/appcast.xml'
  homepage 'http://manytricks.com/moom/'

  app 'Moom.app'
  zap :delete => [
                  '~/Library/Preferences/com.manytricks.Moom.plist',
                  '~/Library/Application Support/Many Tricks',
                 ]
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package hackerrank.thirtydaysofcode;

import java.util.Scanner;

/**
 *
 * @author bharat
 */
public class Day3Conditional {
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      int n = scan.nextInt();
      scan.close();
      String ans="";

      // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
      if(n%2==1){
         ans = "Weird";
      }
      else if(n%2==0 && (n>=2 && n<=5)) {
         // Complete the code
         ans = "Not Weird";
      } else if (n%2==0 && (n>=6 && n<=20)) {
           ans = "Weird";
      } else if (n%2==0 && (n>20)) {
          ans = "Not Weird";
      }
      System.out.println(ans);
   }
}


text:
package org.nexbook.tags

import org.scalatest.Tag

/**
  * Created by milczu on 1/1/16.
  */
object Performance extends Tag("org.nexbook.tags.Performance")


text:
import os

from . import product
from .. import shell
from .. import targets

class PythonKit(product.Product):
    @classmethod
    def product_source_name(cls):
        return "PythonKit"

    @classmethod
    def is_build_script_impl_product(cls):
        return False

    def should_build(self, host_target):
        return True

    def build(self, host_target):
        toolchain_path = targets.toolchain_path(self.args.install_destdir,
                                                self.args.install_prefix)
        swiftc = os.path.join(toolchain_path, 'bin', 'swiftc')

        # FIXME: this is a workaround for CMake <3.16 which does not correctly
        # generate the build rules if you are not in the build directory.  As a
        # result, we need to create the build tree before we can use it and
        # change into it.
        #
        # NOTE: unfortunately, we do not know if the build is using Python
        # 2.7 or Python 3.2+.  In the latter, the `exist_ok` named parameter
        # would alleviate some of this issue.
        try:
            os.makedirs(self.build_dir)
        except OSError:
            pass

        with shell.pushd(self.build_dir):
            shell.call([
                self.toolchain.cmake,
                '-G', 'Ninja',
                '-D', 'BUILD_SHARED_LIBS=YES',
                '-D', 'CMAKE_INSTALL_PREFIX={}'.format(
                    self.install_toolchain_path()),
                '-D', 'CMAKE_MAKE_PROGRAM={}'.format(self.toolchain.ninja),
                '-D', 'CMAKE_Swift_COMPILER={}'.format(swiftc),
                '-B', self.build_dir,
                '-S', self.source_dir,
            ])
            shell.call([
                self.toolchain.cmake,
                '--build', self.build_dir,
            ])

    def should_test(self, host_target):
        return self.args.test_pythonkit

    def test(self, host_target):
        pass

    def should_install(self, host_target):
        return self.args.install_pythonkit

    def install(self, host_target):
        shell.call([
            self.toolchain.cmake,
            '--build', self.build_dir,
            '--target', 'install',
        ])


text:
  Artists
  Albums
  Songs
  Upload Music

Playlists


text:
package com.service;

public final class Constants {
    public static final String CODE = "code";
    public static final String CLIENT_ID = "client_id";
    public static final String CLIENT_SECRET = "client_secret";
    public static final String TYPE = "type";
    public static final String ALL = "all";
    public static final String SCOPE = "scope";
    public static final String REPO = "repo";
    public static final String CONTENT_TYPE = "Content-Type";
    public static final String ACCEPT = "Accept";
    public static final String APLLICATION_JSON = "application/json";
    public static final String AUTHORIZATION = "Authorization";
    public static final String TOKEN = "token";
    public static final String BEARER = "Bearer";
    public static final String RESPONSE_TYPE = "response_type";
    public static final String ACCESS_TOKEN = "access_token";
    public static final String AUTHORIZATION_CODE = "authorization_code";
    public static final String REFRESH_TOKEN = "refresh_token";
    public static final String BASIC = "Basic";
    public static final String USERNAME = "username";
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:agui="http://schemas.agui.com/apk/res/agui"
	agui:id="@agui:id/text1"
	agui:layout_width="match_parent"
	agui:layout_height="wrap_content"
	agui:text="Text1"
	/>


text:
.class final Landroid/hardware/scontext/SContextActivityTracker$1;
.super Ljava/lang/Object;
.source "SContextActivityTracker.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/scontext/SContextActivityTracker;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/hardware/scontext/SContextActivityTracker;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/hardware/scontext/SContextActivityTracker;
    .locals 1

    new-instance v0, Landroid/hardware/scontext/SContextActivityTracker;

    invoke-direct {v0, p1}, Landroid/hardware/scontext/SContextActivityTracker;-><init>(Landroid/os/Parcel;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/hardware/scontext/SContextActivityTracker$1;->createFromParcel(Landroid/os/Parcel;)Landroid/hardware/scontext/SContextActivityTracker;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/hardware/scontext/SContextActivityTracker;
    .locals 1

    new-array v0, p1, [Landroid/hardware/scontext/SContextActivityTracker;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/hardware/scontext/SContextActivityTracker$1;->newArray(I)[Landroid/hardware/scontext/SContextActivityTracker;

    move-result-object v0

    return-object v0
.end method


text:
<launch>

  <!-- This file makes it easy to include the settings for sensor managers -->

  <!-- Set the file describing which sensor(s) to use to build the octomap  -->
  <arg name="moveit_octomap_sensor_params_file" default="$(find pr2_moveit_config)/config/sensors_kinect.yaml" />

  <!-- Load the robot specific sensor manager; this sets the moveit_sensor_manager ROS parameter -->
  <arg name="moveit_sensor_manager" default="pr2" />

  <!--<include file="$(find pr2_moveit_config)/launch/$(arg moveit_sensor_manager)_moveit_sensor_manager.launch.xml">
    <arg name="moveit_octomap_sensor_params_file" value="$(arg moveit_octomap_sensor_params_file)"/>
  </include>-->

</launch>


text:
/**
 * @brief Global Position plugin
 * @file global_position.cpp
 * @author Nuno Marques <n.marques21@hotmail.com>
 * @author Vladimir Ermakov <vooon341@gmail.com>
 *
 * @addtogroup plugin
 * @{
 */
/*
 * Copyright 2014 Nuno Marques.
 *
 * This file is part of the mavros package and subject to the license terms
 * in the top-level LICENSE file of the mavros repository.
 * https://github.com/mavlink/mavros/tree/master/LICENSE.md
 */

#include <mavros/mavros_plugin.h>
#include <mavros/gps_conversions.h>
#include <pluginlib/class_list_macros.h>

#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <sensor_msgs/NavSatFix.h>
#include <sensor_msgs/NavSatStatus.h>
#include <geometry_msgs/Vector3Stamped.h>
#include <geometry_msgs/Quaternion.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Header.h>

namespace mavplugin {
/**
 * @brief Global position plugin.
 *
 * Publishes global position. Convertion from GPS to UTF allows
 * publishing local position to TF and PoseWithCovarianceStamped.
 *
 */
class GlobalPositionPlugin : public MavRosPlugin {
public:
	GlobalPositionPlugin() :
		gp_nh("~global_position"),
		uas(nullptr),
		send_tf(false),
		rot_cov(99999.0)
	{ };

	void initialize(UAS &uas_)
	{
		uas = &uas_;

		gp_nh.param("send_tf", send_tf, true);
		gp_nh.param<std::string>("frame_id", frame_id, "local_origin");
		gp_nh.param<std::string>("child_frame_id", child_frame_id, "fcu");
		gp_nh.param<double>("rot_covariance", rot_cov, 99999.0);

		fix_pub = gp_nh.advertise<sensor_msgs::NavSatFix>("global", 10);
		pos_pub = gp_nh.advertise<geometry_msgs::PoseWithCovarianceStamped>("local", 10);
		vel_pub = gp_nh.advertise<geometry_msgs::Vector3Stamped>("gp_vel", 10);
		rel_alt_pub = gp_nh.advertise<std_msgs::Float64>("rel_alt", 10);
		hdg_pub = gp_nh.advertise<std_msgs::Float64>("compass_hdg", 10);
	}

	const message_map get_rx_handlers() {
		return {
			       MESSAGE_HANDLER(MAVLINK_MSG_ID_GLOBAL_POSITION_INT, &GlobalPositionPlugin::handle_global_position_int)
		};
	}

private:
	ros::NodeHandle gp_nh;
	UAS *uas;

	ros::Publisher fix_pub;
	ros::Publisher pos_pub;
	ros::Publisher vel_pub;
	ros::Publisher hdg_pub;
	ros::Publisher rel_alt_pub;

	tf::TransformBroadcaster tf_broadcaster;

	std::string frame_id;		//!< origin for TF
	std::string child_frame_id;	//!< frame for TF and Pose
	bool send_tf;
	double rot_cov;

	/**
	 * @todo Handler for GLOBAL_POSITION_INT_COV
	 */

	void handle_global_position_int(const mavlink_message_t *msg, uint8_t sysid, uint8_t compid) {
		mavlink_global_position_int_t gp_pos;
		mavlink_msg_global_position_int_decode(msg, &gp_pos);

		ROS_DEBUG_THROTTLE_NAMED(10, "global_position", "Global position: boot_ms:%06d "
				"lat/lon/alt:(%d %d %d) relative_alt: (%d) gp_vel:(%d %d %d) compass_heading: (%d)",
				gp_pos.time_boot_ms,
				gp_pos.lat, gp_pos.lon, gp_pos.alt, gp_pos.relative_alt,
				gp_pos.vx, gp_pos.vy, gp_pos.vz, gp_pos.hdg);

		auto pose_cov = boost::make_shared<geometry_msgs::PoseWithCovarianceStamped>();
		auto gp_fix = boost::make_shared<sensor_msgs::NavSatFix>();
		auto gp_vel = boost::make_shared<geometry_msgs::Vector3Stamped>();
		auto relative_alt = boost::make_shared<std_msgs::Float64>();
		auto compass_heading = boost::make_shared<std_msgs::Float64>();

		std_msgs::Header header;
		header.frame_id = frame_id;
		header.stamp = uas->synchronise_stamp(gp_pos.time_boot_ms);

		// Global position fix
		gp_fix->header = header;
		gp_fix->latitude = gp_pos.lat / 1E7;
		gp_fix->longitude = gp_pos.lon / 1E7;
		gp_fix->altitude = gp_pos.alt / 1E3;	// in meters

		// fill GPS status fields using GPS_RAW data
		auto raw_fix = uas->get_gps_fix();
		if (raw_fix) {
			gp_fix->status.service = raw_fix->status.service;
			gp_fix->status.status = raw_fix->status.status;
			gp_fix->position_covariance = raw_fix->position_covariance;
			gp_fix->position_covariance_type = raw_fix->position_covariance_type;
		}
		else {
			// no GPS_RAW_INT -> fix status unknown
			gp_fix->status.service = sensor_msgs::NavSatStatus::SERVICE_GPS;
			gp_fix->status.status = sensor_msgs::NavSatStatus::STATUS_NO_FIX;

			// we don't know covariance
			std::fill(gp_fix->position_covariance.begin(),
					gp_fix->position_covariance.end(), 0.0);
			gp_fix->position_covariance[0] = -1.0;
			gp_fix->position_covariance_type =
					sensor_msgs::NavSatFix::COVARIANCE_TYPE_UNKNOWN;
		}

		// Global position velocity
		gp_vel->header = header;
		gp_vel->vector.x = gp_pos.vx / 1E2;	// in m/s
		gp_vel->vector.y = gp_pos.vy / 1E2;
		gp_vel->vector.z = gp_pos.vz / 1E2;

		relative_alt->data = gp_pos.relative_alt / 1E3;	// in meters
		compass_heading->data = (gp_pos.hdg != UINT16_MAX) ? gp_pos.hdg / 1E2 : NAN;	// in degrees

		double northing, easting;
		std::string zone;

		/** Adapted from gps_umd ROS package @a http://wiki.ros.org/gps_umd
		 *  Author: Ken Tossell <ken AT tossell DOT net>
		 */
		UTM::LLtoUTM(gp_fix->latitude, gp_fix->longitude, northing, easting, zone);

		pose_cov->header = header;
		pose_cov->pose.pose.position.x = easting;
		pose_cov->pose.pose.position.y = northing;
		pose_cov->pose.pose.position.z = relative_alt->data;

		// XXX Check #193
		tf::quaternionTFToMsg(uas->get_attitude_orientation(), pose_cov->pose.pose.orientation);

		// Use ENU covariance to build XYZRPY covariance
		boost::array<double, 36> covariance = {
			gp_fix->position_covariance[0],
			gp_fix->position_covariance[1],
			gp_fix->position_covariance[2],
			0, 0, 0,
			gp_fix->position_covariance[3],
			gp_fix->position_covariance[4],
			gp_fix->position_covariance[5],
			0, 0, 0,
			gp_fix->position_covariance[6],
			gp_fix->position_covariance[7],
			gp_fix->position_covariance[8],
			0, 0, 0,
			0, 0, 0, rot_cov, 0, 0,
			0, 0, 0, 0, rot_cov, 0,
			0, 0, 0, 0, 0, rot_cov
		};

		pose_cov->pose.covariance = covariance;

		fix_pub.publish(gp_fix);
		pos_pub.publish(pose_cov);
		vel_pub.publish(gp_vel);
		rel_alt_pub.publish(relative_alt);
		hdg_pub.publish(compass_heading);

		if (send_tf) {
			tf::Transform transform;
			// XXX: we realy need change frame?
			transform.setOrigin(tf::Vector3(pose_cov->pose.pose.position.y,
						pose_cov->pose.pose.position.x,
						-pose_cov->pose.pose.position.z));

			transform.setRotation(uas->get_attitude_orientation());

			tf_broadcaster.sendTransform(
					tf::StampedTransform(
						transform,
						pose_cov->header.stamp,
						frame_id, child_frame_id));
		}
	}
};
};	// namespace mavplugin

PLUGINLIB_EXPORT_CLASS(mavplugin::GlobalPositionPlugin, mavplugin::MavRosPlugin)


text:
package org.broad.igv.util;

import junit.framework.TestCase;
import htsjdk.samtools.seekablestream.SeekableHTTPStream;
import org.broad.igv.util.stream.IGVSeekableHTTPStream;
import org.broad.igv.util.stream.SeekableServiceStream;
import org.junit.Test;

import java.net.URL;

/**
 * @author jrobinso
 * @date Jul 28, 2010
 */
public class SeekableServiceStreamTest extends TestCase {

    /**
     * Test a file at some random position using the webservice, and compare results obtained to the standard
     * http stream.
     *
     * @throws Exception
     */
    @Test
    public void testRead() throws Exception {

        String tdfFile = "https://data.broadinstitute.org/igvdata/annotations/hg18/conservation/omega.12mer.tdf";

        HttpUtils.getInstance().updateProxySettings();

        IGVSeekableHTTPStream hs = new IGVSeekableHTTPStream(new URL(tdfFile));
        final int position = 100;
        hs.seek(position);
        final int range = 1000;
        byte[] expectedBytes = new byte[range];
        hs.read(expectedBytes, 0, expectedBytes.length);

        SeekableServiceStream sss = new SeekableServiceStream(new URL(tdfFile));
        sss.seek(position);
        byte[] bytes = new byte[range];
        sss.read(bytes, 0, bytes.length);

        for (int i = 0; i < expectedBytes.length; i++) {
            assertEquals(expectedBytes[i], bytes[i]);
        }
    }

}


text:
require 'active_support/core_ext/hash/slice'

module ActsAsOrderedTree
  class Tree
    # Tree callbacks storage
    #
    # @example
    #   MyModel.ordered_tree.callbacks.before_add(parent, child)
    #
    # @api private
    class Callbacks
      VALID_KEYS = :before_add,
                   :after_add,
                   :before_remove,
                   :after_remove

      def initialize(klass, options)
        @klass = klass
        @callbacks = {}

        options.slice(*VALID_KEYS).each do |k, v|
          @callbacks[k] = v if v
        end
      end

      # generate accessors and predicates
      VALID_KEYS.each do |method|
        define_method(method) do |parent, record| # def before_add(parent, record)
          run_callbacks(method, parent, record)
        end
      end

      private
      def run_callbacks(method, parent, record)
        callback = callback_for(method)

        case callback
          when Symbol
            parent.send(callback, record)
          when Proc
            callback.call(parent, record)
          when nil, false
            # do nothing
          else
            # parent.before_add(record)
            callback.send(method, parent, record)
        end
      end

      def callback_for(method)
        @callbacks[method]
      end
    end # class Callbacks
  end # class Tree
end # module ActsAsOrderedTree


text:
package common

import (
	"github.com/graph-gophers/graphql-go/errors"
	"github.com/graph-gophers/graphql-go/types"
)

func ParseType(l *Lexer) types.Type {
	t := parseNullType(l)
	if l.Peek() == '!' {
		l.ConsumeToken('!')
		return &types.NonNull{OfType: t}
	}
	return t
}

func parseNullType(l *Lexer) types.Type {
	if l.Peek() == '[' {
		l.ConsumeToken('[')
		ofType := ParseType(l)
		l.ConsumeToken(']')
		return &types.List{OfType: ofType}
	}

	return &types.TypeName{Ident: l.ConsumeIdentWithLoc()}
}

type Resolver func(name string) types.Type

// ResolveType attempts to resolve a type's name against a resolving function.
// This function is used when one needs to check if a TypeName exists in the resolver (typically a Schema).
//
// In the example below, ResolveType would be used to check if the resolving function
// returns a valid type for Dimension:
//
// type Profile {
//    picture(dimensions: Dimension): Url
// }
//
// ResolveType recursively unwraps List and NonNull types until a NamedType is reached.
func ResolveType(t types.Type, resolver Resolver) (types.Type, *errors.QueryError) {
	switch t := t.(type) {
	case *types.List:
		ofType, err := ResolveType(t.OfType, resolver)
		if err != nil {
			return nil, err
		}
		return &types.List{OfType: ofType}, nil
	case *types.NonNull:
		ofType, err := ResolveType(t.OfType, resolver)
		if err != nil {
			return nil, err
		}
		return &types.NonNull{OfType: ofType}, nil
	case *types.TypeName:
		refT := resolver(t.Name)
		if refT == nil {
			err := errors.Errorf("Unknown type %q.", t.Name)
			err.Rule = "KnownTypeNames"
			err.Locations = []errors.Location{t.Loc}
			return nil, err
		}
		return refT, nil
	default:
		return t, nil
	}
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

  UserBundle DevTool

                <?php if( ! empty($envData)):?>

                                        viewData

                                    <?php foreach($envData as $k=>$v):?>
                                        <?php if( ! is_array($v) && ! is_object($v)):?>

<?=$k;?>

<?=$v;?>

                                        <?php endif;?>
                                    <?php endforeach;?>

                        <?php foreach($envData as $k=>$v):?>
                            <?php if( is_array($v) || is_object($v)):?>

                                            <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse<?=$k;?>" aria-expanded="false" aria-controls="collapse<?=$k;?>" class="collapsed">

                                                <?=$k;?>

                                    <div id="collapse<?=$k;?>" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading<?=$k;?>" aria-expanded="false">

                                            <?php foreach($v as $vk=>$vv):?>

<?=$vk;?>

                                                        <?php if( !  is_array($vv) && ! is_object($vv)):?>
                                                            <?=htmlentities($vv);?>
                                                        <?php else:?>

<?=var_dump($vv);?>

                                                        <?php endif;?>

                                            <?php endforeach;?>

                            <?php endif;?>
                        <?php endforeach;?>

                <?php endif;?>


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/api/serviceusage/v1beta1/serviceusage.proto

package com.google.api.serviceusage.v1beta1;

public interface BatchCreateConsumerOverridesResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.api.serviceusage.v1beta1.BatchCreateConsumerOverridesResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The overrides that were created.
   *

   *
   * repeated .google.api.serviceusage.v1beta1.QuotaOverride overrides = 1;
   */
  java.util.List<com.google.api.serviceusage.v1beta1.QuotaOverride> getOverridesList();
  /**
   *
   *
   *

   * The overrides that were created.
   *

   *
   * repeated .google.api.serviceusage.v1beta1.QuotaOverride overrides = 1;
   */
  com.google.api.serviceusage.v1beta1.QuotaOverride getOverrides(int index);
  /**
   *
   *
   *

   * The overrides that were created.
   *

   *
   * repeated .google.api.serviceusage.v1beta1.QuotaOverride overrides = 1;
   */
  int getOverridesCount();
  /**
   *
   *
   *

   * The overrides that were created.
   *

   *
   * repeated .google.api.serviceusage.v1beta1.QuotaOverride overrides = 1;
   */
  java.util.List<? extends com.google.api.serviceusage.v1beta1.QuotaOverrideOrBuilder>
      getOverridesOrBuilderList();
  /**
   *
   *
   *

   * The overrides that were created.
   *

   *
   * repeated .google.api.serviceusage.v1beta1.QuotaOverride overrides = 1;
   */
  com.google.api.serviceusage.v1beta1.QuotaOverrideOrBuilder getOverridesOrBuilder(int index);
}


text:
define( [
            'dojo/_base/declare',
            'dojo/_base/lang',
            'dojo/_base/array',
            'dojo/_base/url',
            'JBrowse/has',
            'JBrowse/Store/SeqFeature',
            'JBrowse/Store/DeferredStatsMixin',
            'JBrowse/Store/DeferredFeaturesMixin',
            './BigWig/Window',
            'JBrowse/Util',
            'JBrowse/Model/XHRBlob'
        ],
        function( declare, lang, array, urlObj, has, SeqFeatureStore, DeferredFeaturesMixin, DeferredStatsMixin, Window, Util, XHRBlob ) {
return declare([ SeqFeatureStore, DeferredFeaturesMixin, DeferredStatsMixin ],

 /**
  * @lends JBrowse.Store.BigWig
  */
{

    BIG_WIG_MAGIC: -2003829722,
    BIG_BED_MAGIC: -2021002517,

    BIG_WIG_TYPE_GRAPH: 1,
    BIG_WIG_TYPE_VSTEP: 2,
    BIG_WIG_TYPE_FSTEP: 3,

    /**
     * Data backend for reading wiggle data from BigWig or BigBed files.
     *
     * Adapted by Robert Buels from bigwig.js in the Dalliance Genome
     * Explorer which is copyright Thomas Down 2006-2010
     * @constructs
     */
    constructor: function( args ) {

        this.data = args.blob ||
            new XHRBlob( this.resolveUrl(
                             args.urlTemplate || 'data.bigwig'
                         )
                       );

        this.name = args.name || ( this.data.url && new urlObj( this.data.url ).path.replace(/^.+\//,'') ) || 'anonymous';

        this._load();
    },

    _getGlobalStats: function( successCallback, errorCallback ) {
        var s = this._globalStats || {};

        // calc mean and standard deviation if necessary
        if( !( 'scoreMean' in s ))
            s.scoreMean = s.basesCovered ? s.scoreSum / s.basesCovered : 0;
        if( !( 'scoreStdDev' in s ))
            s.scoreStdDev = this._calcStdFromSums( s.scoreSum, s.scoreSumSquares, s.basesCovered );

        successCallback( s );
    },

    _load: function() {
        var bwg = this;
        var headerSlice = bwg.data.slice(0, 512);
        headerSlice.fetch( function( result ) {
            if( ! result ) {
                this._failAllDeferred( 'BBI header not readable' );
                return;
            }

            bwg.fileSize = result.fileSize;;
            var header = result;
            var sa = new Int16Array(header);
            var la = new Int32Array(header);
            if (la[0] == bwg.BIG_WIG_MAGIC) {
                bwg.type = 'bigwig';
            } else if (la[0] == bwg.BIG_BED_MAGIC) {
                bwg.type = 'bigbed';
            } else {
                console.error( 'Format '+la[0]+' not supported' );
                bwg._failAllDeferred( 'Format '+la[0]+' not supported' );
                return;
            }
            //        dlog('magic okay');

            bwg.version = sa[2];             // 4
            bwg.numZoomLevels = sa[3];       // 6
            bwg.chromTreeOffset = (la[2] << 32) | (la[3]);     // 8
            bwg.unzoomedDataOffset = (la[4] << 32) | (la[5]);  // 16
            bwg.unzoomedIndexOffset = (la[6] << 32) | (la[7]); // 24
            bwg.fieldCount = sa[16];         // 32
            bwg.definedFieldCount = sa[17];  // 34
            bwg.asOffset = (la[9] << 32) | (la[10]);    // 36 (unaligned longlong)
            bwg.totalSummaryOffset = (la[11] << 32) | (la[12]);    // 44 (unaligned longlong)
            bwg.uncompressBufSize = la[13];  // 52

            // dlog('bigType: ' + bwg.type);
            // dlog('chromTree at: ' + bwg.chromTreeOffset);
            // dlog('uncompress: ' + bwg.uncompressBufSize);
            // dlog('data at: ' + bwg.unzoomedDataOffset);
            // dlog('index at: ' + bwg.unzoomedIndexOffset);
            // dlog('field count: ' + bwg.fieldCount);
            // dlog('defined count: ' + bwg.definedFieldCount);

            bwg.zoomLevels = [];
            for (var zl = 0; zl < bwg.numZoomLevels; ++zl) {
                var zlReduction = la[zl*6 + 16];
                var zlData = (la[zl*6 + 18]<<32)|(la[zl*6 + 19]);
                var zlIndex = (la[zl*6 + 20]<<32)|(la[zl*6 + 21]);
                //          dlog('zoom(' + zl + '): reduction=' + zlReduction + '; data=' + zlData + '; index=' + zlIndex);
                bwg.zoomLevels.push({reductionLevel: zlReduction, dataOffset: zlData, indexOffset: zlIndex});
            }

            // parse the totalSummary if present (summary of all data in the file)
            if( bwg.totalSummaryOffset ) {
                if( Float64Array ) {
                    (function() {
                        var ua = new Uint32Array( header, bwg.totalSummaryOffset, 2 );
                        var da = new Float64Array( header, bwg.totalSummaryOffset+8, 4 );
                        var s = {
                            basesCovered: ua[0]<<32 | ua[1],
                            scoreMin: da[0],
                            scoreMax: da[1],
                            scoreSum: da[2],
                            scoreSumSquares: da[3]
                        };
                        bwg._globalStats = s;
                        // rest of these will be calculated on demand in getGlobalStats
                    }).call();
                } else {
                    console.warn("BigWig "+bwg.data.url+ " total summary not available, this web browser is not capable of handling this data type.");
                }
            } else {
                    console.warn("BigWig "+bwg.data.url+ " has no total summary data.");
            }

            bwg._readChromTree(
                function() {
                    bwg._deferred.features.resolve({success: true});
                    bwg._deferred.stats.resolve({success: true});
                },
                dojo.hitch( bwg, '_failAllDeferred' )
            );
        },
        dojo.hitch( this, '_failAllDeferred' )
       );
    },

    _readInt: function(ba, offset) {
        return (ba[offset + 3] << 24) | (ba[offset + 2] << 16) | (ba[offset + 1] << 8) | (ba[offset]);
    },

    _readShort: function(ba, offset) {
        return (ba[offset + 1] << 8) | (ba[offset]);
    },

    /**
     * @private
     */
    _readChromTree: function( callback, errorCallback ) {
        var thisB = this;
        this.refsByNumber = {};
        this.refsByName = {};

        var udo = this.unzoomedDataOffset;
        while ((udo % 4) != 0) {
            ++udo;
        }

        var readInt   = this._readInt;
        var readShort = this._readShort;

        this.data.slice( this.chromTreeOffset, udo - this.chromTreeOffset )
            .fetch(function(bpt) {
                       if( ! has('typed-arrays') ) {
                           thisB._failAllDeferred( 'Web browser does not support typed arrays' );
                           return;
                       }
                       var ba = new Uint8Array(bpt);
                       var la = new Int32Array(bpt, 0, 6);
                       var bptMagic = la[0];
                       if( bptMagic !== 2026540177 )
                           throw "parse error: not a Kent bPlusTree";
                       var blockSize = la[1];
                       var keySize = la[2];
                       var valSize = la[3];
                       var itemCount = (la[4] << 32) | (la[5]);
                       var rootNodeOffset = 32;

                       //dlog('blockSize=' + blockSize + '    keySize=' + keySize + '   valSize=' + valSize + '    itemCount=' + itemCount);

                       var bptReadNode = function(offset) {
                           if( offset >= ba.length )
                               throw "reading beyond end of buffer";
                           var isLeafNode = ba[offset];
                           var cnt = readShort( ba, offset+2 );
                           //dlog('ReadNode: ' + offset + '     type=' + isLeafNode + '   count=' + cnt);
                           offset += 4;
                           for (var n = 0; n < cnt; ++n) {
                               if( isLeafNode ) {
                                   // parse leaf node
                                   var key = '';
                                   for (var ki = 0; ki < keySize; ++ki) {
                                       var charCode = ba[offset++];
                                       if (charCode != 0) {
                                           key += String.fromCharCode(charCode);
                                       }
                                   }
                                   var refId = readInt( ba, offset );
                                   var refSize = readInt( ba, offset+4 );
                                   offset += 8;

                                   var refRec = { name: key, id: refId, length: refSize };

                                   //dlog(key + ':' + refId + ',' + refSize);
                                   thisB.refsByName[ thisB.browser.regularizeReferenceName(key) ] = refRec;
                                   thisB.refsByNumber[refId] = refRec;
                               } else {
                                   // parse index node
                                   offset += keySize;
                                   var childOffset = (readInt( ba, offset+4 ) << 32) | readInt( ba, offset );
                                   offset += 8;
                                   childOffset -= thisB.chromTreeOffset;
                                   bptReadNode(childOffset);
                               }
                           }
                       };
                       bptReadNode(rootNodeOffset);

                       callback.call( thisB, thisB );
            }, errorCallback );
    },

    /**
     * Interrogate whether a store has data for a given reference
     * sequence.  Calls the given callback with either true or false.
     *
     * Implemented as a binary interrogation because some stores are
     * smart enough to regularize reference sequence names, while
     * others are not.
     */
    hasRefSeq: function( seqName, callback, errorCallback ) {
        var thisB = this;
        seqName = thisB.browser.regularizeReferenceName( seqName );
        this._deferred.features.then(function() {
            callback( seqName in thisB.refsByName );
        }, errorCallback );
    },

    _getFeatures: function( query, featureCallback, endCallback, errorCallback ) {

        var chrName = this.browser.regularizeReferenceName( query.ref );
        var min = query.start;
        var max = query.end;

        var v = query.basesPerSpan ? this.getView( 1/query.basesPerSpan ) :
                       query.scale ? this.getView( scale )                :
                                     this.getView( 1 );

        if( !v ) {
            endCallback();
            return;
        }

        v.readWigData( chrName, min, max, dojo.hitch( this, function( features ) {
            array.forEach( features || [], featureCallback );
            endCallback();
        }), errorCallback );
    },

    getUnzoomedView: function() {
        if (!this.unzoomedView) {
            var cirLen = 4000;
            var nzl = this.zoomLevels[0];
            if (nzl) {
                cirLen = this.zoomLevels[0].dataOffset - this.unzoomedIndexOffset;
            }
            this.unzoomedView = new Window( this, this.unzoomedIndexOffset, cirLen, false );
        }
        return this.unzoomedView;
    },

    getView: function( scale ) {
        if( ! this.zoomLevels || ! this.zoomLevels.length )
            return null;

        if( !this._viewCache || this._viewCache.scale != scale ) {
            this._viewCache = {
                scale: scale,
                view: this._getView( scale )
            };
        }
        return this._viewCache.view;
    },

    _getView: function( scale ) {
        var basesPerSpan = 1/scale;
        //console.log('getting view for '+basesPerSpan+' bases per span');
        for( var i = this.zoomLevels.length - 1; i > 0; i-- ) {
            var zh = this.zoomLevels[i];
            if( zh && zh.reductionLevel <= basesPerSpan ) {
                var indexLength = i < this.zoomLevels.length - 1
                    ? this.zoomLevels[i + 1].dataOffset - zh.indexOffset
                    : this.fileSize - 4 - zh.indexOffset;
                //console.log( 'using zoom level '+i);
                return new Window( this, zh.indexOffset, indexLength, true );
            }
        }
        //console.log( 'using unzoomed level');
        return this.getUnzoomedView();
    }
});

});


text:
/*****************************************************************************
*
* expns - ex_put_node_set
*
* entry conditions -
*   input parameters:
*       int     exoid                   exodus file id
*       int     node_set_id             node set id
*       int*    node_set_node_list      node list array for the node set
*
* exit conditions -
*
* revision history -
*
*  Id
*
*****************************************************************************/

#include "exodusII.h"
#include "exodusII_int.h"

/*!
 * writes the node list for a single node set
 * \param   exoid                   exodus file id
 * \param   node_set_id             node set id
 * \param   node_set_node_list      node list array for the node set
 * \deprecated Use ex_put_set()(exoid, EX_NODE_SET, node_set_id, node_set_node_list, NULL)
 */

int ex_put_node_set (int   exoid,
                     int   node_set_id,
                     const int  *node_set_node_list)
{
  return ex_put_set(exoid, EX_NODE_SET, node_set_id,
                    node_set_node_list, NULL);
}


text:
package jobsupervisor

type dummyJobSupervisor struct {
	status    string
	processes []Process
}

func NewDummyJobSupervisor() JobSupervisor {
	return &dummyJobSupervisor{status: "unknown"}
}

func (s *dummyJobSupervisor) Reload() error {
	return nil
}

func (s *dummyJobSupervisor) Start() error {
	s.status = "running"
	s.processes = []Process{}
	return nil
}

func (s *dummyJobSupervisor) Stop() error {
	s.status = "stopped"
	return nil
}

func (s *dummyJobSupervisor) Unmonitor() error {
	return nil
}

func (s *dummyJobSupervisor) Status() (status string) {
	return s.status
}

func (s *dummyJobSupervisor) Processes() ([]Process, error) {
	return s.processes, nil
}

func (s *dummyJobSupervisor) AddJob(jobName string, jobIndex int, configPath string) error {
	return nil
}

func (s *dummyJobSupervisor) RemoveAllJobs() error {
	return nil
}

func (s *dummyJobSupervisor) MonitorJobFailures(handler JobFailureHandler) error {
	return nil
}


text:
@class TGMediaPickerAsset;
@class TGMediaPickerAssetsGroup;

typedef enum {
    TGMediaPickerAssetAnyType,
    TGMediaPickerAssetPhotoType,
    TGMediaPickerAssetVideoType
} TGMediaPickerAssetType;

typedef enum {
    TGMediaPickerAuthorizationStatusNotDetermined,
    TGMediaPickerAuthorizationStatusRestricted,
    TGMediaPickerAuthorizationStatusDenied,
    TGMediaPickerAuthorizationStatusAuthorized
} TGMediaPickerAuthorizationStatus;

@interface TGMediaPickerAssetsLibrary : NSObject

@property (nonatomic, readonly) TGMediaPickerAssetType assetType;

@property (nonatomic, copy) void (^libraryChanged)(void);

- (instancetype)initForAssetType:(TGMediaPickerAssetType)assetType;

- (void)fetchGroupsWithCompletionBlock:(void(^)(NSArray *groups, TGMediaPickerAuthorizationStatus status, NSError *error))completionBlock;
- (void)fetchAssetsOfAssetsGroup:(TGMediaPickerAssetsGroup *)assetsGroup withCompletionBlock:(void (^)(NSArray *assets, TGMediaPickerAuthorizationStatus status, NSError *error))completionBlock;

- (void)saveAssetWithImage:(UIImage *)image completionBlock:(void(^)(bool success, NSError *error))completionBlock;
- (void)saveAssetWithImageData:(NSData *)data completionBlock:(void(^)(bool success, NSError *error))completionBlock;
- (void)saveAssetWithImageAtURL:(NSURL *)url completionBlock:(void(^)(bool success, NSError *error))completionBlock;
- (void)saveAssetWithVideoAtURL:(NSURL *)url completionBlock:(void(^)(bool success, NSError *error))completionBlock;

@end


text:
package integration

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"os/exec"
	"testing"

	"github.com/sclevine/spec"
	"github.com/stretchr/testify/require"
)

var _ = suite("compute/cdn/flush", func(t *testing.T, when spec.G, it spec.S) {
	var (
		expect *require.Assertions
		server *httptest.Server
	)

	it.Before(func() {
		expect = require.New(t)

		server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
			switch req.URL.Path {
			case "/v2/cdn/endpoints/some-cdn-id/cache":
				auth := req.Header.Get("Authorization")
				if auth != "Bearer some-magic-token" {
					w.WriteHeader(http.StatusUnauthorized)
					return
				}

				if req.Method != http.MethodDelete {
					w.WriteHeader(http.StatusMethodNotAllowed)
					return
				}

				reqBody, err := ioutil.ReadAll(req.Body)
				expect.NoError(err)

				request := struct {
					Files []string `json:"files"`
				}{}

				err = json.Unmarshal(reqBody, &request)
				expect.NoError(err)
				expect.Contains(request.Files, "*")

				w.WriteHeader(http.StatusNoContent)
			default:
				dump, err := httputil.DumpRequest(req, true)
				if err != nil {
					t.Fatal("failed to dump request")
				}

				t.Fatalf("received unknown request: %s", dump)
			}
		}))
	})

	when("required flags are passed", func() {
		it("flushes the cdn", func() {
			cmd := exec.Command(builtBinaryPath,
				"-t", "some-magic-token",
				"-u", server.URL,
				"compute",
				"cdn",
				"flush",
				"some-cdn-id",
			)

			output, err := cmd.CombinedOutput()
			expect.NoError(err, fmt.Sprintf("received error output: %s", output))
			expect.Empty(output)
		})
	})
})

const cdnFlushResponse = `
{
  "files": [
    "assets/img/hero.png",
    "assets/css/*"
  ]
}
`


text:
package cn.binarywang.wx.miniapp.api.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.test.ApiTestModule;
import com.google.inject.Inject;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;

import java.io.File;

/**
 * @author Binary Wang
 */
@Test
@Guice(modules = ApiTestModule.class)
public class WxMaQrcodeServiceImplTest {
  @Inject
  protected WxMaService wxService;

  @Test
  public void testCreateQrCode() throws Exception {
    final File qrCode = this.wxService.getQrcodeService().createQrcode("111", 122);
    System.out.println(qrCode);
  }

  @Test
  public void testCreateWxCode() throws Exception {
    final File wxCode = this.wxService.getQrcodeService().createWxCode("111", 122);
    System.out.println(wxCode);
  }

  @Test
  public void testCreateWxCodeLimit() throws Exception {
    final File wxCode = this.wxService.getQrcodeService().createWxCodeLimit("111", null);
    System.out.println(wxCode);
  }

}


text:
using Autofac;
using Gerenciador.Domain.Snapshot;
using Gerenciador.Repository.EntityFramwork.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gerenciador.Services.Hangfire {
    public class HistoryBackgroundService {
        ILifetimeScope lifetimeScope;
        public HistoryBackgroundService(ILifetimeScope lifetimeScope) {
            this.lifetimeScope = lifetimeScope;
        }

        public void CreateEntry(EventSnapshot snapshot) {
            using (var scope = lifetimeScope.BeginLifetimeScope("AutofacWebRequest")) {
                var eventSnapshotRepository = scope.Resolve<IEventSnapshotRepository>();
                eventSnapshotRepository.Add(snapshot);
                eventSnapshotRepository.SaveChanges();
            }
        }
    }//class
}


text:
const assert = require(`assert`)
const fs = require(`fs`)
const removeDir = require(`rimraf`)
const store = require(`../cache-fs.ts`)
const cacheDirectory = __dirname + `/cache`

function countFilesInCacheDir() {
  return fs.readdirSync(cacheDirectory).length
}

describe(`DiskStore`, function () {
  let cache
  // remove test directory before each test
  beforeEach(async function () {
    return new Promise(resolve => {
      removeDir(cacheDirectory, () => {
        cache = store.create({ path: cacheDirectory })
        resolve()
      })
    })
  })
  // remove test directory after last test
  afterEach(async function () {
    return new Promise(resolve => removeDir(cacheDirectory, resolve))
  })

  describe(`construction`, function () {
    it(`should create cache dir`, function () {
      assert(fs.existsSync(cache.options.path))
    })
  })

  describe(`get()`, function () {
    it(`should return undefined on non existing key callback`, async function () {
      return new Promise(resolve => {
        cache.get(`not existing key`, function (err, data) {
          expect(err).toEqual(null)
          expect(data).toEqual(undefined)
          resolve()
        })
      })
    })

    it(`should return undefined on non existing key promise`, async function () {
      const data = await cache.get(`not existing key`)
      expect(data).toEqual(undefined)
    })

    it(`should not be that slow reading the same non existing cache key sequentially`, async function () {
      for (let i = 0; i < 30; i++) {
        const data = await cache.get(`not existing key`)
        expect(data).toEqual(undefined)
      }
    })

    it(`should not be that slow reading the same non existing cache key parallel`, async function () {
      // this.slow(100)

      for (let i = 0; i < 20; i++) {
        await Promise.all(
          [1, 2, 3, 4, 5].map(async function () {
            const data = await cache.get(`not existing key`)
            expect(data).toEqual(undefined)
          })
        )
      }
    })

    it(`should not be that slow reading different non existing cache keys parallel`, async function () {
      // this.slow(30)

      await Promise.all(
        Array(30)
          .fill()
          .map(async function (v, i) {
            const data = await cache.get(`not existing key` + i)
            expect(data).toEqual(undefined)
          })
      )
    })
  })

  describe(`set()`, function () {
    it(`should create a file for each saved value`, async function () {
      await cache.set(`key`, `value`)
      expect(countFilesInCacheDir()).toEqual(1)
      await cache.set(`key2`, `value`)
      expect(countFilesInCacheDir()).toEqual(2)
    })

    it(`should save buffers in separate files promise`, async function () {
      await cache.set(`key`, Buffer.alloc(100000))
      expect(countFilesInCacheDir()).toEqual(2)
    })

    it(`should not modify the value while saving`, async function () {
      const value = {
        int: 5,
        bool: true,
        float: 0.1,
        buffer: Buffer.from(`Hello World!`),
        string: `#äö=)@€²(/&%$§"`,
        largeBuffer: Buffer.alloc(100000),
      }
      await cache.set(`key`, value)
      expect(value).toEqual({
        int: 5,
        bool: true,
        float: 0.1,
        buffer: Buffer.from(`Hello World!`),
        string: `#äö=)@€²(/&%$§"`,
        largeBuffer: Buffer.alloc(100000),
      })
    })
  })

  describe(`del()`, function () {
    it(`should not throw for deleting nonexisting key`, async function () {
      // this.slow(20)
      const cache = store.create({ path: cacheDirectory })
      await cache.del(`nonexisting key`)
      expect(true).toEqual(true)
    })

    it(`should not throw for deleting nonexisting key (subdirs)`, async function () {
      // this.slow(20)
      const cache = store.create({ path: cacheDirectory, subdirs: true })
      await cache.del(`nonexisting key`)
      expect(true).toEqual(true)
    })
  })

  describe(`set() and get()`, function () {
    it(`should load the same value that was saved (simple object)`, async function () {
      const originalValue = {
        int: 5,
        bool: true,
        float: 0.1,
        string: `#äö=)@€²(/&%$§"`,
      }
      await cache.set(`(simple object)`, originalValue)
      const loadedValue = await cache.get(`(simple object)`)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should load the same value that was saved (large buffers)`, async function () {
      // this.slow(500)
      // this.timeout(30000)

      const originalValue = {
        smallbuffer: Buffer.from(`Hello World!`),
        largeBuffer: Buffer.alloc(1000 * 1000 * 10 /* 10MB */, 5),
        largeBuffer2: Buffer.alloc(1000 * 1000 * 5 /* 5MB */, 100),
      }
      await cache.set(`(large buffers)`, originalValue)
      const loadedValue = await cache.get(`(large buffers)`)
      assert.deepEqual(originalValue, loadedValue)
    })

    it(`should not load expired data (global options)`, async function () {
      const cache = store.create({ path: cacheDirectory, ttl: 0 })
      await cache.set(`key`, `value`)
      const loadedValue = await cache.get(`key`)
      expect(loadedValue).toEqual(undefined)
    })

    it(`should not load expired data (set options)`, async function () {
      await cache.set(`key`, `value`, { ttl: 0 })
      const loadedValue = await cache.get(`key`)
      expect(loadedValue).toEqual(undefined)
    })

    it(`should work with numeric keys`, async function () {
      const originalValue = `value`
      await cache.set(5, originalValue)
      const loadedValue = await cache.get(5)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should work with numeric and string keys mixed`, async function () {
      const originalValue = `value`
      await cache.set(5, originalValue)
      const loadedValue = await cache.get(`5`)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should be able to get a value written by an other cache instance using the same directory`, async function () {
      const originalValue = `value`
      const cache1 = store.create({ path: cacheDirectory })
      const cache2 = store.create({ path: cacheDirectory })

      await cache1.set(`key`, originalValue)
      const loadedValue = await cache2.get(`key`)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should work with subdirs`, async function () {
      const cache = store.create({ path: cacheDirectory, subdirs: true })
      const originalValue = {
        int: 8,
        bool: true,
        float: 0.9,
        string: `dsfsdöv`,
      }
      await cache.set(`(simple object)`, originalValue)
      const loadedValue = await cache.get(`(simple object)`)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should be able to set & get a value on different instances simultaneously`, async function () {
      // this.slow(600)
      // this.timeout(5000)

      const cache1 = store.create({ path: cacheDirectory })
      const cache2 = store.create({ path: cacheDirectory })
      const cache3 = store.create({ path: cacheDirectory })

      const value1 = {
        int: 5,
        bool: true,
        float: Math.random(),
        buffer: Buffer.from(`Hello World1!`),
        string: `#äö=)@€²(/&%$§"1`,
        largeBuffer: Buffer.alloc(1),
      }
      const value2 = {
        int: 6,
        bool: true,
        float: Math.random(),
        buffer: Buffer.from(`Hello World2!`),
        string: `#äö=)@€²(/&%$§"2`,
        largeBuffer: Buffer.alloc(2),
      }
      const value3 = {
        int: 7,
        bool: true,
        float: Math.random(),
        buffer: Buffer.from(`Hello World3!`),
        string: `#äö=)@€²(/&%$§"3`,
        largeBuffer: Buffer.alloc(3),
      }

      await Promise.all([
        cache1.set(`key`, value1),
        cache2.set(`key`, value2),
        cache3.set(`key`, value3),
      ])
      const values = await Promise.all([
        cache1.get(`key`),
        cache2.get(`key`),
        cache3.get(`key`),
      ])
      // all caches should be the same
      expect(values[0]).toEqual(values[1])
      expect(values[0]).toEqual(values[2])

      // the cache should be one of the values that was stored to it
      try {
        expect(values[0]).toEqual(values[1])
      } catch (e) {
        try {
          expect(values[0]).toEqual(value2)
        } catch (e) {
          expect(values[0]).toEqual(value3)
        }
      }
    })

    it(`should work with zip option`, async function () {
      const cache = store.create({ path: cacheDirectory, zip: true })
      const originalValue = {
        int: 5,
        bool: true,
        float: Math.random(),
        buffer: Buffer.from(`Hello World1!`),
        string: `#äö=)@€²(/&%$§"1`,
        largeBuffer: Buffer.alloc(1),
      }

      await cache.set(`key`, originalValue)
      const loadedValue = await cache.get(`key`)
      expect(loadedValue).toEqual(originalValue)
    })

    it(`should be able to store the number Infinity`, async function () {
      const cache = store.create({ path: cacheDirectory })
      const originalValue = Infinity

      await cache.set(`key`, originalValue)
      const loadedValue = await cache.get(`key`)
      expect(loadedValue).toEqual(originalValue)
    })
  })
})


text:
<?php

namespace common\models;

use Yii;
use \common\models\base\AttributeValue as BaseAttributeValue;

/**
 * This is the model class for table "attribute_value".
 */
class AttributeValue extends BaseAttributeValue
{
		public $attribute_value;

	    /**
	     * @inheritdoc
	     */
	    public function attributeLabels()
	    {
	        return array_merge([
	            'attribute_value' => Yii::t('gip', 'Value'),
	        ], parent::attributeLabels());
	    }

		public function getListOfValues() {
			if($ea = $this->getEntityAttribute()->one()) {
				if($at = $ea->getAttributeType()->one()) {
					if($lv = $at->getListOfValues()->one()) {
						return $lv->getValues();
					}
				}
			}
			return null;
		}

}


text:
module BuPr
  class Configuration
    ATTRS = %i(
      branch
      title
      token
      repo
    )

    attr_accessor(*ATTRS) # @return [String]

    # @param  opts [Hash]
    # @option opts [String] :branch Base branch name
    # @option opts [String] :title pull-request title
    # @option opts [String] :token GitHub access token
    # @option opts [String] :repo GitHub repository name
    def initialize opts = {}
      @branch = opts.fetch(:branch) { ENV.fetch("BUPR_BRANCH") { "master" } }
      @title  = opts.fetch(:title)  { ENV.fetch("BUPR_TITLE")  { default_title } }

      @token  = opts.fetch(:token) { ENV["BUPR_TOKEN"] }
      @repo   = opts.fetch(:repo)  { ENV["BUPR_REPO"] }
    end

    # @return [Boolean]
    def valid?
      token? && branch? && title? && repo?
    end

    private

    ATTRS.each do |attr|
      # @private
      # @return [Boolean]
      define_method "#{attr}?" do
        v = public_send attr
        !v.nil? && v != ""
      end
    end

    # @private
    # @return [String]
    def default_title
      "Bundle update #{Time.now.strftime('%F')}"
    end
  end
end


text:
import * as fs from 'fs';
import * as path from 'path';
import * as _ from 'lodash';
import * as ts from 'typescript';
import { toUnix } from './helpers';
import { Checker } from './checker';
import { CompilerInfo, LoaderConfig, TsConfig } from './interfaces';
import { WatchModeSymbol } from './watch-mode';
import { createHash } from 'crypto';

let colors = require('colors/safe');
let pkg = require('../package.json');
let mkdirp = require('mkdirp');

export interface Instance {
    id: number;
    babelImpl?: any;
    compiledFiles: { [key: string]: boolean };
    configFilePath: string;
    compilerConfig: TsConfig;
    loaderConfig: LoaderConfig;
    checker: Checker;
    cacheIdentifier: string;
    context: string;

    times: Dict<number>;
    watchedFiles?: Set<string>;
    startTime?: number;
}

export interface Compiler {
    inputFileSystem: typeof fs;
    _tsInstances: { [key: string]: Instance };
    options: {
        watch: boolean
    };
}

export interface Loader {
    _compiler: Compiler;
    cacheable: () => void;
    query: string;
    async: () => (err: Error, source?: string, map?: string) => void;
    resourcePath: string;
    resolve: () => void;
    addDependency: (dep: string) => void;
    clearDependencies: () => void;
    emitFile: (fileName: string, text: string) => void;
    emitWarning: (msg: string) => void;
    emitError: (msg: string) => void;
    context: string;
    options: {
        ts?: LoaderConfig
    };
}

export type QueryOptions = LoaderConfig & ts.CompilerOptions;

export function getRootCompiler(compiler) {
    if (compiler.parentCompilation) {
        return getRootCompiler(compiler.parentCompilation.compiler);
    } else {
        return compiler;
    }
}

function resolveInstance(compiler, instanceName): Instance {
     if (!compiler._tsInstances) {
        compiler._tsInstances = {};
    }
    return compiler._tsInstances[instanceName];
}

const COMPILER_ERROR = colors.red(`\n\nTypescript compiler cannot be found, please add it to your package.json file:
    npm install --save-dev typescript
`);

const BABEL_ERROR = colors.red(`\n\nBabel compiler cannot be found, please add it to your package.json file:
    npm install --save-dev babel-core
`);

let id = 0;
export function ensureInstance(
    webpack: Loader,
    query: QueryOptions,
    options: LoaderConfig,
    instanceName: string,
    rootCompiler: any
): Instance {
    let exInstance = resolveInstance(rootCompiler, instanceName);
    if (exInstance) {
        return exInstance;
    }

    const watching = isWatching(rootCompiler);
    const context = options.context || process.cwd();

    let compilerInfo = setupTs(query.compiler);
    let { tsImpl } = compilerInfo;

    let { configFilePath, compilerConfig, loaderConfig } = readConfigFile(
        context,
        query,
        options,
        tsImpl
    );

    applyDefaults(
        configFilePath,
        compilerConfig,
        loaderConfig,
        context
    );

    if (!loaderConfig.silent) {
        const sync = watching === WatchMode.Enabled ? ' (in a forked process)' : '';
        console.log(`\n[${instanceName}] Using typescript@${compilerInfo.compilerVersion} from ${compilerInfo.compilerPath} and `
            + `"tsconfig.json" from ${configFilePath}${sync}.\n`);
    }

    let babelImpl = setupBabel(loaderConfig, context);
    let cacheIdentifier = setupCache(
        compilerConfig,
        loaderConfig,
        tsImpl,
        webpack,
        babelImpl,
        context
    );
    let compiler = (<any>webpack._compiler);

    setupWatchRun(compiler, instanceName);
    setupAfterCompile(compiler, instanceName);

    const webpackOptions = _.pick(webpack._compiler.options, 'resolve');
    const checker = new Checker(
        compilerInfo,
        loaderConfig,
        compilerConfig,
        webpackOptions,
        context,
        watching === WatchMode.Enabled
    );

    return rootCompiler._tsInstances[instanceName] = {
        id: ++id,
        babelImpl,
        compiledFiles: {},
        loaderConfig,
        configFilePath,
        compilerConfig,
        checker,
        cacheIdentifier,
        context,
        times: {}
    };
}

function findTsImplPackage(inputPath: string) {
    let pkgDir = path.dirname(inputPath);
    if (fs.readdirSync(pkgDir).find((value) => value === 'package.json')) {
        return path.join(pkgDir, 'package.json');
    } else {
        return findTsImplPackage(pkgDir);
    }
}

export function setupTs(compiler: string): CompilerInfo {
    let compilerPath = compiler || 'typescript';

    let tsImpl: typeof ts;
    let tsImplPath: string;
    try {
        tsImplPath = require.resolve(compilerPath);
        tsImpl = require(tsImplPath);
    } catch (e) {
        console.error(e);
        console.error(COMPILER_ERROR);
        process.exit(1);
    }

    const pkgPath = findTsImplPackage(tsImplPath);
    const compilerVersion = require(pkgPath).version;

    let compilerInfo: CompilerInfo = {
        compilerPath,
        compilerVersion,
        tsImpl,
    };

    return compilerInfo;
}

function setupCache(
    compilerConfig: TsConfig,
    loaderConfig: LoaderConfig,
    tsImpl: typeof ts,
    webpack: Loader,
    babelImpl: any,
    context: string
): string {
    if (loaderConfig.useCache) {
        if (!loaderConfig.cacheDirectory) {
            loaderConfig.cacheDirectory = path.join(context, '.awcache');
        }

        if (!fs.existsSync(loaderConfig.cacheDirectory)) {
            mkdirp.sync(loaderConfig.cacheDirectory);
        }

        let hash = createHash('sha512') as any;
        let contents = JSON.stringify({
            typescript: tsImpl.version,
            'awesome-typescript-loader': pkg.version,
            'babel-core': babelImpl ? babelImpl.version : null,
            babelPkg: pkg.babel,
            // TODO: babelrc.json/babelrc.js
            compilerConfig,
            env: process.env.BABEL_ENV || process.env.NODE_ENV || 'development'
        });

        hash.end(contents);
        return hash.read().toString('hex');
    }
}

function setupBabel(loaderConfig: LoaderConfig, context: string): any {
    let babelImpl: any;
    if (loaderConfig.useBabel) {
        try {
            let babelPath = loaderConfig.babelCore || path.join(context, 'node_modules', 'babel-core');
            babelImpl = require(babelPath);
        } catch (e) {
            console.error(BABEL_ERROR, e);
            process.exit(1);
        }
    }

    return babelImpl;
}

function applyDefaults(
    configFilePath: string,
    compilerConfig: TsConfig,
    loaderConfig: LoaderConfig,
    context: string
) {
    const def: any = {
        sourceMap: true,
        verbose: false,
        skipDefaultLibCheck: true,
        suppressOutputPathCheck: true
    };

    if (compilerConfig.options.outDir && compilerConfig.options.declaration) {
        def.declarationDir = compilerConfig.options.outDir;
    }

    _.defaults(compilerConfig.options, def);

    if (loaderConfig.transpileOnly) {
        compilerConfig.options.isolatedModules = true;
    }

    _.defaults(compilerConfig.options, {
        sourceRoot: compilerConfig.options.sourceMap ? context : undefined
    });

    _.defaults(loaderConfig, {
        sourceMap: true,
        verbose: false,
    });

    delete compilerConfig.options.outDir;
    delete compilerConfig.options.outFile;
    delete compilerConfig.options.out;
    delete compilerConfig.options.noEmit;
}

export interface Configs {
    configFilePath: string;
    compilerConfig: TsConfig;
    loaderConfig: LoaderConfig;
}

function absolutize(fileName: string, context: string) {
    if (path.isAbsolute(fileName)) {
        return fileName;
    } else {
        return path.join(context, fileName);
    }
}

export function readConfigFile(
    context: string,
    query: QueryOptions,
    options: LoaderConfig,
    tsImpl: typeof ts
): Configs {
    let configFilePath: string;
    if (query.configFileName  && query.configFileName.match(/\.json$/)) {
        configFilePath = absolutize(query.configFileName, context);
    } else {
        configFilePath = tsImpl.findConfigFile(context, tsImpl.sys.fileExists);
    }

    let existingOptions = tsImpl.convertCompilerOptionsFromJson(query, context, 'atl.query');

    if (!configFilePath || query.configFileContent) {
        return {
            configFilePath: configFilePath || path.join(context, 'tsconfig.json'),
            compilerConfig: tsImpl.parseJsonConfigFileContent(
                query.configFileContent || {},
                tsImpl.sys,
                context,
                _.extend({}, tsImpl.getDefaultCompilerOptions(), existingOptions.options) as ts.CompilerOptions,
                context
            ),
            loaderConfig: query as LoaderConfig
        };
    }

    let jsonConfigFile = tsImpl.readConfigFile(configFilePath, tsImpl.sys.readFile);
    let compilerConfig = tsImpl.parseJsonConfigFileContent(
        jsonConfigFile.config,
        tsImpl.sys,
        path.dirname(configFilePath),
        existingOptions.options,
        configFilePath
    );

    return {
        configFilePath,
        compilerConfig,
        loaderConfig: _.defaults(
            query,
            jsonConfigFile.config.awesomeTypescriptLoaderOptions,
            options
        )
    };
}

let EXTENSIONS = /\.tsx?$|\.jsx?$/;
export type Dict<T> = {[key: string]: T};

const filterMtimes = (mtimes: any) => {
    const res = {};
    Object.keys(mtimes).forEach(fileName => {
        if (!!EXTENSIONS.test(fileName)) {
            res[fileName] = mtimes[fileName];
        }
    });

    return res;
};

function setupWatchRun(compiler, instanceName: string) {
    compiler.plugin('watch-run', function (watching, callback) {
        const instance = resolveInstance(watching.compiler, instanceName);
        const checker = instance.checker;
        const watcher = watching.compiler.watchFileSystem.watcher
            || watching.compiler.watchFileSystem.wfs.watcher;

        const startTime = instance.startTime || watching.startTime;
        const times = filterMtimes(watcher.getTimes());
        const lastCompiled = instance.compiledFiles;

        instance.compiledFiles = {};
        instance.startTime = startTime;

        const set = new Set(Object.keys(times).map(toUnix));
        if (instance.watchedFiles || lastCompiled) {
            const removedFiles = [];
            const checkFiles = (instance.watchedFiles || Object.keys(lastCompiled)) as any;
            checkFiles.forEach(file => {
                if (!set.has(file)) {
                    removedFiles.push(file);
                }
            });

            removedFiles.forEach(file => {
                checker.removeFile(file);
            });
        }
        instance.watchedFiles = set;

        const instanceTimes = instance.times;
        instance.times = Object.assign({}, times) as any;

        const updates = Object.keys(times)
            .filter(fileName => {
                const updated = times[fileName] > (instanceTimes[fileName] || startTime);
                return updated;
            })
            .map(fileName => {
                const unixFileName = toUnix(fileName);
                if (fs.existsSync(unixFileName)) {
                    checker.updateFile(unixFileName, fs.readFileSync(unixFileName).toString(), true);
                } else {
                    checker.removeFile(unixFileName);
                }
            });

        Promise.all(updates)
            .then(() => {
                callback();
            })
            .catch(callback);
    });
}

enum WatchMode {
    Enabled,
    Disabled,
    Unknown
}

function isWatching(compiler: any): WatchMode {
    const value = compiler && compiler[WatchModeSymbol];
    if (value === true) {
        return WatchMode.Enabled;
    } else if (value === false) {
        return WatchMode.Disabled;
    } else {
        return WatchMode.Unknown;
    }
}

function setupAfterCompile(compiler, instanceName, forkChecker = false) {
    compiler.plugin('after-compile', function (compilation, callback) {
        // Don't add errors for child compilations
        if (compilation.compiler.isChild()) {
            callback();
            return;
        }

        const watchMode = isWatching(compilation.compiler);
        const instance: Instance = resolveInstance(compilation.compiler, instanceName);
        const silent = instance.loaderConfig.silent;
        const asyncErrors = watchMode === WatchMode.Enabled && !silent;

        let emitError = (msg) => {
            if (asyncErrors) {
                console.log(msg, '\n');
            } else {
                compilation.errors.push(new Error(msg));
            }
        };

        const files = instance.checker.getFiles()
            .then(({files}) => {
                const normalized = files.map(file => {
                    const rpath = path.normalize(file);
                    instance.compiledFiles[file] = true;
                    return rpath;
                });
                Array.prototype.push.apply(compilation.fileDependencies, normalized);
            });

        const timeStart = +(new Date());
        const diag = () => instance.loaderConfig.transpileOnly
            ? Promise.resolve()
            : instance.checker.getDiagnostics()
                .then(diags => {
                    if (!silent) {
                        if (diags.length) {
                            console.error(colors.red(`\n[${instanceName}] Checking finished with ${diags.length} errors`));
                        } else {
                            let timeEnd = +new Date();
                            console.log(
                                colors.green(`\n[${instanceName}] Ok, ${(timeEnd - timeStart) / 1000} sec.`)
                            );
                        }
                    }

                    diags.forEach(diag => emitError(diag.pretty));
                });

        files
            .then(() => {
                if (asyncErrors) {
                    diag(); // Don't wait for diags in watch mode
                    return;
                } else {
                    return diag();
                }
            })
            .then(() => callback())
            .catch(callback);
    });
}


text:
module Cinch
  module Plugin
    module ClassMethods
      def use_blacklist
        hook :pre, for: [:match, :listen_to], method: :not_blacklisted?
      end
    end

    def not_blacklisted?(m)
      !@bot.blacklist.include?(m.user.nick) && !@bot.blacklist.include?(m.user.host)
    end
  end
end


text:
package org.assertj.core.api;

import static org.assertj.core.api.Java6Assertions.assertThat;

import org.junit.Test;

// at least one test for Java6Assertions
public class Java6Assertions_assertThat_with_String_Test {

  @Test
  public void should_create_Assert() {
    AbstractCharSequenceAssert<?, ?> assertions = assertThat("Yoda");
    assertThat(assertions).isNotNull();
  }

  @Test
  public void should_pass_actual() {
    String actual = "Yoda";
    AbstractCharSequenceAssert<?, ?> assertions = assertThat(actual);
    assertThat(assertions.actual).isSameAs(actual);
  }
}


text:
personal do
  name 'Peter Brindisi'
  phone '555-555-5555'
  email 'superduperprivate@example.com'
  github 'https://github.com/npj'
end

background do
  description <<-DESCRIPTION
    I am a guy that does things. Things are awesome and they are also cool.
  DESCRIPTION
end

skills do
  things %{foo bar baz qux}
end

hobbies do
  info do
    point 'Reading about Haskell'
    point 'Evangelizing monads'
    point 'Making beer'
  end
end


text:
/*
 * $Log: TrackID.java,v $
 * Revision 1.2  2011/01/04 10:42:32  vizigoth
 * Refactor all package names to simpler forms more consistent with typical Java usage.
 *
 * Revision 1.1  2009/03/30 09:04:51  vizigoth
 * Refactor to use SMPTE harmonized names and add early KLV file support.
 *
 * Revision 1.3  2007/12/12 12:52:27  vizigoth
 * Added documentation tag to annotations.
 *
 * Revision 1.2  2007/11/23 15:04:16  vizigoth
 * Edited javadoc comments to release standard.
 *
 * Revision 1.1  2007/11/13 22:08:03  vizigoth
 * Public release of MAJ API.
 */

package tv.amwa.maj.misctype;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

/**
Labels an integer (Java int) value used to uniquely identify a
 * {@linkplain tv.amwa.maj.model.Track track} within a {@linkplain tv.amwa.maj.model.Package
 * package}. This identifier is known as a track id.

 *
 *

 * Original C name: aafSlotID_t

 * C base type: aafUInt32

 * Java base type: int
 *

 *
 * @see tv.amwa.maj.model.Track
 * @see tv.amwa.maj.model.Package
 * @see tv.amwa.maj.union.SourceReferenceValue
 *
 *
 */
@Documented
@Target(value={ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface TrackID { }


text:
<?php
if (empty($_SESSION['userid'])) {
	?>
	<?= ""; //(isset($_SESSION['error']) && !empty($_SESSION['error'])) ? "
".$_SESSION['error']."
" : "" ;?>
	<form method='POST' action='' style='padding:2%'>
		Enter your email address

		<input type='email' placeholder='enter your email address here' value='<?=(isset($_SESSION['email']))?$_SESSION['email']:$_SESSION['register_email'];?>' name='forgotten_email' />

		<input type='hidden' value='forgotten_password' name='function' />
		<input type='hidden' value='<?=$_SESSION['token']?>' name='token' />

		<input type='submit' value='Send Password' />
	</form>
	<?php
} else {
	?>

    <?php
}


text:
package picocli;

import org.junit.Rule;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;

import org.junit.Test;
import picocli.CommandLine.Parameters;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static picocli.CommandLine.Help.Ansi.OFF;

public class SplitSynopsisLabelTest {

    // allows tests to set any kind of properties they like, without having to individually roll them back
    @Rule
    public final TestRule restoreSystemProperties = new RestoreSystemProperties();

    @Rule
    public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");

    @Test
    public void testSimple() {
        @Command(name = "UsageSplit")
        class Simple {
            @Option(names = "v", split = "\\|", splitSynopsisLabel = "|")
            String args[] = {};
        }

        String expected = String.format("" +
            "Usage: UsageSplit [v=<args>[|<args>...]]...%n" +
            "      v=<args>[|<args>...]%n");
        String actual = new CommandLine(new Simple()).getUsageMessage(OFF);
        assertEquals(expected, actual);
    }

    @Test
    public void testOptionWithoutSplit() {
        @Command(name = "WithoutSplit")
        class WithoutSplit {
            @Option(names = "v", splitSynopsisLabel = "|", description = "xxx yyy zzz")
            String args[] = {};
        }

        String expected = String.format("" +
                "Usage: WithoutSplit [v=<args>]...%n" +
                "      v=<args>   xxx yyy zzz%n");
        String actual = new CommandLine(new WithoutSplit()).getUsageMessage(OFF);
        assertEquals(expected, actual);
    }

    @Test
    public void testParameters() {
        @Command(name = "cmd")
        class Simple {
            @Parameters(split = "\\|", splitSynopsisLabel = "|",
                    paramLabel = "VAL", description = "This is the description.")
            List<String> list;
        }

        String expected = String.format("" +
                "Usage: cmd [VAL[|VAL...]...]%n" +
                "      [VAL[|VAL...]...]   This is the description.%n");
        String actual = new CommandLine(new Simple()).getUsageMessage(OFF);
        assertEquals(expected, actual);

    }
}


text:
import { ILogger } from './components/logging/ILogger';
import { IShellProvider } from './IShellProvider';
import { Shell } from './Shell';
import { NotWindowsShellProvider } from './NotWindowsShellProvider';
import { WindowsShellProvider } from './WindowsShellProvider';

/**
 * The main goal of the class is to provide the current value of the shell
 */
export class ShellProviderManager {
    private _shellProvider: IShellProvider;

    /**
     * Creates a new object which can be used to get the current value of the shell
     * @param logger The logger which is used to create child logger which will be used to log
     * messages
     */
    public constructor(logger: ILogger) {
        if (process.platform === 'win32') {
            this._shellProvider = new WindowsShellProvider(logger);
        } else {
            this._shellProvider = new NotWindowsShellProvider();
        }
    }

    /**
     * Gets the current value of the shell and returns it
     */
    public async getValue(): Promise<Shell | undefined> {
        return await this._shellProvider.getValue();
    }
}