text:
package com.example.joshskeen.myapplication;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.fest.assertions.api.ANDROID.assertThat;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 21)
public class MyActivityTest {

    private MyActivity mActivity;

    @Before
    public void setup() {
        mActivity = Robolectric.buildActivity(MyActivity.class).create().get();
    }

    @Test
    public void myActivityAppearsAsExpectedInitially() {
        assertThat(mActivity.mClickMeButton).hasText("Click me!");
        assertThat(mActivity.mHelloWorldTextView).hasText("Hello world!");
    }

    @Test
    public void clickingClickMeButtonChangesHelloWorldText() {
        assertThat(mActivity.mHelloWorldTextView).hasText("Hello world!");
        mActivity.mClickMeButton.performClick();
        assertThat(mActivity.mHelloWorldTextView).hasText("HEY WORLD");
    }
}


text:
//-*- Mode: C++ -*-
// $Id$

#ifndef ALIHLTPREDICTIONPROCESSORGRP_H
#define ALIHLTPREDICTIONPROCESSORGRP_H
/
class AliHLTPredictionProcessorGRP : public AliHLTPredictionProcessorInterface
{
public:

  /**
   * Constructor for AliHLTPredictionProcessorGRP
   *
   * @param pendolino pointer to the hosting pendolino
   */
  AliHLTPredictionProcessorGRP(AliHLTPendolino* pendolino);

  /// Destructor for AliHLTPredictionProcessorGRP
  virtual ~AliHLTPredictionProcessorGRP();

  /**
   * Virtual function to force the Prediction Processor to implement
   * a function to flag that prediction making is required.
   * This function is called by the Pendolino before the fetched DCS data
   * is handed in for (prediction) processing.
   *
   * @param doPrediction if true, prediction making shall be switched on,
   * 			if false, switched off.
   *
   * @return 0 on success; a value greater than 0 refers to an error
   */
  virtual UInt_t makePrediction(Bool_t doPrediction = true);

  /**
   * Virtual function, implemented in the detector specific
   * PredictionProcessors to initialize them.
   *
   * @param run run number
   * @param startTime start time of data
   * @param endTime end time of data
   */
  virtual void Initialize(Int_t run, UInt_t startTime, UInt_t endTime);

  /**
   * Function called by the Pendolino for each participating subdetector
   * producing the required condition settings. This includes the
   * encoding of a prediction to the values due to the fact, that only
   * data up to now can be fetched from DCS (the latest data can also be
   * up to 2 min old until it is received on HLT side). To write the data
   * to the HCDB, the detector specific implementation of this class has
   * to call the appropriated storing function provided by the interface.
   *
   * @param dcsAliasMap the map containing aliases and corresponding DCS
   * 			values and timestamps
   *
   * @return 0 on success; a value greater than 0 refers to an error
   */
  virtual UInt_t Process(TMap* dcsAliasMap);

  /**
   * Indicates if DCS data shall be processed.
   * NOTE: should always return true, since it is used as prediction
   * processor, which will only process DCS data
   *
   * @return true if DCS data can be processed, else false. Note: if false
   * 				the Pendolino would stop, so make sure that it is true.
   */
  virtual Bool_t ProcessDCS();

  /**
   * Function to let the PredictionProcessor produce dummy input data,
   * that can be used in Pendolino tests, where no DCS Archieve DB is
   * contacted. This function is called by the Pendolino, the result is
   * given back to the PredictionProcessor via the Process(...) call.
   * Since the DCSMaps requested from DCS are detector specific, the
   * PredictionProcessor should know, how the maps look like, that it
   * expects.
   * NOTE: The clean - up (delete) of the TMap will be performed by the
   * Pendolino after the usage. The PredictionProcessor has never to
   * call delete on the returned TMap pointer.
   *
   * @param aliasName optional parameter, that can be given in order to
   *          create a DCSMap for dedicated aliases. For a general test
   *          this paramter should be empty. If more than one alias name
   *          shall be specified, they are separated by blanks " ".
   *
   * @return DCSMap containing dummy data for testing the Pendolino.
   */
  virtual TMap* produceTestData(TString aliasName = "");

  /**
   * Create the initial GRP entry.
   * The beam type and run type parameters are propagated form the ECS to
   * the run manager, and provided as arguments to the pendolino.
   * The initial GRP entry is created ignoring the magnetic field, this
   * is updated by the pendolino afterwords.
   */
  static bool CreateInitialGRPEntry(int runno, const char* beamtype,
				    const char* runtype, const char* detectorList);

protected:

private:
  /**
   * Disabled Copy constructor
   * (parent class is disabled so derived class does the same)
   */
  AliHLTPredictionProcessorGRP(const AliHLTPredictionProcessorGRP& predictPro);

  /**
   * Disabled Assignment operator
   * (parent class is disabled so derived class does the same)
   */
  AliHLTPredictionProcessorGRP& operator=(const AliHLTPredictionProcessorGRP& rhs);

  ClassDef(AliHLTPredictionProcessorGRP, 1);

};

inline Bool_t AliHLTPredictionProcessorGRP::ProcessDCS() {
	// indicates if DCS values are processed; always true
	return true;
}

#endif

redpajama_set_name: RedPajamaGithub


text:
# Si7005.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# mar 2014 python port of Si7005 arduino library
# AKA
from __future__ import division
from Adafruit_I2C import Adafruit_I2C
import Adafruit_BBIO.GPIO as GPIO
import time

class si7005():
    # /* Si7005 Registers */
    REG_STATUS         = 0x00
    REG_DATA           = 0x01
    REG_CONFIG         = 0x03
    REG_ID             = 0x11

    # /* Status Register */
    STATUS_NOT_READY   = 0x01

    # /* Config Register */
    CONFIG_START       = 0x01
    CONFIG_HEAT        = 0x02
    CONFIG_HUMIDITY    = 0x00
    CONFIG_TEMPERATURE = 0x10
    CONFIG_FAST        = 0x20

    # /* ID Register */
    ID_SAMPLE          = 0xF0
    ID_SI7005          = 0x50

    # /* Coefficients */
    TEMPERATURE_OFFSET  =  50
    TEMPERATURE_SLOPE   =  32
    HUMIDITY_OFFSET     =  24
    HUMIDITY_SLOPE      =  16
    a0 = (-4.7844)
    a1 =  0.4008
    a2 = (-0.00393)
    q0 =  0.1973
    q1 =  0.00237

    WAKE_UP_TIME = 0.015 # AKA thinks this was 15ms, so changing it to 0.015sec
    # address
    SI7005_ADR = 0x40

    def __init__(self,pin):
        print 'init si'
    	self.i2c = Adafruit_I2C(self.SI7005_ADR)
    	GPIO.setup(pin, GPIO.OUT)
    	GPIO.output(pin,GPIO.HIGH)
    	self._cs_pin = pin

    	self._last_temperature = 25.0
    	self._config_reg = 0

    def detectSensor(self):
        # byte deviceID
        GPIO.output(self._cs_pin, GPIO.LOW)
        time.sleep(self.WAKE_UP_TIME)
        print 'detect detectSensor'
        # i2c.beginTransmission(self.SI7005_ADR)
        self.i2c.write8(self.SI7005_ADR, self.REG_ID)
        # i2c.endTransmission(false)
        # i2c.requestFrom(SI7005_ADR,1)
        deviceID = self.i2c.readU8(self.SI7005_ADR)
        GPIO.output(self._cs_pin, GPIO.HIGH)
        if (deviceID & self.ID_SAMPLE) == self.ID_SI7005:
            return True
        else:
            return False

    def doMeasurement(self,configValue):
        GPIO.output(self._cs_pin, GPIO.LOW) # enable sensor
        time.sleep(self.WAKE_UP_TIME) # wait for wakeup

        self.i2c.write8(self.SI7005_ADR, self.REG_CONFIG) # select config register
        self.i2c.write8(self.SI7005_ADR, (self.CONFIG_START | configValue | self._config_reg)) # Start measurement of the selected type (Temperature / humidity)
        measurementStatus = self.STATUS_NOT_READY

        while (measurementStatus & self.STATUS_NOT_READY):
            self.i2c.write8(self.SI7005_ADR, self.REG_STATUS)
            measurementStatus = self.i2c.readU8(self.SI7005_ADR)

        self.i2c.write8(self.SI7005_ADR, REG_DATA)
        rawData = self.i2c.readU8(self.SI7005_ADR) << 8 # MSB
        rawData |= self.i2c.readU8(self.SI7005_ADR) # LSB

        GPIO.output(self._cs_pin, GPIO.HIGH) # disable sensor

        return rawData

    def getTemperature(self):
    	rawTemperature = self.doMeasurement(self.CONFIG_TEMPERATURE) >> 2
        _last_temperature = ( rawTemperature / self.TEMPERATURE_SLOPE ) - self.TEMPERATURE_OFFSET
        return _last_temperature

    def getHumidity( self):
    	rawHumidity = doMeasurement(self.CONFIG_HUMIDITY) >> 4
        curve = (rawHumidity / self.HUMIDITY_SLOPE) - self.HUMIDITY_OFFSET
        linearHumidity = curve - ( (curve*curve)*a2 + curve*a1 +  a0)
        linearHumidity = linearHumidity + ( _last_temperature - 30 ) * ( linearHumidity * q1 + q0 )
        return linearHumidity

    def enableHeater(self ):
    	_config_reg |= CONFIG_HEAT

    def disableHeater(self ):
    	_config_reg ^= CONFIG_HEAT

    def enableFastMeasurements(self ):
    	_config_reg |= CONFIG_FAST

    def disableFastMeasurements(self ):
    	_config_reg ^= CONFIG_FAST


text:
package test.confordering;

import java.util.ArrayList;
import java.util.List;

import org.testng.Assert;
import org.testng.TestNG;

import test.confordering.subpckg1.Parent;
import test.confordering.subpckg2.NonOverriddingChild;
import test.confordering.subpckg2.OverriddingChild;
import test.confordering.subpckg2.SimpleOverriddingChild;

import testhelper.OutputDirectoryPatch;

public class ConfigurationMethodOrderingTest {
  public static List LOG;

  /**
   * @testng.test
   */
  public void checkConfOrderInInheritanceWithNoOverrides() {
    LOG= new ArrayList();
    TestNG tng= new TestNG();
    tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory());
    tng.setTestClasses(new Class[] {NonOverriddingChild.class});
    tng.setVerbose(1);
    tng.run();
    System.out.println("[[NonOverriddingChild]]:" + LOG.toString());

