text:
<?php
/**
 * Created by PhpStorm.
 * User: joeldg
 * Date: 6/25/17
 * Time: 12:57 PM
 */
namespace Bowhead\Console\Commands;

use Bowhead\Console\Kernel;
use Bowhead\Util\Coinbase;
use Bowhead\Util\Console;
use Illuminate\Console\Command;

/**
 * Class WebsocketCommand
 * @package App\Console\Commands
 *
 *          This console command is for doing a websocket to GDAX
 *          https://docs.gdax.com/?php#overview
 *
 *          To keep a real-time book of a instrument use level 3
 *          https://docs.gdax.com/?php#get-product-order-book
 *
 *          Then match this up with the proper sequence
 */
class WebsocketCoinbaseTestCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'bowhead:wscoinbase_test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Handle the GDAX websocket and display realitime data in the terminal';

    /**
     * @var currency pairs
     */
    protected $instrument;

    /**
     * @var
     */
    protected $console;

    /**
     * @var current book
     */
    public $book;

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->console = $util = new Console();

        $this->instrument = 'BTC-USD';
        $loop = \React\EventLoop\Factory::create();
        $connector = new \Ratchet\Client\Connector($loop);

        $connector('wss://ws-feed.gdax.com')
            ->then(function(\Ratchet\Client\WebSocket $conn) {
                $conn->send('{"type": "subscribe","product_id": "'. $this->instrument .'"}');
                $conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
                    /**
                     *   DO ALL PROCESSING HERE
                     *   match up sequence and keep the book up to date.
                     */
                    if (empty($this->book)) {
                        $this->book = $this->getBook($this->instrument);
                        $this->processBook();
                        $this->displayBook();
                    }
                    $this->displayPage(json_decode($msg,1));
                    #echo "Received: {$msg}\n";

                });

                $conn->on('close', function($code = null, $reason = null) {
                    /** log errors here */
                    echo "Connection closed ({$code} - {$reason})\n";
                });

            }, function(\Exception $e) use ($loop) {
                /** hard error */
                echo "Could not connect: {$e->getMessage()}\n";
                $loop->stop();
            });

        $loop->run();
    }

    public function displayPage($message)
    {
        if ($message['type'] == 'match') {
            print_r($message);
        }

        $cols = getenv('COLUMNS');
        $rows = getenv('LINES');

        #print_r($message);

    }

    /**
     * @return mixed
     */
    private function getBook($instrument)
    {
        $util = new Coinbase();
        return $util->get_endpoint('book', null, '?level=2', $instrument);
    }

    /**
     *  reformat $this->book
     */
    private function processBook()
    {
        $_bids = array_reverse($this->book['bids']);
        $_asks = array_reverse($this->book['asks']);

        foreach ($_bids as $bid){
            $bids[$bid[0]] = ($bid[1] * $bid[2]); #array($bid[1], $bid[2], 0);
        }
        foreach ($_asks as $ask){
            $asks[$ask[0]] = ($ask[1] * $ask[2]); #array($ask[1], $ask[2], 0);
        }
        $this->book = array('sell'=>$asks, 'buy'=>$bids);

        print_r($this->book);
        die();
    }

    public function displayBook($modify=null){
        $cols = getenv('COLUMNS');
        $rows = getenv('LINES');
        $halfway = round(($rows/2)-1);

        if(!empty($modify)) {
            if ($modify['type'] == 'received' || $modify['type']=='match' ) {
                return true;
            }

            if ($modify['type'] == 'open') {
                if ($modify['side'] == 'sell') {
                    $this->book['sell'][$modify['price']] = array(@$modify['remaining_size'],1,1);
                } else {
                    $this->book['buy'][$modify['price']] = array(@$modify['remaining_size'],1,1);
                }
            }elseif($modify['type'] == 'done'){
                if ($modify['side'] == 'sell') {
                    unset($this->book['sell'][@$modify['price']]);
                } else {
                    unset($this->book['buy'][@$modify['price']]);
                }
            }
        }

        foreach($this->book['sell'] as $key => $sell) {
            $line = str_pad(money_format('%.2n',$key), 10, ' ', STR_PAD_LEFT) . str_pad($sell[0], 15, ' ', STR_PAD_LEFT);
            $color = ($sell[2] == 1 ? 'bg_light_red' : 'light_red');
            $lines[$key] = $this->console->colorize($line, $color) . "\n";
            $this->book['sell'][$key][2] = 0;
        }
        krsort($lines);
        $sells = array_slice($lines, -$halfway);
        foreach($sells as $sell) {
            echo $sell;
        }
        echo "----------|-----------------\n";
        $lines = array();
        foreach($this->book['buy'] as $key => $buy) {
            $line = str_pad(money_format('%.2n',$key), 10, ' ', STR_PAD_LEFT) . str_pad($buy[0], 15, ' ', STR_PAD_LEFT);
            $bcolor = ($buy[2] == 1 ? 'bg_light_green' : 'light_green');
            $lines[$key] = $this->console->colorize($line, $bcolor) . "\n";
            $this->book['buy'][$key][2] = 0;
        }
        ksort($lines);
        $buys = array_slice($lines, -$halfway);
        foreach($buys as $buy) {
            echo $buy;
        }

        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="abc_action_bar_home_description">Одлазак на Почетну</string>
    <string name="abc_action_bar_home_description_format">%1$s, %2$s</string>
    <string name="abc_action_bar_home_subtitle_description_format">%1$s, %2$s, %3$s</string>
    <string name="abc_action_bar_up_description">Кретање нагоре</string>
    <string name="abc_action_menu_overflow_description">Још опција</string>
    <string name="abc_action_mode_done">Готово</string>
    <string name="abc_activity_chooser_view_see_all">Прикажи све</string>
    <string name="abc_activitychooserview_choose_application">Избор апликације</string>
    <string name="abc_capital_off">ИСКЉУЧИ</string>
    <string name="abc_capital_on">УКЉУЧИ</string>
    <string name="abc_search_hint">Претражите...</string>
    <string name="abc_searchview_description_clear">Брисање упита</string>
    <string name="abc_searchview_description_query">Упит за претрагу</string>
    <string name="abc_searchview_description_search">Претрага</string>
    <string name="abc_searchview_description_submit">Слање упита</string>
    <string name="abc_searchview_description_voice">Гласовна претрага</string>
    <string name="abc_shareactionprovider_share_with">Дели са</string>
    <string name="abc_shareactionprovider_share_with_application">Дели са апликацијом %s</string>
    <string name="abc_toolbar_collapse_description">Скупи</string>
    <string name="common_android_wear_notification_needs_update_text">%1$s захтева ажурирање апликације Android Wear.</string>
    <string name="common_android_wear_update_text">%1$s не може да се покрене ако не ажурирате апликацију Android Wear.</string>
    <string name="common_android_wear_update_title">Ажурирајте Android Wear</string>
    <string name="common_google_play_services_api_unavailable_text">%1$s захтева једну Google Play услугу која тренутно није доступна или више њих. Контактирајте програмера да бисте добили помоћ.</string>
    <string name="common_google_play_services_enable_button">Омогући Google Play услуге</string>
    <string name="common_google_play_services_enable_text">%1$s неће функционисати ако не омогућите Google Play услуге.</string>
    <string name="common_google_play_services_enable_title">Омогућавање Google Play услуга</string>
    <string name="common_google_play_services_error_notification_requested_by_msg">Захтева %1$s</string>
    <string name="common_google_play_services_install_button">Преузми Google Play услуге</string>
    <string name="common_google_play_services_install_text_phone">%1$s не може да се покрене без Google Play услуга, које недостају на телефону.</string>
    <string name="common_google_play_services_install_text_tablet">%1$s не може да се покрене без Google Play услуга, које недостају на таблету.</string>
    <string name="common_google_play_services_install_title">Преузимање Google Play услуга</string>
    <string name="common_google_play_services_invalid_account_text">Наведени налог не постоји на овом уређају. Одаберите други налог.</string>
    <string name="common_google_play_services_invalid_account_title">Неважећи налог</string>
    <string name="common_google_play_services_needs_enabling_title">Апликација захтева да Google Play услуге буду омогућене.</string>
    <string name="common_google_play_services_network_error_text">За повезивање са Google Play услугама потребна је веза за пренос података.</string>
    <string name="common_google_play_services_network_error_title">Грешка на мрежи</string>
    <string name="common_google_play_services_notification_needs_update_title">Апликација захтева ажурирање Google Play услуга.</string>
    <string name="common_google_play_services_notification_ticker">Грешка Google Play услуга</string>
    <string name="common_google_play_services_sign_in_failed_text">Дошло је до грешке при пријављивању на наведени налог. Изаберите други налог.</string>
    <string name="common_google_play_services_sign_in_failed_title">Пријављивање није успело</string>
    <string name="common_google_play_services_unknown_issue">Непознат проблем са Google Play услугама.</string>
    <string name="common_google_play_services_unsupported_text">%1$s користи Google Play услуге, које уређај не подржава. Контактирајте произвођача да бисте добили помоћ.</string>
    <string name="common_google_play_services_unsupported_title">Google Play услуге</string>
    <string name="common_google_play_services_update_button">Ажурирај</string>
    <string name="common_google_play_services_update_text">%1$s не може да се покрене ако не ажурирате Google Play услуге.</string>
    <string name="common_google_play_services_update_title">Ажурирање Google Play услуга</string>
    <string name="common_google_play_services_updating_text">%1$s не може да се покрене без Google Play услуга, које се тренутно ажурирају.</string>
    <string name="common_google_play_services_updating_title">Google Play услуге се ажурирају</string>
    <string name="common_open_on_phone">Отвори на телефону</string>
    <string name="common_signin_button_text">Пријави ме</string>
    <string name="common_signin_button_text_long">Пријави ме на Google</string>
    <string name="mr_media_route_button_content_description">Излаз медија</string>
    <string name="mr_media_route_chooser_searching">Претраживање уређаја…</string>
    <string name="mr_media_route_chooser_title">Повежите са уређајем</string>
    <string name="mr_media_route_controller_disconnect">Прекини везу</string>
    <string name="mr_system_route_name">Систем</string>
    <string name="mr_user_route_category_name">Уређаји</string>
    <string name="status_bar_notification_info_overflow">>999</string>
    <string name="wallet_buy_button_place_holder">Купи помоћу Google-а</string>
    <string name="tw__allow_btn_txt">Дозволи</string>
    <string name="tw__cta_text">Отвори на Vine</string>
    <string name="tw__like_tweet">Свиђа ти се твит</string>
    <string name="tw__liked_tweet">Опозови свиђање</string>
    <string name="tw__loading_tweet">Учитавање твита</string>
    <string name="tw__login_btn_txt">Пријави се преко Твитера</string>
    <string name="tw__not_now_btn_txt">Не сада</string>
    <string name="tw__pause">пауза</string>
    <string name="tw__play">пусти</string>
    <string name="tw__replay">понови</string>
    <string name="tw__retweeted_by_format">Ретвитовано од стране %1$s</string>
    <string name="tw__share_content_format">Провери твит @%1$s: https://twitter.com/%1$s/status/%2$s</string>
    <string name="tw__share_email_desc">Дозволи %1$s да приступи твојој е-пошти која је повезана са Твитер налогом @%2$s тако да %1$s то може користити у складу са својом политиком приватности. На пример, %1$s може ти послати ажурирања и друге информације на ту адресу.</string>
    <string name="tw__share_email_title">Подели своју адресу е-поште</string>
    <string name="tw__share_subject_format">Твит од %1$s (@%2$s)</string>
    <string name="tw__share_tweet">Подели твит</string>
    <string name="tw__tweet_content_description">%1$s. %2$s. %3$s.</string>
    <string name="tw__tweet_media">Mедиј из твита</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: gseidel
 * Date: 2019-09-15
 * Time: 16:58
 */

namespace Enhavo\Bundle\TranslationBundle\AutoGenerator\Generator;

use Enhavo\Bundle\RoutingBundle\AutoGenerator\AbstractGenerator;
use Enhavo\Bundle\RoutingBundle\Factory\RouteFactory;
use Enhavo\Bundle\RoutingBundle\Slugifier\Slugifier;
use Enhavo\Bundle\TranslationBundle\Translation\TranslationManager;
use Enhavo\Bundle\TranslationBundle\Translator\TranslatorInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class LocalePrefixGenerator extends AbstractGenerator
{
    /** @var TranslationManager */
    private $translationManager;

    /** @var TranslatorInterface */
    private $routeTranslator;

    /** @var TranslatorInterface */
    private $textTranslator;

    /** @var RouteFactory */
    private $routeFactory;

    /**
     * LocalePrefixGenerator constructor.
     * @param TranslationManager $translationManager
     * @param TranslatorInterface $routeTranslator
     * @param TranslatorInterface $textTranslator
     * @param RouteFactory $routeFactory
     */
    public function __construct(TranslationManager $translationManager, TranslatorInterface $routeTranslator, TranslatorInterface $textTranslator, RouteFactory $routeFactory)
    {
        $this->translationManager = $translationManager;
        $this->routeTranslator = $routeTranslator;
        $this->textTranslator = $textTranslator;
        $this->routeFactory = $routeFactory;
    }

    public function generate($resource, $options = [])
    {
        if ($options['generate_default']) {
            $this->generateDefaultRoute($resource, $options);
        }

        if ($options['generate_translations']) {
            $this->generateTranslationRoutes($resource, $options);
        }
    }

    private function generateDefaultRoute($resource, $options = [])
    {
        $locale = $this->translationManager->getDefaultLocale();

        $value = $value = $this->getProperty($resource, $options['property']);
        if ($value !== null) {
            $route = $this->getProperty($resource, $options['route_property']);
            if (!$options['overwrite'] && $route->getStaticPrefix()) {
                return;
            }

            if ($options['default_prefix_locale']) {
                $route->setStaticPrefix($this->createLocalePrefix($locale, $value));
            } else {
                $route->setStaticPrefix($this->createPrefix($value));
            }
        }
    }

    private function generateTranslationRoutes($resource, $options)
    {
        $locales = $this->translationManager->getLocales();

        foreach ($locales as $locale) {
            if ($locale == $this->translationManager->getDefaultLocale()) {
                continue;
            }

            $route = $this->routeTranslator->getTranslation($resource, $options['route_property'], $locale)
                ?? $this->routeFactory->createNew();
            if (!$options['overwrite'] && $route->getStaticPrefix()) {
                continue;
            }

            $value = $this->textTranslator->getTranslation($resource, $options['property'], $locale)
                ?? ($options['allow_fallback'] ? $this->getProperty($resource, $options['property']) : null);

            if (null !== $value) {
                if ($options['translation_prefix_locale']) {
                    $route->setStaticPrefix($this->createLocalePrefix($locale, $value));
                } else {
                    $route->setStaticPrefix($this->createPrefix($value));
                }

                $this->routeTranslator->setTranslation($resource, $options['route_property'], $locale, $route);
            }
        }
    }

    private function createPrefix($value)
    {
        return sprintf('/%s', Slugifier::slugify($value));
    }

    private function createLocalePrefix($locale, $value)
    {
        return sprintf('/%s/%s', $locale, Slugifier::slugify($value));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'overwrite' => false,
            'route_property' => 'route',
            'allow_fallback' => true,
            'generate_default' => true,
            'generate_translations' => true,
            'default_prefix_locale' => true,
            'translation_prefix_locale' => true
        ]);
        $resolver->setRequired('property');
    }

    public function getType()
    {
        return 'locale_prefix';
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Shape2D" inherits="Resource" category="Core" version="3.0.alpha.custom_build">
	<brief_description>
		Base class for all 2D Shapes.
	</brief_description>
	<description>
		Base class for all 2D Shapes. All 2D shape types inherit from this.
	</description>
	<tutorials>
	</tutorials>
	<demos>
	</demos>
	<methods>
		<method name="collide">
			<return type="bool">
			</return>
			<argument index="0" name="local_xform" type="Transform2D">
			</argument>
			<argument index="1" name="with_shape" type="Shape2D">
			</argument>
			<argument index="2" name="shape_xform" type="Transform2D">
			</argument>
			<description>
				Return whether this shape is colliding with another.
				This method needs the transformation matrix for this shape ([code]local_xform[/code]), the shape to check collisions with ([code]with_shape[/code]), and the transformation matrix of that shape ([code]shape_xform[/code]).
			</description>
		</method>
		<method name="collide_and_get_contacts">
			<return type="Variant">
			</return>
			<argument index="0" name="local_xform" type="Transform2D">
			</argument>
			<argument index="1" name="with_shape" type="Shape2D">
			</argument>
			<argument index="2" name="shape_xform" type="Transform2D">
			</argument>
			<description>
				Return a list of the points where this shape touches another. If there are no collisions, the list is empty.
				This method needs the transformation matrix for this shape ([code]local_xform[/code]), the shape to check collisions with ([code]with_shape[/code]), and the transformation matrix of that shape ([code]shape_xform[/code]).
			</description>
		</method>
		<method name="collide_with_motion">
			<return type="bool">
			</return>
			<argument index="0" name="local_xform" type="Transform2D">
			</argument>
			<argument index="1" name="local_motion" type="Vector2">
			</argument>
			<argument index="2" name="with_shape" type="Shape2D">
			</argument>
			<argument index="3" name="shape_xform" type="Transform2D">
			</argument>
			<argument index="4" name="shape_motion" type="Vector2">
			</argument>
			<description>
				Return whether this shape would collide with another, if a given movement was applied.
				This method needs the transformation matrix for this shape ([code]local_xform[/code]), the movement to test on this shape ([code]local_motion[/code]), the shape to check collisions with ([code]with_shape[/code]), the transformation matrix of that shape ([code]shape_xform[/code]), and the movement to test onto the other object ([code]shape_motion[/code]).
			</description>
		</method>
		<method name="collide_with_motion_and_get_contacts">
			<return type="Variant">
			</return>
			<argument index="0" name="local_xform" type="Transform2D">
			</argument>
			<argument index="1" name="local_motion" type="Vector2">
			</argument>
			<argument index="2" name="with_shape" type="Shape2D">
			</argument>
			<argument index="3" name="shape_xform" type="Transform2D">
			</argument>
			<argument index="4" name="shape_motion" type="Vector2">
			</argument>
			<description>
				Return a list of the points where this shape would touch another, if a given movement was applied. If there are no collisions, the list is empty.
				This method needs the transformation matrix for this shape ([code]local_xform[/code]), the movement to test on this shape ([code]local_motion[/code]), the shape to check collisions with ([code]with_shape[/code]), the transformation matrix of that shape ([code]shape_xform[/code]), and the movement to test onto the other object ([code]shape_motion[/code]).
			</description>
		</method>
		<method name="get_custom_solver_bias" qualifiers="const">
			<return type="float">
			</return>
			<description>
				Return the custom solver bias.
			</description>
		</method>
		<method name="set_custom_solver_bias">
			<return type="void">
			</return>
			<argument index="0" name="bias" type="float">
			</argument>
			<description>
				Use a custom solver bias. No need to change this unless you really know what you are doing.
				The solver bias is a factor controlling how much two objects "rebound" off each other, when colliding, to avoid them getting into each other because of numerical imprecision.
			</description>
		</method>
	</methods>
	<members>
		<member name="custom_solver_bias" type="float" setter="set_custom_solver_bias" getter="get_custom_solver_bias">
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Solution.Base.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Solution.Base.Json
{
    public class DateTimeZoneConverter : DateTimeConverterBase
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null) return null;
            var dateTime = DateTime.Parse(reader.Value.ToString());
            return dateTime.FromConfigLocalTimeToUTC();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var localDT = ((DateTime)value).ToConfigLocalTime();
            writer.WriteValue(localDT);
        }
    }
}


