# 多策略, 多品种回测示例

from OnePy.custom_module.cleaner_talib import Talib

from OnePy.custom_module.cleaner_sma import SMA

if self.sma1(ticker) > self.sma2(ticker):

self.sma = Talib(ind='sma', frequency='D',

self.bbands = Talib(ind='BBANDS', frequency='D',

self.buy(position, ticker, price=cur_price -

if ticker not in self.finished['short']:

self.short(position, ticker, price=cur_price +

stdout

|readers_1  |  000001|

|readers_2  |  000002|

|cleaners_1  |    SMA_1|

|cleaners_2  |    SMA_2|

|cleaners_3  |  Talib_3|

|cleaners_4  |  Talib_4|

|strategy_1  |  SmaStrategy|

|strategy_2  |       BBANDS|

|brokers_1  |  StockBroker|

|risk_managers_1  |  StockLimitFilterRiskManager|

|recorders_1  |  StockRecorder|

go = op.backtest.stock(TICKER_LIST, FREQUENCY, INITIAL_CASH, START, END)

stderr

正在初始化OnePy

Retry Talib_3, perfect buffer_day = 29

Retry Talib_3, perfect buffer_day = 27

Retry Talib_3, perfect buffer_day = 25

Retry Talib_3, perfect buffer_day = 23

Retry Talib_3, perfect buffer_day = 21

Retry Talib_3, perfect buffer_day = 19

Retry Talib_3, perfect buffer_day = 17

Retry Talib_3, perfect buffer_day = 15

Retry Talib_3, perfect buffer_day = 13

Retry Talib_3, perfect buffer_day = 11

Retry Talib_3, perfect buffer_day = 9

Retry Talib_3, perfect buffer_day = 7

=============== OnePy初始化成功！ ===============

开始寻找OnePiece之旅~~~

Cash is not enough for trading!

Cash is not enough for trading!

stdout

+--------------------------------+
|Fromdate           |  2012-08-07|
|Todate             |  2018-08-07|
|Initial_Value      |   $20000.00|
|Final_Value        |   $18241.37|
|Total_Return       |     -8.793%|
|Max_Drawdown       |     12.887%|
|Max_Duration       |    916 days|
|Max_Drawdown_Date  |  2018-07-20|
|Sharpe_Ratio       |       -0.26|
+--------------------------------+

|Start_date                |  2012-08-07|

|End_date                  |  2018-08-07|

|Initial_balance           |   $20000.00|

|End_balance               |   $18241.37|

|Total_return              |      -8.79%|

|Total_net_pnl             |   -$1758.63|

|Total_commission          |    $2527.56|

|Total_trading_days        |   1566 days|

|Max_drawdown              |      12.89%|

|Max_drawdown_date         |  2018-07-20|

|Max_duration_in_drawdown  |    916 days|

|Max_margin                |      $69.57|

|Max_win_holding_pnl       |     $104.54|

|Max_loss_holding_pnl      |    -$661.70|

|Sharpe_ratio              |       -0.26|

|Sortino_ratio             |       -0.33|

|Number_of_trades          |        2211|

|Number_of_daily_trades    |        1.41|

|Number_of_profit_days     |   1566 days|

|Number_of_loss_days       |      0 days|

|Avg_daily_pnl             |      -$1.12|

|Avg_daily_commission      |       $1.61|

|Avg_daily_return          |      -0.01%|

|Avg_daily_std             |      -0.01%|

|Annual_compound_return    |      -1.47%|

|Annual_average_return     |      -1.48%|

|Annual_std                |      -0.08%|

|Annual_pnl                |    -$283.00|

All Trades  Long Trades Short Trades

Total_number_of_trades                2211         2209            2

Total_net_pnl                    -$1758.63    -$1742.93      -$15.70

Ratio_avg_win_avg_loss                0.96         0.96         0.43

Profit_factor                         1.05         1.05         0.43

Percent_profitable                  52.01%       52.01%       50.00%

Number_of_winning_trades              1150         1149            1

Number_of_losing_trades               1057         1056            1

Max_holding_period             199.62 days  199.62 days   20.62 days

Max_consecutive_winning_trade           30           30            1

Max_consecutive_losing_trade            32           32            0

Largest_winning_trade               $15.00       $15.00       $10.51

Largest_losing_trade              -$100.00     -$100.00      -$24.35

Gross_profit                     $16623.41    $16612.90       $10.51

Gross_loss                      -$15854.48   -$15830.14      -$24.35

Gross_commission                  $2527.56     $2525.69        $1.87

Expectancy_adjusted_ratio             0.02         0.02        -0.28

Expectancy                           $0.32        $0.33       -$6.92

Avg_winning_trade                   $14.46       $14.46       $10.51

Avg_net_pnl_per_trade               -$0.80       -$0.79       -$7.85

Avg_losing_trade                   -$15.00      -$14.99      -$24.35

Avg_holding_period              13.08 days   13.08 days   11.12 days

{'repo_name': 'Chandlercjy/OnePy', 'stars': '246', 'repo_language': 'Python', 'file_name': 'oanda_api.py', 'mime_type': 'text/x-python', 'hash': 4731305930267117498, 'source_dataset': 'data'}


// Copyright 2013 the V8 project authors. All rights reserved.
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1.  Redistributions of source code must retain the above copyright
//     notice, this list of conditions and the following disclaimer.
// 2.  Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

description("Test for correct handling of exceptions from instanceof and 'new' expressions");

shouldThrow("new {}.undefined");
shouldThrow("1 instanceof {}.undefined");

{'repo_name': 'v8mips/v8mips', 'stars': '161', 'repo_language': 'C++', 'file_name': 'gmock.gyp', 'mime_type': 'text/plain', 'hash': 1032038198828132527, 'source_dataset': 'data'}


<?xml version="1.0" encoding="utf-8"?>
<LCX SchemaVersion="6.0" Name="E:\A\_work\80\b\raw\binaries\Microsoft.PythonTools.Debugger.Concord.dll" PsrId="211" FileType="1" SrcCul="en-US" TgtCul="ru-RU" xmlns="http://schemas.microsoft.com/locstudio/2006/6/lcx">
  <OwnedComments>
    <Cmt Name="Dev" />
    <Cmt Name="LcxAdmin" />
    <Cmt Name="Rccx" />
  </OwnedComments>
  <Settings Name="@SettingsPath@\default.lss" Type="Lss" />
  <Item ItemId=";Managed Resources" ItemType="0" PsrId="211" Leaf="true">
    <Disp Icon="Expand" Expand="true" Disp="true" LocTbl="false" />
  </Item>
  <Item ItemId=";Version" ItemType="0" PsrId="211" Leaf="false">
    <Disp Icon="Ver" Disp="true" LocTbl="false" Path=" \ ;Version \ 8 \ 0" />
    <Item ItemId=";AssemblyVersion" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text" DevLk="true">
        <Val><![CDATA[15.0.0.0]]></Val>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";Comments" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text">
        <Val><![CDATA[Provides integration with the Visual Studio mixed-mode debugger for Python processes.]]></Val>
        <Tgt Cat="Text" Stat="Loc" Orig="New">
          <Val><![CDATA[Обеспечивает интеграцию с отладчиком смешанного режима Visual Studio для процессов Python.]]></Val>
        </Tgt>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";CompanyName" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text">
        <Val><![CDATA[Microsoft Corporation]]></Val>
        <Tgt Cat="Text" Stat="Loc" Orig="New">
          <Val><![CDATA[Корпорация Майкрософт]]></Val>
        </Tgt>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";FileDescription" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text">
        <Val><![CDATA[Visual Studio - Python mixed-mode debugger support]]></Val>
        <Tgt Cat="Text" Stat="Loc" Orig="New">
          <Val><![CDATA[Visual Studio — поддержка отладчика смешанного режима для Python]]></Val>
        </Tgt>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";FileVersion" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text" DevLk="true">
        <Val><![CDATA[15.7.18073.1]]></Val>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";InternalName" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text" DevLk="true">
        <Val><![CDATA[Microsoft.PythonTools.Debugger.Concord.dll]]></Val>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";LegalCopyright" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text">
        <Val><![CDATA[© Microsoft Corporation]]></Val>
        <Tgt Cat="Text" Stat="Loc" Orig="New">
          <Val><![CDATA[© Корпорация Майкрософт (Microsoft Corporation)]]></Val>
        </Tgt>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";OriginalFilename" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text" DevLk="true">
        <Val><![CDATA[Microsoft.PythonTools.Debugger.Concord.dll]]></Val>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";ProductName" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text">
        <Val><![CDATA[Python support for Microsoft® Visual Studio®]]></Val>
        <Tgt Cat="Text" Stat="Loc" Orig="New">
          <Val><![CDATA[Поддержка Python для Microsoft® Visual Studio®]]></Val>
        </Tgt>
      </Str>
      <Disp Icon="Str" />
    </Item>
    <Item ItemId=";ProductVersion" ItemType="0" PsrId="211" Leaf="true">
      <Str Cat="Text" DevLk="true">
        <Val><![CDATA[15.7.18073.1]]></Val>
      </Str>
      <Disp Icon="Str" />
    </Item>
  </Item>
  <Item ItemId=";Version" ItemType="8" PsrId="211" Leaf="true">
    <Disp Icon="Expand" Expand="true" Disp="true" LocTbl="false" />
  </Item>
</LCX>

{'repo_name': 'microsoft/PTVS', 'stars': '2276', 'repo_language': 'C#', 'file_name': 'LaunchConditions.wxs', 'mime_type': 'text/xml', 'hash': -7294614497780674352, 'source_dataset': 'data'}


// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * ads117x.c  --  Driver for ads1174/8 ADC chips
 *
 * Copyright 2009 ShotSpotter Inc.
 * Author: Graeme Gregory <gg@slimlogic.co.uk>
 */

#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/soc.h>

#include <linux/of.h>

#define ADS117X_RATES (SNDRV_PCM_RATE_8000_48000)
#define ADS117X_FORMATS (SNDRV_PCM_FMTBIT_S16_LE)

static const struct snd_soc_dapm_widget ads117x_dapm_widgets[] = {
SND_SOC_DAPM_INPUT("Input1"),
SND_SOC_DAPM_INPUT("Input2"),
SND_SOC_DAPM_INPUT("Input3"),
SND_SOC_DAPM_INPUT("Input4"),
SND_SOC_DAPM_INPUT("Input5"),
SND_SOC_DAPM_INPUT("Input6"),
SND_SOC_DAPM_INPUT("Input7"),
SND_SOC_DAPM_INPUT("Input8"),
};

static const struct snd_soc_dapm_route ads117x_dapm_routes[] = {
	{ "Capture", NULL, "Input1" },
	{ "Capture", NULL, "Input2" },
	{ "Capture", NULL, "Input3" },
	{ "Capture", NULL, "Input4" },
	{ "Capture", NULL, "Input5" },
	{ "Capture", NULL, "Input6" },
	{ "Capture", NULL, "Input7" },
	{ "Capture", NULL, "Input8" },
};

static struct snd_soc_dai_driver ads117x_dai = {
/* ADC */
	.name = "ads117x-hifi",
	.capture = {
		.stream_name = "Capture",
		.channels_min = 1,
		.channels_max = 32,
		.rates = ADS117X_RATES,
		.formats = ADS117X_FORMATS,},
};

static const struct snd_soc_component_driver soc_component_dev_ads117x = {
	.dapm_widgets		= ads117x_dapm_widgets,
	.num_dapm_widgets	= ARRAY_SIZE(ads117x_dapm_widgets),
	.dapm_routes		= ads117x_dapm_routes,
	.num_dapm_routes	= ARRAY_SIZE(ads117x_dapm_routes),
	.idle_bias_on		= 1,
	.use_pmdown_time	= 1,
	.endianness		= 1,
	.non_legacy_dai_naming	= 1,
};

static int ads117x_probe(struct platform_device *pdev)
{
	return devm_snd_soc_register_component(&pdev->dev,
			&soc_component_dev_ads117x, &ads117x_dai, 1);
}

#if defined(CONFIG_OF)
static const struct of_device_id ads117x_dt_ids[] = {
	{ .compatible = "ti,ads1174" },
	{ .compatible = "ti,ads1178" },
	{ },
};
MODULE_DEVICE_TABLE(of, ads117x_dt_ids);
#endif

static struct platform_driver ads117x_codec_driver = {
	.driver = {
			.name = "ads117x-codec",
			.of_match_table = of_match_ptr(ads117x_dt_ids),
	},

	.probe = ads117x_probe,
};

module_platform_driver(ads117x_codec_driver);

MODULE_DESCRIPTION("ASoC ads117x driver");
MODULE_AUTHOR("Graeme Gregory");
MODULE_LICENSE("GPL");

{'repo_name': 'WireGuard/wireguard-linux', 'stars': '163', 'repo_language': 'C', 'file_name': 'Kconfig', 'mime_type': 'text/plain', 'hash': -1768110393879946948, 'source_dataset': 'data'}


#coding=utf-8
import tensorflow as tf
import keras
from keras.models import *
from keras.layers import *

def conv_block(input, filters):
    out = Conv2D(filters, kernel_size=(3,3), strides=1, padding='same')(input)
    out = BatchNormalization()(out)
    out = Activation('relu')(out)
    out = Conv2D(filters, kernel_size=(3,3), strides=1, padding='same')(out)
    out = BatchNormalization()(out)
    out = Activation('relu')(out)
    return out

def up_conv(input, filters):
    out = UpSampling2D()(input)
    out = Conv2D(filters, kernel_size=(3,3), strides=1, padding='same')(out)
    out = BatchNormalization()(out)
    out = Activation('relu')(out)
    return out

def UNet(nClasses, input_height=224, input_width=224):
    """
    UNet - Basic Implementation
    Paper : https://arxiv.org/abs/1505.04597
    """
    inputs = Input(shape=(input_height, input_width, 3))

    n1 = 32
    filters = [n1, n1 * 2, n1 * 4, n1 * 8, n1 * 16]
    conv1 = conv_block(inputs, n1)

    conv2 = MaxPooling2D(strides=2)(conv1)
    conv2 = conv_block(conv2, filters[1])

    conv3 = MaxPooling2D(strides=2)(conv2)
    conv3 = conv_block(conv3, filters[2])

    conv4 = MaxPooling2D(strides=2)(conv3)
    conv4 = conv_block(conv4, filters[3])

    conv5 = MaxPooling2D(strides=2)(conv4)
    conv5 = conv_block(conv5, filters[4])

    d5 = up_conv(conv5, filters[3])
    d5 = Concatenate()([conv4, d5])

    d4 = up_conv(d5, filters[2])
    d4 = Concatenate()([conv3, d4])
    d4 = conv_block(d4, filters[2])

    d3 = up_conv(d4, filters[1])
    d3 = Concatenate()([conv2, d3])
    d3 = conv_block(d3, filters[1])

    d2 = up_conv(d3, filters[0])
    d2 = Concatenate()([conv1, d2])
    d2 = conv_block(d2, filters[0])

    o = Conv2D(nClasses, (3, 3), padding='same')(d2)

    outputHeight = Model(inputs, o).output_shape[1]
    outputWidth = Model(inputs, o).output_shape[2]

    out = (Reshape((outputHeight * outputWidth, nClasses)))(o)
    out = Activation('softmax')(out)

    model = Model(input=inputs, output=out)
    model.outputHeight = outputHeight
    model.outputWidth = outputWidth

    return model

{'repo_name': 'BBuf/Keras-Semantic-Segmentation', 'stars': '135', 'repo_language': 'Python', 'file_name': 'ReadMe.txt', 'mime_type': 'text/plain', 'hash': 4946013221581574683, 'source_dataset': 'data'}


require "rails_helper"

describe PaperSerializer do

  it "should serialize properly" do
    user = create(:user)

    paper = build(:paper, document_location:"https://example.com", title:"Teh awesomeness", submittor:user)
    serializer = PaperSerializer.new(paper)
    hash = hash_from_json(serializer.to_json)

    expect(hash.keys).to contain_exactly('typed_provider_id',
                                         'user_permissions',
                                         'state',
                                         'submitted_at',
                                         'title',
                                         'pending_issues_count',
                                         'submittor',
                                         'doi',
                                         'authors'
                         )
  end

  it "should serialize the submittor properly" do
    user = create(:user)

    paper = build(:paper, submittor:user)
    serializer = PaperSerializer.new(paper)
    hash = hash_from_json(serializer.to_json)

    expect(hash['submittor'].keys).to contain_exactly("name")
  end

end

{'repo_name': 'openjournals/theoj', 'stars': '125', 'repo_language': 'Ruby', 'file_name': 'openjournal.cls', 'mime_type': 'text/x-tex', 'hash': 1157334223964848986, 'source_dataset': 'data'}


Request header lacks authorization parameters，it should be: Authorization

The authorization code prefix is incorrect. it should be: Bearer

{'repo_name': 'juicycleff/ultimate-backend', 'stars': '494', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 3495195513610656631, 'source_dataset': 'data'}


curecoin-qt: Qt5 GUI for Curecoin
================================

Build instructions
===================

##Debian
-------

First, make sure that the required packages for Qt5 development of your
distribution are installed, for Debian and Ubuntu these are:

This involves downloading the source, meeting the dependencies, compiling the code, and then installing the resulting software.

git clone https://github.com/cygnusxi/CurecoinSource.git

##FOR THE GUI CLIENT:

sudo apt-get install qt5-default qt5-qmake qtbase5-dev-tools qttools5-dev-tools libboost-dev libboost-system-dev libboost-filesystem-dev libboost-program-options-dev libboost-thread-dev libssl-dev libminiupnpc-dev libdb5.3++-dev dh-make build-essential

From the main directory, run the following:

qmake && make

sudo make install

Alternatively, don't run that command and just place the binary wherever you want.

##FOR THE HEADLESS CURECOIND:

sudo apt-get install libboost-all-dev libqrencode-dev libssl-dev libdb5.3-dev libdb5.3++-dev libminiupnpc-dev dh-make build-essential
cd src/ && mkdir obj/ && make -f makefile.unix

sudo make

install

Alternatively, don't run that command and just place the binary wherever you want.
libdb4.8 should also work if libdb5.1 is too high a version for you. Newer versions of Linux will need libdb5.3++-dev

Alternatively, install `Qt Creator`_ and open the `curecoin-qt.pro` file.

An executable named `curecoin-qt` will be built.

.. _`Qt Creator`: http://qt.nokia.com/downloads/

##Windows
--------

Windows build instructions:

- Download the `Qt Windows SDK`_ and install it. You don't need the Symbian stuff, just the desktop Qt.

- Download and extract the `dependencies archive`_  [#]_, or compile openssl, boost and dbcxx yourself.

- Copy the contents of the folder "deps" to "X:\\QtSDK\\mingw", replace X:\\ with the location where you installed the Qt SDK. Make sure that the contents of "deps\\include" end up in the current "include" directory.

- Open the bitcoin-qt.pro file in Qt Creator and build as normal (ctrl-B)

.. _`Qt Windows SDK`: http://qt.nokia.com/downloads/sdk-windows-cpp
.. _`dependencies archive`: https://download.visucore.com/bitcoin/qtgui_deps_1.zip
.. [#] PGP signature: https://download.visucore.com/bitcoin/qtgui_deps_1.zip.sig (signed with RSA key ID `610945D0`_)
.. _`610945D0`: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x610945D0

##Mac OS X
--------

- Download and install the `Qt Mac OS X SDK`_. It is recommended to also install Apple's Xcode with UNIX tools.

- Download and install `MacPorts`_.

- Execute the following commands in a terminal to get the dependencies:

::

	sudo port selfupdate
	sudo port install boost db48 miniupnpc

- Open the bitcoin-qt.pro file in Qt Creator and build as normal (cmd-B)

.. _`Qt Mac OS X SDK`: http://qt.nokia.com/downloads/sdk-mac-os-cpp
.. _`MacPorts`: http://www.macports.org/install.php

Build configuration options
============================

UPnP port forwarding
---------------------

To use UPnP for port forwarding behind a NAT router (recommended, as more connections overall allow for a faster and more stable curecoin experience), pass the following argument to qmake:

::

    qmake "USE_UPNP=1"

(in **Qt Creator**, you can find the setting for additional qmake arguments under "Projects" -> "Build Settings" -> "Build Steps", then click "Details" next to **qmake**)

This requires miniupnpc for UPnP port mapping.  It can be downloaded from
http://miniupnp.tuxfamily.org/files/.  UPnP support is not compiled in by default.

Set USE_UPNP to a different value to control this:

+------------+--------------------------------------------------------------------------+
| USE_UPNP=- | no UPnP support, miniupnpc not required;                                 |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=0 | (the default) built with UPnP, support turned off by default at runtime; |
+------------+--------------------------------------------------------------------------+
| USE_UPNP=1 | build with UPnP support turned on by default at runtime.                 |
+------------+--------------------------------------------------------------------------+

Notification support for recent (k)ubuntu versions
---------------------------------------------------

To see desktop notifications on (k)ubuntu versions starting from 10.04, enable usage of the
FreeDesktop notification interface through DBUS using the following qmake option:

::

    qmake "USE_DBUS=1"

Generation of QR codes
-----------------------

libqrencode may be used to generate QRCode images for payment requests.
It can be downloaded from http://fukuchi.org/works/qrencode/index.html.en, or installed via your package manager. Pass the USE_QRCODE
flag to qmake to control this:

+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=0 | (the default) No QRCode support - libarcode not required                 |
+--------------+--------------------------------------------------------------------------+
| USE_QRCODE=1 | QRCode support enabled                                                   |
+--------------+--------------------------------------------------------------------------+

Berkely DB version warning
==========================

A warning for people using the *static binary* version of curecoin on a Linux/UNIX-ish system (tl;dr: **Berkely DB databases are not forward compatible**).

The static binary version of curecoin is linked against libdb4.8 (see also `this Debian issue`_).

Now the nasty thing is that databases from 5.X are not compatible with 4.X.

If the globally installed development package of Berkely DB installed on your system is 5.X, any source you
build yourself will be linked against that. The first time you run with a 5.X version the database will be upgraded,
and 4.X cannot open the new format. This means that you cannot go back to the old statically linked version without
significant hassle!

.. _`this Debian issue`: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=621425

{'repo_name': 'cygnusxi/CurecoinSource', 'stars': '114', 'repo_language': 'C++', 'file_name': 'Doxyfile', 'mime_type': 'text/plain', 'hash': -5110935226594839434, 'source_dataset': 'data'}


LightmappedGeneric
{
	"$basetexture"	"decals\decalgraffiti046a_cs"
	"$translucent" "1"
	"$decal" "1"
	"$decalscale" "0.500"

}

{'repo_name': 'BSVino/DoubleAction', 'stars': '119', 'repo_language': 'C++', 'file_name': 'settings.scr', 'mime_type': 'text/plain', 'hash': -8575318379715845791, 'source_dataset': 'data'}


import config from './config';
import { warn } from './debug';

export function handleError(err, vm, info) {
  if (vm) {
    let cur = vm;
    while ((cur = cur.$parent)) {
      const hooks = cur.$options.errorCaptured;
      if (hooks) {
        for (let i = 0; i < hooks.length; i++) {
          try {
            const capture = hooks[i].call(cur, err, vm, info) === false;
            if (capture) return;
          } catch (e) {
            globalHandleError(e, cur, 'errorCaptured hook');
          }
        }
      }
    }
  }
  globalHandleError(err, vm, info);
}

function globalHandleError(err, vm, info) {
  if (config.errorHandler) {
    try {
      return config.errorHandler.call(null, err, vm, info);
    } catch (e) {
      logError(e, null, 'config.errorHandler');
    }
  }
  logError(err, vm, info);
}

function logError(err, vm, info) {
  if (process.env.NODE_ENV !== 'production') {
    warn(`Error in ${info}: "${err.toString()}"`, vm);
  }
  /* istanbul ignore else */
  if (typeof console !== 'undefined') {
    // eslint-disable-next-line
    console.error(err);
  } else {
    throw err;
  }
}

{'repo_name': 'tencentyun/TIMSDK', 'stars': '1168', 'repo_language': 'JavaScript', 'file_name': 'elementAt.js', 'mime_type': 'text/x-java', 'hash': 7061091660104365480, 'source_dataset': 'data'}


/*
 * Copyright 2014 - 2020 Rafael Winterhalter
 *
 * 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 net.bytebuddy.build.gradle;

import net.bytebuddy.build.gradle.api.ChangeType;
import net.bytebuddy.build.gradle.api.FileChange;
import org.gradle.api.Project;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * An incremental resolver is responsible to determine the file set to transform after a change.
 */
public interface IncrementalResolver {

    /**
     * Returns a list of files to transform after an incremental change.
     *
     * @param project    The current project.
     * @param changes    An iterable of all changes that were found.
     * @param sourceRoot The source directory.
     * @param targetRoot The target directory.
     * @param classPath  The class path available.
     * @return A list of files to include in the transformation.
     */
    List<File> apply(Project project, Iterable<FileChange> changes, File sourceRoot, File targetRoot, Iterable<File> classPath);

    /**
     * An incremental resolver that retransforms any file that has changed but no other files.
     */
    enum ForChangedFiles implements IncrementalResolver {

        /**
         * The singleton instance.
         */
        INSTANCE;

        /**
         * {@inheritDoc}
         */
        public List<File> apply(Project project, Iterable<FileChange> changes, File sourceRoot, File targetRoot, Iterable<File> classPath) {
            List<File> files = new ArrayList<File>();
            for (FileChange change : changes) {
                if (change.getChangeType() == ChangeType.REMOVED) {
                    File target = new File(targetRoot, sourceRoot.toURI().relativize(change.getFile().toURI()).getPath());
                    if (project.delete(target)) {
                        project.getLogger().debug("Deleted removed file {} to prepare incremental build", target);
                    }
                } else {
                    files.add(change.getFile());
                }
            }
            return files;
        }
    }
}

{'repo_name': 'raphw/byte-buddy', 'stars': '3588', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': 7665492095745187145, 'source_dataset': 'data'}


module.exports = function test (grunt) {
	// to be run prior to submitting a PR
	grunt.registerTask('test', 'run jshint, qunit source w/ coverage, and validate HTML',
		['jshint', 'connect:testServer', 'qunit:noMoment', 'qunit:globals', 'test-dist', 'htmllint']);

	grunt.registerTask('unittest', 'Just unit test the dist without all the fluff',
		['connect:testServer', 'test-dist']);

	grunt.registerTask('prep-commonjs-test', 'run commonjs config build and browserify to prep for commonjs test',
		['commonjs', 'browserify:commonjs']);

	grunt.registerTask('test-dist', 'run jshint, qunit source w/ coverage, and validate HTML',
		['dist', 'prep-commonjs-test', 'qunit:dist', 'clean:commonjs']);

	// If qunit:source is working but qunit:full is breaking, check to see if the dist broke the code. This would be especially useful if we start mangling our code, but, is 99.99% unlikely right now
	grunt.registerTask('validate-dist', 'run qunit:source, dist, and then qunit:full',
		['connect:testServer', 'qunit:source', 'test-dist']);

	// multiple jQuery versions, then run SauceLabs VMs
	grunt.registerTask('releasetest', 'run jshint, build dist, all source tests, validation, and qunit on SauceLabs',
		['test'/*, 'saucelabs-qunit:defaultBrowsers'*/]);

	// Due to TravisCI security concerns, Saucelabs can not be run for PRs from forks. Therefore, it can not become part of our PR process.
	// https://docs.travis-ci.com/user/pull-requests/#Pull-Requests-and-Security-Restrictions
	// can be run locally instead. Requires the Fuel UX Saucelabs API key file.
	grunt.registerTask('saucelabs', 'run jshint, and qunit on saucelabs',
		['connect:testServer', 'jshint', 'saucelabs-qunit:defaultBrowsers']);

	grunt.registerTask('travisci', 'Tests to run when in Travis CI environment',
		['test']);

	// if you've already accidentally added your files for commit, this will at least unstage them. If you haven't, this will wipe them out.
	grunt.registerTask('resetdist', 'resets changes to dist to keep them from being checked in', function resetdist () {
		// default resetdist to true... basically.
		if (typeof grunt.option('resetdist') === 'undefined' || grunt.option('resetdist')) {
			var exec = require('child_process').execSync;
			exec('git reset HEAD dist');
			exec('git checkout -- dist');
		}
	});
};

{'repo_name': 'ExactTarget/fuelux', 'stars': '5356', 'repo_language': 'JavaScript', 'file_name': 'commonjs-reference-module.js', 'mime_type': 'text/plain', 'hash': 8287928145418097488, 'source_dataset': 'data'}


#!/bin/bash -vex
set -v -e -x

export DEBIAN_FRONTEND=noninteractive

# Update apt-get lists
apt-get update -y

# Install dependencies
apt-get install -y \
    curl \
    tar \
    jq \
    python \
    build-essential # Only needed for zstd installation, will be removed later

# Install mercurial
. /setup/common.sh
. /setup/install-mercurial.sh

# Install build-image.sh script
chmod +x /usr/local/bin/build-image.sh
chmod +x /usr/local/bin/run-task

# Create workspace
mkdir -p /home/worker/workspace

# Install zstd 1.1.1
cd /setup
tooltool_fetch <<EOF
[
  {
    "size": 734872,
    "visibility": "public",
    "digest": "a8817e74254f21ee5b76a21691e009ede2cdc70a78facfa453902df3e710e90e78d67f2229956d835960fd1085c33312ff273771b75f9322117d85eb35d8e695",
    "algorithm": "sha512",
    "filename": "zstd.tar.gz"
  }
]
EOF
cd -
tar -xvf /setup/zstd.tar.gz -C /setup
make -C /setup/zstd-1.1.1/programs install
rm -rf /tmp/zstd-1.1.1/ /tmp/zstd.tar.gz
apt-get purge -y build-essential

# Purge apt-get caches to minimize image size
apt-get auto-remove -y
apt-get clean -y
rm -rf /var/lib/apt/lists/

# Remove this script
rm -rf /setup/

{'repo_name': 'mozilla/positron', 'stars': '514', 'repo_language': 'None', 'file_name': 'moz.build', 'mime_type': 'text/plain', 'hash': 2183299468164182204, 'source_dataset': 'data'}


//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Security
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.Globalization;
    using System.IdentityModel.Policy;
    using System.IdentityModel.Tokens;
    using System.Runtime;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Description;
    using System.ServiceModel.Diagnostics;
    using System.ServiceModel.Dispatcher;
    using System.ServiceModel.Security.Tokens;
    using System.Xml;

    abstract class NegotiationTokenAuthenticator<T> : CommunicationObjectSecurityTokenAuthenticator, IIssuanceSecurityTokenAuthenticator, ISecurityContextSecurityTokenCacheProvider
        where T : NegotiationTokenAuthenticatorState
    {
        internal const string defaultServerMaxNegotiationLifetimeString = "00:01:00";
        internal const string defaultServerIssuedTokenLifetimeString = "10:00:00";
        internal const string defaultServerIssuedTransitionTokenLifetimeString = "00:15:00";
        internal const int defaultServerMaxActiveNegotiations = 128;
        internal static readonly TimeSpan defaultServerMaxNegotiationLifetime = TimeSpan.Parse(defaultServerMaxNegotiationLifetimeString, CultureInfo.InvariantCulture);
        internal static readonly TimeSpan defaultServerIssuedTokenLifetime = TimeSpan.Parse(defaultServerIssuedTokenLifetimeString, CultureInfo.InvariantCulture);
        internal static readonly TimeSpan defaultServerIssuedTransitionTokenLifetime = TimeSpan.Parse(defaultServerIssuedTransitionTokenLifetimeString, CultureInfo.InvariantCulture);
        internal const int defaultServerMaxCachedTokens = 1000;
        internal const bool defaultServerMaintainState = true;
        internal static readonly SecurityStandardsManager defaultStandardsManager = SecurityStandardsManager.DefaultInstance;
        internal static readonly SecurityStateEncoder defaultSecurityStateEncoder = new DataProtectionSecurityStateEncoder();

        NegotiationTokenAuthenticatorStateCache<T> stateCache;
        RenewedSecurityTokenHandler renewedSecurityTokenHandler;
        NegotiationHost negotiationHost;
        bool encryptStateInServiceToken;
        TimeSpan serviceTokenLifetime;
        int maximumCachedNegotiationState;
        TimeSpan negotiationTimeout;
        bool isClientAnonymous;
        SecurityStandardsManager standardsManager;
        SecurityAlgorithmSuite securityAlgorithmSuite;
        SecurityTokenParameters issuedSecurityTokenParameters;
        ISecurityContextSecurityTokenCache issuedTokenCache;
        BindingContext issuerBindingContext;
        Uri listenUri;
        string sctUri;
        AuditLogLocation auditLogLocation;
        bool suppressAuditFailure;
        AuditLevel messageAuthenticationAuditLevel;
        SecurityStateEncoder securityStateEncoder;
        SecurityContextCookieSerializer cookieSerializer;
        IMessageFilterTable<EndpointAddress> endpointFilterTable;
        IssuedSecurityTokenHandler issuedSecurityTokenHandler;
        int maxMessageSize;
        IList<Type> knownTypes;
        int maximumConcurrentNegotiations;
        List<IChannel> activeNegotiationChannels1;
        List<IChannel> activeNegotiationChannels2;
        IOThreadTimer idlingNegotiationSessionTimer;
        bool isTimerCancelled;

        protected NegotiationTokenAuthenticator() : base()
        {
            InitializeDefaults();
        }

        public IssuedSecurityTokenHandler IssuedSecurityTokenHandler
        {
            get
            {
                return this.issuedSecurityTokenHandler;
            }
            set
            {
                this.issuedSecurityTokenHandler = value;
            }

        }

        public RenewedSecurityTokenHandler RenewedSecurityTokenHandler
        {
            get
            {
                return this.renewedSecurityTokenHandler;
            }
            set
            {
                this.renewedSecurityTokenHandler = value;
            }
        }

        // settings
        public bool EncryptStateInServiceToken
        {
            get
            {
                return this.encryptStateInServiceToken;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.encryptStateInServiceToken = value;
            }
        }

        public TimeSpan ServiceTokenLifetime
        {
            get
            {
                return this.serviceTokenLifetime;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value <= TimeSpan.Zero)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
                }

                if (TimeoutHelper.IsTooLarge(value))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
                }
                this.serviceTokenLifetime = value;
            }
        }

        public int MaximumCachedNegotiationState
        {
            get
            {
                return this.maximumCachedNegotiationState;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.ValueMustBeNonNegative)));
                }
                this.maximumCachedNegotiationState = value;
            }
        }

        public int MaximumConcurrentNegotiations
        {
            get
            {
                return this.maximumConcurrentNegotiations;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value < 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.ValueMustBeNonNegative)));
                }
                this.maximumConcurrentNegotiations = value;
            }
        }

        public TimeSpan NegotiationTimeout
        {
            get
            {
                return this.negotiationTimeout;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value <= TimeSpan.Zero)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
                }

                if (TimeoutHelper.IsTooLarge(value))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
                        SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
                }
                this.negotiationTimeout = value;
            }
        }

        public bool IsClientAnonymous
        {
            get
            {
                return this.isClientAnonymous;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.isClientAnonymous = value;
            }
        }

        public SecurityAlgorithmSuite SecurityAlgorithmSuite
        {
            get
            {
                return this.securityAlgorithmSuite;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.securityAlgorithmSuite = value;
            }
        }

        public IMessageFilterTable<EndpointAddress> EndpointFilterTable
        {
            get
            {
                return this.endpointFilterTable;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.endpointFilterTable = value;
            }
        }

        ISecurityContextSecurityTokenCache ISecurityContextSecurityTokenCacheProvider.TokenCache
        {
            get
            {
                return this.IssuedTokenCache;
            }
        }

        public virtual XmlDictionaryString RequestSecurityTokenAction
        {
            get
            {
                return this.StandardsManager.TrustDriver.RequestSecurityTokenAction;
            }
        }

        public virtual XmlDictionaryString RequestSecurityTokenResponseAction
        {
            get
            {
                return this.StandardsManager.TrustDriver.RequestSecurityTokenResponseAction;
            }
        }

        public virtual XmlDictionaryString RequestSecurityTokenResponseFinalAction
        {
            get
            {
                return this.StandardsManager.TrustDriver.RequestSecurityTokenResponseFinalAction;
            }
        }

        public SecurityStandardsManager StandardsManager
        {
            get
            {
                return this.standardsManager;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.standardsManager = (value != null ? value : SecurityStandardsManager.DefaultInstance);
            }
        }

        public SecurityTokenParameters IssuedSecurityTokenParameters
        {
            get
            {
                return this.issuedSecurityTokenParameters;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.issuedSecurityTokenParameters = value;
            }
        }

        public ISecurityContextSecurityTokenCache IssuedTokenCache
        {
            get { return this.issuedTokenCache; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.issuedTokenCache = value;
            }
        }

        public AuditLogLocation AuditLogLocation
        {
            get
            {
                return this.auditLogLocation;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.auditLogLocation = value;
            }
        }

        public bool SuppressAuditFailure
        {
            get
            {
                return this.suppressAuditFailure;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.suppressAuditFailure = value;
            }
        }

        public AuditLevel MessageAuthenticationAuditLevel
        {
            get
            {
                return this.messageAuthenticationAuditLevel;
            }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.messageAuthenticationAuditLevel = value;
            }
        }

        public BindingContext IssuerBindingContext
        {
            get { return this.issuerBindingContext; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
                }
                this.issuerBindingContext = value.Clone();
            }
        }

        public Uri ListenUri
        {
            get { return this.listenUri; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.listenUri = value;
            }
        }

        public SecurityStateEncoder SecurityStateEncoder
        {
            get { return this.securityStateEncoder; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.securityStateEncoder = value;
            }
        }

        public IList<Type> KnownTypes
        {
            get { return this.knownTypes; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                if (value != null)
                {
                    this.knownTypes = new Collection<Type>(value);
                }
                else
                {
                    this.knownTypes = null;
                }
            }
        }

        public int MaxMessageSize
        {
            get { return this.maxMessageSize; }
            set
            {
                this.CommunicationObject.ThrowIfDisposedOrImmutable();
                this.maxMessageSize = value;
            }
        }

        protected string SecurityContextTokenUri
        {
            get
            {
                this.CommunicationObject.ThrowIfNotOpened();
                return this.sctUri;
            }
        }

        Object ThisLock
        {
            get
            {
                return this.CommunicationObject;
            }
        }

        // helpers
        protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key,
            DateTime tokenEffectiveTime, DateTime tokenExpirationTime,
            ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
        {
            return IssueSecurityContextToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, null,
                tokenEffectiveTime, tokenExpirationTime, authorizationPolicies, isCookieMode);
        }

        protected SecurityContextSecurityToken IssueSecurityContextToken(UniqueId contextId, string id, byte[] key,
            DateTime tokenEffectiveTime, DateTime tokenExpirationTime, UniqueId keyGeneration, DateTime keyEffectiveTime,
            DateTime keyExpirationTime, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies, bool isCookieMode)
        {
            this.CommunicationObject.ThrowIfClosedOrNotOpen();
            if (this.securityStateEncoder == null && isCookieMode)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SctCookieNotSupported)));
            }
            byte[] cookieBlob = (isCookieMode) ? this.cookieSerializer.CreateCookieFromSecurityContext(contextId, id, key, tokenEffectiveTime, tokenExpirationTime, keyGeneration,
                                keyEffectiveTime, keyExpirationTime, authorizationPolicies) : null;

            SecurityContextSecurityToken issuedToken = new SecurityContextSecurityToken(contextId, id, key, tokenEffectiveTime, tokenExpirationTime,
                authorizationPolicies, isCookieMode, cookieBlob, keyGeneration, keyEffectiveTime, keyExpirationTime);
            return issuedToken;
        }

        void InitializeDefaults()
        {
            this.encryptStateInServiceToken = !defaultServerMaintainState;
            this.serviceTokenLifetime = defaultServerIssuedTokenLifetime;
            this.maximumCachedNegotiationState = defaultServerMaxActiveNegotiations;
            this.negotiationTimeout = defaultServerMaxNegotiationLifetime;
            this.isClientAnonymous = false;
            this.standardsManager = defaultStandardsManager;
            this.securityStateEncoder = defaultSecurityStateEncoder;
            this.maximumConcurrentNegotiations = defaultServerMaxActiveNegotiations;
            // we rely on the transport encoders to enforce the message size except in the
            // mixed mode nego case, where the client is unauthenticated and the maxMessageSize is too
            // large to be a mitigation
            this.maxMessageSize = Int32.MaxValue;
        }

        public override void OnClose(TimeSpan timeout)
        {
            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            if (this.negotiationHost != null)
            {
                this.negotiationHost.Close(timeoutHelper.RemainingTime());
                this.negotiationHost = null;
            }

            lock (ThisLock)
            {
                if (this.idlingNegotiationSessionTimer != null && !this.isTimerCancelled)
                {
                    this.isTimerCancelled = true;
                    this.idlingNegotiationSessionTimer.Cancel();
                }
            }
            base.OnClose(timeoutHelper.RemainingTime());
        }

        public override void OnAbort()
        {
            if (this.negotiationHost != null)
            {
                this.negotiationHost.Abort();
                this.negotiationHost = null;
            }

            lock (ThisLock)
            {
                if (this.idlingNegotiationSessionTimer != null && !this.isTimerCancelled)
                {
                    this.isTimerCancelled = true;
                    this.idlingNegotiationSessionTimer.Cancel();
                }
            }
            base.OnAbort();
        }

        public override void OnOpen(TimeSpan timeout)
        {
            if (this.IssuerBindingContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuerBuildContextNotSet, this.GetType())));
            }
            if (this.IssuedSecurityTokenParameters == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuedSecurityTokenParametersNotSet, this.GetType())));
            }
            if (this.SecurityAlgorithmSuite == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecurityAlgorithmSuiteNotSet, this.GetType())));
            }
            if (this.IssuedTokenCache == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.IssuedTokenCacheNotSet, this.GetType())));
            }

            TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
            this.SetupServiceHost();
            negotiationHost.Open(timeoutHelper.RemainingTime());
            this.stateCache = new NegotiationTokenAuthenticatorStateCache<T>(this.NegotiationTimeout, this.MaximumCachedNegotiationState);
            this.sctUri = this.StandardsManager.SecureConversationDriver.TokenTypeUri;
            if (this.SecurityStateEncoder != null)
            {
                this.cookieSerializer = new SecurityContextCookieSerializer(this.SecurityStateEncoder, this.KnownTypes);
            }
            if (this.negotiationTimeout < TimeSpan.MaxValue)
            {
                lock (ThisLock)
                {
                    this.activeNegotiationChannels1 = new List<IChannel>();
                    this.activeNegotiationChannels2 = new List<IChannel>();
                    this.idlingNegotiationSessionTimer = new IOThreadTimer(new Action<object>(this.OnIdlingNegotiationSessionTimer), this, false);
                    this.isTimerCancelled = false;
                    this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
                }
            }
            base.OnOpen(timeoutHelper.RemainingTime());
        }

        protected override bool CanValidateTokenCore(SecurityToken token)
        {
            return (token is SecurityContextSecurityToken);
        }

        protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token)
        {
            SecurityContextSecurityToken sct = (SecurityContextSecurityToken)token;
            return sct.AuthorizationPolicies;
        }

        protected abstract Binding GetNegotiationBinding(Binding binding);
        protected abstract bool IsMultiLegNegotiation { get; }
        protected abstract MessageFilter GetListenerFilter();

        void SetupServiceHost()
        {
            ChannelBuilder channelBuilder = new ChannelBuilder(this.IssuerBindingContext.Clone(), true);
            channelBuilder.Binding.Elements.Insert(0, new ReplyAdapterBindingElement());
            channelBuilder.Binding = new CustomBinding(this.GetNegotiationBinding(channelBuilder.Binding));
            negotiationHost = new NegotiationHost(this, this.ListenUri, channelBuilder, this.GetListenerFilter());
        }

        // message processing abstract method
        protected abstract BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out T negotiationState);
        protected abstract BodyWriter ProcessRequestSecurityTokenResponse(T negotiationState, Message request, RequestSecurityTokenResponse requestSecurityTokenResponse);

        // message handlers
        protected virtual void ParseMessageBody(Message message, out string context, out RequestSecurityToken requestSecurityToken, out RequestSecurityTokenResponse requestSecurityTokenResponse)
        {
            requestSecurityToken = null;
            requestSecurityTokenResponse = null;
            if (message.Headers.Action == this.RequestSecurityTokenAction.Value)
            {
                XmlDictionaryReader reader = message.GetReaderAtBodyContents();
                using (reader)
                {
                    requestSecurityToken = RequestSecurityToken.CreateFrom(this.StandardsManager, reader);
                    message.ReadFromBodyContentsToEnd(reader);
                }
                context = requestSecurityToken.Context;
            }
            else if (message.Headers.Action == this.RequestSecurityTokenResponseAction.Value)
            {
                XmlDictionaryReader reader = message.GetReaderAtBodyContents();
                using (reader)
                {
                    requestSecurityTokenResponse = RequestSecurityTokenResponse.CreateFrom(this.StandardsManager, reader);
                    message.ReadFromBodyContentsToEnd(reader);
                }
                context = requestSecurityTokenResponse.Context;
            }
            else
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.InvalidActionForNegotiationMessage, message.Headers.Action)), message);
            }
        }

        static Message CreateReply(Message request, XmlDictionaryString action, BodyWriter body)
        {
            if (request.Headers.MessageId != null)
            {
                Message reply = Message.CreateMessage(request.Version, ActionHeader.Create(action, request.Version.Addressing), body);
                reply.InitializeReply(request);
                return reply;
            }
            else
            {
                // the message id may not be present if MapToHttp is true
                return Message.CreateMessage(request.Version, ActionHeader.Create(action, request.Version.Addressing), body);
            }
        }

        void OnTokenIssued(SecurityToken token)
        {
            if (this.issuedSecurityTokenHandler != null)
            {
                this.issuedSecurityTokenHandler(token, null);
            }
        }

        void AddNegotiationChannelForIdleTracking()
        {
            if (OperationContext.Current.SessionId == null)
            {
                return;
            }
            lock (ThisLock)
            {
                if (this.idlingNegotiationSessionTimer == null)
                {
                    return;
                }
                IChannel channel = OperationContext.Current.Channel;
                if (!this.activeNegotiationChannels1.Contains(channel) && !this.activeNegotiationChannels2.Contains(channel))
                {
                    this.activeNegotiationChannels1.Add(channel);
                }
                if (this.isTimerCancelled)
                {
                    this.isTimerCancelled = false;
                    this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
                }
            }
        }

        void RemoveNegotiationChannelFromIdleTracking()
        {
            if (OperationContext.Current.SessionId == null)
            {
                return;
            }
            lock (ThisLock)
            {
                if (this.idlingNegotiationSessionTimer == null)
                {
                    return;
                }
                IChannel channel = OperationContext.Current.Channel;
                this.activeNegotiationChannels1.Remove(channel);
                this.activeNegotiationChannels2.Remove(channel);
                if (this.activeNegotiationChannels1.Count == 0 && this.activeNegotiationChannels2.Count == 0)
                {
                    this.isTimerCancelled = true;
                    this.idlingNegotiationSessionTimer.Cancel();
                }
            }
        }

        void OnIdlingNegotiationSessionTimer(object state)
        {
            lock (ThisLock)
            {
                if (this.isTimerCancelled || (this.CommunicationObject.State != CommunicationState.Opened && this.CommunicationObject.State != CommunicationState.Opening))
                {
                    return;
                }

                try
                {
                    for (int i = 0; i < this.activeNegotiationChannels2.Count; ++i)
                    {
                        this.activeNegotiationChannels2[i].Abort();
                    }
                    List<IChannel> temp = this.activeNegotiationChannels2;
                    temp.Clear();
                    this.activeNegotiationChannels2 = this.activeNegotiationChannels1;
                    this.activeNegotiationChannels1 = temp;
                }
#pragma warning suppress 56500
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }
                }
                finally
                {
                    if (this.CommunicationObject.State == CommunicationState.Opened || this.CommunicationObject.State == CommunicationState.Opening)
                    {
                        if (this.activeNegotiationChannels1.Count == 0 && this.activeNegotiationChannels2.Count == 0)
                        {
                            this.isTimerCancelled = true;
                            this.idlingNegotiationSessionTimer.Cancel();
                        }
                        else
                        {
                            this.idlingNegotiationSessionTimer.Set(this.negotiationTimeout);
                        }
                    }
                }
            }
        }

        Message ProcessRequestCore(Message request)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            Uri to = null;
            RequestSecurityToken rst = null;
            RequestSecurityTokenResponse rstr = null;
            string context = null;
            bool disposeRequest = false;
            bool isNegotiationFailure = true;
            T negotiationState = null;

            try
            {
                // validate the message size if needed
                if (this.maxMessageSize < int.MaxValue)
                {
                    string action = request.Headers.Action;
                    try
                    {
                        using (MessageBuffer buffer = request.CreateBufferedCopy(this.maxMessageSize))
                        {
                            request = buffer.CreateMessage();
                            disposeRequest = true;
                        }
                    }
                    catch (QuotaExceededException e)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityNegotiationException(SR.GetString(SR.SecurityNegotiationMessageTooLarge, action, this.maxMessageSize), e));
                    }
                }
                try
                {
                    to = request.Headers.To;
                    ParseMessageBody(request, out context, out rst, out rstr);
                    // check if there is existing state
                    if (context != null)
                    {
                        negotiationState = this.stateCache.GetState(context);
                    }
                    else
                    {
                        negotiationState = null;
                    }
                    bool disposeState = false;
                    BodyWriter replyBody;
                    try
                    {
                        if (rst != null)
                        {
                            if (negotiationState != null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.NegotiationStateAlreadyPresent, context)));
                            }
                            replyBody = this.ProcessRequestSecurityToken(request, rst, out negotiationState);
                            lock (negotiationState.ThisLock)
                            {
                                if (negotiationState.IsNegotiationCompleted)
                                {
                                    // if session-sct add it to cache and add a redirect header
                                    if (!negotiationState.ServiceToken.IsCookieMode)
                                    {
                                        this.IssuedTokenCache.AddContext(negotiationState.ServiceToken);
                                    }
                                    this.OnTokenIssued(negotiationState.ServiceToken);
                                    SecurityTraceRecordHelper.TraceServiceSecurityNegotiationCompleted(request, this, negotiationState.ServiceToken);
                                    disposeState = true;
                                }
                                else
                                {
                                    this.stateCache.AddState(context, negotiationState);
                                    disposeState = false;
                                }
                                AddNegotiationChannelForIdleTracking();
                            }
                        }
                        else
                        {
                            if (negotiationState == null)
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotFindNegotiationState, context)));
                            }
                            lock (negotiationState.ThisLock)
                            {
                                replyBody = this.ProcessRequestSecurityTokenResponse(negotiationState, request, rstr);
                                if (negotiationState.IsNegotiationCompleted)
                                {
                                    // if session-sct add it to cache and add a redirect header
                                    if (!negotiationState.ServiceToken.IsCookieMode)
                                    {
                                        this.IssuedTokenCache.AddContext(negotiationState.ServiceToken);
                                    }
                                    this.OnTokenIssued(negotiationState.ServiceToken);
                                    SecurityTraceRecordHelper.TraceServiceSecurityNegotiationCompleted(request, this, negotiationState.ServiceToken);
                                    disposeState = true;
                                }
                                else
                                {
                                    disposeState = false;
                                }
                            }
                        }

                        if (negotiationState.IsNegotiationCompleted && null != this.ListenUri)
                        {
                            if (AuditLevel.Success == (this.messageAuthenticationAuditLevel & AuditLevel.Success))
                            {
                                string primaryIdentity = negotiationState.GetRemoteIdentityName();
                                SecurityAuditHelper.WriteSecurityNegotiationSuccessEvent(this.auditLogLocation,
                                    this.suppressAuditFailure, request, request.Headers.To, request.Headers.Action,
                                    primaryIdentity, this.GetType().Name);
                            }
                        }
                        isNegotiationFailure = false;
                    }
                    catch (Exception exception)
                    {
                        if (Fx.IsFatal(exception))
                            throw;

                        if (PerformanceCounters.PerformanceCountersEnabled && null != this.ListenUri)
                        {
                            PerformanceCounters.AuthenticationFailed(request, this.ListenUri);
                        }
                        if (AuditLevel.Failure == (this.messageAuthenticationAuditLevel & AuditLevel.Failure))
                        {
                            try
                            {
                                string primaryIdentity = (negotiationState != null) ? negotiationState.GetRemoteIdentityName() : String.Empty;
                                SecurityAuditHelper.WriteSecurityNegotiationFailureEvent(this.auditLogLocation,
                                    this.suppressAuditFailure, request, request.Headers.To, request.Headers.Action,
                                    primaryIdentity, this.GetType().Name, exception);
                            }
#pragma warning suppress 56500
                            catch (Exception auditException)
                            {
                                if (Fx.IsFatal(auditException))
                                    throw;

                                DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error);
                            }
                        }

                        disposeState = true;
                        throw;
                    }
                    finally
                    {
                        if (disposeState)
                        {
                            if (negotiationState != null)
                            {
                                if (context != null)
                                {
                                    stateCache.RemoveState(context);
                                }
                                negotiationState.Dispose();
                            }
                        }
                    }

                    return CreateReply(request, (replyBody is RequestSecurityTokenResponseCollection) ? RequestSecurityTokenResponseFinalAction : RequestSecurityTokenResponseAction, replyBody);
                }
                finally
                {
                    if (disposeRequest)
                    {
                        request.Close();
                    }
                }
            }
            finally
            {
                if (isNegotiationFailure)
                {
                    AddNegotiationChannelForIdleTracking();
                }
                else if (negotiationState != null && negotiationState.IsNegotiationCompleted)
                {
                    RemoveNegotiationChannelFromIdleTracking();
                }
            }
        }

        // negotiation failure methods
        Message HandleNegotiationException(Message request, Exception e)
        {

            SecurityTraceRecordHelper.TraceServiceSecurityNegotiationFailure<T>(
                                    EventTraceActivityHelper.TryExtractActivity(request),
                                    this,
                                    e);
            return CreateFault(request, e);
        }

        Message CreateFault(Message request, Exception e)
        {
            MessageVersion version = request.Version;
            FaultCode subCode;
            FaultReason reason;
            bool isSenderFault;
            if (e is SecurityTokenValidationException || e is System.ComponentModel.Win32Exception)
            {
                subCode = new FaultCode(TrustApr2004Strings.FailedAuthenticationFaultCode, TrustFeb2005Strings.Namespace);
                reason = new FaultReason(SR.GetString(SR.FailedAuthenticationTrustFaultCode), CultureInfo.CurrentCulture);
                isSenderFault = true;
            }
            else if (e is QuotaExceededException)
            {
                // send a receiver fault so that the sender can retry
                subCode = new FaultCode(DotNetSecurityStrings.SecurityServerTooBusyFault, DotNetSecurityStrings.Namespace);
                reason = new FaultReason(SR.GetString(SR.NegotiationQuotasExceededFaultReason), CultureInfo.CurrentCulture);
                isSenderFault = false;
            }
            else
            {
                subCode = new FaultCode(TrustApr2004Strings.InvalidRequestFaultCode, TrustFeb2005Strings.Namespace);
                reason = new FaultReason(SR.GetString(SR.InvalidRequestTrustFaultCode), CultureInfo.CurrentCulture);
                isSenderFault = true;
            }
            FaultCode faultCode;
            if (isSenderFault)
            {
                faultCode = FaultCode.CreateSenderFaultCode(subCode);
            }
            else
            {
                faultCode = FaultCode.CreateReceiverFaultCode(subCode);
            }
            MessageFault fault = MessageFault.CreateFault(faultCode, reason);
            Message faultReply = Message.CreateMessage(version, fault, version.Addressing.DefaultFaultAction);
            faultReply.Headers.RelatesTo = request.Headers.MessageId;

            return faultReply;
        }

        class NegotiationHost : ServiceHostBase
        {
            NegotiationTokenAuthenticator<T> authenticator;
            Uri listenUri;
            ChannelBuilder channelBuilder;
            MessageFilter listenerFilter;

            public NegotiationHost(NegotiationTokenAuthenticator<T> authenticator, Uri listenUri, ChannelBuilder channelBuilder, MessageFilter listenerFilter)
            {
                this.authenticator = authenticator;
                this.listenUri = listenUri;
                this.channelBuilder = channelBuilder;
                this.listenerFilter = listenerFilter;
            }

            protected override ServiceDescription CreateDescription(out IDictionary<string, ContractDescription> implementedContracts)
            {
                implementedContracts = null;
                return null;
            }

            protected override void InitializeRuntime()
            {
                MessageFilter contractFilter = this.listenerFilter;
                int filterPriority = 10;
                Type[] endpointChannelTypes = new Type[] { typeof(IReplyChannel),
                                                           typeof(IDuplexChannel),
                                                           typeof(IReplySessionChannel),
                                                           typeof(IDuplexSessionChannel) };
                IChannelListener listener = null;
                BindingParameterCollection parameters = new BindingParameterCollection(this.channelBuilder.BindingParameters);
                Binding binding = this.channelBuilder.Binding;
                binding.ReceiveTimeout = this.authenticator.NegotiationTimeout;
                parameters.Add(new ChannelDemuxerFilter(contractFilter, filterPriority));
                DispatcherBuilder.MaybeCreateListener(true, endpointChannelTypes, binding, parameters,
                                                      this.listenUri, "", ListenUriMode.Explicit, this.ServiceThrottle, out listener);
                if (listener == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.CannotCreateTwoWayListenerForNegotiation)));
                }
                ChannelDispatcher channelDispatcher = new ChannelDispatcher(listener, null, binding);
                channelDispatcher.MessageVersion = binding.MessageVersion;
                channelDispatcher.ManualAddressing = true;
                channelDispatcher.ServiceThrottle = new ServiceThrottle(this);
                channelDispatcher.ServiceThrottle.MaxConcurrentCalls = this.authenticator.MaximumConcurrentNegotiations;
                channelDispatcher.ServiceThrottle.MaxConcurrentSessions = this.authenticator.MaximumConcurrentNegotiations;

                EndpointDispatcher endpointDispatcher = new EndpointDispatcher(new EndpointAddress(this.listenUri), "SecurityNegotiationContract", NamingHelper.DefaultNamespace, true);
                endpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(null, this.authenticator, false);
                endpointDispatcher.DispatchRuntime.ConcurrencyMode = ConcurrencyMode.Multiple;
                endpointDispatcher.AddressFilter = new MatchAllMessageFilter();
                endpointDispatcher.ContractFilter = contractFilter;
                endpointDispatcher.FilterPriority = filterPriority;
                endpointDispatcher.DispatchRuntime.PrincipalPermissionMode = PrincipalPermissionMode.None;
                endpointDispatcher.DispatchRuntime.InstanceContextProvider = new SingletonInstanceContextProvider(endpointDispatcher.DispatchRuntime);
                endpointDispatcher.DispatchRuntime.SynchronizationContext = null;

                DispatchOperation operation = new DispatchOperation(endpointDispatcher.DispatchRuntime, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction);
                operation.Formatter = new MessageOperationFormatter();
                operation.Invoker = new NegotiationSyncInvoker(this.authenticator);

                endpointDispatcher.DispatchRuntime.UnhandledDispatchOperation = operation;
                channelDispatcher.Endpoints.Add(endpointDispatcher);
                this.ChannelDispatchers.Add(channelDispatcher);
            }

            class NegotiationSyncInvoker : IOperationInvoker
            {
                NegotiationTokenAuthenticator<T> parent;

                internal NegotiationSyncInvoker(NegotiationTokenAuthenticator<T> parent)
                {
                    this.parent = parent;
                }

                public bool IsSynchronous { get { return true; } }

                public object[] AllocateInputs()
                {
                    return EmptyArray<object>.Allocate(1);
                }

                public object Invoke(object instance, object[] inputs, out object[] outputs)
                {
                    Message request = (Message)inputs[0];
                    outputs = EmptyArray<object>.Allocate(0);
                    try
                    {
                        return parent.ProcessRequestCore(request);
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                        {
                            throw;
                        }
                        return parent.HandleNegotiationException(request, e);
                    }
                }

                public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }

                public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
        }
    }
}