    assertIsBefore(LOG, "parentBeforeTestClass", "childBeforeTestClass");
    assertIsBefore(LOG, "parentInheritBeforeTestClass", "childBeforeTestClass");
    assertIsBefore(LOG, "parentBeforeTestMethod", "childBeforeTestMethod");
    assertIsBefore(LOG, "parentInheritBeforeTestMethod", "childBeforeTestMethod");
    assertIsAfter(LOG, "parentAfterTestMethod", "childAfterTestMethod");
    assertIsAfter(LOG, "parentInheritAfterTestMethod", "childAfterTestMethod");
    assertIsAfter(LOG, "parentInheritAfterTestClass", "childAfterTestClass");
    assertIsAfter(LOG, "parentAfterTestClass", "childAfterTestClass");
  }

  /**
   * @testng.test
   */
  public void checkConfOrderInInheritanceWithSimpleOverrides() {
    LOG= new ArrayList();
    TestNG tng= new TestNG();
    tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory());
    tng.setTestClasses(new Class[] {SimpleOverriddingChild.class});
    tng.setVerbose(1);
    tng.run();
    System.out.println("[[SimpleOverriddingChild]]:" + LOG.toString());

    assertIsBefore(LOG, "parentBeforeTestClass", "childBeforeTestClass");
    assertIsBefore(LOG, "parentBeforeTestClass", "childInheritBeforeTestClass");
    assertIsBefore(LOG, "parentBeforeTestMethod", "childBeforeTestMethod");
    assertIsBefore(LOG, "parentBeforeTestMethod", "childInheritBeforeTestMethod");
    assertIsAfter(LOG, "parentAfterTestMethod", "childAfterTestMethod");
    assertIsAfter(LOG, "parentAfterTestMethod", "childInheritAfterTestMethod");
    assertIsAfter(LOG, "parentAfterTestClass", "childInheritAfterTestClass");
    assertIsAfter(LOG, "parentAfterTestClass", "childAfterTestClass");
  }

  /**
   * @testng.test
   */
  public void checkConfOrderInInheritanceWithFullOverrides() {
    LOG= new ArrayList();
    TestNG tng= new TestNG();
    tng.setOutputDirectory(OutputDirectoryPatch.getOutputDirectory());
    tng.setTestClasses(new Class[] {OverriddingChild.class});
    tng.setVerbose(1);
    tng.run();
    System.out.println("[[OverriddingChild]]:" + LOG.toString());

    assertIsBefore(LOG, "parentBeforeTestClass", "childBeforeTestClass");
    assertIsBefore(LOG, "parentBeforeTestClass", "childInheritBeforeTestClass");
    assertIsBefore(LOG, "parentBeforeTestMethod", "childBeforeTestMethod");
    assertIsBefore(LOG, "parentBeforeTestMethod", "childInheritBeforeTestMethod");
    assertIsAfter(LOG, "parentAfterTestMethod", "childAfterTestMethod");
    assertIsAfter(LOG, "parentAfterTestMethod", "childInheritAfterTestMethod");
    assertIsAfter(LOG, "parentAfterTestClass", "childInheritAfterTestClass");
    assertIsAfter(LOG, "parentAfterTestClass", "childAfterTestClass");
  }

  private void assertIsBefore(List list, final String first, final String second) {
    int firstIdx = list.indexOf(first);
    int secondIdx = list.indexOf(second);

    Assert.assertTrue(firstIdx != -1, "<" + first + "> should be in the list");
    Assert.assertTrue(secondIdx != -1, "<" + second + "> should be in the list");
    Assert.assertTrue(firstIdx < secondIdx, "<" + first + "> should be before <" + second + ">");
  }

  private void assertIsAfter(List list, final String second, final String first) {
    assertIsBefore(list, first, second);
  }
}


text:
package com.lothrazar.cyclic.block.fishing;

import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.block.model.ItemTransforms.TransformType;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.core.Direction;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.IItemHandler;

public class RenderFisher implements BlockEntityRenderer<TileFisher> {

  public RenderFisher(BlockEntityRendererProvider.Context d) {}

  @Override
  public void render(TileFisher tankHere, float v, PoseStack matrixStack,
      MultiBufferSource buffer, int light, int overlayLight) {
    IItemHandler itemHandler = tankHere.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, Direction.UP).orElse(null);
    if (itemHandler != null) {
      ItemStack stack = itemHandler.getStackInSlot(0);
      if (!stack.isEmpty()) {
        matrixStack.pushPose();
        //        matrixStack.scale(0.5f, 0.5f, 0.5f);
        matrixStack.translate(0.4, 0.45, 0.4);
        Minecraft.getInstance().getItemRenderer().renderStatic(stack, TransformType.GROUND, 0x910911, 0, matrixStack, buffer, light);
        matrixStack.popPose();
      }
    }
  }
}