text:
<?php

namespace PhpToZephir\Converter\Printer\Stmt\TraitUseAdaptation;

use PhpParser\Node\Stmt;
use PhpToZephir\Converter\SimplePrinter;

class PrecedencePrinter extends SimplePrinter
{
    public static function getType()
    {
        return 'pStmt_TraitUseAdaptation_Precedence';
    }

    public function convert(Stmt\TraitUseAdaptation\Precedence $node)
    {
        return $this->dispatcher->p($node->trait).'::'.$node->method
             .' insteadof '.$this->dispatcher->pCommaSeparated($node->insteadof).';';
    }
}


text:
package com.unascribed.farrago.client.tools;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.stats.Achievement;
import net.minecraft.stats.StatBase;
import net.minecraft.stats.StatFileWriter;
import net.minecraft.util.IJsonSerializable;
import net.minecraft.util.JsonSerializableSet;

public class FakeStatFileWriter extends StatFileWriter {
	@Override
	public boolean canUnlockAchievement(Achievement p_77442_1_) {
		return false;
	}

	@Override
	public IJsonSerializable func_150870_b(StatBase p_150870_1_) {
		return new JsonSerializableSet();
	}

	@Override public void func_150871_b(EntityPlayer p_150871_1_, StatBase p_150871_2_, int p_150871_3_) {}

	@Override
	public IJsonSerializable func_150872_a(StatBase p_150872_1_, IJsonSerializable p_150872_2_) {
		return new JsonSerializableSet();
	}

	@Override public void func_150873_a(EntityPlayer p_150873_1_, StatBase p_150873_2_, int p_150873_3_) {}

	@Override
	public int func_150874_c(Achievement p_150874_1_) {
		return 0;
	}

	@Override
	public boolean hasAchievementUnlocked(Achievement p_77443_1_) {
		return false;
	}

	@Override
	public int writeStat(StatBase p_77444_1_) {
		return 0;
	}
}


text:
package com.googlecode.jmxtrans.util;

import java.util.function.Function;

import static java.lang.String.format;

public class ObjectToDouble implements Function<Object, Double> {

	@Override
	public Double apply(Object input) {
		if (input == null) return null;
		if (input instanceof Double) return (Double) input;
		if (input instanceof Number) return ((Number) input).doubleValue();

		throw new IllegalArgumentException(format("There is no converter from [%s] to Double ", input.getClass().getName()));
	}
}


text:
namespace generator
{
class WikiUrlDumper
{
public:
  explicit WikiUrlDumper(std::string const & path, std::vector<std::string> const & dataFiles);

  static void DumpOne(std::string const & path, std::ostream & stream);

  void Dump(size_t cpuCount) const;

private:
  std::string m_path;
  std::vector<std::string> m_dataFiles;
};

class WikiDataFilter
{
public:
  explicit WikiDataFilter(std::string const & path, std::vector<std::string> const & dataFiles);

  static void FilterOne(std::string const & path, std::map<base::GeoObjectId, std::string> const & idToWikiData,
                        std::ostream & stream);

  void Filter(size_t cpuCount);

private:
  std::string m_path;
  std::map<base::GeoObjectId, std::string> m_idToWikiData;
  std::vector<std::string> m_dataFiles;
};
}  // namespace generator


text:
<?php

namespace SkiPHP;

class Config
{
    protected static $loaded_core = array();