{'repo_name': 'microsoft/referencesource', 'stars': '2229', 'repo_language': 'C#', 'file_name': 'SecurityTokenServiceDescriptor.cs', 'mime_type': 'text/plain', 'hash': 4049575753792278347, 'source_dataset': 'data'}


package layout

import model.pressed._

case class FaciaCardHeader(
    quoted: Boolean,
    isExternal: Boolean,
    isVideo: Boolean,
    isGallery: Boolean,
    isAudio: Boolean,
    kicker: Option[ItemKicker],
    headline: String,
    url: EditionalisedLink,
)

object FaciaCardHeader {
  def fromTrail(faciaContent: PressedContent, config: Option[CollectionConfig]): FaciaCardHeader =
    fromTrailAndKicker(
      faciaContent,
      faciaContent.header.kicker,
      config,
    )

  def fromTrailAndKicker(
      faciaContent: PressedContent,
      itemKicker: Option[ItemKicker],
      config: Option[CollectionConfig],
  ): FaciaCardHeader =
    FaciaCardHeader(
      faciaContent.display.showQuotedHeadline,
      faciaContent.card.cardStyle == ExternalLink,
      faciaContent.header.isVideo,
      faciaContent.header.isGallery,
      faciaContent.header.isAudio,
      itemKicker,
      faciaContent.header.headline,
      EditionalisedLink.fromFaciaContent(faciaContent),
    )
}