text:
<!--
* Flightdeck - {{ site.data.package.description }}
* @version {{ site.data.package.version }}
* @link {{ site.data.package.homepage }}
* Copyright 2017-{{ 'now' | date: "%Y" }} The Flightdeck Authors
* Licensed under MIT (https://github.com/flight-deck/flightdeck-jekyll/blob/master/LICENSE)
-->


text:
import argparse
import os
import platform
import subprocess
import tempfile
from contextlib import contextmanager
from enum import Enum, auto
from pathlib import Path
from typing import Iterable, Iterator, List, NamedTuple, Optional, Set, Union

from common import banner, die, green, travis_section

def main() -> None:
    banner("CI BEGINS")

    args = create_parser().parse_args()
    setup_environment(python_version=args.python_version)

    with maybe_get_remote_execution_oauth_token_path(
        remote_execution_enabled=args.remote_execution_enabled
    ) as remote_execution_oauth_token_path:

        if args.bootstrap:
            bootstrap(clean=args.bootstrap_clean, python_version=args.python_version)
        set_run_from_pex()

        if args.githooks:
            run_githooks()
        if args.sanity_checks:
            run_sanity_checks()
        if args.lint:
            run_lint(oauth_token_path=remote_execution_oauth_token_path)
        if args.doc_gen:
            run_doc_gen_tests()
        if args.clippy:
            run_clippy()
        if args.cargo_audit:
            run_cargo_audit()
        if args.unit_tests:
            run_unit_tests(oauth_token_path=remote_execution_oauth_token_path)
        if args.rust_tests:
            run_rust_tests()
        if args.jvm_tests:
            run_jvm_tests()
        if args.integration_tests_v1:
            run_integration_tests_v1(shard=args.integration_shard)
        if args.integration_tests_v2:
            run_integration_tests_v2(oauth_token_path=remote_execution_oauth_token_path)
        if args.plugin_tests:
            run_plugin_tests(oauth_token_path=remote_execution_oauth_token_path)
        if args.platform_specific_tests:
            run_platform_specific_tests()

    banner("CI ENDS")
    print()
    green("SUCCESS")

# -------------------------------------------------------------------------
# Options
# -------------------------------------------------------------------------

class PythonVersion(Enum):
    py36 = "3.6"
    py37 = "3.7"

    def __str__(self) -> str:
        return str(self.value)

def create_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Runs commons tests for local or hosted CI.")
    parser.add_argument(
        "--python-version",
        type=PythonVersion,
        choices=list(PythonVersion),
        default=PythonVersion.py36,
        help="Run Pants with this version (defaults to 3.6).",
    )
    parser.add_argument(
        "--remote-execution-enabled",
        action="store_true",
        help="Pants will use remote build execution remote where possible (for now, the V2 unit tests). "
        "If running locally, you must be logged in via the `gcloud` CLI to an account with remote "
        "build execution permissions. If running in CI, the script will ping the secure token "
        "generator at https://github.com/pantsbuild/rbe-token-server.",
    )
    parser.add_argument(
        "--bootstrap", action="store_true", help="Bootstrap a pants.pex from local sources."
    )
    parser.add_argument(
        "--bootstrap-clean",
        action="store_true",
        help="Before bootstrapping, clean the environment so that it's like a fresh git clone.",
    )
    parser.add_argument("--githooks", action="store_true", help="Run pre-commit githook.")
    parser.add_argument(
        "--sanity-checks",
        action="store_true",
        help="Run sanity checks of bootstrapped Pants and repo BUILD files.",
    )
    parser.add_argument("--lint", action="store_true", help="Run lint over whole codebase.")
    parser.add_argument("--doc-gen", action="store_true", help="Run doc generation tests.")
    parser.add_argument("--clippy", action="store_true", help="Run Clippy on Rust code.")
    parser.add_argument(
        "--cargo-audit", action="store_true", help="Run Cargo audit of Rust dependencies."
    )
    parser.add_argument("--unit-tests", action="store_true", help="Run Python unit tests.")
    parser.add_argument("--rust-tests", action="store_true", help="Run Rust tests.")
    parser.add_argument("--jvm-tests", action="store_true", help="Run JVM tests.")
    parser.add_argument(
        "--integration-tests-v1",
        action="store_true",
        help="Run Python integration tests w/ V1 runner.",
    )
    parser.add_argument(
        "--integration-tests-v2",
        action="store_true",
        help="Run Python integration tests w/ V2 runner.",
    )
    parser.add_argument(
        "--integration-shard",
        metavar="SHARD_NUMBER/TOTAL_SHARDS",
        default=None,
        help="Divide integration tests into TOTAL_SHARDS shards and just run those in SHARD_NUMBER. "
        "E.g. `-i 0/2` and `-i 1/2` will split the tests in half.",
    )
    parser.add_argument("--plugin-tests", action="store_true", help="Run tests for pants-plugins.")
    parser.add_argument(
        "--platform-specific-tests", action="store_true", help="Test platform-specific behavior."
    )
    return parser

# -------------------------------------------------------------------------
# Set up the environment
# -------------------------------------------------------------------------

def setup_environment(*, python_version: PythonVersion):
    set_cxx_compiler()
    set_pants_dev()
    setup_python_interpreter(python_version)

def set_pants_dev() -> None:
    """We do this because we are running against a Pants clone."""
    os.environ["PANTS_DEV"] = "1"

def set_cxx_compiler() -> None:
    compiler = "g++" if platform.system() != "Darwin" else "clang++"
    os.environ["CXX"] = compiler

def setup_python_interpreter(version: PythonVersion) -> None:
    if "PY" not in os.environ:
        os.environ["PY"] = f"python{version}"
    constraints_env_var = "PANTS_PYTHON_SETUP_INTERPRETER_CONSTRAINTS"
    if constraints_env_var not in os.environ:
        os.environ[constraints_env_var] = f"['CPython=={version}.*']"
    banner(f"Setting interpreter constraints to {os.environ[constraints_env_var]}")

def set_run_from_pex() -> None:
    # Even though our Python integration tests and commands in this file directly invoke `pants.pex`,
    # some places like the JVM tests may still directly call the script `./pants`. When this happens,
    # we want to ensure that the script immediately breaks out to `./pants.pex` to avoid
    # re-bootstrapping Pants in CI.
    os.environ["RUN_PANTS_FROM_PEX"] = "1"

@contextmanager
def maybe_get_remote_execution_oauth_token_path(
    *, remote_execution_enabled: bool
) -> Iterator[Optional[str]]:
    if not remote_execution_enabled:
        yield None
        return
    command = (
        ["./pants.pex", "--quiet", "run", "build-support/bin:get_rbe_token"]
        if os.getenv("CI")
        else ["gcloud", "auth", "application-default", "print-access-token"]
    )
    token: str = subprocess.run(
        command, encoding="utf-8", stdout=subprocess.PIPE, check=True
    ).stdout
    if not os.getenv("CI"):
        token = token.splitlines()[0]
    with tempfile.NamedTemporaryFile(mode="w+") as tf:
        tf.write(token)
        tf.seek(0)
        yield tf.name

# -------------------------------------------------------------------------
# Blacklists
# -------------------------------------------------------------------------

Target = str
Glob = str
TargetSet = Set[Target]

class TestStrategy(Enum):
    v1_no_chroot = auto()
    v1_chroot = auto()
    v2_local = auto()
    v2_remote = auto()

    def pants_command(
        self,
        *,
        targets: Iterable[Union[Target, Glob]],
        shard: Optional[str] = None,
        oauth_token_path: Optional[str] = None,
    ) -> List[str]:
        if self == self.v2_remote and oauth_token_path is None:  # type: ignore[comparison-overlap]  # issues with understanding `self`
            raise ValueError("Must specify oauth_token_path.")
        result = {
            self.v1_no_chroot: [
                "./pants.pex",
                "test.pytest",
                "--no-chroot",
                *sorted(targets),
                *PYTEST_PASSTHRU_ARGS,
            ],
            self.v1_chroot: ["./pants.pex", "test.pytest", *sorted(targets), *PYTEST_PASSTHRU_ARGS],
            self.v2_local: ["./pants.pex", "--no-v1", "--v2", "test", *sorted(targets)],
            self.v2_remote: [
                "./pants.pex",
                *_use_remote_execution(oauth_token_path or ""),
                "test",
                *sorted(targets),
            ],
        }[
            self  # type: ignore[index]  # issues with understanding `self`
        ]
        if shard is not None and self in [self.v1_no_chroot, self.v1_chroot]:  # type: ignore[comparison-overlap]  # issues with understanding `self`
            result.insert(2, f"--test-pytest-test-shard={shard}")
        return result

class TestType(Enum):
    unit = "unit"
    integration = "integration"

    def __str__(self) -> str:
        return str(self.value)

class TestTargetSets(NamedTuple):
    v1_no_chroot: TargetSet
    v1_chroot: TargetSet
    v2_local: TargetSet
    v2_remote: TargetSet

    @staticmethod
    def calculate(
        *, test_type: TestType, remote_execution_enabled: bool = False
    ) -> "TestTargetSets":
        def get_listed_targets(filename: str) -> TargetSet:
            list_path = Path(f"build-support/ci_lists/{filename}")
            if not list_path.exists():
                return set()
            return {line.strip() for line in list_path.read_text().splitlines()}

        all_targets = set(
            subprocess.run(
                [
                    "./pants.pex",
                    f"--tag={'-' if test_type == TestType.unit else '+'}integration",
                    "filter",
                    "--type=python_tests",
                    "build-support::",
                    "src/python::",
                    "tests/python::",
                    "contrib::",
                ],
                stdout=subprocess.PIPE,
                encoding="utf-8",
                check=True,
            )
            .stdout.strip()
            .split("\n")
        )

        blacklisted_chroot_targets = get_listed_targets(f"{test_type}_chroot_blacklist.txt")
        blacklisted_v2_targets = get_listed_targets(f"{test_type}_v2_blacklist.txt")
        blacklisted_remote_targets = get_listed_targets(f"{test_type}_remote_blacklist.txt")

        v1_no_chroot_targets = blacklisted_chroot_targets
        v1_chroot_targets = blacklisted_v2_targets
        v2_local_targets = blacklisted_remote_targets
        v2_remote_targets = (
            all_targets - v2_local_targets - v1_chroot_targets - v1_no_chroot_targets
        )

        if not remote_execution_enabled:
            v2_local_targets |= v2_remote_targets
            v2_remote_targets = set()

        return TestTargetSets(
            v1_no_chroot=v1_no_chroot_targets,
            v1_chroot=v1_chroot_targets,
            v2_local=v2_local_targets,
            v2_remote=v2_remote_targets,
        )

# -------------------------------------------------------------------------
# Bootstrap pants.pex
# -------------------------------------------------------------------------

def bootstrap(*, clean: bool, python_version: PythonVersion) -> None:
    with travis_section("Bootstrap", f"Bootstrapping Pants as a Python {python_version} PEX"):
        if clean:
            try:
                subprocess.run(["./build-support/python/clean.sh"], check=True)
            except subprocess.CalledProcessError:
                die("Failed to clean before bootstrapping Pants.")

        try:
            subprocess.run(["./build-support/bin/bootstrap_pants_pex.sh"], check=True)
        except subprocess.CalledProcessError:
            die("Failed to bootstrap Pants.")

def check_pants_pex_exists() -> None:
    if not Path("pants.pex").is_file():
        die(
            "pants.pex not found! Either run `./build-support/bin/ci.py --bootstrap` or check that "
            "AWS is properly downloading the uploaded `pants.pex`."
        )

# -------------------------------------------------------------------------
# Test commands
# -------------------------------------------------------------------------

# We only want to output failures and skips.
# See https://docs.pytest.org/en/latest/usage.html#detailed-summary-report.
PYTEST_PASSTHRU_ARGS = ["--", "-q", "-rfa"]

def _use_remote_execution(oauth_token_path: str) -> List[str]:
    return [
        "--no-v1",
        "--v2",
        "--pants-config-files=pants.remote.toml",
        f"--remote-oauth-bearer-token-path={oauth_token_path}",
    ]

def _run_command(
    command: List[str],
    *,
    slug: str,
    start_message: str,
    die_message: str,
    requires_pex: bool = True,
) -> None:
    with travis_section(slug, start_message):
        if requires_pex:
            check_pants_pex_exists()
        try:
            subprocess.run(command, check=True)
        except subprocess.CalledProcessError:
            die(die_message)

def run_githooks() -> None:
    _run_command(
        ["./build-support/githooks/pre-commit"],
        slug="PreCommit",
        start_message="Running pre-commit checks",
        die_message="Pre-commit checks failed.",
    )

def run_sanity_checks() -> None:
    def run_check(command: List[str]) -> None:
        print(f"* Executing `./pants.pex {' '.join(command)}` as a sanity check")
        try:
            subprocess.run(
                ["./pants.pex", *command],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.STDOUT,
                check=True,
            )
        except subprocess.CalledProcessError:
            die(f"Failed to execute `./pants {command}`.")

    checks = [
        ["bash-completion"],
        ["reference"],
        ["clean-all"],
        ["goals"],
        ["list", "::"],
        ["roots"],
        ["targets"],
    ]
    with travis_section("SanityCheck", "Sanity checking bootstrapped Pants and repo BUILD files"):
        check_pants_pex_exists()
        for check in checks:
            run_check(check)

def run_lint(*, oauth_token_path: Optional[str] = None) -> None:
    targets = ["contrib::", "examples::", "src::", "tests::", "zinc::"]
    command_prefix = ["./pants.pex", "--tag=-nolint"]

    v2_command = (
        ["--no-v1", "--v2", "lint", *targets]
        if oauth_token_path is None
        else [*command_prefix, *_use_remote_execution(oauth_token_path), "lint", *targets]
    )
    _run_command(
        v2_command,
        slug="Lint (V2)",
        start_message="Running V2 lint checks",
        die_message="Lint check failure.",
    )
    _run_command(
        [*command_prefix, "lint", *targets],
        slug="Lint (V1)",
        start_message="Running V1 lint checks",
        die_message="Lint check failure.",
    )

def run_doc_gen_tests() -> None:
    _run_command(
        ["build-support/bin/publish_docs.sh"],
        slug="DocGen",
        start_message="Running site doc generation test",
        die_message="Failed to generate site docs.",
    )

def run_clippy() -> None:
    _run_command(
        ["build-support/bin/check_clippy.sh"],
        slug="RustClippy",
        start_message="Running Clippy on Rust code",
        die_message="Clippy failure.",
        requires_pex=False,
    )

def run_cargo_audit() -> None:
    with travis_section("CargoAudit", "Running Cargo audit on Rust code"):
        try:
            subprocess.run(
                [
                    "build-support/bin/native/cargo",
                    "ensure-installed",
                    "--package=cargo-audit",
                    "--version=0.7.0",
                ],
                check=True,
            )
            subprocess.run(
                [
                    "build-support/bin/native/cargo",
                    "audit",
                    "-f",
                    "src/rust/engine/Cargo.lock",
                    # TODO(John Sirois): Kill --ignore RUSTSEC-2019-0003 when we can upgrade to an official
                    # released version of protobuf with a fix.
                    # See: https://github.com/pantsbuild/pants/issues/7760 for context.
                    "--ignore",
                    "RUSTSEC-2019-0003",
                ],
                check=True,
            )
        except subprocess.CalledProcessError:
            die("Cargo audit failure")

def run_unit_tests(*, oauth_token_path: Optional[str] = None) -> None:
    target_sets = TestTargetSets.calculate(
        test_type=TestType.unit, remote_execution_enabled=oauth_token_path is not None
    )
    if target_sets.v2_remote:
        _run_command(
            command=TestStrategy.v2_remote.pants_command(
                targets=target_sets.v2_remote, oauth_token_path=oauth_token_path
            ),
            slug="UnitTestsV2Remote",
            start_message="Running unit tests via remote V2 strategy",
            die_message="Unit test failure (remote V2 strategy)",
        )
    if target_sets.v2_local:
        _run_command(
            command=TestStrategy.v2_local.pants_command(targets=target_sets.v2_local),
            slug="UnitTestsV2Local",
            start_message="Running unit tests via local V2 strategy",
            die_message="Unit test failure (local V2)",
        )
    if target_sets.v1_chroot:
        _run_command(
            command=TestStrategy.v1_chroot.pants_command(targets=target_sets.v1_chroot),
            slug="UnitTestsV1Chroot",
            start_message="Running unit tests via local V1 chroot strategy",
            die_message="Unit test failure (V1 chroot)",
        )

    if target_sets.v1_no_chroot:
        _run_command(
            command=TestStrategy.v1_no_chroot.pants_command(targets=target_sets.v1_no_chroot),
            slug="UnitTestsV1NoChroot",
            start_message="Running unit tests via local V1 no-chroot strategy",
            die_message="Unit test failure (V1 no-chroot)",
        )

def run_rust_tests() -> None:
    is_macos = platform.system() == "Darwin"
    command = [
        "build-support/bin/native/cargo",
        "test",
        "--all",
        # We pass --tests to skip doc tests, because our generated protos contain invalid doc tests in
        # their comments.
        "--tests",
        "--manifest-path=src/rust/engine/Cargo.toml",
        "--",
        "--nocapture",
    ]
    if is_macos:
        # The osx travis environment has a low file descriptors ulimit, so we avoid running too many
        # tests in parallel.
        command.append("--test-threads=1")
    with travis_section("RustTests", "Running Rust tests"):
        try:
            subprocess.run(command, env={**os.environ, "RUST_BACKTRACE": "all"}, check=True)
        except subprocess.CalledProcessError:
            die("Rust test failure.")

def run_jvm_tests() -> None:
    targets = ["src/java::", "src/scala::", "tests/java::", "tests/scala::", "zinc::"]
    _run_command(
        ["./pants.pex", "doc", "test", *targets],
        slug="CoreJVM",
        start_message="Running JVM tests",
        die_message="JVM test failure.",
    )

def run_integration_tests_v1(*, shard: Optional[str]) -> None:
    target_sets = TestTargetSets.calculate(
        test_type=TestType.integration, remote_execution_enabled=False
    )
    if target_sets.v1_no_chroot:
        _run_command(
            command=TestStrategy.v1_no_chroot.pants_command(
                targets=target_sets.v1_no_chroot, shard=shard
            ),
            slug="IntegrationTestsV1NoChroot",
            start_message="Running integration tests via V1 no-chroot strategy.",
            die_message="Integration test failure (V1 no-chroot)",
        )
    if target_sets.v1_chroot:
        _run_command(
            command=TestStrategy.v1_chroot.pants_command(
                targets=target_sets.v1_chroot, shard=shard
            ),
            slug="IntegrationTestsV1Chroot",
            start_message="Running integration tests via V1 chroot strategy.",
            die_message="Integration test failure (V1 chroot)",
        )

def run_integration_tests_v2(*, oauth_token_path: Optional[str] = None) -> None:
    target_sets = TestTargetSets.calculate(
        test_type=TestType.integration, remote_execution_enabled=oauth_token_path is not None
    )
    if target_sets.v2_remote:
        _run_command(
            command=TestStrategy.v2_remote.pants_command(
                targets=target_sets.v2_remote, oauth_token_path=oauth_token_path
            ),
            slug="IntegrationTestsV2Remote",
            start_message="Running integration tests via V2 remote strategy.",
            die_message="Integration test failure (V2 remote)",
        )
    if target_sets.v2_local:
        _run_command(
            command=TestStrategy.v2_local.pants_command(targets=target_sets.v2_local),
            slug="IntegrationTestsV2Local",
            start_message="Running integration tests via V2 local strategy.",
            die_message="Integration test failure (V2 local)",
        )

def run_plugin_tests(*, oauth_token_path: Optional[str] = None) -> None:
    _run_command(
        TestStrategy.v2_remote.pants_command(
            targets={"pants-plugins/src/python::", "pants-plugins/tests/python::"},
            oauth_token_path=oauth_token_path,
        ),
        slug="BackendTests",
        start_message="Running internal backend Python tests",
        die_message="Internal backend Python test failure.",
    )

def run_platform_specific_tests() -> None:
    command = TestStrategy.v1_no_chroot.pants_command(targets=["src/python/::", "tests/python::"])
    command.insert(1, "--tag=+platform_specific_behavior")
    _run_command(
        command,
        slug="PlatformSpecificTests",
        start_message=f"Running platform-specific tests on platform {platform.system()}",
        die_message="Pants platform-specific test failure.",
    )

if __name__ == "__main__":
    main()


text:
package org.sagebionetworks.evaluation.dao;

import static org.sagebionetworks.repo.model.query.SQLConstants.COL_SUBMISSION_EVAL_ID;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_SUBMISSION_ID;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_SUBSTATUS_ETAG;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_SUBSTATUS_SUBMISSION_ID;
import static org.sagebionetworks.repo.model.query.SQLConstants.COL_SUBSTATUS_VERSION;
import static org.sagebionetworks.repo.model.query.SQLConstants.TABLE_SUBMISSION;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.sagebionetworks.evaluation.dbo.DBOConstants;
import org.sagebionetworks.evaluation.dbo.SubmissionStatusDBO;
import org.sagebionetworks.evaluation.model.SubmissionStatus;
import org.sagebionetworks.repo.model.ConflictingUpdateException;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.InvalidModelException;
import org.sagebionetworks.repo.model.dbo.DBOBasicDao;
import org.sagebionetworks.repo.model.query.SQLConstants;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class SubmissionStatusDAOImpl implements SubmissionStatusDAO {

	@Autowired
	private DBOBasicDao basicDao;

	@Autowired
	private NamedParameterJdbcTemplate namedJdbcTemplate;

	private static final String ID = DBOConstants.PARAM_SUBMISSION_ID;

	private static final String SQL_ETAG_FOR_UPDATE_BATCH = "SELECT " +
			COL_SUBSTATUS_SUBMISSION_ID + " , "+ COL_SUBSTATUS_ETAG +", "+
			COL_SUBSTATUS_VERSION + " FROM " +
			SQLConstants.TABLE_SUBSTATUS +" WHERE "+
			COL_SUBSTATUS_SUBMISSION_ID+" IN (:"+COL_SUBSTATUS_SUBMISSION_ID+")" + " FOR UPDATE";

	// SELECT s.EVALUATION_ID FROM EVALUATION_SUBMISSION s WHERE s.ID IN (:ID)
	private static final String SELECT_EVALUATION_FOR_IDS =
			"SELECT DISTINCT s."+COL_SUBMISSION_EVAL_ID+" FROM "+TABLE_SUBMISSION+
			" s WHERE s."+COL_SUBMISSION_ID+" IN (:"+COL_SUBMISSION_ID+")";

	@Override
	@WriteTransaction
	public String create(SubmissionStatus dto) throws DatastoreException {
		// Convert to DBO
		dto.setStatusVersion(DBOConstants.SUBSTATUS_INITIAL_VERSION_NUMBER);
		SubmissionStatusDBO dbo = SubmissionUtils.convertDtoToDbo(dto);

		// Generate a new eTag
		dbo.seteTag(UUID.randomUUID().toString());

		// Ensure DBO has required information
		verifySubmissionStatusDBO(dbo);

		// Create DBO
		try {
			dbo = basicDao.createNew(dbo);
			return dbo.getId().toString();
		} catch (Exception e) {
			throw new DatastoreException(e.getMessage() + " id=" + dbo.getId(), e);
		}
	}

	@Override
	public SubmissionStatus get(String id) throws DatastoreException, NotFoundException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(ID, id);
		SubmissionStatusDBO dbo = basicDao.getObjectByPrimaryKey(SubmissionStatusDBO.class, param)
				.orElseThrow(() -> new NotFoundException(String.format("Submission status: '%s' does not exist", id)));
		return SubmissionUtils.convertDboToDto(dbo);
	}

	@Override
	@WriteTransaction
	public void update(List<SubmissionStatus> batch)
			throws DatastoreException, InvalidModelException,
			NotFoundException, ConflictingUpdateException {
		Map<String,String> idToEtagMap = new HashMap<String,String>();
		List<SubmissionStatusDBO> dbos = new ArrayList<SubmissionStatusDBO>();
		for (SubmissionStatus dto : batch) {
			SubmissionStatusDBO dbo = SubmissionUtils.convertDtoToDbo(dto);
			dbo.setModifiedOn(System.currentTimeMillis());
			verifySubmissionStatusDBO(dbo);
			dbos.add(dbo);
			if (null!=idToEtagMap.put(dbo.getId().toString(), dbo.geteTag())) {
				throw new InvalidModelException(""+dbo.getId()+" occurs more than once in the SubmissonStatus batch.");
			}
		}

		// update eTag and increment the version
		Map<Long, Long> versionMap = lockForUpdateAndGetVersion(idToEtagMap);
		for (SubmissionStatusDBO dbo : dbos) {
			Long currentVersion = versionMap.get(dbo.getId());
			dbo.seteTag(UUID.randomUUID().toString());
			dbo.setVersion(currentVersion+1);
			// we also need to update the serialized field
			SubmissionStatus dto = SubmissionUtils.convertDboToDto(dbo);
			SubmissionUtils.copyToSerializedField(dto, dbo);
		}

		basicDao.createOrUpdateBatch(dbos);
	}

	@Override
	@WriteTransaction
	public void delete(String id) throws DatastoreException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(ID, id);
		basicDao.deleteObjectByPrimaryKey(SubmissionStatusDBO.class, param);
	}

	/**
	 * Ensure that a SubmissionStatusDBO object has all required components
	 *
	 * @param dbo
	 */
	private void verifySubmissionStatusDBO(SubmissionStatusDBO dbo) {
		ValidateArgument.required(dbo.getId(), "Submission ID");
		ValidateArgument.required(dbo.geteTag(), "eTag");
		ValidateArgument.required(dbo.getModifiedOn(), "Modified date");
		ValidateArgument.required(dbo.getStatusEnum(), "Submission status");
		ValidateArgument.required(dbo.getVersion(), "Status version");
	}

	// returns a map whose key is submission Id and whose value is new Etag and new version
	private Map<Long,Long> lockForUpdateAndGetVersion(Map<String,String> idToEtagMap)
			throws NotFoundException, ConflictingUpdateException, DatastoreException {
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(COL_SUBSTATUS_SUBMISSION_ID, idToEtagMap.keySet());
		List<IdETagVersion> current = namedJdbcTemplate.query(SQL_ETAG_FOR_UPDATE_BATCH, param, new RowMapper<IdETagVersion>() {
			@Override
			public IdETagVersion mapRow(ResultSet rs, int rowNum) throws SQLException {
				return new IdETagVersion(
						rs.getLong(COL_SUBSTATUS_SUBMISSION_ID),
						rs.getString(COL_SUBSTATUS_ETAG),
						rs.getLong(COL_SUBSTATUS_VERSION));
			}
		});
		// Check the eTags
		Map<Long,Long> result = new HashMap<Long,Long>();
		for (IdETagVersion ev : current) {
			String id = ev.getId().toString();
			String etagFromClient = idToEtagMap.get(id);
			String currentEtag = ev.getEtag();
			if(!currentEtag.equals(etagFromClient)) {
				throw new ConflictingUpdateException("Submission Status: "+id+" was updated since you last fetched it, retrieve it again and reapply the update");
			}
			result.put(ev.getId(), ev.getVersion());
		}

		return result;
	}

	@Override
	public long getCount() throws DatastoreException {
		return basicDao.getCount(SubmissionStatusDBO.class);
	}

	@Override
	public Long getEvaluationIdForBatch(List<SubmissionStatus> batch)
			throws DatastoreException, InvalidModelException,
			NotFoundException, ConflictingUpdateException {
		Set<String> ids = new HashSet<String>();
		for (SubmissionStatus s : batch) {
			if (s.getId()!=null) ids.add(s.getId());
		}
		if (ids.isEmpty()) throw new IllegalArgumentException("SubmissionStatus batch has no Submission Ids.");
		MapSqlParameterSource param = new MapSqlParameterSource();
		param.addValue(COL_SUBMISSION_ID, ids);
		try {
			return namedJdbcTemplate.queryForObject(SELECT_EVALUATION_FOR_IDS, param, Long.class);
		} catch (EmptyResultDataAccessException erda) {
			throw new NotFoundException("Submissions are not found in the system.");
		} catch (IncorrectResultSizeDataAccessException irsdae) {
			throw new IllegalArgumentException("Submission batch must be for a single Evaluation queue.", irsdae);

		}
	}
}