    protected static $loaded_modules = array();

    protected $core_path_files;

    public function __construct()
    {
        $this->core_path_files = CORE_PATH . 'config/';
    }

    public function load_core($file)
    {
        if (!array_key_exists($file, self::$loaded_core))
        {
            $pathfile = $this->core_path_files . $file . '.php';
            if (is_file($pathfile))
            {
                include $pathfile;
                self::$loaded_core[$file] = $config[strtolower($file)];
            }
            else
            {
                echo $file . 'not found in ' . $this->core_path_files;
            }
        }
        return self::$loaded_core[$file];
    }
}


text:
module Bunny

  # Queues store and forward messages. Queues can be configured in the server or created at runtime.
  # Queues must be attached to at least one exchange in order to receive messages from publishers.
  class Queue09 < Qrack::Queue
    def initialize(client, name, opts = {})
      # check connection to server
      raise Bunny::ConnectionError, 'Not connected to server' if client.status == :not_connected

      @client = client
      @opts   = opts
      @delivery_tag = nil

      # Queues without a given name are named by the server and are generally
      # bound to the process that created them.
      if !name
        opts = {
          :passive => false,
          :durable => false,
          :exclusive => true,
          :auto_delete => true,
          :deprecated_ticket => 0
        }.merge(opts)
      end

      # ignore the :nowait option if passed, otherwise program will hang waiting for a
      # response that will not be sent by the server
      opts.delete(:nowait)

      opts = { :queue => name || '', :nowait => false, :deprecated_ticket => 0 }.merge(opts)

      client.send_frame(Qrack::Protocol09::Queue::Declare.new(opts))

      method = client.next_method

      client.check_response(method, Qrack::Protocol09::Queue::DeclareOk, "Error declaring queue #{name}")

      @name = method.queue
      client.queues[@name] = self
    end

    # @return [Bunny::Consumer] Default consumer associated with this queue (if any), or nil
    # @note Default consumer is the one registered with the convenience {Bunny::Queue#subscribe} method. It has no special properties of any kind.
    # @see Queue#subscribe
    # @see Bunny::Consumer
    # @api public
    def default_consumer
      @default_consumer
    end

    # @return [Class]
    # @private
    def self.consumer_class
      # Bunny::Consumer
      Bunny::Subscription09
    end # self.consumer_class

    # Acknowledges one or more messages delivered via the _Deliver_ or _Get_-_Ok_ methods. The client can
    # ask to confirm a single message or a set of messages up to and including a specific message.
    #
    # @option opts [String] :delivery_tag
    #
    # @option opts [Boolean] :multiple (false)
    #   If set to @true@, the delivery tag is treated as "up to and including",
    #   so that the client can acknowledge multiple messages with a single method.
    #   If set to @false@, the delivery tag refers to a single message.
    #   If the multiple field is @true@, and the delivery tag is zero,
    #   tells the server to acknowledge all outstanding messages.
    def ack(opts = {})
      # Set delivery tag
      if delivery_tag.nil? and opts[:delivery_tag].nil?
        raise Bunny::AcknowledgementError, "No delivery tag received"
      else
        self.delivery_tag = opts[:delivery_tag] if delivery_tag.nil?
      end

      opts = {:delivery_tag => delivery_tag, :multiple => false}.merge(opts)

      client.send_frame(Qrack::Protocol09::Basic::Ack.new(opts))

      # reset delivery tag
      self.delivery_tag = nil
    end

    # Binds a queue to an exchange. Until a queue is bound it won't receive
    # any messages. Queues are bound to the direct exchange '' by default.
    # If error occurs, a {Bunny::ProtocolError} is raised.
    #
    # @option opts [String] :key
    #   Specifies the routing key for the binding. The routing key is used
    #   for routing messages depending on the exchange configuration.
    #
    # @option opts [Boolean] :nowait (false)
    #   Ignored by Bunny, always @false@.
    #
    # @return [Symbol] @:bind_ok@ if successful.
    def bind(exchange, opts = {})
      exchange = exchange.respond_to?(:name) ? exchange.name : exchange

      # ignore the :nowait option if passed, otherwise program will hang waiting for a
      # response that will not be sent by the server
      opts.delete(:nowait)

      opts = {
        :queue => name,
        :exchange => exchange,
        :routing_key => opts.delete(:key),
        :nowait => false,
        :deprecated_ticket => 0
      }.merge(opts)

      client.send_frame(Qrack::Protocol09::Queue::Bind.new(opts))

      method = client.next_method

      client.check_response(method, Qrack::Protocol09::Queue::BindOk, "Error binding queue: #{name} to exchange: #{exchange}")

      # return message
      :bind_ok
    end

    # Requests that a queue is deleted from broker/server. When a queue is deleted any pending messages
    # are sent to a dead-letter queue if this is defined in the server configuration. Removes reference
    # from queues if successful. If an error occurs raises @Bunny::ProtocolError@.
    #
    # @option opts [Boolean] :if_unused (false)
    #   If set to @true@, the server will only delete the queue if it has no consumers.
    #   If the queue has consumers the server does not delete it but raises a channel exception instead.
    #
    # @option opts [Boolean] :if_empty (false)
    #   If set to @true@, the server will only delete the queue if it has no messages.
    #   If the queue is not empty the server raises a channel exception.
    #
    # @option opts [Boolean] :nowait (false)
    #   Ignored by Bunny, always @false@.
    #
    # @return [Symbol] @:delete_ok@ if successful
    def delete(opts = {})
      # ignore the :nowait option if passed, otherwise program will hang waiting for a
      # response that will not be sent by the server
      opts.delete(:nowait)

      opts = { :queue => name, :nowait => false, :deprecated_ticket => 0 }.merge(opts)

      client.send_frame(Qrack::Protocol09::Queue::Delete.new(opts))

      method = client.next_method

      client.check_response(method, Qrack::Protocol09::Queue::DeleteOk, "Error deleting queue #{name}")

      client.queues.delete(name)

      # return confirmation
      :delete_ok
    end

    # Gets a message from a queue in a synchronous way. If error occurs, raises _Bunny_::_ProtocolError_.
    #
    # @option opts [Boolean] :ack (false)
    #   If set to @false@, the server does not expect an acknowledgement message
    #   from the client. If set to @true@, the server expects an acknowledgement
    #   message from the client and will re-queue the message if it does not receive
    #   one within a time specified by the server.
    #
    # @return [Hash] Hash with @:header@, @:payload@ and @:delivery_details@ keys. @:delivery_details@ is a hash @:consumer_tag@, @:delivery_tag@, @:redelivered@, @:exchange@ and @:routing_key@. If the queue is empty the returned hash will contain: @{:header => nil, :payload => :queue_empty, :delivery_details => nil}@. N.B. If a block is provided then the hash will be passed into the block and the return value will be nil.
    def pop(opts = {}, &blk)
      opts = {
        :queue => name,
        :consumer_tag => name,
        :no_ack => !opts[:ack],
        :nowait => true,
        :deprecated_ticket => 0
      }.merge(opts)

      client.send_frame(Qrack::Protocol09::Basic::Get.new(opts))

      method = client.next_method

      if method.is_a?(Qrack::Protocol09::Basic::GetEmpty) then
        queue_empty = true
      elsif !method.is_a?(Qrack::Protocol09::Basic::GetOk)
        raise Bunny::ProtocolError, "Error getting message from queue #{name}"
      end

      if !queue_empty
        # get delivery tag to use for acknowledge
        self.delivery_tag = method.delivery_tag if opts[:ack]

        header = client.next_payload

        # If maximum frame size is smaller than message payload body then message
        # will have a message header and several message bodies
        msg = ''
        while msg.length < header.size
          msg << client.next_payload
        end

        msg_hash = {:header => header, :payload => msg, :delivery_details => method.arguments}

      else
        msg_hash = {:header => nil, :payload => :queue_empty, :delivery_details => nil}
      end

      # Pass message hash to block or return message hash
      blk ? blk.call(msg_hash) : msg_hash
    end

    # Removes all messages from a queue.  It does not cancel consumers.  Purged messages are deleted
    # without any formal "undo" mechanism. If an error occurs raises {Bunny::ProtocolError}.
    #
    # @option opts [Boolean] :nowait (false)
    #   Ignored by Bunny, always @false@.
    #
    # @return [Symbol] @:purge_ok@ if successful
    def purge(opts = {})
      # ignore the :nowait option if passed, otherwise program will hang waiting for a
      # response that will not be sent by the server
      opts.delete(:nowait)

      opts = { :queue => name, :nowait => false, :deprecated_ticket => 0 }.merge(opts)

      client.send_frame(Qrack::Protocol09::Queue::Purge.new(opts))

      method = client.next_method

      client.check_response(method,   Qrack::Protocol09::Queue::PurgeOk, "Error purging queue #{name}")

      # return confirmation
      :purge_ok
    end

    # @return [Hash] Hash with keys @:message_count@ and @consumer_count@.
    def status
      opts = { :queue => name, :passive => true, :deprecated_ticket => 0 }
      client.send_frame(Qrack::Protocol09::Queue::Declare.new(opts))

      method = client.next_method
      {:message_count => method.message_count, :consumer_count => method.consumer_count}
    end

    def subscribe(opts = {}, &blk)
      raise RuntimeError.new("This queue already has default consumer. Please instantiate Bunny::Consumer directly and call its #consume method to register additional consumers.") if @default_consumer && ! opts[:consumer_tag]

      # Create a subscription.
      @default_consumer = self.class.consumer_class.new(client, self, opts)
      @default_consumer.consume(&blk)
    end

    # Removes a queue binding from an exchange. If error occurs, a _Bunny_::_ProtocolError_ is raised.
    #
    # @option opts [String] :key
    #   Specifies the routing key for the binding.
    #
    # @option opts [Boolean] :nowait (false)
    #   Ignored by Bunny, always @false@.
    #
    # @return [Symbol] @:unbind_ok@ if successful.
    def unbind(exchange, opts = {})
      exchange = exchange.respond_to?(:name) ? exchange.name : exchange

      # ignore the :nowait option if passed, otherwise program will hang waiting for a
      # response that will not be sent by the server
      opts.delete(:nowait)

      opts = {
        :queue => name,
        :exchange => exchange,
        :routing_key => opts.delete(:key),
        :nowait => false,
        :deprecated_ticket => 0
      }.merge(opts)

      client.send_frame(Qrack::Protocol09::Queue::Unbind.new(opts))

      method = client.next_method

      client.check_response(method, Qrack::Protocol09::Queue::UnbindOk, "Error unbinding queue #{name}")

      # return message
      :unbind_ok
    end

    # Cancels a consumer. This does not affect already delivered messages, but it does mean
    # the server will not send any more messages for that consumer.
    #
    # @option opts [String] :consumer_tag
    #   Specifies the identifier for the consumer.
    #
    # @option opts [Boolean] :nowait (false)
    #   Ignored by Bunny, always @false@.
    #
    # @return [Symbol] @:unsubscribe_ok@ if successful
    def unsubscribe(opts = {})
      # Default consumer_tag from subscription if not passed in
      consumer_tag = @default_consumer ? @default_consumer.consumer_tag : opts[:consumer_tag]

      # Must have consumer tag to tell server what to unsubscribe
      raise Bunny::UnsubscribeError,
      "No consumer tag received" if !consumer_tag

      # Cancel consumer
      client.send_frame(Qrack::Protocol09::Basic::Cancel.new(:consumer_tag => consumer_tag, :nowait => false))

      method = client.next_method

      client.check_response(method, Qrack::Protocol09::Basic::CancelOk, "Error unsubscribing from queue #{name}")

      # Reset subscription
      @default_consumer = nil

      # Return confirmation
      :unsubscribe_ok
    end

    private

    def exchange
      @exchange ||= Bunny::Exchange09.new(client, '', :type => :direct, :key => name, :reserved_1 => 0, :reserved_2 => false, :reserved_3 => false)
    end

  end