{'repo_name': 'guardian/frontend', 'stars': '5473', 'repo_language': 'HTML', 'file_name': 'logback.xml', 'mime_type': 'text/plain', 'hash': 8076719201063542768, 'source_dataset': 'data'}


#include "stdlib/genglsl/mx_dodge_float.glsl"

void mx_dodge_color2(vec2 fg, vec2 bg, float mixval, out vec2 result)
{
    mx_dodge_float(fg.x, bg.x, mixval, result.x);
    mx_dodge_float(fg.y, bg.y, mixval, result.y);
}

{'repo_name': 'materialx/MaterialX', 'stars': '572', 'repo_language': 'C++', 'file_name': 'FindMaterialX.cmake', 'mime_type': 'text/plain', 'hash': -6181639646181606906, 'source_dataset': 'data'}


<!-- markdown-link-check-disable -->

These tests follow examples from the free [React Book](https://softchris.github.io/books/react) by [Christoffer Noring](https://twitter.com/chris_noring).

<!-- markdown-link-check-enable -->

{'repo_name': 'bahmutov/cypress-react-unit-test', 'stars': '506', 'repo_language': 'JavaScript', 'file_name': 'file-preprocessor.js', 'mime_type': 'text/plain', 'hash': 4837964843007739410, 'source_dataset': 'data'}


// Boost.Range library
//
//  Copyright Thorsten Ottosen 2003-2004. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/range/
//

#ifndef BOOST_RANGE_DETAIL_DIFFERENCE_TYPE_HPP
#define BOOST_RANGE_DETAIL_DIFFERENCE_TYPE_HPP

#include <boost/range/detail/common.hpp>
#include <boost/iterator/iterator_traits.hpp>

//////////////////////////////////////////////////////////////////////////////
// missing partial specialization  workaround.
//////////////////////////////////////////////////////////////////////////////

namespace boost
{
    namespace range_detail
    {
        template< typename T >
        struct range_difference_type_;

        template<>
        struct range_difference_type_<std_container_>
        {
            template< typename C >
            struct pts
            {
                typedef BOOST_DEDUCED_TYPENAME C::difference_type type;
            };
        };

        template<>
        struct range_difference_type_<std_pair_>
        {
            template< typename P >
            struct pts
            {
                typedef BOOST_RANGE_DEDUCED_TYPENAME boost::iterator_difference< BOOST_DEDUCED_TYPENAME P::first_type>::type type;
            };
        };

        template<>
        struct range_difference_type_<array_>
        {
            template< typename A >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

        template<>
        struct range_difference_type_<char_array_>
        {
            template< typename A >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

        template<>
        struct range_difference_type_<char_ptr_>
        {
            template< typename S >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

        template<>
        struct range_difference_type_<const_char_ptr_>
        {
            template< typename S >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

        template<>
        struct range_difference_type_<wchar_t_ptr_>
        {
            template< typename S >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

        template<>
        struct range_difference_type_<const_wchar_t_ptr_>
        {
            template< typename S >
            struct pts
            {
                typedef std::ptrdiff_t type;
            };
        };

    }

    template< typename C >
    class range_difference
    {
        typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range<C>::type c_type;
    public:
        typedef BOOST_RANGE_DEDUCED_TYPENAME range_detail::range_difference_type_<c_type>::BOOST_NESTED_TEMPLATE pts<C>::type type;
    };

}

#endif

{'repo_name': 'RocketChat/Rocket.Chat.ReactNative', 'stars': '812', 'repo_language': 'JavaScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': 6476678812634839348, 'source_dataset': 'data'}


# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
import warnings

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.mgmt.core.exceptions import ARMErrorFormat

from .. import models

if TYPE_CHECKING:
    # pylint: disable=unused-import,ungrouped-imports
    from typing import Any, Callable, Dict, Generic, Iterable, Optional, TypeVar

    T = TypeVar('T')
    ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

class DeploymentOperationsOperations(object):
    """DeploymentOperationsOperations operations.

    You should not instantiate this class directly. Instead, you should create a Client instance that
    instantiates it for you and attaches it as an attribute.

    :ivar models: Alias to model classes used in this operation group.
    :type models: ~azure.mgmt.resource.resources.v2016_02_01.models
    :param client: Client for service requests.
    :param config: Configuration of service client.
    :param serializer: An object model serializer.
    :param deserializer: An object model deserializer.
    """

    models = models

    def __init__(self, client, config, serializer, deserializer):
        self._client = client
        self._serialize = serializer
        self._deserialize = deserializer
        self._config = config

    def get(
        self,
        resource_group_name,  # type: str
        deployment_name,  # type: str
        operation_id,  # type: str
        **kwargs  # type: Any
    ):
        # type: (...) -> "models.DeploymentOperation"
        """Get a list of deployments operations.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment.
        :type deployment_name: str
        :param operation_id: Operation Id.
        :type operation_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: DeploymentOperation, or the result of cls(response)
        :rtype: ~azure.mgmt.resource.resources.v2016_02_01.models.DeploymentOperation
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.DeploymentOperation"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-02-01"
        accept = "application/json"

        # Construct URL
        url = self.get.metadata['url']  # type: ignore
        path_format_arguments = {
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
            'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str'),
            'operationId': self._serialize.url("operation_id", operation_id, 'str'),
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        request = self._client.get(url, query_parameters, header_parameters)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response, error_format=ARMErrorFormat)

        deserialized = self._deserialize('DeploymentOperation', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    get.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}'}  # type: ignore

    def list(
        self,
        resource_group_name,  # type: str
        deployment_name,  # type: str
        top=None,  # type: Optional[int]
        **kwargs  # type: Any
    ):
        # type: (...) -> Iterable["models.DeploymentOperationsListResult"]
        """Gets a list of deployments operations.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
        :type resource_group_name: str
        :param deployment_name: The name of the deployment.
        :type deployment_name: str
        :param top: Query parameters.
        :type top: int
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either DeploymentOperationsListResult or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.resource.resources.v2016_02_01.models.DeploymentOperationsListResult]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.DeploymentOperationsListResult"]
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2016-02-01"
        accept = "application/json"

        def prepare_request(next_link=None):
            # Construct headers
            header_parameters = {}  # type: Dict[str, Any]
            header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

            if not next_link:
                # Construct URL
                url = self.list.metadata['url']  # type: ignore
                path_format_arguments = {
                    'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'),
                    'deploymentName': self._serialize.url("deployment_name", deployment_name, 'str'),
                    'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
                }
                url = self._client.format_url(url, **path_format_arguments)
                # Construct parameters
                query_parameters = {}  # type: Dict[str, Any]
                if top is not None:
                    query_parameters['$top'] = self._serialize.query("top", top, 'int')
                query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

                request = self._client.get(url, query_parameters, header_parameters)
            else:
                url = next_link
                query_parameters = {}  # type: Dict[str, Any]
                request = self._client.get(url, query_parameters, header_parameters)
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize('DeploymentOperationsListResult', pipeline_response)
            list_of_elem = deserialized.value
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                raise HttpResponseError(response=response, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations'}  # type: ignore

{'repo_name': 'Azure/azure-sdk-for-python', 'stars': '1321', 'repo_language': 'Python', 'file_name': 'test_largest_block_blob.py', 'mime_type': 'text/x-python', 'hash': 7905063787988237640, 'source_dataset': 'data'}


"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = getSuggestion;

var _damerauLevenshtein = _interopRequireDefault(require("damerau-levenshtein"));

// Minimum edit distance to be considered a good suggestion.
var THRESHOLD = 2;
/**
 * Returns an array of suggestions given a word and a dictionary and limit of suggestions
 * to return.
 */

function getSuggestion(word) {
  var dictionary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  var limit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
  var distances = dictionary.reduce(function (suggestions, dictionaryWord) {
    var distance = (0, _damerauLevenshtein["default"])(word.toUpperCase(), dictionaryWord.toUpperCase());
    var steps = distance.steps;
    suggestions[dictionaryWord] = steps; // eslint-disable-line

    return suggestions;
  }, {});
  return Object.keys(distances).filter(function (suggestion) {
    return distances[suggestion] <= THRESHOLD;
  }).sort(function (a, b) {
    return distances[a] - distances[b];
  }) // Sort by distance
  .slice(0, limit);
}

{'repo_name': 'wallace5303/dapps', 'stars': '384', 'repo_language': 'JavaScript', 'file_name': 'README.md', 'mime_type': 'text/html', 'hash': -6865110440316066056, 'source_dataset': 'data'}


import produce from "immer";
import { WeatherLoaded } from "./weather-actions";

export const weatherReducer = (state, action) => {
    return produce(state || {}, draft => {
        switch (action.type) {
            case WeatherLoaded: {
                draft.weather = action.payload;
                break;
            }

            default: {
                //do nothing
            }
        }
    });
};

{'repo_name': 'microsoft/redux-dynamic-modules', 'stars': '775', 'repo_language': 'TypeScript', 'file_name': 'config.yml', 'mime_type': 'text/plain', 'hash': -8380593531821005883, 'source_dataset': 'data'}


/*
 * Copyright (c) 2002 - 2006 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 */
package com.ibm.wala.ipa.callgraph.propagation;

import com.ibm.wala.classLoader.IClass;
import com.ibm.wala.classLoader.NewSiteReference;
import com.ibm.wala.ipa.callgraph.CGNode;
import com.ibm.wala.ipa.callgraph.CallGraph;
import com.ibm.wala.util.collections.NonNullSingletonIterator;
import com.ibm.wala.util.collections.Pair;
import java.util.Iterator;

/** An {@link InstanceKey} which represents a {@link NewSiteReference} in some {@link CGNode}. */
public abstract class AllocationSiteInNode extends AbstractTypeInNode {
  private final NewSiteReference site;

  public AllocationSiteInNode(CGNode node, NewSiteReference allocation, IClass type) {
    super(node, type);
    this.site = allocation;
  }

  @Override
  public abstract boolean equals(Object obj);

  @Override
  public abstract int hashCode();

  @Override
  public String toString() {
    return "SITE_IN_NODE{"
        + getNode().getMethod()
        + ':'
        + site
        + " in "
        + getNode().getContext()
        + '}';
  }

  /** @return Returns the site. */
  public NewSiteReference getSite() {
    return site;
  }

  @Override
  public Iterator<Pair<CGNode, NewSiteReference>> getCreationSites(CallGraph CG) {
    return new NonNullSingletonIterator<>(Pair.make(getNode(), getSite()));
  }
}

{'repo_name': 'wala/WALA', 'stars': '318', 'repo_language': 'Java', 'file_name': 'MANIFEST.MF', 'mime_type': 'text/plain', 'hash': -2714446126297894472, 'source_dataset': 'data'}