text:
import {
  ControlType,
  DynamicFormService,
  FormBuilder,
  FormBuilderSubset,
} from '@angular-dynaform/core';
import { Component } from '@angular/core';
import { FormTestBaseComponent } from './form-test-base.component';

const TITLE = 'Test Slider';
const FORM_ID = 'test-slider';
const TEST_CONTROL_ID = 'test-slider-control';
const TEST_CONTROL_LABEL = 'slider';
const TEST_CONTROL_PLACEHOLDER = 'placeholder';

@Component({
  selector: 'adf-form-test-slider',
  moduleId: module.id,
  templateUrl: './form-test-base.component.html',
})
export class FormTestSliderComponent extends FormTestBaseComponent {
  constructor(dynamicFormService: DynamicFormService, formBuilder: FormBuilder) {
    super(dynamicFormService, formBuilder, TITLE, { id: FORM_ID, updateOn: 'change' });
  }

  addControl(fieldsdiv: FormBuilderSubset): void {
    fieldsdiv.group.addControl({
      id: TEST_CONTROL_ID,
      controlType: ControlType.CONTROL_SLIDER,
      options: {
        label: TEST_CONTROL_LABEL,
        placeholder: TEST_CONTROL_PLACEHOLDER,
        min: 0,
        max: 100,
        step: 2,
      },
    });
  }
}


text:
typedef unsigned char byte;

struct nulltype { };
#ifdef __CUDACC__
EAVL_HOSTDEVICE const nulltype cnull() { return nulltype(); }
#else
inline const nulltype cnull() { return nulltype(); }
#endif

#define MAX_LOCAL_TOPOLOGY_IDS 12

#endif


text:
package cc.redpen.util;

import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StringUtilsTest {
    @Test
    public void tesIsKatakanaWithHiraganaA() {
        assertFalse(StringUtils.isKatakana('あ'));
    }

    @Test
    public void tesIsKatakanaWithKatakanaA() {
        assertTrue(StringUtils.isKatakana('ア'));
    }

    @Test
    public void tesIsKatakanaWithHyphen() {
        assertTrue(StringUtils.isKatakana('ー'));
    }

    @Test
    public void tesIsKatakanaWithKatakanaMiddleDot() {
        assertTrue(StringUtils.isKatakana('・'));
    }

    @Test
    public void tesIsBasicLatinWithHiraganaA() {
        assertFalse(StringUtils.isBasicLatin('あ'));
    }

    @Test
    public void tesIsBasicLatinWithKatakanaA() {
        assertFalse(StringUtils.isBasicLatin('ア'));
    }

    @Test
    public void tesIsBasicLatinWithHyphen() {
        assertTrue(StringUtils.isBasicLatin('-'));
    }

    @Test
    public void tesIsBasicLatinWithPeriod() {
        assertTrue(StringUtils.isBasicLatin('.'));
    }

    @Test
    public void tesIsBasicLatinWithKatakanaMiddleDot() {
        assertFalse(StringUtils.isBasicLatin('・'));
    }

}