end


text:
package gov.hhs.fha.nhinc.subscription.repository.service.test;

import gov.hhs.fha.nhinc.subscription.repository.service.SubscriptionRepositoryFactory;
import gov.hhs.fha.nhinc.subscription.repository.service.SubscriptionRepositoryService;
import gov.hhs.fha.nhinc.subscription.repository.SubscriptionRepositoryException;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * Unit tests for the SubscriptionRepositoryFactory class.
 *
 * @author Neil Webb
 */
@Ignore
public class SubscriptionRepositoryFactoryTest {
    /**
     * Test the creation of a concrete subscription repository service
     */
    @Test
    public void testSubscriptionFactory() {
        System.out.println("Begin testSubscriptionFactory");
        try {
            SubscriptionRepositoryService repositoryService = new SubscriptionRepositoryFactory()
                    .getSubscriptionRepositoryService();
            assertNotNull("Subscription service was null", repositoryService);

            String serviceClassName = repositoryService.getClass().getName();
            System.out.println("Subscription repository class name: " + serviceClassName);
            assertEquals("Impl class name",
                    "gov.hhs.fha.nhinc.subscription.repository.service.FileSubscriptionRepository", serviceClassName);
        } catch (SubscriptionRepositoryException ex) {
            ex.printStackTrace();
            fail(ex.getMessage());
        }
        System.out.println("End testSubscriptionFactory");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Hardcodet.Wpf.TaskbarNotification;
using RSCoreLib;
using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = false, ConfigFile = "Log4Net.config")]
namespace Builder
    {
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
        {
        private TaskbarIcon notifyIcon;
        private Mutex singleInstanceMutex;
        private static readonly ILog log = LogManager.GetLogger(typeof(App));
        internal static readonly DateTime LinkerTime = typeof(App).Assembly.GetLinkerTime();

        protected override void OnStartup (StartupEventArgs e)
            {
            base.OnStartup(e);

            bool isSingleInstance = false;
            singleInstanceMutex = new Mutex(true, "BuilderSingleInstance", out isSingleInstance);
            if (!isSingleInstance)
                {
                MessageBox.Show("Another instance of this application is already running.", "Builder"); //Modal
                if (singleInstanceMutex != null)
                    singleInstanceMutex.Dispose();

                Shutdown();
                return;
                }

            try
                {
                log.InfoFormat("Started new Session. Builder {0}, compiled on {1}",
                    typeof(App).Assembly.GetName().Version.ToString(), LinkerTime.ToString("yyyy-MM-dd HH:mm:ss"));

                Stopwatch sw = new Stopwatch();
                sw.Start();
                var settings = Task.Run(() => AppDataManager.LoadSettings());
                var environments = Task.Run(() => AppDataManager.LoadEnvironments());

                Task.WaitAll(settings, environments);

                SettingsVM svm = CreateSettingsVM(settings.Result);
                var viewModel = new MainVM(svm, environments.Result);
                svm.RefreshAutomaticTCCPathAsync();

                Exit += (sender, _) => GracefulShutdown();
                SessionEnding += (sender, _) => GracefulShutdown();

                notifyIcon = (TaskbarIcon)FindResource("NotifyIcon");
                notifyIcon.DataContext = viewModel;

                sw.Stop();
                log.InfoFormat("Startup took {0:0.0} seconds.", sw.Elapsed.TotalSeconds);

                if (settings.Result != null && settings.Result.StartInTray)
                    return;

                sw.Restart();
                viewModel.ShowUICommand.Execute();
                sw.Stop();
                log.InfoFormat("Opening Main UI took {0:0.0} seconds.", sw.Elapsed.TotalSeconds);
                }
            catch (Exception ex)
                {
                log.Error("Exception during startup.", ex);
                Shutdown();
                }
            }

        private SettingsVM CreateSettingsVM (Settings s)
            {
            if (s == null)
                s = new Settings();

            return new SettingsVM(s);
            }

        private void GracefulShutdown ()
            {
            lock (this)
                {
                if (notifyIcon != null)
                    {
                    notifyIcon.Dispose(); //the icon would clean up automatically, but this is cleaner
                    notifyIcon = null;
                    }

                if (singleInstanceMutex != null)
                    {
                    singleInstanceMutex.Dispose();
                    singleInstanceMutex = null;
                    }
                }
            }
        }
    }


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MetroLog.Internal;

namespace MetroLog
{
    public class LogEventInfo
    {
        public long SequenceID { get; set; }
        public LogLevel Level { get; set; }
        public string Logger { get; set; }
        public string Message { get; set; }
        public DateTimeOffset TimeStamp { get; set; }

        [JsonIgnore]
        public Exception Exception { get; set; }

        private ExceptionWrapper _exceptionWrapper;

        private static long _globalSequenceId;

        public LogEventInfo(LogLevel level, string logger, string message, Exception ex)
        {
            Level = level;
            Logger = logger;
            Message = message;
            Exception = ex;
            TimeStamp = LogManagerBase.GetDateTime();
            SequenceID = GetNextSequenceId();
        }

        internal static long GetNextSequenceId()
        {
            return Interlocked.Increment(ref _globalSequenceId);
        }

        public string ToJson()
        {
            return SimpleJson.SerializeObject(this);
        }

        public ExceptionWrapper ExceptionWrapper
        {
            get
            {
                if (_exceptionWrapper == null && this.Exception != null)
                    _exceptionWrapper = new ExceptionWrapper(this.Exception);
                return _exceptionWrapper;
            }
            set
            {
                _exceptionWrapper = value;
            }
        }
    }
}


text:
package org.jtwig.translate.function;

import com.google.common.base.Supplier;
import org.jtwig.environment.Environment;
import org.jtwig.translate.TranslateExtension;
import org.jtwig.translate.message.decorate.CompositeMessageDecorator;
import org.jtwig.translate.message.decorate.MessageDecorator;

import java.util.Collection;
import java.util.Locale;

public class Translator {
    public String translate (Environment environment, String message, Locale locale, Collection<MessageDecorator> messageDecorators) {
        String key = message.trim();
        MessageDecorator messageDecorator = new CompositeMessageDecorator(messageDecorators);
        return TranslateExtension.enviroment(environment).getMessageResolver()
                .resolve(locale, key, messageDecorator)
                .or(defaultMessage(key, messageDecorator));
    }

    private Supplier<String> defaultMessage(final String key, final MessageDecorator messageDecorator) {
        return new Supplier<String>() {
            @Override
            public String get() {
                return messageDecorator.decorate(key);
            }
        };
    }
}


text:
//
//  DYBaseViewModel.h
//  DYPlayNews
//
//  Created by 袁斌 on 2017/5/25.
//  Copyright © 2017年 https://github.com/DefaultYuan All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import "DYCellProtocol.h"
#import "DYViewModelProtocol.h"
#import "DYCellRenderProtocol.h"
#import "UIView+DYY.h"

@interface DYBaseViewModel : NSObject<DYViewModelProtocol, DYCellRenderProtocol>

@property (nonatomic)  NSUInteger pageIndex;
@property (nonatomic) NSUInteger pageSize;
@property (nonatomic) NSArray *dataSource;
@property (nonatomic) NSString *topId;

@property (nonatomic) RACCommand *fetchDataCommand; /**< 请求 */
@end


text:
package com.beyondtechnicallycorrect.pong;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import com.beyondtechnicallycorrect.pong.ai.AIModule;
import com.beyondtechnicallycorrect.pong.ai.AIRunner;
import com.beyondtechnicallycorrect.pong.ai.AIRunnerFactory;
import com.beyondtechnicallycorrect.pong.models.ball.BallModule;
import com.beyondtechnicallycorrect.pong.models.collision.CollisionModule;
import com.beyondtechnicallycorrect.pong.models.frame.FrameModule;
import com.beyondtechnicallycorrect.pong.models.game.CourtViewModelSubscription;
import com.beyondtechnicallycorrect.pong.models.game.GameModule;
import com.beyondtechnicallycorrect.pong.models.game.MatchStateSubscription;
import com.beyondtechnicallycorrect.pong.models.movement.MovementModule;
import com.beyondtechnicallycorrect.pong.models.paddle.PaddleModule;
import com.beyondtechnicallycorrect.pong.models.placeable.PlaceableModule;
import com.beyondtechnicallycorrect.pong.models.player.PlayerModule;
import com.beyondtechnicallycorrect.pong.models.position.PositionModule;
import com.beyondtechnicallycorrect.pong.models.terminalwall.TerminalWallModule;
import com.beyondtechnicallycorrect.pong.models.velocity.VelocityModule;
import com.beyondtechnicallycorrect.pong.models.wall.WallModule;
import com.beyondtechnicallycorrect.pong.view.PongPanel;
import com.beyondtechnicallycorrect.pong.viewmodel.AppViewModel;
import com.beyondtechnicallycorrect.pong.viewmodel.AppViewModelFactory;
import com.beyondtechnicallycorrect.pong.viewmodel.AppViewModelModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class App {

	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(
				new Runnable() {
					public void run() {
						setupGui();
					}
			});
	}

	private static void setupGui() {
		Injector injector = getInjector();
		AppViewModelFactory appViewModelFactory =
				injector.getInstance(AppViewModelFactory.class);
		AppViewModel appViewModel = appViewModelFactory.create();

		appViewModel.createMatch();

		JFrame frame = new JFrame("Pong");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		CourtViewModelSubscription viewModelChangeSubscription =
				injector.getInstance(CourtViewModelSubscription.class);
		MatchStateSubscription matchStateSubscription =
				injector.getInstance(MatchStateSubscription.class);

		AIRunnerFactory aiFactory =
				injector.getInstance(AIRunnerFactory.class);
		AIRunner aiRunner = aiFactory.create(appViewModel);
		matchStateSubscription.subscribe(aiRunner);

		PongPanel pongPanel =
				new PongPanel(
						appViewModel,
						viewModelChangeSubscription,
						matchStateSubscription
					);
		frame.getContentPane().add(pongPanel);

		frame.pack();
		frame.setVisible(true);

		JOptionPane.showMessageDialog(frame,
				"Welcome to my Pong implementation!\n\n" +
						"You are the top paddle, use the 'a' key to\nmove left and the 'd' key to move right.\n" +
						"Click on 'Start Match' when you are ready\nto start the match.\n\n" +
						"Good luck!",
				"Welcome!",
				JOptionPane.PLAIN_MESSAGE
			);
	}

	private static Injector getInjector() {
		Injector injector = Guice.createInjector(
				new AIModule(),
				new AppViewModelModule(),
				new BallModule(),
				new CollisionModule(),
				new FrameModule(),
				new GameModule(),
				new MovementModule(),
				new PaddleModule(),
				new PlaceableModule(),
				new PlayerModule(),
				new PositionModule(),
				new TerminalWallModule(),
				new VelocityModule(),
				new WallModule()
			);
		return injector;
	}

}


text:
 Benjamin Eysenbach,   Sergey Levine,   Ruslan Salakhutdinov

 NeurIPS 2021 (oral)

   paper, website

**tldr**: In many scenarios, the user is unable to describe the task in words or numbers, but can readily provide examples of what the world would look like if the task were solved. To address this problem of *example-based control*, we propose an off-policy algorithm, *recursive-classification of examples* (RCE). In contrast to prior approaches, out method does require expert demonstrations and never learns an explicit reward function. Nonetheless, this method retains many of the theoretical properties of reward-based learning, such as Bellman equations, where the standard reward function term is replaced by data. Experiments show that our approach outperforms these prior approaches on a range of simulated robotic manipulation tasks.

If you use this code, please consider adding the corresponding citation:

```
@inproceedings{
  eysenbach2021replacing,
  title={Replacing Rewards with Examples: Example-Based Policy Search via Recursive Classification},
  author={Benjamin Eysenbach and Sergey Levine and Ruslan Salakhutdinov},
  booktitle={Advances in Neural Information Processing Systems},
  year={2021},
}
```

## Installation
These instructions were tested in Google Cloud Compute with Ubuntu version 18.04.

### 1. Install Mujoco
Copy your mujoco key to `~/.mujoco/mjkey.txt`, then complete the steps below:

```
sudo apt install unzip gcc libosmesa6-dev libgl1-mesa-glx libglfw3 patchelf
sudo ln -s /usr/lib/x86_64-linux-gnu/libGL.so.1 /usr/lib/x86_64-linux-gnu/libGL.so
wget https://www.roboti.us/download/mujoco200_linux.zip -P /tmp
unzip /tmp/mujoco200_linux.zip -d ~/.mujoco
mv ~/.mujoco/mujoco200_linux ~/.mujoco/mujoco200
echo "export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:$HOME/.mujoco/mujoco200/bin" >> ~/.bashrc
```

### 2. Install Anaconda
```
wget https://repo.anaconda.com/miniconda/Miniconda2-latest-Linux-x86_64.sh
chmod +x Miniconda2-latest-Linux-x86_64.sh
./Miniconda2-latest-Linux-x86_64.sh
```
Restart your terminal so the changes take effect.

### 3. Create an Anaconda environment and install the remaining dependencies

*Updated 12/28/22. Thanks to Kevin Lin and Mingdong Wu for developing these revised instructions.*

* `conda env create -f environment.yml`
* `git clone https://github.com/rail-berkeley/d4rl.git`
* In `d4rl/setup.py`, remove installation requirements of `mjrl@master` and `dm_control@master`.
* In the d4rl repository, run `pip install -e .`

## Running Experiments

The following lines replicate the RCE experiments on the Sawyer tasks and Adept task using state-based observations. Please see the discussion below for an explanation of what the various command line options do.

```
python train_eval.py --root_dir=~/rce/sawyer_drawer_open --gin_bindings='train_eval.env_name="sawyer_drawer_open"'

python train_eval.py --root_dir=~/rce/sawyer_push --gin_bindings='train_eval.env_name="sawyer_push"'

python train_eval.py --root_dir=~/rce/sawyer_lift --gin_bindings='train_eval.env_name="sawyer_lift"'

python train_eval.py --root_dir=~/rce/door --gin_bindings='train_eval.env_name="door-human-v0"'

python train_eval.py --root_dir=~/rce/sawyer_box_close --gin_bindings='train_eval.env_name="sawyer_box_close"'

python train_eval.py --root_dir=~/rce/sawyer_bin_picking --gin_bindings='train_eval.env_name="sawyer_bin_picking"' --gin_bindings='critic_loss.q_combinator="max"' --gin_bindings='actor_loss.q_combinator="max"'

python train_eval.py --root_dir=~/rce/hammer --gin_bindings='train_eval.env_name="hammer-human-v0"'
```

To run SQIL, add the additional arguments:

```--gin_bindings='critic_loss.loss_name="q"' --gin_bindings='train_eval.n_step=None'```

### Questions?
If you have any questions, comments, or suggestions, please reach out to Benjamin Eysenbach (eysenbach@google.com).


text:
package com.dailystudio.hellorx;

import com.dailystudio.app.DevBricksApplication;

/**
 * Created by nanye on 17/2/9.
 */

public class HelloRxApplication extends DevBricksApplication {

    @Override
    protected boolean isDebugBuild() {
        return BuildConfig.DEBUG;
    }

}


text:
#include "mainwindow.h"
#include "qtwin/qtwin.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
#ifdef Q_WS_WIN
    if (QtWin::isCompositionEnabled()) {
        QtWin::extendFrameIntoClientArea(this);
        this->setContentsMargins(0, 0, 0, 0);
    }
#endif
    playing = false;
    stopped = true;
    paused = false;
    Make();
}