text:
package main

import (
	"fmt"
	"go_dev/day11/project/logagent/server/etcd"
	"go_dev/day11/project/logagent/server/kafka"
	"go_dev/day11/project/logagent/server/tailf"

	"github.com/astaxie/beego/logs"
)

func initConfig() (err error) {
	configPath := "H:/360_update/oldboy_go/src/go_dev/day11/project/logagent/conf/logagent.conf"
	err = loadConf("ini", configPath)
	if err != nil {
		fmt.Println("load config failed, err:", err)
		panic("load config failed")
		return
	}
	return
}

func initRun() {
	err := etcd.InitEtcd(appConf.etcdAddr, appConf.etcdKey)
	if err != nil {
		logs.Warn("Init tailf err, err:%v", err)
		return
	}

	err = tailf.InitTailf(appConf.chanSize)
	if err != nil {
		logs.Warn("Init tailf err, err:%v", err)
		return
	}
	kafka.ServerRun(appConf.kafka_addr)

}

func main() {
	err := initConfig()
	if err != nil {
		fmt.Println("config read failed, err:", err)
		return
	}
	initRun()
	logs.Debug("initialize all success")
}


text:
#include "core/svg/graphics/SVGImageForContainer.h"

#include "platform/geometry/FloatRect.h"
#include "platform/geometry/FloatSize.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkImage.h"
#include "wtf/PassRefPtr.h"

namespace blink {

IntSize SVGImageForContainer::size() const {
  FloatSize scaledContainerSize(m_containerSize);
  scaledContainerSize.scale(m_zoom);
  return roundedIntSize(scaledContainerSize);
}

void SVGImageForContainer::draw(SkCanvas* canvas,
                                const SkPaint& paint,
                                const FloatRect& dstRect,
                                const FloatRect& srcRect,
                                RespectImageOrientationEnum,
                                ImageClampingMode,
                                const ColorBehavior& colorBehavior) {
  // TODO(ccameron): This function should not ignore |colorBehavior|.
  // https://crbug.com/667431
  m_image->drawForContainer(canvas, paint, m_containerSize, m_zoom, dstRect,
                            srcRect, m_url);
}

void SVGImageForContainer::drawPattern(GraphicsContext& context,
                                       const FloatRect& srcRect,
                                       const FloatSize& scale,
                                       const FloatPoint& phase,
                                       SkBlendMode op,
                                       const FloatRect& dstRect,
                                       const FloatSize& repeatSpacing) {
  // TODO(ccameron): This function should not ignore |context|'s color behavior.
  // https://crbug.com/667431
  m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect,
                                   scale, phase, op, dstRect, repeatSpacing,
                                   m_url);
}

sk_sp<SkImage> SVGImageForContainer::imageForCurrentFrame(
    const ColorBehavior& colorBehavior) {
  // TODO(ccameron): This function should not ignore |colorBehavior|.
  // https://crbug.com/667431
  return m_image->imageForCurrentFrameForContainer(m_url, size());
}

}  // namespace blink


text:
/// \file       ParamGeneration.h
///
/// \brief      Parameter generation routines for Zerocoin.
///
/// \author     Ian Miers, Christina Garman and Matthew Green
/// \date       June 2013
///
/// \copyright  Copyright 2013 Ian Miers, Christina Garman and Matthew Green
/// \license    This project is released under the MIT license.

#ifndef PARAMGENERATION_H_
#define PARAMGENERATION_H_

namespace libzerocoin {

void CalculateParams(Params &params, Bignum N, std::string aux, uint32_t securityLevel);
void calculateGroupParamLengths(uint32_t maxPLen, uint32_t securityLevel,
                            uint32_t *pLen, uint32_t *qLen);

// Constants
#define STRING_COMMIT_GROUP         "COIN_COMMITMENT_GROUP"
#define STRING_AVC_GROUP            "ACCUMULATED_VALUE_COMMITMENT_GROUP"
#define STRING_AVC_ORDER            "ACCUMULATED_VALUE_COMMITMENT_ORDER"
#define STRING_AIC_GROUP            "ACCUMULATOR_INTERNAL_COMMITMENT_GROUP"
#define STRING_QRNCOMMIT_GROUPG     "ACCUMULATOR_QRN_COMMITMENT_GROUPG"
#define STRING_QRNCOMMIT_GROUPH     "ACCUMULATOR_QRN_COMMITMENT_GROUPH"
#define ACCUMULATOR_BASE_CONSTANT   31
#define MAX_PRIMEGEN_ATTEMPTS       10000
#define MAX_ACCUMGEN_ATTEMPTS       10000
#define MAX_GENERATOR_ATTEMPTS      10000
#define NUM_SCHNORRGEN_ATTEMPTS     10000

// Prototypes
bool                primalityTestByTrialDivision(uint32_t candidate);
uint256             calculateSeed(Bignum modulus, std::string auxString, uint32_t securityLevel, std::string groupName);
uint256             calculateGeneratorSeed(uint256 seed, uint256 pSeed, uint256 qSeed, std::string label, uint32_t index, uint32_t count);

uint256             calculateHash(uint256 input);
IntegerGroupParams  deriveIntegerGroupParams(uint256 seed, uint32_t pLen, uint32_t qLen);
IntegerGroupParams  deriveIntegerGroupFromOrder(Bignum &groupOrder);
void                calculateGroupModulusAndOrder(uint256 seed, uint32_t pLen, uint32_t qLen,
                                                  Bignum *resultModulus, Bignum *resultGroupOrder,
                                                  uint256 *resultPseed, uint256 *resultQseed);
Bignum              calculateGroupGenerator(uint256 seed, uint256 pSeed, uint256 qSeed, Bignum modulus,
                                            Bignum groupOrder, uint32_t index);
Bignum              generateRandomPrime(uint32_t primeBitLen, uint256 in_seed, uint256 *out_seed,
                                        uint32_t *prime_gen_counter);
Bignum              generateIntegerFromSeed(uint32_t numBits, uint256 seed, uint32_t *numIterations);
bool                primalityTestByTrialDivision(uint32_t candidate);

}/* namespace libzerocoin */

#endif /* PARAMGENERATION_H_ */


text:
require 'tempfile'

def tidy(html)
  input = Tempfile.new('tidy_xhtml_converstion')
  input.write(html)
  input.close

  `tidy -asxhtml #{input.path} 2>&1`

  unless $?.exitstatus == 2
    html = IO.read(input.path)
  else
    html = nil
  end

  input.delete
  html
end


text:
<?php

include (__DIR__).'/../vendor/autoload.php';

class SteemMarketTest extends PHPUnit_Framework_TestCase
{
	protected function setUp()
	{
		$this->SteemMarket = new \SteemPHP\SteemMarket('https://steemd.steemit.com');
	}

	public function testGetApi()
	{
		$this->assertInternalType('int', $this->SteemMarket->getApi('login_api'));
	}

	public function testGetOrderBook()
	{
		$order = $this->SteemMarket->getOrderBook(5);
		$this->assertArrayHasKey('asks', $order);
		$this->assertArrayHasKey('bids', $order);
	}

	public function testGetOpenOrders()
	{
		$this->assertInternalType('array', $this->SteemMarket->getOpenOrders('david'));
	}

	public function testGetLiquidityQueue()
	{
		$this->assertInternalType('array', $this->SteemMarket->getLiquidityQueue('davidk', 5));
	}

	public function testGetOwnerHistory()
	{
		$this->assertInternalType('array', $this->SteemMarket->getOwnerHistory('davidk'));
	}

	public function testGetTicker()
	{
		$this->assertArrayHasKey('latest', $this->SteemMarket->getTicker());
	}

	public function testGetMarketHistory()
	{
		$this->assertInternalType('array', $this->SteemMarket->getMarketHistory('2017/7/11', '2017/8/11', 60));
	}

	public function testGetMarketHistoryBuckets()
	{
		$this->assertEquals('15', $this->SteemMarket->getMarketHistoryBuckets()[0]);
	}

	public function testGetOrderBookFromMarket()
	{
		$order = $this->SteemMarket->getOrderBookFromMarket();
		$this->assertArrayHasKey('asks', $order);
		$this->assertArrayHasKey('bids', $order);
	}

	public function testGetRecentTrades()
	{
		$this->assertArrayHasKey('date', $this->SteemMarket->getRecentTrades(5)[0]);
	}

	public function testGetTradeHistory()
	{
		$this->assertArrayHasKey('date', $this->SteemMarket->getTradeHistory('2017/8/10', '2017/8/11', 5)[0]);
	}

	public function testGetVolume()
	{
		$this->assertArrayHasKey('steem_volume', $this->SteemMarket->getVolume());
	}

}

?>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

using JetBrains.Annotations;
using JetBrains.DocumentManagers;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.ReSharper.Psi.Xml.Impl.Tree;
using JetBrains.ReSharper.Psi.Xml.Tree;

using Newtonsoft.Json.Linq;

using Resharper.ConfigurationSense.Constants;
using Resharper.ConfigurationSense.Models;