MainWindow::~MainWindow()
{

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Class1.cs" company="Naos Project">
//    Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// <auto-generated>
//   Sourced from NuGet package. Will be overwritten with package update except in [PROJECT_NAME] source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------

namespace [PROJECT_NAME]
{
    /// <summary>
    /// bug: DOCUMENTATION HERE.
    /// </summary>
#if ![SOLUTION_NAME_CONDITIONAL_COMPILATION_SYMBOL]
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    [System.CodeDom.Compiler.GeneratedCode("[PROJECT_NAME]", "See package version number")]
    internal
#else
    public
#endif
    class Class1
    {
    }
}


text:
package dosingdecision

import (
	"strconv"
	"time"

	"github.com/tidepool-org/platform/data"
	dataBloodGlucose "github.com/tidepool-org/platform/data/blood/glucose"
	"github.com/tidepool-org/platform/structure"
	structureValidator "github.com/tidepool-org/platform/structure/validator"
)

const (
	BloodGlucoseArrayLengthMaximum = 60 * 24
)

type BloodGlucose struct {
	Time  *time.Time `json:"time,omitempty" bson:"time,omitempty"`
	Value *float64   `json:"value,omitempty" bson:"value,omitempty"`
}

func ParseBloodGlucose(parser structure.ObjectParser) *BloodGlucose {
	if !parser.Exists() {
		return nil
	}
	datum := NewBloodGlucose()
	parser.Parse(datum)
	return datum
}

func NewBloodGlucose() *BloodGlucose {
	return &BloodGlucose{}
}

func (b *BloodGlucose) Parse(parser structure.ObjectParser) {
	b.Time = parser.Time("time", time.RFC3339Nano)
	b.Value = parser.Float64("value")
}

func (b *BloodGlucose) Validate(validator structure.Validator, units *string) {
	validator.Float64("value", b.Value).Exists().InRange(dataBloodGlucose.ValueRangeForUnits(units))
}

func (b *BloodGlucose) Normalize(normalizer data.Normalizer, units *string) {
	if normalizer.Origin() == structure.OriginExternal {
		b.Value = dataBloodGlucose.NormalizeValueForUnits(b.Value, units)
	}
}

type BloodGlucoseArray []*BloodGlucose

func ParseBloodGlucoseArray(parser structure.ArrayParser) *BloodGlucoseArray {
	if !parser.Exists() {
		return nil
	}
	datum := NewBloodGlucoseArray()
	parser.Parse(datum)
	return datum
}

func NewBloodGlucoseArray() *BloodGlucoseArray {
	return &BloodGlucoseArray{}
}

func (b *BloodGlucoseArray) Parse(parser structure.ArrayParser) {
	for _, reference := range parser.References() {
		*b = append(*b, ParseBloodGlucose(parser.WithReferenceObjectParser(reference)))
	}
}

func (b *BloodGlucoseArray) Validate(validator structure.Validator, units *string) {
	if length := len(*b); length == 0 {
		validator.ReportError(structureValidator.ErrorValueEmpty())
	} else if length > BloodGlucoseArrayLengthMaximum {
		validator.ReportError(structureValidator.ErrorLengthNotLessThanOrEqualTo(length, BloodGlucoseArrayLengthMaximum))
	}
	for index, datum := range *b {
		if datumValidator := validator.WithReference(strconv.Itoa(index)); datum != nil {
			datum.Validate(datumValidator, units)
		} else {
			datumValidator.ReportError(structureValidator.ErrorValueNotExists())
		}
	}
}

func (b *BloodGlucoseArray) Normalize(normalizer data.Normalizer, units *string) {
	for index, datum := range *b {
		if datum != nil {
			datum.Normalize(normalizer.WithReference(strconv.Itoa(index)), units)
		}
	}
}


text:
cd /home/ec2-user/edurange
rake db:migrate
echo "Migrated database."
crontab -l | { cat; echo "@reboot /home/ec2-user/edurange/start.sh > /home/ec2-user/edurange/cron.log 2>&1"; } | crontab -
echo "Installed crontab entry."


text:
#pragma once

//! \cond INTERNAL

/*!
 * \file MidiDeviceEnumeratorImpl.h
 * \warning This file is not a part of library public interface!
 * Contains Linux implementation of MidiDeviceEnumerator
 */

#include "../../../include/smidi/MidiDeviceEnumerator.h"
#include "../../../include/smidi/MidiDevice.h"
#include "../../../include/smidi/MidiPort.h"
#include <map>
#include <set>
#include <vector>
#include <tuple>
#include <string>
#include <memory>
#include <functional>
#include <alsa/asoundlib.h>

class MidiDeviceEnumerator::Implementation
{
	static const int kWriteCapabilities;
	static const int kReadCapabilities;

	enum DeviceInfoFields
	{
		ClientId,
		DeviceObject
	};

	using PortAction   = std::function<void(snd_seq_t*, snd_seq_client_info_t*, snd_seq_port_info_t*)>;
	using ClientAction = std::function<void(snd_seq_t*, snd_seq_client_info_t*)>;
	using DeviceInfo = std::tuple<int, std::shared_ptr<MidiDevice>>;
	using DeviceMap  = std::map<std::string, DeviceInfo>;

public:
	Implementation();
	~Implementation();

	std::list<std::string> deviceNames() const;
	std::shared_ptr<MidiDevice> createDevice(const std::string& deviceName);

	void updateDeviceList();

private:
	void clearDevices();
	void refreshDevices();

	void updateAllDeviceInformation(DeviceMap& devices) const;

	void collectClientInformation(snd_seq_t* sequencer, snd_seq_client_info_t* clientInfo, DeviceMap& devices) const;
	void collectMidiPortObjects(snd_seq_t* sequencer, snd_seq_client_info_t* clientInfo, snd_seq_port_info_t*portInfo, std::vector<std::shared_ptr<MidiInPort>>& inputPorts, std::vector<std::shared_ptr<MidiOutPort> >& outputPorts);

	void traverseAllClients(snd_seq_t* sequencer, ClientAction action) const;
	void traverseClientPorts(snd_seq_t* sequencer, snd_seq_client_info_t* clientInfo, int capabilities, MidiDeviceEnumerator::Implementation::PortAction action) const;

	bool isOurClient(const unsigned char clientId) const;

private:
	DeviceMap     _deviceMap;
	std::set<int> _ourClientIds;
	snd_seq_t*    _sequencer;
	unsigned char _myClientId;
};


text:
#include "Basic/ERMsg.h"
#include "Basic/WeatherStation.h"
#include "Basic/modelStat.h"

namespace WBSF
{

	class CPlantHardinessUSA
	{
	public:

		CPlantHardinessUSA()
		{}

		void Compute(const CWeatherStation& weather, CModelStatVector& result);

		static double GetSuitabilityIndex(const CWeatherStation& weather);
	};

}


text:
package com.akh.algorithms.sample;

import junit.framework.TestCase;

/**
 *  @fileName: SampleTest.java
 *  @author: Akhash Ramamurthy
 *  Created on: Jul 15, 2018
 */

public class SampleTest extends TestCase {

	@Override
	protected void setUp() throws Exception {
		// TODO Auto-generated method stub
		super.setUp();
	}

	@Override
	protected void tearDown() throws Exception {
		// TODO Auto-generated method stub
		super.tearDown();
	}

}


text:
var Backbone = require('backbone');
var Person = require('./person');

module.exports = Backbone.Collection.extend({
    model: Person,
    url: '/api/people'
});


text:
[![npm version](https://badge.fury.io/js/fuzzy-array-filter.svg)](https://badge.fury.io/js/fuzzy-array-filter)

A simple fuzzy filter function for [`array.prototype.filter`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/filter) using [fuse.js](http://fusejs.io/).

## Install

```sh
npm i -S fuzzy-array-filter
```

## How to use it : Simple data structure

### Basics

use this wrapper with simple array `[val1, val2, ...]` il is really (really) easy :

```js
ìmport fuzzyFilter from 'fuzzy-array-filter';

const array = ['There is a house in New Orleans',
  'They call the Rising Sun',
  'And \'s been the ruin of many a poor boy',
  'And God, I know I\'m one',
  'My mother was a tailor',
  'She sewed my new blue jeans',
  'My father was a gamblin man',
  'Down in New Orleans',
  'Now the only thing a gambler needs',
  'Is a suitcase and trunk',
  'And the only time he\'s satisfied',
  'Is when he\'s on a drunk',
  'Oh mother, tell your children',
  'Not to do what I have done',
  'Spend your lives in sin and misery',
  'In the House of the Rising Sun' ];

console.log(array.filter(fuzzyFilter('new orleans')));
// => [ 'There is a house in New Orleans', 'Down in New Orleans' ]

```

Default fuzzy options are
```JSON
{
  "threshold": 0.4,
  "location": 0,
  "distance": 100,
  "maxPatternLength": 32,
  "keys": []
}
```

### With custom options

```js
ìmport fuzzyFilter from 'fuzzy-array-filter';

const array = theRisingSunArray; // the previous one

const options = {
  caseSensitive: true,
};

console.log(array.filter(fuzzyFilter('new orleans', options)));
// => []

console.log(array.filter(fuzzySearch('man', options)));
// => [ 'And \'s been the ruin of many a poor boy', 'My father was a gamblin man' ]

```

For more details, please see the [fuse.js](http://fusejs.io/) options documentation

## How to use it : More complex data structures

### Basics

When you use this wrapper with more complex data structure, make sure you have provided some custom options.
You **MUST** fill the `id` and the `keys` options.

`id` option is a single value. It can represent anything, like a string or a number.

### Simple complex

```js
const array = [
  { uniqueValue: 1, names: 'Edwina' },
  { uniqueValue: 2, names: 'Augusta' },
  { uniqueValue: 3, names: 'Lina' },
  { uniqueValue: 4, names: 'Ware' },
  { uniqueValue: 5, names: 'Kim' },
  { uniqueValue: 6, names: 'Nita' },
  { uniqueValue: 7, names: 'Garrett' },
  { uniqueValue: 8, names: 'Concepcion' },
  { uniqueValue: 9, names: 'Laverne' },
  { uniqueValue: 10, names: 'Alford' },
  { uniqueValue: 11, names: 'Jill' },
  { uniqueValue: 12, names: 'Reed' },
  { uniqueValue: 13, names: 'Shaw' },
];

const options = {
  keys: ['names'],
  id: 'uniqueValue'
}

const filteredArray = array.filter(fuzzyFilter('in', options))
console.log(filteredArray)

```

### Complex

```js
const array2 = [
  { id: 1, names: { first: 'Edwina', last:'random' } },
  { id: 2, names: { first: 'Augusta', last:'random' } },
  { id: 3, names: { first: 'Lina', last:'random' } },
  { id: 4, names: { first: 'Ware', last:'random' } },
  { id: 5, names: { first: 'Kim', last:'random' } },
  { id: 6, names: { first: 'Nita', last:'random' } },
  { id: 7, names: { first: 'Garrett', last:'random' } },
  { id: 8, names: { first: 'Concepcion', last:'random' } },
  { id: 9, names: { first: 'Laverne', last:'random' } },
  { id: 10, names: { first: 'Alford', last:'random' } },
  { id: 11, names: { first: 'Jill', last:'random' } },
  { id: 12, names: { first: 'Reed', last:'random' } },
  { id: 13, names: { first: 'Shaw', last:'random' } },
];

const options2 = {
  keys: ['names.first', 'names.last'],
  id: 'id'
}

const filteredArray2 = array2.filter(fuzzyFilter('in', options2))
console.log(filteredArray2)

```

### More complex

```js
const array3 = [
  { id: 1, names: { first: ['Edwina'], last:['random'] } },
  { id: 2, names: { first: ['Augusta'], last:['random'] } },
  { id: 3, names: { first: ['Lina'], last:['random'] } },
  { id: 4, names: { first: ['Ware'], last:['random'] } },
  { id: 5, names: { first: ['Kim'], last:['random'] } },
  { id: 6, names: { first: ['Nita'], last:['random'] } },
  { id: 7, names: { first: ['Garrett'], last:['random'] } },
  { id: 8, names: { first: ['Concepcion'], last:['random'] } },
  { id: 9, names: { first: ['Laverne'], last:['random'] } },
  { id: 10, names: { first: ['Alford'], last:['random'] } },
  { id: 11, names: { first: ['Jill'], last:['random'] } },
  { id: 12, names: { first: ['Reed'], last:['random'] } },
  { id: 13, names: { first: ['Shaw'], last:['random'] } },
];

const options3 = {
  keys: ['names.first'],
  id: 'id'
}

const filteredArray3 = array3.filter(fuzzyFilter('in', options3))
console.log(filteredArray3)

```

## Dependencies

* [fuse.js](https://www.npmjs.com/package/fuse.js)

## ToDo

* Any idea ?


text:
layout: default
---

Zynq Getting Started Resources

Getting Started

               Xilinx UG585: Zynq Technical Reference Manual

               Zynq Mooc, TU Kaislautern (11 Lessons)

               Why Zynq

               Zynq Development Tools Overview

               Using IP Integrator with Zynq

Using Zynq

               Xilinx UG873: Concepts, Tools, Techniques

               Zynq Architecture overview

               Zynq Processing System Overview

               Zynq Programmable Logic Overview

               Using MIO and EMIO

               Zynq coprocessors for system acceleration

Software & Debug

               Xilinx UG821: Software Developers Guide

               Hello World on Zynq in 5 minutes

               Xilinx SDK Software Development Kit

               Zynq Software Ecosystem

               How to create a Zynq Boot Image

Linux

               Xilinx wiki - Linux resources for Zynq

               Linux for Zynq

               How to create Linux Applications

               How to debug Linux Applications

               Build Linux for Zynq from the Device Tree

               Embedded Linux, Zynq and Microblaze (6 lessons)

Going Further

               SDK System Performance Tools

               SDSoC Development Environment Estimation and Implementation

               SDSoC Environment Demo

Recommended Reading

            The Zynq Book - Comprehensive guide to Zynq (includes Tutorials) - Free download

            Adam Taylor's Zynq Chronicles- hands-on Zynq examples

Tutorials

            Embedded Linux Tutorial on Zybo

            FPGAdeveloper Tutorial- Creating a Base System for the Zynq in Vivado

            Svenand Blog - Getting started Tutorial for Zedboard

            Xilinx UG1165: Embedded Design Tutorial

            Xillybus Tutorials - general tutorials for Zynq (PCI, Device Tree, U-Boot, FPGA Co-processing

Zynq boards

            Zybo - low cost teaching board with academic discount available

            MicroZed - low cost standalone, or SOM Zynq board

            Zedboard - mid-range teaching/research board with academic discount available

            Xilinx ZC702 - Mid-High End Zynq Development board

            Xilinx ZC706 - High End Zynq Development board

            FPGAdeveloper, Zynq board comparison


text:
package main

import (
	"bytes"
	"os/exec"
	"strings"
	"time"

	"github.com/go-check/check"
)

// non-blocking wait with 0 exit code
func (s *DockerSuite) TestWaitNonBlockedExitZero(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "true")
	containerID := strings.TrimSpace(out)

	if err := waitInspect(containerID, "{{.State.Running}}", "false", 1*time.Second); err != nil {
		c.Fatal("Container should have stopped by now")
	}

	out, _ = dockerCmd(c, "wait", containerID)
	if strings.TrimSpace(out) != "0" {
		c.Fatal("failed to set up container", out)
	}

}

// blocking wait with 0 exit code
func (s *DockerSuite) TestWaitBlockedExitZero(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "trap 'exit 0' TERM; while true; do sleep 0.01; done")
	containerID := strings.TrimSpace(out)

	c.Assert(waitRun(containerID), check.IsNil)

	chWait := make(chan string)
	go func() {
		out, _, _ := runCommandWithOutput(exec.Command(dockerBinary, "wait", containerID))
		chWait <- out
	}()

	time.Sleep(100 * time.Millisecond)
	dockerCmd(c, "stop", containerID)

	select {
	case status := <-chWait:
		if strings.TrimSpace(status) != "0" {
			c.Fatalf("expected exit 0, got %s", status)
		}
	case <-time.After(2 * time.Second):
		c.Fatal("timeout waiting for `docker wait` to exit")
	}

}

// non-blocking wait with random exit code
func (s *DockerSuite) TestWaitNonBlockedExitRandom(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "exit 99")
	containerID := strings.TrimSpace(out)

	if err := waitInspect(containerID, "{{.State.Running}}", "false", 1*time.Second); err != nil {
		c.Fatal("Container should have stopped by now")
	}

	out, _ = dockerCmd(c, "wait", containerID)
	if strings.TrimSpace(out) != "99" {
		c.Fatal("failed to set up container", out)
	}

}

// blocking wait with random exit code
func (s *DockerSuite) TestWaitBlockedExitRandom(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "trap 'exit 99' TERM; while true; do sleep 0.01; done")
	containerID := strings.TrimSpace(out)
	c.Assert(waitRun(containerID), check.IsNil)

	chWait := make(chan error)
	waitCmd := exec.Command(dockerBinary, "wait", containerID)
	waitCmdOut := bytes.NewBuffer(nil)
	waitCmd.Stdout = waitCmdOut
	if err := waitCmd.Start(); err != nil {
		c.Fatal(err)
	}

	go func() {
		chWait <- waitCmd.Wait()
	}()

	dockerCmd(c, "stop", containerID)

	select {
	case err := <-chWait:
		if err != nil {
			c.Fatal(err)
		}
		status, err := waitCmdOut.ReadString('\n')
		if err != nil {
			c.Fatal(err)
		}
		if strings.TrimSpace(status) != "99" {
			c.Fatalf("expected exit 99, got %s", status)
		}
	case <-time.After(2 * time.Second):
		waitCmd.Process.Kill()
		c.Fatal("timeout waiting for `docker wait` to exit")
	}
}


text:
name = "python"

version = "2.7.15"

authors = [
    "Guido van Rossum"
]

description = \
    """
    The Python programming language.
    """

@early()
def variants():
    from rez.package_py_utils import expand_requires
    requires = ["platform-**"]
    return [expand_requires(*requires)]

tools = [
    "2to3",
    "idle",
    "pydoc",
    "python",
    "python2",
    "python2.7",
    "python2.7-config",
    "python2-config",
    "python-config",
    "smtpd.py"
]

def commands():
    env.PATH.prepend("{root}/bin")
    env.LD_LIBRARY_PATH.prepend("{root}/lib")
    if building:
        env.CMAKE_MODULE_PATH.prepend("{root}/cmake")


text:
/**************************************************************************
 * shpread.h  declarations for shpread.c, extracted from shpopen.c
 **************************************************************************/

#include "shapefil.h"

extern SHPInfo* SHPOpen( const char * pszLayer, const char * pszAccess );

extern void SHPClose(SHPHandle psSHP );

extern SHPObject* SHPReadObject( SHPHandle psSHP, int hEntity );

extern void SHPDestroyObject( SHPObject * psShape );


text:
namespace asn1 {

	inline OCTET_STRING_t mkOctetStringRaw (char const * raw_str, size_t ln)
	{
		OCTET_STRING_t ostr;
		ostr.buf = const_cast<unsigned char *>(reinterpret_cast<unsigned char const *>(raw_str));
		ostr.size = ln;
		return ostr;
	}

	inline OCTET_STRING_t mkOctetString (char const * raw_str)
	{
		OCTET_STRING_t ostr;
		ostr.buf = const_cast<unsigned char *>(reinterpret_cast<unsigned char const *>(raw_str));
		ostr.size = strlen(raw_str);
		return ostr;
	}
}


text:
#include <config/config_type_string.h>

ConfigTypeString config_type_string;


text:
import { IGatsbyPage } from "../redux/types";
import { IExecutionResult } from "../query/types";
interface IPageData {
    componentChunkName: IGatsbyPage["componentChunkName"];
    matchPath?: IGatsbyPage["matchPath"];
    path: IGatsbyPage["path"];
    staticQueryHashes: Array<string>;
}
export interface IPageDataWithQueryResult extends IPageData {
    result: IExecutionResult;
}
export declare function fixedPagePath(pagePath: string): string;
export declare function reverseFixedPagePath(pageDataRequestPath: string): string;
export declare function readPageData(publicDir: string, pagePath: string): Promise<IPageDataWithQueryResult>;
export declare function removePageData(publicDir: string, pagePath: string): Promise<void>;
export declare function pageDataExists(publicDir: string, pagePath: string): boolean;
export declare function writePageData(publicDir: string, { componentChunkName, matchPath, path: pagePath, staticQueryHashes, }: IPageData): Promise<IPageDataWithQueryResult>;
export declare function isFlushEnqueued(): boolean;
export declare function flush(): Promise<void>;
export declare function enqueueFlush(): void;
export declare function handleStalePageData(): Promise<void>;
export {};


text:
require('source-map-support').install();

import * as _ from 'lodash';

export class Once {
  private done: boolean = false;
  private oncePromise: Promise<any>;

  constructor(f: () => Promise<any>) {
    this.oncePromise = f().then(() => {
      this.done = true;
    }).catch(error => {
      // We might as well log here so we know what happened, since this will pop to the top of the stack anyway
      // tslint:disable:no-console
      console.error(`Fatal exception caught: ${error}`);

      // Throw error outside of promise
      _.defer(() => {
        throw error;
      });
    });
  }

  public do(): Promise<any> {
    return this.oncePromise;
  }

  public getDone() {
    return this.done;
  }
}

export default Once;


text:
import json
import logging

from django.utils.translation import ugettext as _

import requests

from fjord.base.google_utils import ga_track_event
from fjord.suggest import Link, Suggester
from fjord.redirector import Redirector, build_redirect_url

PROVIDER = 'sumosuggest'
# Increment this any time we change the heuristics for creating
# suggestions.
PROVIDER_VERSION = 1

# Append provider version so that if we change the algorithm, we
# increment the version and then we can compare the two flows.
EVENT_CATEGORY = 'sumo_suggest' + str(PROVIDER_VERSION)

SUMO_HOST = 'https://support.mozilla.org'
SUMO_SUGGEST_API_URL = SUMO_HOST + '/api/2/search/suggest/'
SUMO_SUGGEST_SESSION_KEY = 'sumo_suggest_docs_{0}'
SUMO_AAQ_URL = 'https://support.mozilla.org/questions/new'

logger = logging.getLogger('i.sumosuggest')

def get_kb_articles(locale, product, text):
    """Retrieves kb articles using the SUMO search suggest API

    Throws a variety of exceptions all of which the caller should
    deal with.

    :arg text: The text to search
    """
    params = {
        'q': text,
        'locale': 'en-US',
        'product': 'firefox',
        'max_documents': 3,
        'max_questions': 0
    }
    headers = {
        'content-type': 'application/json',
        'accept': 'application/json',
    }
    resp = requests.get(
        SUMO_SUGGEST_API_URL,
        data=json.dumps(params),
        headers=headers,
        # This is slightly larger than 3 which is what the requests
        # docs suggest, but we really want the shortest timeout we can
        # get away with since this happens during the http request
        # handling cycle.
        timeout=3.5
    )
    docs = resp.json()['documents']
    return [
        {
            'summary': doc['title'],
            'description': doc['summary'],
            'url': SUMO_HOST + doc['url']
        }
        for doc in docs
    ]

class RedirectParseError(Exception):
    pass

def format_redirect(rank):
    return 'sumosuggest.{0}'.format(rank)

def parse_redirect(redirect):
    try:
        trigger, rank = redirect.split('.')
        if rank != 'aaq':
            rank = int(rank)
        return trigger, rank
    except (ValueError, IndexError, TypeError) as exc:
        raise RedirectParseError(str(exc))

class SUMOSuggestRedirector(Redirector):
    """Provides redirection urls

    """
    def handle_redirect(self, request, redirect):
        # If it's not a sumosuggest redirect, return.
        if not redirect.startswith('sumosuggest'):
            return

        # Get the response id for the last feedback left.
        response_id = request.session.get('response_id', None)
        if response_id is None:
            return

        # If the session has no links, then we have nothing to
        # redirect to, so return.
        session_key = SUMO_SUGGEST_SESSION_KEY.format(response_id)
        docs = request.session.get(session_key, None)
        if not docs:
            return

        # Extract the rank.
        try:
            trigger, rank = parse_redirect(redirect)
        except RedirectParseError:
            return

        if rank == 'aaq':
            url = SUMO_AAQ_URL
        else:
            try:
                url = docs[rank]['url']
            except IndexError:
                # This doc doesn't exist.
                return

        ga_track_event({
            'cid': str(response_id),
            'ec': EVENT_CATEGORY,
            'ea': 'view' if rank != 'aaq' else 'viewaaq',
            'el': url
        }, async=True)

        return url

class SUMOSuggest(Suggester):
    """Provides suggest links based on SUMO Search Suggest API results

    .. Note::

       If you add this provider, you should also add the related
       redirector. If you don't, you'll get busted links.

    """
    def docs_to_links(self, docs):
        """Converts docs from SUMO Suggest API to links and adds AAQ link"""
        links = [
            Link(
                provider=PROVIDER,
                provider_version=PROVIDER_VERSION,
                cssclass=u'document',
                summary=doc['summary'],
                description=doc['description'],
                url=build_redirect_url(format_redirect(i))
            )
            for i, doc in enumerate(docs)
        ]
        links.append(
            Link(
                provider=PROVIDER,
                provider_version=PROVIDER_VERSION,
                cssclass=u'support',
                summary=_(u'Ask a question in our support forum'),
                description='',
                url=build_redirect_url(format_redirect('aaq'))
            )
        )
        return links

    def get_suggestions(self, feedback, request=None):
        # Note: We only want to run suggestions for sad responses for
        # Firefox product with en-US locale and for feedback that has
        # more than 7 words.
        #
        # If any of that changes, we'll need to rethink this.
        if ((feedback.happy
             or feedback.locale != u'en-US'
             or feedback.product != u'Firefox'
             or len(feedback.description.split()) < 7)):
            return []

        session_key = SUMO_SUGGEST_SESSION_KEY.format(feedback.id)

        # Check the session to see if we've provided links already and
        # if so, re-use those.
        if request is not None:
            docs = request.session.get(session_key, None)
            if docs is not None:
                return self.docs_to_links(docs)

        try:
            docs = get_kb_articles(u'en-US', u'Firefox', feedback.description)
        except Exception:
            # FIXME: As we discover what exceptions actually get
            # kicked up, we can handle them individually as
            # appropriate.
            logger.exception('SUMO Suggest API raised exception.')
            return []

        # Note: This needs to be synchronous so that "suggest" events
        # come before their respective "view*" events.
        ga_track_event({
            'cid': str(feedback.id),
            'ec': EVENT_CATEGORY,
            'ea': 'suggest'
        }, async=False)

        links = self.docs_to_links(docs)

        if request is not None:
            request.session[session_key] = docs

        return links


text:
var hostname = require('os').hostname();
var _ = require('underscore');
var openDB = require('./db');
var pending = [];
var collectionByName = {};
var counter = 0;
var restartCount;
var db;
process.on("config", function(config, callback) {
  restartCount = config["restart-count"];
  openDB(config.config.mongo, function(_db) {
    db = _db;
    callback();
  }, true); // Let it leak
});

function mergeProperties(source, target) {
  _.each(source, function(value, key) {
    if (!target[key]) {
      target[key] = value;
    }
  });
}

function addEntry(normalized, type, measurement) {
  var values = normalized[type];
  if (!values) {
    normalized[type] = values = [];
  }
  values.push(measurement);
}

function normalizeEvents(event, events, normalized) {
  if (!events) {
    return;
  }
  var eventCounter = 0;
  var measurementCounter = 0;
  if (!_.isArray(events)) {
    events = [events];
  }
  _.each(events, function(event) {
    eventCounter++;
    var eventType = event.type;
    var measurements = event.measurements;
    if (!measurements) {
      measurements = event.metrics;
    }
    delete event.metrics;
    delete event.measurements;
    delete event.type;
    if (measurements) {
      _.each(measurements, function(_measurements, type) {
        if (!_.isArray(_measurements)) {
          _measurements = [_measurements];
        }
        _.each(_measurements, function(measurement) {
          measurementCounter++;
          if (eventType) {
            measurement.eventType = eventType;
          }
          mergeProperties(event, measurement);
          addEntry(normalized, type, measurement);
        });
      });
    }
    if (eventType) {
      event.eventType = eventType;
    }
    addEntry(normalized, "event", event);
  });
  event.eventCount = eventCounter;
  event.measurementCount = measurementCounter;
}

function normalizeLogs(event, logs, normalized) {
  if (!logs) {
    return;
  }
  var counter = 0;
  if (!_.isArray(logs)) {
    logs = [logs];
  }
  _.each(logs, function(log) {
    counter++;
    addEntry(normalized, "log-record", log);
  });
  event.logCount = counter;
}

function insertCollectedValues(collection, values) {
  collection.insert(values, function(error) {
    if (error) {
      console.error("failed to insert", error.stack);
    }
  });
}

function insertValues(name, values) {
  var collection = collectionByName[name];
  if (collection) {
    return insertCollectedValues(collection, values);
  }
  db.collection(name, function(error, collection) {
    if (error) {
      console.error("failed to open", error.stack);
    }
    else {
      collectionByName[name] = collection;
      insertCollectedValues(collection, values);
    }
  });
}

function insert(valByCollection) {
  _.each(valByCollection, function(values, name) {
    insertValues(name, values);
  });
}

function pushMeasurement(type, message) {
  addEntry(pending, type, message);
  if (pending.length === 1) {
    setTimeout(function() {
      insert(pending);
      pending = {};
    }, 2500);
  }
}

function postMeasurement(receiveTimestamp, body, remoteAddress, callback) {
  var timestamp = Date.now();
  var submitTimestamp = body.timestamp;
  var events = body.events;
  var logs = body.logs;
  delete body.logs;
  delete body.events;
  delete body.timestamp;
  var normalized = {};
  var event = {
    "timestamp": timestamp,
    "hostname": hostname,
    "queuing": timestamp - receiveTimestamp
  };
  if (submitTimestamp) {
    event.transmitting = receiveTimestamp - submitTimestamp;
  }
  normalizeEvents(event, events, normalized);
  normalizeLogs(event, logs, normalized);
  _.each(normalized, function(measurements) {
    _.each(measurements, function(measurement) {
      mergeProperties(body, measurement);
    });
  });
  _.each(pending, function(event, name) {
    addEntry(normalized, name, event);
  });
  pending = {};
  insert(normalized);
  event.eventType = "server-tracker";
  event.duration = Date.now() - timestamp;
  pushMeasurement("measurement-loader", event);
  if (callback) {
    callback();
  }
  event.processing = Date.now() - timestamp;
}
process.on("message", function(message, callback) {
  counter++;
  var _callback = function() {
      if (callback) {
        callback();
      }
      if (counter >= restartCount) {
        process.exit(0); // restarting to work around a mongodb-native memory leak
      }
      };
  if (message.type) {
    var type = message.type;
    delete message.type;
    pushMeasurement(type, message);
    _callback();
    return;
  }
  var body = message.body;
  var remoteAddress = message.remoteAddress;
  var timestamp = message.timestamp;
  postMeasurement(timestamp, body, remoteAddress, _callback);
});


text:
"""A default config for gSCAN compositional splits."""

import ml_collections

def get_dataset_config():
  """Config for dataset and input pipeline."""
  config = ml_collections.ConfigDict()
  config.data_dir = 'data/compositional_splits'
  config.grid_size = 6
  config.max_seq_len = 10
  config.max_target_seq_len = 105
  config.num_epochs = 40
  config.img_dim = 16
  config.eos_idx = 2
  config.train_split = 'train'
  config.eval_split = 'dev'
  config.test_splits = [
      'test', 'visual_easier', 'visual', 'situational_1', 'situational_2',
      'contextual', 'adverb_1', 'adverb_2'
  ]
  config.split = 'compositional_splits'
  # If batches should be added to evaluate the entire dataset.
  config.eval_pad_last_batch = True
  config.test_pad_last_batch = True
  config.shuffle_buffer_size = 1000
  config.train_per_device_batch_size = 128
  config.eval_per_device_batch_size = 1000
  config.test_per_device_batch_size = 1000

  return config

def get_model_config():
  """Config for Transformer."""
  config = ml_collections.ConfigDict()
  config.vocab_size = 21
  config.target_vocab_size = 9
  config.max_decode_step = 120
  config.cross_attn = True
  config.bi_hidden_dim = 128
  config.v_hidden_dim = 128
  config.l_hidden_dim = 128
  config.l_intermediate_dim = 256
  config.v_intermediate_dim = 256
  config.bi_num_heads = 8
  config.l_num_heads = 8
  config.v_num_heads = 8
  config.decode_num_heads = 8
  config.l_num_layers = 6
  config.v_num_layers = 6
  config.bi_num_layers = 6
  config.decode_num_layers = 6
  config.num_conv_channels = 50
  config.conv_kernel_sizes = (1, 5, 7)
  config.beam_size = 1

  return config

def get_config():
  """Config for training and evaluation."""
  config = ml_collections.ConfigDict()

  # Training config
  config.learning_rate = 16e-4
  config.learning_rate_schedule = 'step'
  config.learning_rate_step_boundaries = [0.5, 0.75]
  config.learning_rate_weight_decay = 0.01
  config.optimizer = 'AdamW'
  config.no_weight_decay = ['bias', 'LayerNorm/bias', 'LayerNorm/scale']
  config.warmup_proportion = 0.1
  config.grad_clip = 0.5

  # If num_train_steps == -1 then the number of training steps is calculated
  # from num_epochs.
  config.num_train_steps = -1
  config.num_eval_steps = -1
  config.num_test_steps = -1
  config.num_profile_steps = 1
  config.log_loss_every_steps = 20
  # If eval_every_steps == -1 then the model is not evaluated.
  config.eval_every_steps = 1000
  config.checkpoint_every_steps = 1000

  config.seed = 0
  config.dataset = get_dataset_config()
  config.model = get_model_config()

  return config


text:
/*
 * The contents of this file cannot be used anywhere without the seeking prior permission from author
 */

package com.netsec.messages;

/**
 *
 * @author suparngupta
 */
public class Ticket1 extends GenericMessage{
    private String userId;
    private String serverName;

    public Ticket1(){
        this.setType(MessageType.TICKET_1);
    }
    @Override
    public String toString() {
        return "Ticket1{" + "userId=" + userId + ", serverName=" + serverName + ", expiration=" + expiration + ", userMFSKey=" + userMFSKey + ", MFSFSKey=" + MFSFSKey + '}';
    }
    private long expiration;
    private String userMFSKey;
    private String MFSFSKey;

    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the serverName
     */
    public String getServerName() {
        return serverName;
    }

    /**
     * @param serverName the serverName to set
     */
    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    /**
     * @return the expiration
     */
    public long getExpiration() {
        return expiration;
    }

    /**
     * @param expiration the expiration to set
     */
    public void setExpiration(long expiration) {
        this.expiration = expiration;
    }

    /**
     * @return the userMFSKey
     */
    public String getUserMFSKey() {
        return userMFSKey;
    }

    /**
     * @param userMFSKey the userMFSKey to set
     */
    public void setUserMFSKey(String userMFSKey) {
        this.userMFSKey = userMFSKey;
    }

    /**
     * @return the MFSFSKey
     */
    public String getMFSFSKey() {
        return MFSFSKey;
    }

    /**
     * @param MFSFSKey the MFSFSKey to set
     */
    public void setMFSFSKey(String MFSFSKey) {
        this.MFSFSKey = MFSFSKey;
    }

}


text:
package io.netty.testsuite.transport.socket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.channel.socket.SocketChannel;
import org.junit.Test;

import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.*;

public class SocketShutdownOutputByPeerTest extends AbstractServerSocketTest {

    @Test(timeout = 30000)
    public void testShutdownOutput() throws Throwable {
        run();
    }

    public void testShutdownOutput(ServerBootstrap sb) throws Throwable {
        TestHandler h = new TestHandler();
        Socket s = new Socket();
        try {
            sb.childHandler(h).childOption(ChannelOption.ALLOW_HALF_CLOSURE, true).bind().sync();

            s.connect(addr, 10000);
            s.getOutputStream().write(1);

            assertEquals(1, (int) h.queue.take());

            assertTrue(h.ch.isOpen());
            assertTrue(h.ch.isActive());
            assertFalse(h.ch.isInputShutdown());
            assertFalse(h.ch.isOutputShutdown());

            s.shutdownOutput();

            h.halfClosure.await();

            assertTrue(h.ch.isOpen());
            assertTrue(h.ch.isActive());
            assertTrue(h.ch.isInputShutdown());
            assertFalse(h.ch.isOutputShutdown());
            assertEquals(1, h.closure.getCount());
            Thread.sleep(100);
            assertEquals(1, h.halfClosureCount.intValue());
        } finally {
            s.close();
        }
    }

    @Test(timeout = 30000)
    public void testShutdownOutputWithoutOption() throws Throwable {
        run();
    }

    public void testShutdownOutputWithoutOption(ServerBootstrap sb) throws Throwable {
        TestHandler h = new TestHandler();
        Socket s = new Socket();
        try {
            sb.childHandler(h).bind().sync();

            s.connect(addr, 10000);
            s.getOutputStream().write(1);

            assertEquals(1, (int) h.queue.take());

            assertTrue(h.ch.isOpen());
            assertTrue(h.ch.isActive());
            assertFalse(h.ch.isInputShutdown());
            assertFalse(h.ch.isOutputShutdown());

            s.shutdownOutput();

            h.closure.await();

            assertFalse(h.ch.isOpen());
            assertFalse(h.ch.isActive());
            assertTrue(h.ch.isInputShutdown());
            assertTrue(h.ch.isOutputShutdown());

            assertEquals(1, h.halfClosure.getCount());
            Thread.sleep(100);
            assertEquals(0, h.halfClosureCount.intValue());
        } finally {
            s.close();
        }
    }

    private static class TestHandler extends SimpleChannelInboundHandler<ByteBuf> {
        volatile SocketChannel ch;
        final BlockingQueue<Byte> queue = new LinkedBlockingQueue<Byte>();
        final CountDownLatch halfClosure = new CountDownLatch(1);
        final CountDownLatch closure = new CountDownLatch(1);
        final AtomicInteger halfClosureCount = new AtomicInteger();

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ch = (SocketChannel) ctx.channel();
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            closure.countDown();
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            queue.offer(msg.readByte());
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof ChannelInputShutdownEvent) {
                halfClosureCount.incrementAndGet();
                halfClosure.countDown();
            }
        }
    }
}


text:
package org.wisdom.samples.ajax;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import org.apache.felix.ipojo.annotations.Requires;
import org.wisdom.api.DefaultController;
import org.wisdom.api.annotations.*;
import org.wisdom.api.http.HttpMethod;
import org.wisdom.api.http.Result;
import org.wisdom.api.router.Router;
import org.wisdom.api.templates.Template;

import java.util.List;

/**
 * A simple controller to manage a todo list (in memory).
 */
@Controller
public class TodoListController extends DefaultController {

    @View("ajax/index")
    private Template index;
    @Requires
    private Router router;
    private List<Task> items = Lists.newArrayList();

    @Route(method = HttpMethod.GET, uri = "/todo")
    public Result index() {
        return ok(render(index));
    }

    @Route(method = HttpMethod.GET, uri = "/todo/tasks")
    public Result retrieve() {
        return ok(items).json();
    }

    @Route(method = HttpMethod.DELETE, uri = "/todo/tasks/{id}")
    public Result delete(@Parameter("id") int id) {
        removeTaskById(id);
        return ok();
    }

    @Route(method = HttpMethod.POST, uri = "/todo/tasks")
    public Result create(@FormParameter("name") String name) {
        Task task = new Task(name);
        task.setUpdateUrl(router.getReverseRouteFor(this, "update", "id", task.id));
        task.setDeleteUrl(router.getReverseRouteFor(this, "delete", "id", task.id));
        items.add(task);
        return ok(task).json();
    }

    @Route(method = HttpMethod.POST, uri = "/todo/tasks/{id}")
    public Result update(@Parameter("id") int id, @FormParameter("completed") boolean completed) {
        Task task = getTaskById(id);
        if (task == null) {
            return notFound().render(ImmutableMap.of("message", "Task " + context().parameterFromPath
                    ("id") + " not found")).json();
        } else {
            task.completed(completed);
            if (completed) {
                return ok().render(ImmutableMap.of("message", "Task " + context().parameterFromPath
                        ("id") + " completed")).json();
            } else {
                return ok().render(ImmutableMap.of("message", "Task " + context().parameterFromPath
                        ("id") + " uncompleted")).json();
            }
        }
    }

    private Task getTaskById(int id) {
        for (Task t : items) {
            if (t.id == id) {
                return t;
            }
        }
        return null;
    }

    private void removeTaskById(int id) {
        Task t = getTaskById(id);
        if (t != null) {
            items.remove(t);
        }
    }

}


text: - Updated the Docker image to: *demisto/bigquery:1.0.0.26886*.


text:
package gfxdperf.tpch.oracle;

import gfxdperf.tpch.AbstractQ12;

import java.sql.Connection;
import java.util.Random;

/**
 * Encapsulates TPC-H Q12.
 */
public class Q12 extends AbstractQ12 {

  public Q12(Connection conn, Random rng) {
    super();
    this.connection = conn;
    this.rng = rng;
  }
}