namespace Resharper.ConfigurationSense.Extensions
{
    public static class ProjectExtensions
    {
        public static IEnumerable<KeyValueSetting> GetJsonProjectSettings(
            this IProject project,
            JsonSettingType settingType,
            string searchPath = null)
        {
            var configFiles = GetNetCoreJsonConfigFiles(project);

            var settings = new Dictionary<string, HashSet<string>>();
            foreach (var projectFile in configFiles)
            {
                var json = ParseJsonProjectFile(projectFile);

                var properties = new Queue<JProperty>();
                properties.EnqueueRange(json.Properties());

                var secretsJson = ReadSecretsSafe(project);
                if (secretsJson != null)
                {
                    properties.EnqueueRange(secretsJson.Properties());
                }

                while (properties.Count > 0)
                {
                    var property = properties.Dequeue();
                    if (!property.HasValues || string.IsNullOrEmpty(property.Path))
                    {
                        continue;
                    }

                    string formattedPath = null;

                    if (property.Value.Type == JTokenType.Object)
                    {
                        foreach (var nestedProperty in ((JObject)property.Value).Properties())
                        {
                            properties.Enqueue(nestedProperty);
                        }
                    }

                    if ((property.Value.Type != JTokenType.Object && property.Value.Type != JTokenType.Array
                             && settingType == JsonSettingType.Value) || settingType == JsonSettingType.All)
                    {
                        formattedPath = property.GetSettingsPath();
                    }

                    if (string.IsNullOrEmpty(formattedPath))
                    {
                        continue;
                    }

                    if (!string.IsNullOrEmpty(searchPath))
                    {
                        if (formattedPath.StartsWith(searchPath, StringComparison.OrdinalIgnoreCase))
                        {
                            formattedPath = formattedPath.Replace(searchPath, string.Empty);
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (!settings.TryGetValue(formattedPath, out var settingValues))
                    {
                        settingValues = new HashSet<string>();
                        settings.Add(formattedPath, settingValues);
                    }

                    settingValues.Add(property.Value.ToString());
                }
            }

            return settings.Select(x => new KeyValueSetting(x.Key, string.Join(", ", x.Value)));
        }

        public static IEnumerable<KeyValueSetting> GetXmlProjectSettings(
            this IProjectFolder project,
            string settingsTagName,
            string settingsKeyAttribute,
            string settingsValueAttributes)
        {
            var result = new Dictionary<string, HashSet<string>>();

            var configFiles = GetXmlConfigFiles(project);

            foreach (var configFile in configFiles)
            {
                var settingsTags = new Queue<IXmlTag>(GetSettingTags(settingsTagName, configFile));
                while (settingsTags.Count > 0)
                {
                    var settingTag = settingsTags.Dequeue();

                    var configName = settingTag.GetExternalConfigName();
                    if (!string.IsNullOrEmpty(configName))
                    {
                        var projectItems =
                            project.FindProjectItemsByLocation(configFile.Location.Directory.Combine(configName));
                        foreach (var projectItem in projectItems)
                        {
                            var projectFile = projectItem as IProjectFile;
                            var externalSettingsTags = GetSettingTags(settingsTagName, projectFile);
                            foreach (var settingsTag in externalSettingsTags)
                            {
                                settingsTags.Enqueue(settingsTag);
                            }
                        }

                        continue;
                    }

                    var settings = settingTag.GetChildSettings(settingsKeyAttribute, settingsValueAttributes);
                    foreach (var setting in settings)
                    {
                        if (!result.TryGetValue(setting.Key, out var settingValues))
                        {
                            settingValues = new HashSet<string>();
                            result.Add(setting.Key, settingValues);
                        }

                        settingValues.Add(setting.Value);
                    }
                }
            }

            return result.Select(x => new KeyValueSetting(x.Key, string.Join(", ", x.Value)));
        }

        private static IEnumerable<IXmlTag> GetSettingTags(string settingsTagName, IProjectFile configFile)
        {
            var xmlFile = configFile.GetPrimaryPsiFile() as XmlFile;
            if (xmlFile == null)
            {
                return new List<IXmlTag>();
            }

            var collection = xmlFile.FindAllByTagName(settingsTagName);
            return collection;
        }

        private static IEnumerable<IProjectFile> GetXmlConfigFiles(IProjectFolder project)
        {
            var additionalConfigurationFiles = project.GetSolution().GetAdditionalConfigurationFiles();

            var xmlConfigFiles = new HashSet<IProjectFile>(
                project.GetAllProjectFiles(
                    file => file.LanguageType.Is<XmlProjectFileType>()
                            && (file.Name.Equals(FileNames.WebConfig, StringComparison.OrdinalIgnoreCase)
                                || file.Name.Equals(FileNames.AppConfig, StringComparison.OrdinalIgnoreCase)
                                || additionalConfigurationFiles.Contains(file.GetPersistentID()))));

            UnionWithDependentFiles(xmlConfigFiles);

            return xmlConfigFiles;
        }

        private static IEnumerable<IProjectFile> GetNetCoreJsonConfigFiles(IProjectFolder project)
        {
            var additionalConfigurationFiles = project.GetSolution().GetAdditionalConfigurationFiles();

            var netCoreJsonConfigFiles = new HashSet<IProjectFile>(
                project.GetAllProjectFiles(
                    file => file.LanguageType.Is<JsonProjectFileType>()
                            && (file.Name.Equals(FileNames.NetCoreAppSettingsJson, StringComparison.OrdinalIgnoreCase)
                                || additionalConfigurationFiles.Contains(file.GetPersistentID()))));

            UnionWithDependentFiles(netCoreJsonConfigFiles);

            return netCoreJsonConfigFiles;
        }

        private static JObject ParseJsonProjectFile(IProjectFile projectFile)
        {
            var primaryPsiFile = projectFile.GetPrimaryPsiFile();

            string text;

            // Starting from 2019.1 JSON (and also js/ts/css) files are only processed by WebStorm (frontend) engine in Rider,
            // so there is no PSI for them in Rider backend for performance reasons.
            if (primaryPsiFile == null)
            {
                var component = projectFile.GetSolution().GetPsiServices().GetComponent<DocumentsOnProjectFiles>();
                text = component.GetOrCreateDocument(projectFile).GetText();
            }
            else
            {
                text = primaryPsiFile.GetUnquotedText();
            }

            return JObject.Parse(text);
        }

        private static string GetUserSecretId(this IProject project)
        {
            var xmlFile = project.ProjectFile?.GetPrimaryPsiFile() as IXmlFile;
            var enumerable = xmlFile?.FindAllByTagName("UserSecretsId");
            if (enumerable != null)
            {
                foreach (var xmlTag in enumerable)
                {
                    if (!string.IsNullOrEmpty(xmlTag.InnerValue))
                    {
                        return xmlTag.InnerValue;
                    }
                }
            }

            var projectFiles =
                project.GetAllProjectFiles(
                    file => file.Name.Equals(FileNames.NetCoreProjectJson, StringComparison.OrdinalIgnoreCase));
            foreach (var file in projectFiles)
            {
                var jsonProjectFile = ParseJsonProjectFile(file);

                var jsonToken = jsonProjectFile[SettingsConstants.NetCoreUserSecretsIdJsonProperty];

                if (jsonToken != null && jsonToken.Type == JTokenType.String)
                {
                    return jsonToken.Value<string>();
                }
            }

            return null;
        }

        [CanBeNull]
        private static JObject ReadSecretsSafe(IProject project)
        {
            try
            {
                var userSecretId = project.GetUserSecretId();

                var filePath = string.Format(
                    FileNames.UserSecretsPathFormat,
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    userSecretId);

                var secretsFile = File.ReadAllText(filePath);

                return JObject.Parse(secretsFile);
            }
            // ReSharper disable once EmptyGeneralCatchClause
            // ReSharper disable once CatchAllClause
            catch (Exception)
            {
                // Just swallow the exception
            }

            return null;
        }

        private static void UnionWithDependentFiles(HashSet<IProjectFile> projectFiles)
        {
            projectFiles.UnionWith(projectFiles.SelectMany(p => p.GetDependentFiles()).ToArray());
        }
    }
}


text:
package com.badlogic.gdx.backends.jogamp;

import java.awt.Canvas;
import java.awt.Cursor;

import com.badlogic.gdx.ApplicationListener;
import com.jogamp.newt.awt.NewtCanvasAWT;

/**
 * An OpenGL surface on a NEWT canvas linked to an AWT peer, allowing OpenGL to
 * be embedded in a Swing application
 *
 * @author Julien Gouesse
 *
 */
public class JoglNewtAwtCanvas extends JoglNewtApplication {

	private NewtCanvasAWT canvas;

	public JoglNewtAwtCanvas(final ApplicationListener listener, final String title, final int width, final int height) {
		this(listener, title, width, height, null);
	}

	public JoglNewtAwtCanvas(final ApplicationListener listener, final String title, final int width, final int height,
			JoglNewtAwtCanvas shared) {
		super(listener, title, width, height);
		// FIXME it is too early to get the canvas. It was working with JOGL 1 but
		// the context is available later with JOGL 2
		/*
		 * if (shared != null && shared.getGLCanvas().getContext() != null) {
		 * getGLCanvas().setSharedContext(shared.getGLCanvas().getContext()); }
		 */
		canvas = new NewtCanvasAWT(getGLCanvas());
	}

	@Override
	protected JoglNewtGraphics createGraphics(ApplicationListener listener, JoglApplicationConfiguration config) {
		return new JoglNewtGraphics(listener, (JoglNewtApplicationConfiguration) config) {

			@Override
			public void setTitle(String title) {
				super.setTitle(title);
				JoglNewtAwtCanvas.this.setTitle(title);
			}

			@Override
			public boolean setWindowedMode(int width, int height) {
				if (!super.setWindowedMode(width, height)) return false;
				return true;
			}

			@Override
			public boolean setFullscreenMode(DisplayMode displayMode) {
				if (!super.setFullscreenMode(displayMode))
					return false;
				JoglNewtAwtCanvas.this.setDisplayMode(displayMode.width, displayMode.height);
				return true;
			}
		};
	}

	protected void setDisplayMode(int width, int height) {
	}

	protected void setTitle(String title) {
	}

	public void setCursor(Cursor cursor) {
		canvas.setCursor(cursor);
	}

	public Canvas getCanvas() {
		return (canvas);
	}
}


text:
_released at 2022-02-22 07:52:27 UTC_

- Add support for Ruby 3.1, Rails 7.0 and JRuby 9.3.3.0

## [v2.0.0](https://github.com/yuki24/rambulance/tree/v2.0.0)

_released at 2021-09-22 02:49:18 UTC_

#### Breaking Changes

- Drop support for Rails 4.1 and older ([#62](https://github.com/yuki24/rambulance/pull/62), [@yuki24](https://github.com/yuki24))

#### Features

- Add support for Rails 6.1 and Ruby 3.0 ([#61](https://github.com/yuki24/rambulance/pull/61), [#63](https://github.com/yuki24/rambulance/pull/63), [@gingerlime](https://github.com/gingerlime), [@yuki24](https://github.com/yuki24))

#### Bug fixes

- POST with invalid JSON triggers a 500 ([#59](https://github.com/yuki24/rambulance/pull/59), [@gingerlime](https://github.com/gingerlime))
- Fix 'directry' typo ([#57](https://github.com/yuki24/rambulance/pull/57), [@andyw8](https://github.com/andyw8))

## [v1.1.1](https://github.com/yuki24/rambulance/tree/v1.1.1)

_released at 2020-05-28 23:22:10 UTC_

#### Bug fixes

- Fixes a bug where a malformed `Content-Type` header could break the exceptions app ([#55](https://github.com/yuki24/rambulance/pull/55), [@gingerlime](https://github.com/gingerlime))

## [v1.1.0](https://github.com/yuki24/rambulance/tree/v1.1.0)

_released at 2020-05-23 02:52:27 UTC_

#### Features

- Add support for Ruby 2.7 ([<tt>718531c</tt>](https://github.com/yuki24/rambulance/commit/718531c45b61d01dce91f401fd81dd6aefdefb31))

#### Bug fixes

- Fixes a bug where malformed MIME type in HTTP headers could break the exceptions app ([#53](https://github.com/yuki24/rambulance/issues/53), [#54](https://github.com/yuki24/rambulance/pull/54), [@gingerlime](https://github.com/gingerlime))

## [v1.0.3](https://github.com/yuki24/rambulance/tree/v1.0.3)

_released at 2019-10-03 03:39:17 UTC_

#### Fixes

- Fixes a bug where custom exceptions app can not be loaded properly on Rails 6 and Zeitwerk ([#52](https://github.com/yuki24/rambulance/issues/52), [@sho918](https://github.com/sho918))

## [v1.0.2](https://github.com/yuki24/rambulance/tree/v1.0.2)

_released at 2019-06-06 23:39:38 UTC_

#### Fixes

- Fixes a bug where `ExceptionsApp` is not loaded when action controller is not loaded ([<tt>ec9d9e5</tt>](https://github.com/yuki24/rambulance/commit/ec9d9e5de98eeec501042a0bbb95ae8ac8d7b4e3))

## [v1.0.1](https://github.com/yuki24/rambulance/tree/v1.0.1)

_released at 2019-06-04 16:30:38 UTC_

#### Fixes

- Fixes an issue where `ExceptionsApp` prevents Rails from booting up ([#49](https://github.com/yuki24/rambulance/issues/49))

## [v1.0.0](https://github.com/yuki24/rambulance/tree/v1.0.0)

_released at 2019-06-03 05:01:14 UTC_

#### Features

- Add support for Ruby 2.6
- Add support for Rails 6.0

#### Bug fixes

- Fixes a bug where POST requests cause the exceptions app to throw an `ActionController::InvalidAuthenticityToken` error on Rails 5.2 ([<tt>d68d677</tt>](https://github.com/yuki24/rambulance/commit/d68d677de75059fa09f70e37c97f4bae95885c53), [#48](https://github.com/yuki24/rambulance/issues/48), [@adrianhuna](https://github.com/adrianhuna))

#### Breaking Changes

- Drop support for Ruby \<= 2.2
- Drop support for Rails \<= 4.1

## [v0.6.0](https://github.com/yuki24/rambulance/tree/v0.6.0)

_released at 2018-03-08 18:36:16 UTC_

#### New features

- Add support for Rails 5.2
- Add a test helper method `#with_exceptions_app` for easier testing ([<tt>f5c16b9</tt>](https://github.com/yuki24/rambulance/commit/f5c16b90ecf5eb4903faa30d760bf5863441e9c5), [#27](https://github.com/yuki24/rambulance/pull/27), [@kbaba1001](https://github.com/kbaba1001))

#### Bug fixes

- Fixed a bug where an `ActionController::UnknownFormat` error could cause a number of issues ([<tt>1b824e6</tt>](https://github.com/yuki24/rambulance/commit/1b824e6c170479ed90e24df1680dd2dec7c98160), [#41](https://github.com/yuki24/rambulance/issues/41), [#42](https://github.com/yuki24/rambulance/pull/42), [@willnet](https://github.com/willnet), [@joker-777](https://github.com/joker-777))
- Fixed a bug where the methods on the `ExceptionApp` weren't easily inspectable ([<tt>6b4c834</tt>](https://github.com/yuki24/rambulance/commit/6b4c834bb0b8e81f619d9f598310ce68f4f9c66b))

## [v0.5.0](https://github.com/yuki24/rambulance/tree/v0.5.0)

_released at 2018-01-02 21:36:02 UTC_

#### New features

- Add support for Ruby 2.5.0
- Add support for Rails 5.1

#### Breaking changes & deprecations

- Drop support for Ruby 1.9.3
- Drop support for Haml and Slim templates

#### Bug fixes

- Fixes a bug where the exceptions app fails to show an error page properly when a malformed body is posted ([<tt>474b6b3</tt>](https://github.com/yuki24/rambulance/commit/474b6b329e5590db3c0a7e33c795b18c00812729), [#40](https://github.com/yuki24/rambulance/issues/40), [@jasim](https://github.com/jasim))

## [v0.4.0](https://github.com/yuki24/rambulance/tree/v0.4.0)

_released at 2016-10-12 02:25:55 UTC_

- Added support for Rails 5 and edge
- Added the ability to use helper methods in error templates([@willnet](https://github.com/willnet), [#37](https://github.com/yuki24/rambulance/pull/37))

## [v0.3.1](https://github.com/yuki24/rambulance/tree/v0.3.1)

_released at 2015-05-18 01:53:59 UTC_

- Added slim support ([@liubin](https://github.com/liubin), [#20](https://github.com/yuki24/rambulance/pull/20))
- `rails g rambulance:install` no longer generates jbuilder templates if it's undefined
- The exceptions app no longer attempts to render layouts when the request format is json
- Now `rails g rambulance:install` always copies `application.html.erb` to `error.html.erb` again
- **incompatible change** : `error_layout` option for the install command has been removed in favor of the change above

## [v0.3.0](https://github.com/yuki24/rambulance/tree/v0.3.0)

_released at 2015-01-23 13:42:35 UTC_

- Added 2 helper methods `#exception` and `#status_in_words` that you can use in views

## [v0.2.0](https://github.com/yuki24/rambulance/tree/v0.2.0)

_released at 2014-09-18 03:38:18 UTC_

- Add support for Rails 4.2 beta
- Do not copy application.html.erb when `rails g rambulance:install` [[@kenn](https://github.com/kenn), [#5](https://github.com/yuki24/rambulance/issues/5)]
- Capture `ActionController::BadRequest` before processing action
- Dynamically generate exception/status mapping in initializer
- Add option to copy `application.html.erb` for error page layout

## [v0.1.2](https://github.com/yuki24/rambulance/tree/v0.1.2)

_released at 2014-09-05 12:22:37 UTC_

- Fixed a bug where changing config.layout\_name doesn't actually switch layout [[@kenn](https://github.com/kenn), [#4](https://github.com/yuki24/rambulance/issues/4)]
- Exceptions app now refers to `app/views/#{config.view_path}` by default

## [v0.1.1](https://github.com/yuki24/rambulance/tree/v0.1.1)

_released at 2014-06-22 02:39:06 UTC_

- Fixed a bug where installer command doesn't work

## [v0.1.0](https://github.com/yuki24/rambulance/tree/v0.1.0)

_released at 2014-06-20 01:00:02 UTC_

- First release of rambulance!


text:
set -x #echo on

# These are more or less the compiler and linker flags used by Python's distutils.core.setup()

CC_FLAGS="-pthread -g -fwrapv -O2 -Wall -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2"
LD_FLAGS="-shared -fPIC -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-O1"

gcc $CC_FLAGS mypy.c -ldl -o mypy
gcc $CC_FLAGS mypydl.c -I/usr/include/python3.4m -lpython3.4m $LD_FLAGS -o mypydl.so

python3 setup.py install --user


text:
define(function(require, exports, module) {
    'use strict';
    module.exports = {
        root: true,
        pt: true,
        es: true
    };
});


text:
class AddInteractionsTable < ActiveRecord::Migration
  def change
    create_table :interactions do |t|
      t.belongs_to :user
      t.integer :hn_item, index: true
    end
  end
end


text:
package wallettemplate;

import org.bitcoinj.core.listeners.DownloadProgressTracker;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.MonetaryFormat;
import com.subgraph.orchid.TorClient;
import com.subgraph.orchid.TorInitializationListener;
import javafx.animation.FadeTransition;
import javafx.animation.ParallelTransition;
import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.util.Duration;
import org.fxmisc.easybind.EasyBind;
import wallettemplate.controls.ClickableBitcoinAddress;
import wallettemplate.controls.NotificationBarPane;
import wallettemplate.utils.BitcoinUIModel;
import wallettemplate.utils.easing.EasingMode;
import wallettemplate.utils.easing.ElasticInterpolator;

import static wallettemplate.Main.bitcoin;

/**
 * Gets created auto-magically by FXMLLoader via reflection. The widget fields are set to the GUI controls they're named
 * after. This class handles all the updates and event handling for the main UI.
 */
public class MainController {
    public HBox controlsBox;
    public Label balance;
    public Button sendMoneyOutBtn;
    public ClickableBitcoinAddress addressControl;

    private BitcoinUIModel model = new BitcoinUIModel();
    private NotificationBarPane.Item syncItem;

    // Called by FXMLLoader.
    public void initialize() {
        addressControl.setOpacity(0.0);
    }

    public void onBitcoinSetup() {
        model.setWallet(bitcoin.wallet());
        addressControl.addressProperty().bind(model.addressProperty());
        balance.textProperty().bind(EasyBind.map(model.balanceProperty(), coin -> MonetaryFormat.BTC.noCode().format(coin).toString()));
        // Don't let the user click send money when the wallet is empty.
        sendMoneyOutBtn.disableProperty().bind(model.balanceProperty().isEqualTo(Coin.ZERO));

        TorClient torClient = Main.bitcoin.peerGroup().getTorClient();
        if (torClient != null) {
            SimpleDoubleProperty torProgress = new SimpleDoubleProperty(-1);
            String torMsg = "Initialising Tor";
            syncItem = Main.instance.notificationBar.pushItem(torMsg, torProgress);
            torClient.addInitializationListener(new TorInitializationListener() {
                @Override
                public void initializationProgress(String message, int percent) {
                    Platform.runLater(() -> {
                        syncItem.label.set(torMsg + ": " + message);
                        torProgress.set(percent / 100.0);
                    });
                }

                @Override
                public void initializationCompleted() {
                    Platform.runLater(() -> {
                        syncItem.cancel();
                        showBitcoinSyncMessage();
                    });
                }
            });
        } else {
            showBitcoinSyncMessage();
        }
        model.syncProgressProperty().addListener(x -> {
            if (model.syncProgressProperty().get() >= 1.0) {
                readyToGoAnimation();
                if (syncItem != null) {
                    syncItem.cancel();
                    syncItem = null;
                }
            } else if (syncItem == null) {
                showBitcoinSyncMessage();
            }
        });
    }

    private void showBitcoinSyncMessage() {
        syncItem = Main.instance.notificationBar.pushItem("Synchronising with the Bitcoin network", model.syncProgressProperty());
    }

    public void sendMoneyOut(ActionEvent event) {
        // Hide this UI and show the send money UI. This UI won't be clickable until the user dismisses send_money.
        Main.instance.overlayUI("send_money.fxml");
    }

    public void settingsClicked(ActionEvent event) {
        Main.OverlayUI<WalletSettingsController> screen = Main.instance.overlayUI("wallet_settings.fxml");
        screen.controller.initialize(null);
    }

    public void restoreFromSeedAnimation() {
        // Buttons slide out ...
        TranslateTransition leave = new TranslateTransition(Duration.millis(1200), controlsBox);
        leave.setByY(80.0);
        leave.play();
    }

    public void readyToGoAnimation() {
        // Buttons slide in and clickable address appears simultaneously.
        TranslateTransition arrive = new TranslateTransition(Duration.millis(1200), controlsBox);
        arrive.setInterpolator(new ElasticInterpolator(EasingMode.EASE_OUT, 1, 2));
        arrive.setToY(0.0);
        FadeTransition reveal = new FadeTransition(Duration.millis(1200), addressControl);
        reveal.setToValue(1.0);
        ParallelTransition group = new ParallelTransition(arrive, reveal);
        group.setDelay(NotificationBarPane.ANIM_OUT_DURATION);
        group.setCycleCount(1);
        group.play();
    }

    public DownloadProgressTracker progressBarUpdater() {
        return model.getDownloadProgressTracker();
    }
}


text:
<?php

namespace PhpBench\Benchmark\Metadata\Annotations;

/**
 * @Annotation
 *
 * @Taget({"METHOD", "CLASS"})
 * @Attributes({
 *    @Attribute("value", required = true, type="integer")
 * })
 */
class Sleep
{
    private $sleep;

    public function __construct($params)
    {
        $this->sleep = (int) $params['value'];
    }

    public function getSleep(): int
    {
        return $this->sleep;
    }
}


text:
require 'spec_helper'

module InheritedControllerSpec
  # example setup
  class SuperController < ApplicationController
    response_for :a_response do |format|
      format.html { super_inside_a_response }
    end

    def a_response
    end

    def an_action
      inside_an_action
    end

    def performing_action
      respond_to do |format|
        format.html { redirect_to 'http://redirected.from.an_action_which_performs' }
      end
    end

  protected
    def super_inside_a_response; end
    def inside_an_action; end
  end

  class SubController < SuperController
    response_for :a_response do |format|
      format.html { sub_inside_a_response }
    end

    response_for :an_action do |format|
      format.html do
        redirect_to 'http://redirected.from.response_for'
      end
    end

    response_for :performing_action do |format|
      never_reached_because_action_performs
    end

  protected
    def sub_inside_a_response; end
  end

  # specs
  describe "action_responses", :type => :spec do
    it "SuperController.action_responses should not == SubController.action_responses" do
      SuperController.action_responses.should_not == SubController.action_responses
    end

    it "SuperController should have one action_response for 'a_response'" do
      SuperController.action_responses.keys.should == ['a_response']
      SuperController.action_responses['a_response'].size.should == 1
    end

    it "SubController should have two action_responses for 'a_response', and one each for 'an_action', and 'performing_action'" do
      SubController.action_responses.keys.sort.should == ['a_response', 'an_action', 'performing_action']
      SubController.action_responses['a_response'].size.should == 2
      SubController.action_responses['an_action'].size.should == 1
      SubController.action_responses['performing_action'].size.should == 1
    end
  end

  describe SuperController do
    describe "GET :an_action" do

      it "should execute action" do
        @controller.should_receive :inside_an_action
        get :an_action
      end

      it "should render :an_action" do
        get :an_action
        response.should render_template('inherited_controller_spec/super/an_action')
      end
    end

    describe "GET :a_response" do
      it "should execute inside the super response block" do
        @controller.should_receive :super_inside_a_response
        get :a_response
      end

      it "should NOT execute inside the sub response block" do
        @controller.should_not_receive :sub_inside_a_response
        get :a_response
      end
    end

    describe "GET :performing_action" do
      it "should redirect" do
        get :performing_action
        response.should redirect_to('http://redirected.from.an_action_which_performs')
      end
    end
  end

  describe SubController do
    describe "GET :an_action (decorated with redirecting response_for)" do
      it "should execute action" do
        @controller.should_receive :inside_an_action
        get :an_action
      end

      it "should redirect" do
        get :an_action
        response.should redirect_to('http://redirected.from.response_for')
      end
    end

    describe "GET :a_response (decorated with a new response)" do
      it "should NOT execute the super response" do
        @controller.should_not_receive :super_inside_a_response
        get :a_response
      end

      it "should execute the sub response" do
        @controller.should_receive :sub_inside_a_response
        get :a_response
      end
    end

    describe "GET :performing_action" do
      it "should NOT execute the sub response" do
        @controller.should_not_receive :never_reached_because_action_performs
        get :performing_action
      end

      it "should redirect as per the super def" do
        get :performing_action
        response.should redirect_to('http://redirected.from.an_action_which_performs')
      end
    end
  end
end


text:
package com.codebroker.api.internal;

import java.util.Optional;

/**
 * 系统组件管理器.
 *
 *  @author LongJu
 */
public interface ComponentRegistry extends Iterable<IService > {

    /**
     * 根据CLASS类型获得已经注册的组件.
     *
     * @param <T>  the generic type
     * @param type the type
     * @return the component
     */
    <T> Optional<T> getComponent(Class<T> type);

    /**
     * 移除组件
     * @param type
     */
    void removeComponent(Class type);
}


text:
/**
 * Location Intelligence APIs
 * Incorporate our extensive geodata into everyday applications, business processes and workflows.
 *
 * OpenAPI spec version: 8.5.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pb.locationintelligence.model;

import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import pb.locationintelligence.model.IndividualValueVariable;
import pb.locationintelligence.model.MatchedAddress;

/**
 * GeoPropertyResponse
 */
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-04-16T15:55:12.092+05:30")
public class GeoPropertyResponse   {
  @SerializedName("objectId")
  private String objectId = null;

  @SerializedName("category")
  private String category = null;

  @SerializedName("individualValueVariable")
  private List<IndividualValueVariable> individualValueVariable = new ArrayList<IndividualValueVariable>();

  @SerializedName("matchedAddress")
  private MatchedAddress matchedAddress = null;

  public GeoPropertyResponse objectId(String objectId) {
    this.objectId = objectId;
    return this;
  }

   /**
   * Get objectId
   * @return objectId
  **/
  @ApiModelProperty(example = "null", value = "")
  public String getObjectId() {
    return objectId;
  }

  public void setObjectId(String objectId) {
    this.objectId = objectId;
  }

  public GeoPropertyResponse category(String category) {
    this.category = category;
    return this;
  }

   /**
   * Get category
   * @return category
  **/
  @ApiModelProperty(example = "null", value = "")
  public String getCategory() {
    return category;
  }

  public void setCategory(String category) {
    this.category = category;
  }

  public GeoPropertyResponse individualValueVariable(List<IndividualValueVariable> individualValueVariable) {
    this.individualValueVariable = individualValueVariable;
    return this;
  }

   /**
   * Get individualValueVariable
   * @return individualValueVariable
  **/
  @ApiModelProperty(example = "null", value = "")
  public List<IndividualValueVariable> getIndividualValueVariable() {
    return individualValueVariable;
  }

  public void setIndividualValueVariable(List<IndividualValueVariable> individualValueVariable) {
    this.individualValueVariable = individualValueVariable;
  }

  public GeoPropertyResponse matchedAddress(MatchedAddress matchedAddress) {
    this.matchedAddress = matchedAddress;
    return this;
  }

   /**
   * Get matchedAddress
   * @return matchedAddress
  **/
  @ApiModelProperty(example = "null", value = "")
  public MatchedAddress getMatchedAddress() {
    return matchedAddress;
  }

  public void setMatchedAddress(MatchedAddress matchedAddress) {
    this.matchedAddress = matchedAddress;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    GeoPropertyResponse geoPropertyResponse = (GeoPropertyResponse) o;
    return Objects.equals(this.objectId, geoPropertyResponse.objectId) &&
        Objects.equals(this.category, geoPropertyResponse.category) &&
        Objects.equals(this.individualValueVariable, geoPropertyResponse.individualValueVariable) &&
        Objects.equals(this.matchedAddress, geoPropertyResponse.matchedAddress);
  }

  @Override
  public int hashCode() {
    return Objects.hash(objectId, category, individualValueVariable, matchedAddress);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class GeoPropertyResponse {\n");

    sb.append("    objectId: ").append(toIndentedString(objectId)).append("\n");
    sb.append("    category: ").append(toIndentedString(category)).append("\n");
    sb.append("    individualValueVariable: ").append(toIndentedString(individualValueVariable)).append("\n");
    sb.append("    matchedAddress: ").append(toIndentedString(matchedAddress)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<?php

return [

    'audit-log'           => [
        'category'              => 'Settings',
        'msg-index'             => 'Accessed list of settings.',
        'msg-show'              => 'Accessed details of setting: :key.',
        'msg-store'             => 'Created new setting: :key.',
        'msg-edit'              => 'Initiated edit of setting: :key.',
        'msg-update'            => 'Submitted edit of setting: :key.',
        'msg-destroy'           => 'Deleted setting: :key.',
        'msg-load'              => 'Triggered loading of settings based on \'.env\' file.',
    ],

    'status'              => [
        'created'                   => 'Setting successfully created',
        'updated'                   => 'Setting successfully updated',
        'deleted'                   => 'Setting successfully deleted',
        'settings-loaded'           => 'Successfully loaded :number settings from :env file.',
        'no-settings-loaded'        => 'Nothing loaded from :env settings file.',
        'settings-file-not-found'   => 'Could not find :env settings file.',
        'no-setting-selected'       => 'No setting selected.',
    ],

    'error'               => [
        'cant-edit-this-setting'   => 'This setting cannot be edited',
    ],

    'page'              => [
        'index'              => [
            'title'             => 'Admin | Setting',
            'description'       => 'List of settings',
            'table-title'       => 'Setting list',
        ],
        'show'              => [
            'title'             => 'Admin | Setting | Show',
            'description'       => 'Displaying setting: :key',
            'section-title'     => 'Setting details'
        ],
        'create'            => [
            'title'            => 'Admin | Setting | Create',
            'description'      => 'Creating a new setting',
            'section-title'    => 'New setting'
        ],
        'edit'              => [
            'title'            => 'Admin | Setting | Edit',
            'description'      => 'Editing setting: :key',
            'section-title'    => 'Edit setting'
        ],
    ],

    'columns'           => [
        'name'                      =>  'Name',
        'value'                     =>  'Value',
        'actions'                   =>  'Actions',
        'encrypted'                 =>  'Encrypted',
    ],

    'action'               => [
        'create'                => 'Create new setting',
        'load'                  => 'Load settings',
    ],

];


text:
package terraform

// UIOutput is the interface that must be implemented to output
// data to the end user.
type UIOutput interface {
	Output(string)
}


text:
import { expect } from 'chai';
import bracketMatcher from '../../src/medium/bracketMatcher';

describe('bracketMatcher', () => {
  it('should detect if brackets in string match', () => {
    expect(bracketMatcher('(hello (world))')).to.be.ok;
    expect(bracketMatcher('(coder)(byte))')).to.be.not.ok;
    expect(bracketMatcher('(c(oder)) b(yte)')).to.be.ok;
    expect(bracketMatcher('good night')).to.be.ok;
    expect(bracketMatcher('((c((oder)) b(yte)')).to.be.not.ok;
  });
});


text:
/* First created by JCasGen Fri Jul 22 13:16:57 CEST 2016 */
package de.julielab.jcore.types;

import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.JCasRegistry;
import org.apache.uima.cas.impl.CASImpl;
import org.apache.uima.cas.impl.FSGenerator;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.cas.impl.TypeImpl;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.impl.FeatureImpl;
import org.apache.uima.cas.Feature;

/**
 * Updated by JCasGen Fri Jul 22 13:16:57 CEST 2016
 * @generated */
public class Coordination_Type extends Annotation_Type {
  /** @generated
   * @return the generator for this type
   */
  @Override
  protected FSGenerator getFSGenerator() {return fsGenerator;}
  /** @generated */
  private final FSGenerator fsGenerator =
    new FSGenerator() {
      public FeatureStructure createFS(int addr, CASImpl cas) {
  			 if (Coordination_Type.this.useExistingInstance) {
  			   // Return eq fs instance if already created
  		     FeatureStructure fs = Coordination_Type.this.jcas.getJfsFromCaddr(addr);
  		     if (null == fs) {
  		       fs = new Coordination(addr, Coordination_Type.this);
  			   Coordination_Type.this.jcas.putJfsFromCaddr(addr, fs);
  			   return fs;
  		     }
  		     return fs;
        } else return new Coordination(addr, Coordination_Type.this);
  	  }
    };
  /** @generated */
  @SuppressWarnings ("hiding")
  public final static int typeIndexID = Coordination.typeIndexID;
  /** @generated
     @modifiable */
  @SuppressWarnings ("hiding")
  public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.julielab.jcore.types.Coordination");

  /** @generated */
  final Feature casFeat_resolved;
  /** @generated */
  final int     casFeatCode_resolved;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public String getResolved(int addr) {
        if (featOkTst && casFeat_resolved == null)
      jcas.throwFeatMissing("resolved", "de.julielab.jcore.types.Coordination");
    return ll_cas.ll_getStringValue(addr, casFeatCode_resolved);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setResolved(int addr, String v) {
        if (featOkTst && casFeat_resolved == null)
      jcas.throwFeatMissing("resolved", "de.julielab.jcore.types.Coordination");
    ll_cas.ll_setStringValue(addr, casFeatCode_resolved, v);}

  /** @generated */
  final Feature casFeat_elliptical;
  /** @generated */
  final int     casFeatCode_elliptical;
  /** @generated
   * @param addr low level Feature Structure reference
   * @return the feature value
   */
  public boolean getElliptical(int addr) {
        if (featOkTst && casFeat_elliptical == null)
      jcas.throwFeatMissing("elliptical", "de.julielab.jcore.types.Coordination");
    return ll_cas.ll_getBooleanValue(addr, casFeatCode_elliptical);
  }
  /** @generated
   * @param addr low level Feature Structure reference
   * @param v value to set
   */
  public void setElliptical(int addr, boolean v) {
        if (featOkTst && casFeat_elliptical == null)
      jcas.throwFeatMissing("elliptical", "de.julielab.jcore.types.Coordination");
    ll_cas.ll_setBooleanValue(addr, casFeatCode_elliptical, v);}

  /** initialize variables to correspond with Cas Type and Features
	 * @generated
	 * @param jcas JCas
	 * @param casType Type
	 */
  public Coordination_Type(JCas jcas, Type casType) {
    super(jcas, casType);
    casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator());

    casFeat_resolved = jcas.getRequiredFeatureDE(casType, "resolved", "uima.cas.String", featOkTst);
    casFeatCode_resolved  = (null == casFeat_resolved) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_resolved).getCode();

    casFeat_elliptical = jcas.getRequiredFeatureDE(casType, "elliptical", "uima.cas.Boolean", featOkTst);
    casFeatCode_elliptical  = (null == casFeat_elliptical) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_elliptical).getCode();

  }
}