text:
<?php
/**
 * Created by PhpStorm.
 * User: ASGAlex
 * Date: 20.05.2017
 * Time: 1:27
 */

namespace DigitalWand\MVC;

use Bitrix\Main\IO\Directory;
use Bitrix\Main\IO\File;
use Bitrix\Main\IO\FileNotFoundException;

/**
 * Class ComponentBuilder
 * @package DigitalWand\MVC
 *
 * Класс для сборки "рыбы" компонента из шаблонов ивведенных пользователем параметров
 */
class ComponentBuilder
{
    protected $variables;
    protected $componentPath;

    public function __construct($variables)
    {
        $this->variables = $variables;
        $this->componentPath = $_SERVER['DOCUMENT_ROOT'] . '/local/components/' . $this->variables['namespace'] . '/' . $this->variables['name'];
    }

    public static function extractVariablesFromSEF($sef, $existingVariables)
    {
        $matches = array();
        if (preg_match_all('/\#\w.+?\#/', $sef, $matches)) {
            if (!empty($existingVariables)) {
                $existingVariables = explode(',', $existingVariables);
            } else {
                $existingVariables = array();
            }

            if(!empty($matches)){
                $matches = reset($matches);
                foreach ($matches as $match) {
                    $var = str_replace('#', '', $match);
                    if (array_search($var, $existingVariables) === false) {
                        $existingVariables[] = $var;
                    }
                }
            }

        }
        $existingVariables = implode(',', $existingVariables);
        if (is_null($existingVariables)) {
            $existingVariables = '';
        }

        return $existingVariables;
    }

    public function build()
    {
        $dir = Directory::createDirectory($this->componentPath);
        if (!$dir->isExists()) {
            return false;
        }

        try {
            $templates = array(
                '.parameters.php',
                '.description.php',
                'class.php',
            );
            foreach ($templates as $templateName) {
                $file = new File($this->componentPath . '/' . $templateName);
                $render = $this->renderTemplate($templateName);
                $file->putContents($render);
            }

            $render = $this->renderTemplate('templates/.default/template.php');
            foreach ($this->variables['routes'] as $route) {
                $routeTpl = new File($this->componentPath . '/templates/.default/' . $route['id'] . '.php');
                $routeTpl->putContents($render);
            }

        } catch (\Exception $exception) {
            return false;
        }

        return true;
    }

    protected function renderTemplate($name)
    {
        $path = __DIR__ . '/../tpl/' . $name;
        if (File::isFileExists($path)) {
            extract($this->variables);
            ob_start();
            include $path;

            return '<?php' . ob_get_clean();
        } else {
            throw new FileNotFoundException($path);
        }
    }

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

    /**
     * @return string
     */
    public function getComponentRelativePath()
    {
        return str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->componentPath);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Functions to generate random spike trains.

Most of these functions were adapted from the NeuroTools stgen module, which was mostly written by Eilif Muller.

:copyright: Copyright 2015 by the Elephant team, see AUTHORS.txt.
:license: Modified BSD, see LICENSE.txt for details.
"""

from __future__ import division
import numpy as np
from quantities import ms, Hz, Quantity
from neo import SpikeTrain

def _homogeneous_process(interval_generator, args, mean_rate, t_start, t_stop, as_array):
    """
    Returns a spike train whose spikes are a realization of a random process generated by the function `interval_generator`
    with the given rate, starting at time `t_start` and stopping `time t_stop`.
    """
    def rescale(x):
        return (x / mean_rate.units).rescale(t_stop.units)

    n = int(((t_stop - t_start) * mean_rate).simplified)
    number = np.ceil(n + 3 * np.sqrt(n))
    if number < 100:
        number = min(5 + np.ceil(2 * n), 100)
    assert number > 4  # if positive, number cannot be less than 5
    isi = rescale(interval_generator(*args, size=number))
    spikes = np.cumsum(isi)
    spikes += t_start

    i = spikes.searchsorted(t_stop)
    if i == len(spikes):
        # ISI buffer overrun
        extra_spikes = []
        t_last = spikes[-1] + rescale(interval_generator(*args, size=1))[0]
        while t_last < t_stop:
            extra_spikes.append(t_last)
            t_last = t_last + rescale(interval_generator(*args, size=1))[0]
        # np.concatenate does not conserve units
        spikes = Quantity(
            np.concatenate((spikes, extra_spikes)).magnitude, units=spikes.units)
    else:
        spikes = spikes[:i]

    if as_array:
        spikes = spikes.magnitude
    else:
        spikes = SpikeTrain(
            spikes, t_start=t_start, t_stop=t_stop, units=spikes.units)

    return spikes

def homogeneous_poisson_process(rate, t_start=0.0 * ms, t_stop=1000.0 * ms, as_array=False):
    """
    Returns a spike train whose spikes are a realization of a Poisson process
    with the given rate, starting at time `t_start` and stopping time `t_stop`.

    All numerical values should be given as Quantities, e.g. 100*Hz.

    Parameters
    ----------

    rate : Quantity scalar with dimension 1/time
           The rate of the discharge.
    t_start : Quantity scalar with dimension time
              The beginning of the spike train.
    t_stop : Quantity scalar with dimension time
             The end of the spike train.
    as_array : bool
               If True, a NumPy array of sorted spikes is returned,
               rather than a SpikeTrain object.

    Examples
    --------
        >>> from quantities import Hz, ms
        >>> spikes = homogeneous_poisson_process(50*Hz, 0*ms, 1000*ms)
        >>> spikes = homogeneous_poisson_process(20*Hz, 5000*ms, 10000*ms, as_array=True)

    """
    mean_interval = 1 / rate
    return _homogeneous_process(np.random.exponential, (mean_interval,), rate, t_start, t_stop, as_array)

def homogeneous_gamma_process(a, b, t_start=0.0 * ms, t_stop=1000.0 * ms, as_array=False):
    """
    Returns a spike train whose spikes are a realization of a gamma process
    with the given parameters, starting at time `t_start` and stopping time `t_stop`.
    (average rate will be b/a).

    All numerical values should be given as Quantities, e.g. 100*Hz.

    Parameters
    ----------

    a : int or float
        The shape parameter of the gamma distribution.
    b : Quantity scalar with dimension 1/time
        The rate parameter of the gamma distribution.
    t_start : Quantity scalar with dimension time
              The beginning of the spike train.
    t_stop : Quantity scalar with dimension time
             The end of the spike train.
    as_array : bool
               If True, a NumPy array of sorted spikes is returned,
               rather than a SpikeTrain object.

    Examples
    --------
        >>> from quantities import Hz, ms
        >>> spikes = homogeneous_gamma_process(2.0, 50*Hz, 0*ms, 1000*ms)
        >>> spikes = homogeneous_gamma_process(5.0, 20*Hz, 5000*ms, 10000*ms, as_array=True)

    """
    rate = b / a
    k, theta = a, (1 / b)
    return _homogeneous_process(np.random.gamma, (k, theta), rate, t_start, t_stop, as_array)


text:
package com.facebook.buck.apple.simulator;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.google.common.collect.ImmutableSet;
import com.google.common.io.CharStreams;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.junit.Test;

/** Unit tests for {@link SimctlListOutputParsing}. */
public class SimctlListOutputParsingTest {
  @Test
  public void simctlListOutputParsesToAppleSimulators() throws IOException {
    ImmutableSet.Builder<AppleSimulator> simulatorsBuilder = ImmutableSet.builder();

    try (InputStream in = getClass().getResourceAsStream("testdata/simctl-list.txt");
        InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
      SimctlListOutputParsing.parseOutput(CharStreams.toString(reader), simulatorsBuilder);
    }

    ImmutableSet<AppleSimulator> expected =
        ImmutableSet.<AppleSimulator>builder()
            .add(
                AppleSimulator.builder()
                    .setName("iPhone 4s")
                    .setUdid("F7C1CC9A-945E-4258-BA84-DEEBE683798B")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPhone 5")
                    .setUdid("45BD7164-686C-474F-8C68-3730432BC5F2")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPhone 5s")
                    .setUdid("70200ED8-EEF1-4BDB-BCCF-3595B137D67D")
                    .setSimulatorState(AppleSimulatorState.BOOTED)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPhone 6 Plus")
                    .setUdid("92340ACF-2C44-455F-BACD-573B133FB20E")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPhone 6")
                    .setUdid("A75FF972-FE12-4656-A8CC-99572879D4A3")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPad 2")
                    .setUdid("CC1B0BAD-BAE6-4A53-92CF-F79850654057")
                    .setSimulatorState(AppleSimulatorState.SHUTTING_DOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPad Retina")
                    .setUdid("137AAA25-54A1-42E8-8202-84DEADD668E1")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("iPad Air")
                    .setUdid("554B2E0F-63F3-4400-8319-5C5062CF4C95")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("Resizable iPhone")
                    .setUdid("58E3748F-F7E6-4A45-B52C-A136B59F7A42")
                    .setSimulatorState(AppleSimulatorState.CREATING)
                    .build())
            .add(
                AppleSimulator.builder()
                    .setName("Resizable iPad")
                    .setUdid("56FE1CBC-61FF-443D-8E23-19D05864C6DB")
                    .setSimulatorState(AppleSimulatorState.SHUTDOWN)
                    .build())
            .build();

    assertThat(simulatorsBuilder.build(), is(equalTo(expected)));
  }
}


text:
{include file="header.html"}

{$lang.goods_recommended}

{$lang.recommend}

 {$lang.recommend}:
    <select class="infoTableSelect" onchange="location='index.php?app=recommend&act=view_goods&id=' + this.value">{html_options options=$recommends selected=$smarty.get.id}

    </select>

 {if $goods_list}{include file=page.top.html}{/if}

      <input type="checkbox" class="checkall" />
      {$lang.goods_name}
      {$lang.sort_order}
      {$lang.store_name}
      {$lang.brand}
      {$lang.cate_name}
      {$lang.if_show}
      {$lang.closed}
      {$lang.views}

      <input type="checkbox" class="checkitem" value="{$goods.goods_id}" />
      {$goods.goods_name|escape}
      {$goods.sort_order}
      {$goods.store_name|escape}
      {$goods.brand|escape}
      {$goods.cate_name|nl2br}

      {$goods.views|default:0}

      {$lang.no_data}

      <input class="formbtn batchButton" type="button" value="{$lang.unrecommend}" name="goods_id" uri="index.php?app=recommend&act=drop_goods_from&id={$smarty.get.id}" />

 {if $goods_list}{include file=page.bottom.html}{/if}

{include file="footer.html"}


text:
require  'spec_helper'

describe Shopping::CouponsController do
  render_views

  before(:each) do
    activate_authlogic

    @cur_user = FactoryGirl.create(:user)
    login_as(@cur_user)

    #stylist_cart
    @variant  = FactoryGirl.create(:variant)

    create_cart(@cur_user, @cur_user, [@variant])

    @address      = FactoryGirl.create(:address)
    @order        = FactoryGirl.create(:order, :ship_address_id => @address.id)
    @order_item   = FactoryGirl.create(:order_item, :order => @order, :variant => @variant)
    @order.stubs(:order_items).returns([@order_item])
    @controller.stubs(:find_or_create_order).returns(@order)
  end

  it "show action should render show template" do
    get :show
    expect(response).to render_template(:show)
  end

  it "create action should render show template when coupon is not eligible" do
    Coupon.any_instance.stubs(:eligible?).returns(false)
    post :create, params: { coupon: { code: 'qwerty' } }
    expect(response).to render_template(:show)
  end

  it "create action should redirect when model is valid" do
    FactoryGirl.create(:coupon_value, :code => 'qwerty' )
    CouponValue.any_instance.stubs(:eligible?).returns(true)
    Shopping::CouponsController.any_instance.stubs(:update_order_coupon_id).returns(true)
    @controller.expects(:next_form_url).returns(shopping_orders_url)
    post :create, params: {coupon: { code: 'qwerty' }}
    expect(response).to redirect_to(shopping_orders_url)
  end
end


text:
package azblob

// https://docs.microsoft.com/en-us/rest/api/storageservices/blob-service-error-codes

// ServiceCode values indicate a service failure.
const (
	// ServiceCodeAppendPositionConditionNotMet means the append position condition specified was not met.
	ServiceCodeAppendPositionConditionNotMet ServiceCodeType = "AppendPositionConditionNotMet"

	// ServiceCodeBlobAlreadyExists means the specified blob already exists.
	ServiceCodeBlobAlreadyExists ServiceCodeType = "BlobAlreadyExists"

	// ServiceCodeBlobNotFound means the specified blob does not exist.
	ServiceCodeBlobNotFound ServiceCodeType = "BlobNotFound"

	// ServiceCodeBlobOverwritten means the blob has been recreated since the previous snapshot was taken.
	ServiceCodeBlobOverwritten ServiceCodeType = "BlobOverwritten"

	// ServiceCodeBlobTierInadequateForContentLength means the specified blob tier size limit cannot be less than content length.
	ServiceCodeBlobTierInadequateForContentLength ServiceCodeType = "BlobTierInadequateForContentLength"

	// ServiceCodeBlockCountExceedsLimit means the committed block count cannot exceed the maximum limit of 50,000 blocks
	// or that the uncommitted block count cannot exceed the maximum limit of 100,000 blocks.
	ServiceCodeBlockCountExceedsLimit ServiceCodeType = "BlockCountExceedsLimit"

	// ServiceCodeBlockListTooLong means the block list may not contain more than 50,000 blocks.
	ServiceCodeBlockListTooLong ServiceCodeType = "BlockListTooLong"

	// ServiceCodeCannotChangeToLowerTier means that a higher blob tier has already been explicitly set.
	ServiceCodeCannotChangeToLowerTier ServiceCodeType = "CannotChangeToLowerTier"

	// ServiceCodeCannotVerifyCopySource means that the service could not verify the copy source within the specified time.
	// Examine the HTTP status code and message for more information about the failure.
	ServiceCodeCannotVerifyCopySource ServiceCodeType = "CannotVerifyCopySource"

	// ServiceCodeContainerAlreadyExists means the specified container already exists.
	ServiceCodeContainerAlreadyExists ServiceCodeType = "ContainerAlreadyExists"

	// ServiceCodeContainerBeingDeleted means the specified container is being deleted.
	ServiceCodeContainerBeingDeleted ServiceCodeType = "ContainerBeingDeleted"

	// ServiceCodeContainerDisabled means the specified container has been disabled by the administrator.
	ServiceCodeContainerDisabled ServiceCodeType = "ContainerDisabled"

	// ServiceCodeContainerNotFound means the specified container does not exist.
	ServiceCodeContainerNotFound ServiceCodeType = "ContainerNotFound"

	// ServiceCodeContentLengthLargerThanTierLimit means the blob's content length cannot exceed its tier limit.
	ServiceCodeContentLengthLargerThanTierLimit ServiceCodeType = "ContentLengthLargerThanTierLimit"

	// ServiceCodeCopyAcrossAccountsNotSupported means the copy source account and destination account must be the same.
	ServiceCodeCopyAcrossAccountsNotSupported ServiceCodeType = "CopyAcrossAccountsNotSupported"

	// ServiceCodeCopyIDMismatch means the specified copy ID did not match the copy ID for the pending copy operation.
	ServiceCodeCopyIDMismatch ServiceCodeType = "CopyIdMismatch"

	// ServiceCodeFeatureVersionMismatch means the type of blob in the container is unrecognized by this version or
	// that the operation for AppendBlob requires at least version 2015-02-21.
	ServiceCodeFeatureVersionMismatch ServiceCodeType = "FeatureVersionMismatch"

	// ServiceCodeIncrementalCopyBlobMismatch means the specified source blob is different than the copy source of the existing incremental copy blob.
	ServiceCodeIncrementalCopyBlobMismatch ServiceCodeType = "IncrementalCopyBlobMismatch"

	// ServiceCodeIncrementalCopyOfEralierVersionSnapshotNotAllowed means the specified snapshot is earlier than the last snapshot copied into the incremental copy blob.
	ServiceCodeIncrementalCopyOfEralierVersionSnapshotNotAllowed ServiceCodeType = "IncrementalCopyOfEralierVersionSnapshotNotAllowed"

	// ServiceCodeIncrementalCopySourceMustBeSnapshot means the source for incremental copy request must be a snapshot.
	ServiceCodeIncrementalCopySourceMustBeSnapshot ServiceCodeType = "IncrementalCopySourceMustBeSnapshot"

	// ServiceCodeInfiniteLeaseDurationRequired means the lease ID matched, but the specified lease must be an infinite-duration lease.
	ServiceCodeInfiniteLeaseDurationRequired ServiceCodeType = "InfiniteLeaseDurationRequired"

	// ServiceCodeInvalidBlobOrBlock means the specified blob or block content is invalid.
	ServiceCodeInvalidBlobOrBlock ServiceCodeType = "InvalidBlobOrBlock"

	// ServiceCodeInvalidBlobType means the blob type is invalid for this operation.
	ServiceCodeInvalidBlobType ServiceCodeType = "InvalidBlobType"

	// ServiceCodeInvalidBlockID means the specified block ID is invalid. The block ID must be Base64-encoded.
	ServiceCodeInvalidBlockID ServiceCodeType = "InvalidBlockId"

	// ServiceCodeInvalidBlockList means the specified block list is invalid.
	ServiceCodeInvalidBlockList ServiceCodeType = "InvalidBlockList"

	// ServiceCodeInvalidOperation means an invalid operation against a blob snapshot.
	ServiceCodeInvalidOperation ServiceCodeType = "InvalidOperation"

	// ServiceCodeInvalidPageRange means the page range specified is invalid.
	ServiceCodeInvalidPageRange ServiceCodeType = "InvalidPageRange"

	// ServiceCodeInvalidSourceBlobType means the copy source blob type is invalid for this operation.
	ServiceCodeInvalidSourceBlobType ServiceCodeType = "InvalidSourceBlobType"

	// ServiceCodeInvalidSourceBlobURL means the source URL for incremental copy request must be valid Azure Storage blob URL.
	ServiceCodeInvalidSourceBlobURL ServiceCodeType = "InvalidSourceBlobUrl"

	// ServiceCodeInvalidVersionForPageBlobOperation means that all operations on page blobs require at least version 2009-09-19.
	ServiceCodeInvalidVersionForPageBlobOperation ServiceCodeType = "InvalidVersionForPageBlobOperation"

	// ServiceCodeLeaseAlreadyPresent means there is already a lease present.
	ServiceCodeLeaseAlreadyPresent ServiceCodeType = "LeaseAlreadyPresent"

	// ServiceCodeLeaseAlreadyBroken means the lease has already been broken and cannot be broken again.
	ServiceCodeLeaseAlreadyBroken ServiceCodeType = "LeaseAlreadyBroken"

	// ServiceCodeLeaseIDMismatchWithBlobOperation means the lease ID specified did not match the lease ID for the blob.
	ServiceCodeLeaseIDMismatchWithBlobOperation ServiceCodeType = "LeaseIdMismatchWithBlobOperation"

	// ServiceCodeLeaseIDMismatchWithContainerOperation means the lease ID specified did not match the lease ID for the container.
	ServiceCodeLeaseIDMismatchWithContainerOperation ServiceCodeType = "LeaseIdMismatchWithContainerOperation"

	// ServiceCodeLeaseIDMismatchWithLeaseOperation means the lease ID specified did not match the lease ID for the blob/container.
	ServiceCodeLeaseIDMismatchWithLeaseOperation ServiceCodeType = "LeaseIdMismatchWithLeaseOperation"

	// ServiceCodeLeaseIDMissing means there is currently a lease on the blob/container and no lease ID was specified in the request.
	ServiceCodeLeaseIDMissing ServiceCodeType = "LeaseIdMissing"

	// ServiceCodeLeaseIsBreakingAndCannotBeAcquired means the lease ID matched, but the lease is currently in breaking state and cannot be acquired until it is broken.
	ServiceCodeLeaseIsBreakingAndCannotBeAcquired ServiceCodeType = "LeaseIsBreakingAndCannotBeAcquired"

	// ServiceCodeLeaseIsBreakingAndCannotBeChanged means the lease ID matched, but the lease is currently in breaking state and cannot be changed.
	ServiceCodeLeaseIsBreakingAndCannotBeChanged ServiceCodeType = "LeaseIsBreakingAndCannotBeChanged"

	// ServiceCodeLeaseIsBrokenAndCannotBeRenewed means the lease ID matched, but the lease has been broken explicitly and cannot be renewed.
	ServiceCodeLeaseIsBrokenAndCannotBeRenewed ServiceCodeType = "LeaseIsBrokenAndCannotBeRenewed"

	// ServiceCodeLeaseLost means a lease ID was specified, but the lease for the blob/container has expired.
	ServiceCodeLeaseLost ServiceCodeType = "LeaseLost"

	// ServiceCodeLeaseNotPresentWithBlobOperation means there is currently no lease on the blob.
	ServiceCodeLeaseNotPresentWithBlobOperation ServiceCodeType = "LeaseNotPresentWithBlobOperation"

	// ServiceCodeLeaseNotPresentWithContainerOperation means there is currently no lease on the container.
	ServiceCodeLeaseNotPresentWithContainerOperation ServiceCodeType = "LeaseNotPresentWithContainerOperation"

	// ServiceCodeLeaseNotPresentWithLeaseOperation means there is currently no lease on the blob/container.
	ServiceCodeLeaseNotPresentWithLeaseOperation ServiceCodeType = "LeaseNotPresentWithLeaseOperation"

	// ServiceCodeMaxBlobSizeConditionNotMet means the max blob size condition specified was not met.
	ServiceCodeMaxBlobSizeConditionNotMet ServiceCodeType = "MaxBlobSizeConditionNotMet"

	// ServiceCodeNoPendingCopyOperation means there is currently no pending copy operation.
	ServiceCodeNoPendingCopyOperation ServiceCodeType = "NoPendingCopyOperation"

	// ServiceCodeOperationNotAllowedOnIncrementalCopyBlob means the specified operation is not allowed on an incremental copy blob.
	ServiceCodeOperationNotAllowedOnIncrementalCopyBlob ServiceCodeType = "OperationNotAllowedOnIncrementalCopyBlob"

	// ServiceCodePendingCopyOperation means there is currently a pending copy operation.
	ServiceCodePendingCopyOperation ServiceCodeType = "PendingCopyOperation"

	// ServiceCodePreviousSnapshotCannotBeNewer means the prevsnapshot query parameter value cannot be newer than snapshot query parameter value.
	ServiceCodePreviousSnapshotCannotBeNewer ServiceCodeType = "PreviousSnapshotCannotBeNewer"

	// ServiceCodePreviousSnapshotNotFound means the previous snapshot is not found.
	ServiceCodePreviousSnapshotNotFound ServiceCodeType = "PreviousSnapshotNotFound"

	// ServiceCodePreviousSnapshotOperationNotSupported means that differential Get Page Ranges is not supported on the previous snapshot.
	ServiceCodePreviousSnapshotOperationNotSupported ServiceCodeType = "PreviousSnapshotOperationNotSupported"

	// ServiceCodeSequenceNumberConditionNotMet means the sequence number condition specified was not met.
	ServiceCodeSequenceNumberConditionNotMet ServiceCodeType = "SequenceNumberConditionNotMet"

	// ServiceCodeSequenceNumberIncrementTooLarge means the sequence number increment cannot be performed because it would result in overflow of the sequence number.
	ServiceCodeSequenceNumberIncrementTooLarge ServiceCodeType = "SequenceNumberIncrementTooLarge"

	// ServiceCodeSnapshotCountExceeded means the snapshot count against this blob has been exceeded.
	ServiceCodeSnapshotCountExceeded ServiceCodeType = "SnapshotCountExceeded"

	// ServiceCodeSnaphotOperationRateExceeded means the rate of snapshot operations against this blob has been exceeded.
	ServiceCodeSnaphotOperationRateExceeded ServiceCodeType = "SnaphotOperationRateExceeded"

	// ServiceCodeSnapshotsPresent means this operation is not permitted while the blob has snapshots.
	ServiceCodeSnapshotsPresent ServiceCodeType = "SnapshotsPresent"

	// ServiceCodeSourceConditionNotMet means the source condition specified using HTTP conditional header(s) is not met.
	ServiceCodeSourceConditionNotMet ServiceCodeType = "SourceConditionNotMet"

	// ServiceCodeSystemInUse means this blob is in use by the system.
	ServiceCodeSystemInUse ServiceCodeType = "SystemInUse"

	// ServiceCodeTargetConditionNotMet means the target condition specified using HTTP conditional header(s) is not met.
	ServiceCodeTargetConditionNotMet ServiceCodeType = "TargetConditionNotMet"

	// ServiceCodeUnauthorizedBlobOverwrite means this request is not authorized to perform blob overwrites.
	ServiceCodeUnauthorizedBlobOverwrite ServiceCodeType = "UnauthorizedBlobOverwrite"

	// ServiceCodeBlobBeingRehydrated means this operation is not permitted because the blob is being rehydrated.
	ServiceCodeBlobBeingRehydrated ServiceCodeType = "BlobBeingRehydrated"

	// ServiceCodeBlobArchived means this operation is not permitted on an archived blob.
	ServiceCodeBlobArchived ServiceCodeType = "BlobArchived"

	// ServiceCodeBlobNotArchived means this blob is currently not in the archived state.
	ServiceCodeBlobNotArchived ServiceCodeType = "BlobNotArchived"
)


text:
module Importron
  class Step

    def initialize(database, from, entity, options = {}, &block)
      @database = database
      @from = from
      @entity = entity
      @options = options
      @block = block
    end

    CHUNK_SIZE = 1000

    def import(data)
      @entity.import data, :validate => false
    end

    def do(databases, run_options = {})
      db = databases[@database]
      count = db["SELECT count(*) FROM #{@from}"].first['count(*)'.to_sym]
      puts "Exporting table '#{@from}' from database '#{@database.to_s}'. (#{count})"

      if run_options[:debug]
        query = "SELECT * FROM #{@from} LIMIT 10"
      else
        query = @from
      end

      data = []
      db[query].each do |row|
        item = @block.call(row, db)
        data << item if item
        if data.length >= CHUNK_SIZE
          import data
          data = []
          print '*'
        end
      end
      import data
      puts '#'
    end
  end
end


text:
package org.damour.base.client.ui.repository;

import java.util.Comparator;

import org.damour.base.client.objects.RepositoryTreeNode;

public class PriorityComparator implements Comparator<RepositoryTreeNode> {

  boolean ascending = true;

  public PriorityComparator(boolean ascending) {
    this.ascending = ascending;
  }

  public int compare(RepositoryTreeNode obj1, RepositoryTreeNode obj2) {
    Long obj1L = obj1.getFile().getSortPriority();
    Long obj2L = obj2.getFile().getSortPriority();
    if (ascending) {
      return obj1L.compareTo(obj2L);
    }
    // z to a
    return obj2L.compareTo(obj1L);
  };
}


text:
import * as request from "request";
import IPlayer from "./interface/player";
import Config from "../configs/config";
import Util from "./util";
import UrlBuilder from "./url-builder";

export default class PlayerCrawler {
    constructor (private leagueId: number, private firebaseDb: any) {}

    getId() {
        return this.leagueId;
    }

    crawl() : Promise <IPlayer[]> {
        return new Promise ((resolve, reject) => {
            const leagueDataUrl = UrlBuilder.getLeagueDataUrl(this.leagueId);

            request(leagueDataUrl, (error, response, jsonString) => {
                if (!error && response.statusCode == 200) {
                    let leagueData = JSON.parse(jsonString),
                        results = leagueData.standings.results,
                        players: IPlayer[] = results.map(result => {

                            return {
                                name: Util.titleCase(result["player_name"]),
                                team: Util.titleCase(result["entry_name"]),
                                id: String(result["entry"])
                            }
                        });

                    resolve(players);
                } else {
                    reject(error);
                }
            });
        });
    }

    public savePlayers(players: IPlayer[]): Promise<IPlayer[]> {
        return new Promise((resolve, reject) => {
            this.firebaseDb.ref(Config.getLeaguePrefix() + '/players').set(players, error => {
                if (error) {
                    reject(error);
                } else {
                    resolve(players);
                }
            });
        });
    }

    public getPlayers(): Promise<IPlayer[]> {
        return new Promise((resolve, reject) => {
            this.firebaseDb.ref(Config.getLeaguePrefix() + '/players').once('value', snapshot => {
                resolve(snapshot.val());
            }, error => {
                reject(error);
            });
        });
    }
}


text:
@charset "UTF-8";

.fileinput-button {
  position: relative;
  overflow: hidden;
}
.fileinput-button input {
  position: absolute;
  top: 0;
  right: 0;
  margin: 0;
  opacity: 0;
  filter: alpha(opacity=0);
  transform: translate(-300px, 0) scale(4);
  font-size: 23px;
  direction: ltr;
  cursor: pointer;
}
.fileupload-buttonbar .btn,
.fileupload-buttonbar .toggle {
  margin-bottom: 5px;
}
.progress-animated .progress-bar,
.progress-animated .bar {
  background: url(../img/progressbar.gif) !important;
  filter: none;
}

.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default {
    background: none repeat scroll 0 0 #005491;
    border: 1px solid #515091;
    color: #EEEEEE;
    font-weight: bold;
    margin: 0px;
}

.ui-widget-content {
    border: 1px solid #555555;
    height: 14px;
    margin-bottom: 10px;
    width: 80%;
    background: #000000 url(../img/progressbar.gif) 50% 50% repeat;
    color: #ffffff;
}

.ui-widget-header {
border: 1px solid #798E9B;
/*background: #388532 url(images/ui-bg_highlight-soft_44_444444_1x100.png) 50% 50% repeat-x;*/
background: #005491 url(../img/ui-bg_highlight-soft_44_444444_1x100.png) 50% 50% repeat-x;
color: #ffffff;
font-weight: bold;
}

.ui-widget {
    font-size: 0.92em;
}

.ui-corner-all, .ui-corner-bottom, .ui-corner-right, .ui-corner-br {
    border-bottom-right-radius: 6px;
}
.ui-corner-all, .ui-corner-bottom, .ui-corner-left, .ui-corner-bl {
    border-bottom-left-radius: 6px;
}

.ui-corner-all, .ui-corner-top, .ui-corner-right, .ui-corner-tr {
    border-top-right-radius: 6px;
}
.ui-corner-all, .ui-corner-top, .ui-corner-left, .ui-corner-tl {
    border-top-left-radius: 6px;
}

.fileupload-loading {
  float: right;
  width: 32px;
  height: 32px;
  background: url(../img/loading.gif) center no-repeat;
  background-size: contain;
  display: none;
}
.fileupload-processing .fileupload-loading {
  display: block;
}
.files audio,
.files video {
  max-width: 300px;
}

@media (max-width: 767px) {
  .fileupload-buttonbar .toggle,
  .files .toggle,
  .files .btn span {
    display: none;
  }
  .files .name {
    width: 80px;
    word-wrap: break-word;
  }
  .files audio,
  .files video {
    max-width: 80px;
  }
}


text:
/*
 * tls.c
 * by WN @ Mar. 09, 2010
 */

#include <config.h>
#include <common/defs.h>
#include <common/debug.h>
#include <common/spinlock.h>
#include <common/bithacks.h>
#include <common/list.h>
#include <interp/code_cache.h>
#include <interp/logger.h>
#include <interp/auxv.h>
#include <interp/user_entry.h>
/* struct user_desc */
#include <xasm/types_helper.h>
#include <xasm/logger.h>
#include <xasm/compiler.h>
#include <xasm/tls.h>
#include <xasm/syscall.h>
#include <xasm/utils.h>
#include <xasm/string.h>

#include <sys/mman.h>

/*
 * thread_map is used to indicate the usage of ldt number. the
 * ldt slot is free if the corresponding bit is unset.
 * */
/* all tls related control work is protected by __tls_ctl_lock */

#define MAX_THREADS	(1 << 13)
static DEF_SPINLOCK_UNLOCKED(__tls_ctl_lock);

/* all tls struct is linked on this list. */
LIST_HEAD(tpd_list_head);

/* all static array should have been inited to 0 */
#define SZ_MAP	(MAX_THREADS / sizeof(uint32_t))
static uint32_t thread_map[SZ_MAP];

static bool_t
tls_in_shared_context = TRUE;

void
unset_share_context(void)
{
	tls_in_shared_context = FALSE;
}

void
lock_tls(void)
{
	if (!tls_in_shared_context) {
		spin_lock_fake(&__tls_ctl_lock);
	} else {
		spin_lock(&__tls_ctl_lock);
	}
}

void
unlock_tls(void)
{
	if (!tls_in_shared_context) {
		spin_unlock_fake(&__tls_ctl_lock);
	} else {
		spin_unlock(&__tls_ctl_lock);
	}
}

/*
 * find_set_free_slot shoule be called at lock context
 */
static int
find_set_free_slot(void)
{
	assert(spin_is_locked(&__tls_ctl_lock));
	for (int i = 0; i < (int)SZ_MAP; i++) {
		if (thread_map[i] != 0xffffffff) {
			int n = i * 32 + last_0_pos(thread_map[i]);
			thread_map[i] = set_last_0(thread_map[i]);
			return n;
		}
	}
	FATAL(TLS, "TLS slot is full\n");
}

#define READ_LDT		(0)
#define WRITE_LDT_OLD		(1)
#define READ_DEFAULT_LDT	(2)
#define WRITE_LDT			(0x11)

static void
write_ldt(struct user_desc * desc)
{
	int err;
	err = INTERNAL_SYSCALL_int80(modify_ldt, 3,
			WRITE_LDT, desc, sizeof(*desc));
	assert(err == 0);
}

static void
clear_tls_slot(unsigned int tnr)
{
	int nr = tnr / 32;
	int n = tnr % 32;
	thread_map[nr] = unset_bit_n(thread_map[nr], n);

	/* clear the ldt slot */
	struct thread_private_data * tpd = get_tpd();
	if (tpd->tnr == tnr) {
		/* clear 'fs' */
		asm volatile ("movw %w0, %%fs\n"
				:
				: "R" (0)
				: "memory");
	}
	struct user_desc desc;
	/* this is an 'empty' desc */
	desc.entry_number = tnr;
	desc.base_addr = 0;
	desc.limit = 0;
	desc.contents = 0;
	desc.read_exec_only = 1;
	desc.seg_32bit = 0;
	desc.limit_in_pages = 0;
	desc.seg_not_present = 1;
	desc.useable = 0;
	write_ldt(&desc);
}

/*
 * __setup_tls_area will alloc a new thread_private_data and link it
 * into tpd_list_head
 *
 * __setup_tls_area shoule be called at lock context
 */
static struct thread_private_data *
__setup_tls_area(unsigned int tnr)
{

	assert(spin_is_locked(&__tls_ctl_lock));

	/* setup fs: alloc tls stack and init thread private data */
	void * stack_base_addr = TNR_TO_STACK(tnr);

	/* alloc 2 pages from stack_base_addr */
	void * p = (void*)INTERNAL_SYSCALL_int80(mmap2, 6,
			stack_base_addr,
			TLS_STACK_SIZE,
			PROT_READ | PROT_WRITE,
			MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS,
			-1, 0);
	assert(p == stack_base_addr);
	/* mprotect */
	int err = INTERNAL_SYSCALL_int80(mprotect, 3,
			p, GUARDER_LENGTH, PROT_NONE);
	assert(err == 0);

	/* setup ldt */
	struct user_desc desc;
	desc.entry_number = tnr;
	desc.base_addr = (unsigned long int)(stack_base_addr);
	desc.limit = TLS_STACK_SIZE;
	desc.seg_32bit = 1;
	desc.contents = 0;
	desc.read_exec_only = 0;
	desc.limit_in_pages = 0;
	desc.seg_not_present = 0;
	desc.useable = 1;
	write_ldt(&desc);

	/* set tpd */
	struct thread_private_data * tpd =
		(void*)(stack_base_addr) +
		TLS_STACK_SIZE -
		sizeof(struct thread_private_data);

	memset(tpd, '\0', sizeof(*tpd));
	tpd->tnr = tnr;
	tpd->stack_top = tpd;
	tpd->tls_base = stack_base_addr;

	/* segregister: 16bits
	 *
	 * X X X X X X X X X X X X X X X X
	 *                           ^ ^ ^
	 *                           | |-|
	 *        <--- Index ---    TI RPL
	 * 3 is 'user'
	 * */
	tpd->fs_val = (tnr * 8 + 4 + 3);
	tpd->no_record_signals = FALSE;

	/* link tpd into tpd_list_head */
	list_add(&tpd->list, &tpd_list_head);
	return tpd;
}

static struct thread_private_data *
setup_tls_area(unsigned int tnr)
{
	assert(spin_is_locked(&__tls_ctl_lock));
	struct thread_private_data * tpd = __setup_tls_area(tnr);
	/* finally load fs */
	asm volatile ("movw %w0, %%fs\n" :: "R" (tpd->fs_val));
	return tpd;
}

static void
build_tpd(struct thread_private_data * tpd)
{
	tpd->real_branch = real_branch;
	tpd->first_branch = first_branch;

	if (auxv_info.p_sysinfo != NULL) {
		tpd->real_vdso_syscall_entry = *auxv_info.p_sysinfo;
	} else {
		/* we are loaded as a normal shared object */
		asm volatile("movl %%gs:0x10, %0" :
				"=r" (tpd->real_vdso_syscall_entry));
	}

	tpd->int80_syscall_entry = int80_syscall_entry;
	tpd->vdso_syscall_entry = vdso_syscall_entry;

	/* init code cache */
	init_code_cache(&tpd->code_cache);
	/* init logger */
	init_logger(&tpd->logger, tpd->pid, tpd->tid);
}

void
init_tls(void)
{
	int pid, tid;
	pid = INTERNAL_SYSCALL_int80(getpid, 0);
	tid = INTERNAL_SYSCALL_int80(gettid, 0);
	DEBUG(TLS, "init TLS storage: pid=%d, tid=%d\n",
			tid, pid);

	lock_tls();
	int n = find_set_free_slot();
	DEBUG(TLS, "TLS slot: %d\n", n);

	struct thread_private_data * tpd = setup_tls_area(n);
	DEBUG(TLS, "TPD resides at %p\n", tpd);
	unlock_tls();

	tpd->pid = pid;
	tpd->tid = tid;
	tpd->current_syscall_nr = -1;
	build_tpd(tpd);
}

/* return the value of 'fs' */
struct thread_private_data *
create_new_tls(void)
{
	lock_tls();
	int n = find_set_free_slot();
	VERBOSE(TLS, "TLS slot for currently unused tpd: %d\n", n);
	struct thread_private_data * tpd = __setup_tls_area(n);
	unlock_tls();
	return tpd;
}

void
copy_init_base_tpd(struct thread_private_data * dst,
		struct thread_private_data * src)
{
#define cpy_field(f)	do {(dst->f) = (src->f);}while(0)

	cpy_field(first_branch);
	cpy_field(real_branch);
	cpy_field(int80_syscall_entry);
	cpy_field(vdso_syscall_entry);
	cpy_field(real_vdso_syscall_entry);

	memset(&(dst->logger), '\0', sizeof(dst->logger));
	memset(&(dst->code_cache), '\0', sizeof(dst->code_cache));

	memcpy(dst->block_sigmask, src->block_sigmask,
			sizeof(dst->block_sigmask));
	memcpy(dst->unblock_sigmask, src->unblock_sigmask,
			sizeof(dst->unblock_sigmask));
	memcpy(dst->current_sigmask, src->current_sigmask,
			sizeof(dst->current_sigmask));
	memcpy(dst->sigactions, src->sigactions,
			sizeof(dst->sigactions));

	cpy_field(argp_first);
	cpy_field(argp_last);
	cpy_field(conf_trace_fork);
	cpy_field(conf_untrace_clone);
	cpy_field(no_record_signals);

#undef cpy_field
}

void
clone_build_tpd(struct thread_private_data * tpd)
{
	tpd->pid = INTERNAL_SYSCALL_int80(getpid, 0);
	tpd->tid = INTERNAL_SYSCALL_int80(gettid, 0);
	init_code_cache(&tpd->code_cache);
	init_logger(&tpd->logger, tpd->pid, tpd->tid);
}

void
replay_init_tls(unsigned int tnr)
{
	lock_tls();
	setup_tls_area(tnr);
	unlock_tls();
}

static void
unmap_tpd_pages(struct thread_private_data * tpd)
{
	clear_code_cache(&tpd->code_cache);
	close_logger(&tpd->logger);
}

static void
unmap_tpd(struct thread_private_data * tpd)
{
	assert(spin_is_locked(&__tls_ctl_lock));
	int err;
	/* release build don't use tnr */
	unsigned int tnr = tpd->tnr;
	clear_tls_slot(tnr);

	err = INTERNAL_SYSCALL_int80(munmap, 2,
			tpd->tls_base, TLS_STACK_SIZE);
	assert(err == 0);
	DEBUG(TLS, "tls for tnr=%d is cleared\n", tnr);
}

void
clear_tls(void)
{
	struct thread_private_data * tpd = get_tpd();
	unsigned int tnr = tpd->tnr;
	void * stack_base = get_tls_base();
	assert((uint32_t)stack_base == (uint32_t)TNR_TO_STACK(tnr));

	void * cur_esp;
	asm volatile ("movl %%esp, %0" : "=Rm" (cur_esp));
	assert((cur_esp < stack_base) || (cur_esp > stack_base + TLS_STACK_SIZE));

	unmap_tpd_pages(tpd);
	/* unmap this tls */
	lock_tls();
	list_del(&tpd->list);

	/* unmap pages from stack_base to stack_base + TLS_STACK_SIZE */
	/*
	 * FIXME: after tpd structure unmapped, the stack becomes invalidated.
	 */
	unmap_tpd(tpd);

	unlock_tls();
	return;
}

void
update_tls(void)
{
	/* reset pid and tid, reset filename of ckpt and log,
	 * clear (not flush) log data */

	struct thread_private_data * tpd = get_tpd();
	pid_t pid, tid;
	pid = INTERNAL_SYSCALL_int80(getpid, 0);
	tid = INTERNAL_SYSCALL_int80(gettid, 0);
	DEBUG(TLS, "update TLS storage: pid=%d, tid=%d\n",
			tid, pid);

	tpd->pid = pid;
	tpd->tid = tid;

	reset_logger(&tpd->logger, pid, tid);
}

void
unmap_tpds_pages(void)
{
	struct thread_private_data * pos = NULL, *n;
	struct thread_private_data * my_tpd = get_tpd();

	lock_tls();
	list_for_each_entry_safe(pos, n, &tpd_list_head, list) {
		/* remove tls pages */
		unmap_tpd_pages(pos);
		if (pos != my_tpd) {
			list_del(&pos->list);
			unmap_tpd(pos);
		}
	}
	unlock_tls();
}

void
sync_sighandler(int sig)
{
	struct thread_private_data * pos = NULL, *n;
	struct thread_private_data * my_tpd = get_tpd();

	lock_tls();
	list_for_each_entry_safe(pos, n, &tpd_list_head, list) {
		if (pos != my_tpd) {
			memcpy(&(pos->sigactions[sig - 1]),
					&(my_tpd->sigactions[sig - 1]),
					sizeof(struct k_sigaction));
		}
	}
	unlock_tls();
}

// vim:ts=4:sw=4


text:
package com.ejlchina.searcher.group;

import com.ejlchina.searcher.util.LRUCache;
import com.ejlchina.searcher.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * Group 解析器
 * @author Troy.Zhou @ 2022-02-20
 * @since v3.5.0
 */
public class DefaultGroupResolver implements GroupResolver {

    static final Logger log = LoggerFactory.getLogger(DefaultGroupResolver.class);

    static final Group<String> DEFAULT_RAW_GROUP = new Group<>(Group.TYPE_RAW);

    private final Object lock = new Object();

    // LRU 缓存模型
    private LRUCache<Group<String>> cache = new LRUCache<>(50);

    // 是否启用
    private boolean enabled = true;

    private ExprParser.Factory parserFactory = new DefaultParserFactory();

    @Override
    public Group<String> resolve(String gExpr) {
        if (enabled) {
            Group<String> group;
            synchronized (lock) {
                group = cache.get(gExpr);
            }
            if (group == null) {
                group = doResolve(gExpr);
                synchronized (lock) {
                    cache.put(gExpr, group);
                }
            }
            return group;
        }
        return DEFAULT_RAW_GROUP;
    }

    protected Group<String> doResolve(String expr) {
        if (StringUtils.isBlank(expr)) {
            return DEFAULT_RAW_GROUP;
        }
        try {
            return parserFactory.create(expr).parse();
        } catch (Exception e) {
            log.warn("Can not parse expr: [{}], fallback to DEFAULT_RAW_GROUP", expr);
        }
        return DEFAULT_RAW_GROUP;
    }

    @Override
    public ExprParser.Factory getParserFactory() {
        return parserFactory;
    }

    public void setParserFactory(ExprParser.Factory parserFactory) {
        this.parserFactory = parserFactory;
    }

    public LRUCache<Group<String>> getCache() {
        return cache;
    }

    public void setCache(LRUCache<Group<String>> cache) {
        this.cache = Objects.requireNonNull(cache);
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Carex emmonsii Dewey ex Torr.

### Remarks
null


text:
"""Zork configs."""

from __future__ import print_function

BUILD_WORKON_PACKAGES = ('coreboot-zork',)

BUILD_PACKAGES = BUILD_WORKON_PACKAGES + ('chromeos-bootimage',)

# TODO: Remove this line once VBoot is working on Zork.
DEPLOY_SERVO_FORCE_FLASHROM = True

def get_commands(servo):
  """Get specific flash commands for Zork

  Each board needs specific commands including the voltage for Vref, to turn
  on and turn off the SPI flashThe get_*_commands() functions provide a
  board-specific set of commands for these tasks. The voltage for this board
  needs to be set to 1.8 V.

  Args:
    servo (servo_lib.Servo): The servo connected to the target DUT.

  Returns:
    list: [dut_control_on, dut_control_off, flashrom_cmd, futility_cmd]
      dut_control*=2d arrays formmated like [["cmd1", "arg1", "arg2"],
                                             ["cmd2", "arg3", "arg4"]]
                     where cmd1 will be run before cmd2
      flashrom_cmd=command to flash via flashrom
      futility_cmd=command to flash via futility
  """
  dut_control_on = []
  dut_control_off = []
  if servo.is_v2:
    dut_control_on.append([
        'spi2_vref:pp1800',
        'spi2_buf_en:on',
        'spi2_buf_on_flex_en:on',
        'cold_reset:on',
        'servo_present:on',
    ])
    dut_control_off.append([
        'spi2_vref:off',
        'spi2_buf_en:off',
        'spi2_buf_on_flex_en:off',
        'cold_reset:off',
        'servo_present:off',
    ])
    programmer = 'ft2232_spi:type=google-servo-v2,serial=%s' % servo.serial
  elif servo.is_micro:
    dut_control_on.append([
        'spi2_vref:pp1800',
        'spi2_buf_en:on',
        'cold_reset:on',
        'servo_present:on',
    ])
    dut_control_off.append([
        'spi2_vref:off',
        'spi2_buf_en:off',
        'cold_reset:off',
        'servo_present:off',
    ])
    programmer = 'raiden_debug_spi:serial=%s' % servo.serial
  elif servo.is_ccd:
    # Note nothing listed for flashing with ccd_cr50 on go/zork-care.
    # These commands were based off the commands for other boards.
    programmer = 'raiden_debug_spi:target=AP,serial=%s' % servo.serial
  else:
    raise Exception('%s not supported' % servo.version)

  flashrom_cmd = ['flashrom', '-p', programmer, '-w']
  futility_cmd = ['futility', 'update', '-p', programmer, '-i']

  return [dut_control_on, dut_control_off, flashrom_cmd, futility_cmd]


text:
package kg.apc.jmeter.gui;

import java.awt.Dimension;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public abstract class JAbsrtactDialogPanel extends JPanel{
    private int minWidth = 0;

    public int getMinWidth() {
        return minWidth;
    }

    public void setMinWidth(int minWidth) {
        this.minWidth = minWidth;
    }

    protected void repack() {
        JDialog dlgParent = getAssociatedDialog();
        if(dlgParent != null) {
            Dimension newSize = dlgParent.getPreferredSize();
            if(newSize.width < minWidth) {
                newSize.width = minWidth;
            }
            dlgParent.setSize(newSize);
            dlgParent.validate();
        }
    }

    protected JDialog getAssociatedDialog() {
        return (JDialog)SwingUtilities.getWindowAncestor(this);
    }

}


text:
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<script src="https://cdn.firebase.com/js/client/2.2.4/firebase.js"></script>
	<title></title>
	 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
	 <script type="text/javascript" src="app/login.js"></script>
</head>

<body ng-controller="postController">

</body>
</html>


text:
package jsonbroker.library.server.channel;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import jsonbroker.library.common.channel.Channel;
import jsonbroker.library.common.channel.SocketChannel;
import jsonbroker.library.common.exception.BaseException;
import jsonbroker.library.common.log.Log;

public class SocketServerChannel implements ServerChannel {

	private static Log log = Log.getLog( SocketServerChannel.class );

	public static final int DEFAULT_PORT = 8082;

	ServerSocket _serverSocket;

	public SocketServerChannel( int port ) {

		try {
			_serverSocket = new ServerSocket( port );
		} catch (IOException e) {
			throw new BaseException(this, e);
		}
	}

	// returns null if the channel has been 'close'd down
	public Channel accept() {

		if( null == _serverSocket ) {
			return null;
		}

		if( _serverSocket.isClosed() ) {
			return null;
		}

		try {
			Socket socket = _serverSocket.accept();
			return new SocketChannel( socket );

		} catch (IOException e) {

			throw new BaseException(this, e);

		}
	}

	public void close( boolean ignoreErrors ) {

		if( null == _serverSocket ) {
			return;
		}

		if( _serverSocket.isClosed() ) {
			return;
		}

		try {
			_serverSocket.close();

		} catch (IOException e) {

			if( ignoreErrors ) {
				log.warn( e );
			} else {
				throw new BaseException(this, e);
			}
		}
	}

}


text:
#ifndef OpenSkyOperation_OSOOperation_h
#define OpenSkyOperation_OSOOperation_h

@import Foundation;

@protocol OSOOperationObserver;

@class OSOErrorCollection;

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSInteger, OSOOperationState) {
    OSOOperationStateInitialized = 0,
    OSOOperationStatePending     = 1,
    OSOOperationStateReady       = 2,
    OSOOperationStateExecuting   = 3,
    OSOOperationStateFinishing   = 4,
    OSOOperationStateFinished    = 5
};

@interface OSOOperation : NSOperation

- (instancetype)init NS_DESIGNATED_INITIALIZER;

@property (nonatomic, assign, readonly) OSOOperationState state;

- (nullable NSArray<NSError *> *)allErrors;

- (void)willEnqueue;

// MARK: - Observers
- (void)addOperationObserver:(id<OSOOperationObserver>)observer;
- (void)removeOperationObserver:(id<OSOOperationObserver>)observer;
- (nullable NSArray<id<OSOOperationObserver>> *)allOperationObservers;

@end

/**
 *  Override these methods in your subclass to provide custom functionality
 */
@interface OSOOperation (SubclassingHooks)

/**
 *  Override this method in your sublcass to do your work.
 */
- (void)execute;

/**
 *  This method can be overridden if you need to do specific cleanup or error handling.
 *
 *  @param errors The errors the operation finished with.
 */
- (void)operationDidCompleteWithErrors:(nullable NSArray<NSError *> *)errors NS_REQUIRES_SUPER;

/**
 *  If an operation needs other operations to complete before being run a subclass can create them here.
 *
 *  They will be automatically enqueued & added as a pre-requisite of the generating operation.
 *
 *  @return An array of operations or nil
 */
- (nullable NSArray<__kindof OSOOperation *> *)createDependencies;

@end

/**
 *  Methods defined here should be treated as `final` and should not be overridden
 */
@interface OSOOperation (HelperMethods)

- (void)finishOperation;
- (void)finishOperationWithError:(nullable NSError *)error;
- (void)finishOperationWithErrors:(nullable NSArray<NSError *> *)errors;

@end

FOUNDATION_EXTERN NSString *const OSOOperationErrorDomain;
typedef NS_ENUM(NSInteger, OSOOperationError) {
    OSOOperationErrorCanceled = 0
};

FOUNDATION_EXTERN BOOL OSOOperationCanTransitionToState(OSOOperationState, OSOOperationState, BOOL);

NS_ASSUME_NONNULL_END

#endif


text:
    <title><%= appName %></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" >


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
    <!--
    This file contains additional configuration written by modules in the NetBeans IDE.
    The configuration is intended to be shared among all the users of project and
    therefore it is assumed to be part of version control checkout.
    Without this configuration present, some functionality in the IDE may be limited or fail altogether.
    -->
    <properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
        <!--
        Properties that influence various parts of the IDE, especially code formatting and the like.
        You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
        That way multiple projects can share the same settings (useful for formatting rules for example).
        Any value defined here will override the pom.xml file value but is only applicable to the current project.
        -->
        <netbeans.hint.license>apache20</netbeans.hint.license>
        <org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>1.7-web</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>
        <org-netbeans-modules-maven-j2ee.netbeans_2e_deploy_2e_on_2e_save>false</org-netbeans-modules-maven-j2ee.netbeans_2e_deploy_2e_on_2e_save>
        <netbeans.compile.on.save>all</netbeans.compile.on.save>
        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>*;static *</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder>
        <org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateStaticImports>true</org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateStaticImports>
        <org-netbeans-modules-editor-indent.CodeStyle.usedProfile>project</org-netbeans-modules-editor-indent.CodeStyle.usedProfile>
        <org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>4</org-netbeans-modules-editor-indent.CodeStyle.project.tab-size>
        <netbeans.checkstyle.format>true</netbeans.checkstyle.format>
        <com-junichi11-netbeans-changelf.enable>true</com-junichi11-netbeans-changelf.enable>
        <com-junichi11-netbeans-changelf.use-project>true</com-junichi11-netbeans-changelf.use-project>
        <com-junichi11-netbeans-changelf.lf-kind>LF</com-junichi11-netbeans-changelf.lf-kind>
        <com-junichi11-netbeans-changelf.use-global>false</com-junichi11-netbeans-changelf.use-global>
        <org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>words</org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap>
        <org-netbeans-modules-maven-jaxws.rest_2e_config_2e_type>ide</org-netbeans-modules-maven-jaxws.rest_2e_config_2e_type>
        <org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>80</org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width>
    </properties>
</project-shared-configuration>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements. See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You 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.
  -->
<management-context xmlns="http://activemq.org/schema">
   <connector
         connector-port="1099"
         connector-host="localhost"
         secured="true"
         key-store-path="${data.dir}/../etc/activemq.example.keystore"
         key-store-password="activemqexample"
         trust-store-path="${data.dir}/../etc/activemq.example.truststore"
         trust-store-password="activemqexample"/>
   <authorisation>
      <whitelist>
         <entry domain="hawtio"/>
      </whitelist>
      <default-access>
         <access method="list*" roles="view,update,amq,guest"/>
         <access method="get*" roles="view,update,amq,guest"/>
         <access method="is*" roles="view,update,amq,guest"/>
         <access method="set*" roles="update,amq,guest"/>
         <access method="*" roles="amq,guest"/>
      </default-access>
      <role-access>
         <match domain="org.apache.activemq.artemis">
            <access method="list*" roles="view,update,amq,guest"/>
            <access method="get*" roles="view,update,amq,guest"/>
            <access method="is*" roles="view,update,amq,guest"/>
            <access method="set*" roles="update,amq,guest"/>
            <access method="*" roles="amq,guest"/>
         </match>
         <!--example of how to configure a specific object-->
         <!--<match domain="org.apache.activemq.artemis" key="subcomponent=queues">
            <access method="list*" roles="view,update,amq"/>
            <access method="get*" roles="view,update,amq"/>
            <access method="is*" roles="view,update,amq"/>
            <access method="set*" roles="update,amq"/>
            <access method="*" roles="amq"/>
         </match>-->
      </role-access>
   </authorisation>
</management-context>


text:
var Request = function() {
	this.init();
};

Request.prototype = {
	init: function() {
		this.xhr = new XMLHttpRequest();
	},

	post: function(url, params, done) {
		var csrfToken = this.getCsrfToken();
		var paymentToken = this.getPaymentToken();
		var xhr = this.xhr;

		if (csrfToken !== undefined && csrfToken !== '') {
			xhr.open('POST', url);
			xhr.setRequestHeader('Content-Type', 'application/json');
			xhr.setRequestHeader("X-CSRF-TOKEN", csrfToken);
			xhr.setRequestHeader("X-PAYMENT-TOKEN", paymentToken);
			xhr.onload = function() {
				done(xhr.status !== 200, xhr.response || 'An unknown error occurred');
			};
			this.xhr.send(params);
		} else {
			done(true);
		}
	},

	get: function(url, done) {
		var csrfToken = this.getCsrfToken();
		var xhr = this.xhr;

		if (csrfToken !== undefined && csrfToken !== '') {
			xhr.open('GET', url);
			xhr.setRequestHeader('Content-Type', 'application/json');
			xhr.setRequestHeader("X-CSRF-TOKEN", csrfToken);
			xhr.onload = function() {
				done(xhr.status !== 200, xhr.response || 'An unknown error occurred');
			};
			this.xhr.send();
		} else {
			done(true);
		}
	},

	getPaymentToken: function() {
		var elem = document.getElementById('token');
		var token = '';

		if (elem !== undefined) {
			token = document.getElementById('token').value;
		}

		return token;
	},

	getCsrfToken: function() {
		var elem = document.getElementById('csrf');
		var token = '';

		if (elem !== undefined) {
			token = document.getElementById('csrf').value;
		}

		return token;
	}
};


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Feed',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date', models.DateTimeField(auto_now_add=True)),
                ('post', models.TextField(max_length=255)),
                ('likes', models.IntegerField(default=0)),
                ('comments', models.IntegerField(default=0)),
                ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='feeds.Feed')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('-date',),
                'verbose_name': 'Feed',
                'verbose_name_plural': 'Feeds',
            },
        ),
    ]


text:
<?php

// Include the initialization file
require_once dirname(dirname(__FILE__)) . '/init.php';
require_once UTIL_PATH . '/ErrorUtils.php';

// Enter parameters required by the code example.
$adGroupId = 'INSERT_AD_GROUP_ID_HERE';

/**
 * Runs the example.
 * @param AdWordsUser $user the user to run the example with
 * @param string $adGroupId the ID of the ad group to hypothetically add the
 *     text ad to
 */
function ValidateTextAdExample(AdWordsUser $user, $adGroupId) {
  // Get the service, which loads the required classes. Passing true for the
  // parameter $validateOnly will ensure that ads aren't created.
  $adGroupAdValidationService =
      $user->GetService('AdGroupAdService', ADWORDS_VERSION, null, null, true);

  // Create invalid text ad.
  $textAd = new TextAd();
  $textAd->headline = 'This headline is too long and will cause an error';
  $textAd->description1 = 'Description Line 1';
  $textAd->description2 = 'Description Line 2';
  $textAd->displayUrl = 'www.example.com';
  $textAd->finalUrls = array('http://www.example.com');

  // Create ad group ad.
  $adGroupAd = new AdGroupAd();
  $adGroupAd->adGroupId = $adGroupId;
  $adGroupAd->ad = $textAd;

  // Create operation.
  $operation = new AdGroupAdOperation();
  $operation->operand = $adGroupAd;
  $operation->operator = 'ADD';

  $operations = array($operation);

  // Make the mutate request.
  try {
    $result = $adGroupAdValidationService->mutate($operations);
    printf("The text ad is valid.\n");
  } catch (SoapFault $e) {
    $errors = ErrorUtils::GetApiErrors($e);
    if (sizeof($errors) > 0) {
      printf("The text ad is invalid for the following reasons:\n");
      foreach ($errors as $error) {
        printf("  %s @ %s\n", $error->errorString, $error->fieldPath);
      }
    } else {
      // Not an API error, so throw it up a level.
      throw $e;
    }
  }
}

// Don't run the example if the file is being included.
if (__FILE__ != realpath($_SERVER['PHP_SELF'])) {
  return;
}

try {
  // Get AdWordsUser from credentials in "../auth.ini"
  // relative to the AdWordsUser.php file's directory.
  $user = new AdWordsUser();

  // Log every SOAP XML request and response.
  $user->LogAll();

  // Run the example.
  ValidateTextAdExample($user, $adGroupId);
} catch (Exception $e) {
  printf("An error has occurred: %s\n", $e->getMessage());
}


text:
package com.google.api.services.datastore.client;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;

import java.util.Arrays;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

/**
 * Client factory for {@link Datastore}.
 *
 */
abstract class BaseDatastoreFactory<T> {

  // Non-javadoc.
  // This class allows RemoteRpc to be used by factory implementations defined
  // outside of this package.
  public static class RemoteRpc
      extends com.google.api.services.datastore.client.RemoteRpc {
    public RemoteRpc(HttpRequestFactory client, HttpRequestInitializer initializer, String url) {
      super(client, initializer, url);
    }
  }

  private static final Logger logger = Logger.getLogger(BaseDatastoreFactory.class.getName());

  // Lazy load this because we might be running inside App Engine and this
  // class isn't on the whitelist.
  private static ConsoleHandler methodHandler;

  protected abstract String buildUrl(DatastoreOptions options, String overrideUrl);
  public abstract T create(DatastoreOptions options) throws IllegalArgumentException;

  // TODO(user): Support something other than console handler for when we're
  // running in App Engine
  private static synchronized StreamHandler getStreamHandler() {
    if (methodHandler == null) {
      methodHandler = new ConsoleHandler();
      methodHandler.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
          return record.getMessage() + "\n";
        }
      });
      methodHandler.setLevel(Level.FINE);
    }
    return methodHandler;
  }

  protected BaseDatastoreFactory() { }

  protected RemoteRpc
      newRemoteRpc(DatastoreOptions options) {
    return newRemoteRpc(options, System.getenv("DATASTORE_URL_INTERNAL_OVERRIDE"));
  }

  protected RemoteRpc newRemoteRpc(DatastoreOptions options, String  urlOverride) {
    if (options == null) {
      throw new IllegalArgumentException("options not set");
    }
    HttpRequestFactory client = makeClient(options);
    return new RemoteRpc(client, options.getInitializer(), buildUrl(options, urlOverride));
  }

  /**
   * Constructs a Google APIs HTTP client with the associated credentials.
   */
  public HttpRequestFactory makeClient(DatastoreOptions options) {
    Credential credential = options.getCredential();
    if (credential == null) {
      logger.warning("Not using any credentials");
    }
    HttpTransport transport = options.getTransport();
    if (transport == null) {
      transport = credential == null ? new NetHttpTransport() : credential.getTransport();
    }
    return transport.createRequestFactory(credential);
  }

  /**
   * Starts logging datastore method calls to the console. (Useful within tests.)
   */
  public static void logMethodCalls() {
    Logger logger = Logger.getLogger(Datastore.class.getName());
    logger.setLevel(Level.FINE);
    if (!Arrays.asList(logger.getHandlers()).contains(getStreamHandler())) {
      logger.addHandler(getStreamHandler());
    }
  }
}


text:
/**
 * Created by PC on 10/23/2016.
 */
angular.module('myApp')
    .config(function ($stateProvider) {
        $stateProvider.state('category', {
            url: '/category/id=:id',
            parent: 'site',
            views: {
                'content@': {
                    templateUrl: 'src/scripts/user/category/category.html',
                    controller: 'CategoryController'
                }
            }
        })
    });


text:
package net.givelives.givelives.utility;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import net.givelives.givelives.R;

/**
 * Created by MainAcc on 3/12/2017.
 */

public class AboutUsFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater= LayoutInflater.from(getContext());
        View view=inflater.inflate(R.layout.nav_about_us, null);
        TextView textview=(TextView)view.findViewById(R.id.textmsg);
        textview.setText(formatDonationInstructionDetails(getResources()));

        // make the link inside the message clickable
        textview.setMovementMethod(LinkMovementMethod.getInstance());

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.about_us_title))
                .setView(view)
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
        // Create the AlertDialog object and return it
        return builder.create();
    }

    /**
     * Helper method to format the text nicely.
     */
    private static Spanned formatDonationInstructionDetails(Resources res) {
        return Html.fromHtml(res.getString(R.string.about_us_msg));
    }
}


text:
using System;
using IniParser.Model;
using IniParser.Parser;
using NUnit.Framework;

namespace IniFileParser.Tests.Unit.Parser
{
    [TestFixture]
    public class ParserDefaultConfigurationTests
    {

        string iniFileStr =
@"
global key = global value
;comment for section1
[section1]
;comment for key1
key 1 =      value 1
key;2 = va:lu;e.5
[ section 2]
;comment for myKey1
mykey1 = value1
;comment for section2
";

        [Test]
        public void check_data_correctly_parsed()
        {
            var parser = new IniDataParser();
            IniData data = parser.Parse(iniFileStr);

            Assert.That(data, Is.Not.Null);

            // Check global section

            Assert.That(data.Global["global key"], Is.EqualTo("global value"));

            // global section is not computed when counting the number of sections in the
            // ini
            Assert.That(data.Sections.Count, Is.EqualTo(2),"Expected two (2) sections");
            var section1 = data.Sections.GetSectionData("section1");

            Assert.That(section1, Is.Not.Null);
            Assert.That(section1.SectionName, Is.EqualTo("section1"));
            Assert.That(section1.LeadingComments, Is.Not.Empty);
            Assert.That(section1.LeadingComments.Count, Is.EqualTo(1));

            Assert.That(section1.Keys, Is.Not.Null);
            Assert.That(section1.Keys.Count, Is.EqualTo(2));
            Assert.That(section1.Keys.GetKeyData("key 1"), Is.Not.Null);

            // Check keys / values with spaces. Leading & trailing whitespace ignored
            Assert.That(section1.Keys["key 1"], Is.EqualTo("value 1"));

            Assert.That(section1.Keys.GetKeyData("key;2"), Is.Not.Null);
            // Check special characters as part of the key/value name
            Assert.That(section1.Keys["key;2"], Is.EqualTo("va:lu;e.5"));

            //
            var section2 = data.Sections.GetSectionData("section2");
            // Bad section name
            Assert.That(section2, Is.Null);

            // Beware: leading and trailing whitespaces are ignored!
            section2 = data.Sections.GetSectionData("section 2");
            Assert.That(section2, Is.Not.Null);
            Assert.That(section2.SectionName, Is.EqualTo("section 2"));
            Assert.That(section2.LeadingComments, Is.Empty);
            Assert.That(section2.TrailingComments, Is.Not.Empty);
            Assert.That(section2.Comments, Is.Not.Empty);

            // Check comments at the end of the section are parsed and assigned to the section
            Assert.That(section2.TrailingComments.Count, Is.EqualTo(1));
            Assert.That(section2.TrailingComments[0], Is.EqualTo("comment for section2"));
        }

        [Test]
        public void check_ini_writing()
        {
            IniData data =  new IniDataParser().Parse(iniFileStr);

            // ini file string with not-needed whitespace trimmed
            var dataAsString = data.ToString();

            // Generates a valid data file
            IniData data2 = new IniDataParser().Parse(dataAsString);

            // check all strings are equal
            Assert.That(dataAsString, Is.EqualTo(data2.ToString()));
        }
    }
}


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

class Dashboard extends Secure_Controller {

	public function index()
	{
		$this->template->build('admin/dashboard/index');
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<title>jimix</title>
	<meta name="description" content="A Dashboard for your metrics"/>


text:
module TrafficSpy
  class Response
    attr_accessor :status, :body

    DEFAULT_STATUS_CODE = 200
    DEFAULT_BODY = ""

    def initialize(input = {})
      @status = input[:status] || DEFAULT_STATUS_CODE
      @body = input[:body] || DEFAULT_BODY
    end
  end
end


text:
<?php header('Content-Type: text/html; charset=UTF-8;');
    header('Access-Control-Allow-Origin: *');
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
?>

<?php
    // PHP-скрипт, добавляющий заказ в базу данных
    class Order {
        var $id;
        var $firstName;
        var $secondName;
        var $address;
        var $products;
        var $price;
        var $status;
        var $comment;

        function __construct($id, $firstName, $secondName, $address, $products, $price, $status) {
            $this->id = $id;
            $this->firstName = $firstName;
            $this->secondName = $secondName;
            $this->address = $address;
            $this->products = $products;
            $this->price = $price;
            $this->status = $status;
            $this->comment = null;
        }
    }

    $connection = mysqli_connect("fdb16.freehostingeu.com", "2364885_foof", "uLXznx4vwD", "2364885_foof");
    mysqli_set_charset($connection, "utf8");

    if(isset($_POST['dataAboutUser'])) {
        $dataAboutUser = json_decode($_POST['dataAboutUser']);
        $firstName = $dataAboutUser->firstName;
        $secondName = $dataAboutUser->secondName;
        $phone = $dataAboutUser->phone;
        $mail = $dataAboutUser->mail;
        $address = $dataAboutUser->address;
        $products = json_decode($_POST['products']);
        $postProducts = [];
        $price = 0;
        $androidId = $dataAboutUser->androidId;
        $status = "1";
        for($i = 0; $i < sizeof($products); $i++) {
            $price += $products[$i]->price;
            $postProducts[$i] = $products[$i]->product;
        }
        $cost = json_encode($price);
        $products = json_encode($postProducts, JSON_UNESCAPED_UNICODE);
        mysqli_query($connection, "INSERT INTO orders (firstName, secondName, phone, mail, address, products, price, androidId, status) VALUES
                                    ('$firstName','$secondName','$phone','$mail','$address','$products','$cost','$androidId','$status')");
        $id = json_encode(mysqli_insert_id($connection));
        $result = mysqli_query($connection, "SELECT * FROM users WHERE login='$mail'");
        if($result != null) {
            $row = mysqli_fetch_row($result);
            $orders = json_decode($row[4], true);
            $bonus = json_decode($row[5]);
            $bonus += $price*0.1;
            $bonus = json_encode($bonus);
            array_push($orders, new Order($id, $firstName, $secondName, $address, $products, $cost, $status));
            if($orders==null)
                $orders = [];
            $orders = json_encode($orders);
            mysqli_query($connection, "UPDATE users SET orders='".mysqli_real_escape_string($connection, $orders)."', bonus='$bonus' WHERE login='$mail'");
        }
    }
?>


text:
import { inject, TestBed } from '@angular/core/testing';
import { ApplicationService } from './application.service';
import { HttpModule } from '@angular/http';

describe('ApiService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [ApplicationService],
      imports: [HttpModule]
    });
  });

  it('should be created', inject([ApplicationService], (service: ApplicationService) => {
    expect(service).toBeTruthy();
  }));
});


text:
MAGDHOW1 ;WOIFO/PMK/DAC - Capture Consult/Procedure Request data ;09 Aug 2018 7:54 AM
 ;;3.0;IMAGING;**138,174,180,210,208**;Mar 19, 2002;Build 6
 ;; Per VHA Directive 2004-038, this routine should not be modified.
 ;; +---------------------------------------------------------------+
 ;; | Property of the US Government.                                |
 ;; | No permission to copy or redistribute this software is given. |
 ;; | Use of unreleased versions of this software requires the user |
 ;; | to execute a written test agreement with the VistA Imaging    |
 ;; | Development Office of the Department of Veterans Affairs,     |
 ;; | telephone (301) 734-0100.                                     |
 ;; | The Food and Drug Administration classifies this software as  |
 ;; | a medical device.  As such, it may not be changed in any way. |
 ;; | Modifications to this software may result in an adulterated   |
 ;; | medical device under 21CFR820, the use of which is considered |
 ;; | to be a violation of US Federal Statutes.                     |
 ;; +---------------------------------------------------------------+
 ;;
 ;
 ; Supported IA #10006 reference ^DIC routine call
 ; Supported IA #2056 reference $$GET1^DIQ function call
 ; Supported IA #10103 reference $$NOW^XLFDT function call
 ; Controlled IA #4110 to read REQUEST/CONSULTATION file (#123)
 ; Supported IA #6925 to read HLO SUBSCRIPTION REGISTRY (#779.4)
 ;
MSGSETUP(GMRCIEN,SERVICE,ORC1,ORC5,APTSCHED) ; called by ^MAGDHOWC and ^MAGDHOWS
 ; setup to send a message, if required
 N CONSULT,CPTIEN,DATETIME,DIVISION,FMDATE,FMDATETM
 N HL7SUBLIST,I,ITYPCODE,ITYPNAME,MSGTYPE,OBXSEGNO
 N ORCTRL,ORSTATUS,ORIGSERV,PARMS,SEGMENT,SENDIT,X,Y,Z
 ;
 S FMDATETM=$$NOW^XLFDT(),FMDATE=FMDATETM\1
 S MSGTYPE="ORM" ; HL7 message type for orders
 ;
 ; decide if service is one that requires HL7->DICOM gateway and PACS
 ;
 S SENDIT=$$SERVICE(SERVICE,GMRCIEN,.DIVISION,.ITYPNAME,.ITYPCODE,.CPTIEN,.HL7SUBLIST)
 ;
 I SENDIT D  ; send this transaction via HL7 to DICOM gateway and PACS
 . ; check for an "OK" order control value which indicates a new order
 . I ORC1="OK" D
 . . S ORCTRL="NW" ; order control
 . . S ORSTATUS="IP" ; order status
 . . Q
 . ;
 . ; check for a cancelled or discontinued request
 . E  I " CA CR DR OC OD "[(" "_ORC1_" ") D
 . . ; P210 DAC - Instead of Killing FILLER2, it will now be set to cancelled
 . . S FILLER2="GMRC-CANCELLED"
 . . S ORCTRL="CA" ; order control
 . . S ORSTATUS="CA" ; order status
 . . Q
 . ;
 . ; check for scheduled request (set in ^MAGDHOWS)
 . E  I ORC1="XO",ORC5="SC" D
 . . S ORCTRL="XO" ; order control
 . . S ORSTATUS="SC" ; order status
 . . Q
 . ;
 . ; look for a result message
 . E  I ORC1="RE" D  ; result
 . . S MSGTYPE="ORU" ; HL7 message type for results
 . . ;
 . . I (ORC5="A")!($$UNSIGNED^MAGDGMRC(GMRCIEN)) D  ; P180 DAC - Process unsigned TIU notes
 . . . S FILLER2="GMRC-NEW UNSIGNED RESULT"
 . . . S ORCTRL="RE" ; order control
 . . . S ORSTATUS="A" ; order status
 . . . Q
 . . E  D  ; new signed TIU note
 . . . K FILLER2 ; P174 DAC - remove any preset status like GMRC-SCHEDULED set in CHECKAPT^MAGDHOWC
 . . . S ORCTRL="RE" ; order control
 . . . S ORSTATUS="CM" ; order status
 . . . Q
 . . Q
 . ;
 . E  D  ; default
 . . S ORCTRL="SC" ; order control
 . . S ORSTATUS="IP" ; order status
 . . Q
 . D MESSAGE^MAGDHOW2(SERVICE)
 . Q
 ;
 I ORC1="RE" D  ; do this for all consult results
 . ; link any outstanding DICOM images to the new TIU note
 . S I=$$NEWTIU^MAGDHOW0(GMRCIEN)
 . Q
 ;
 Q
 ;
SERVICE(SERVICE,GMRCIEN,DIVISION,ITYPNAME,ITYPCODE,CPTIEN,HL7SUBLIST) ;
 ; check if the service is in the DICOM Clinical Service dictionary, and
 ; if so, then get all of the attributes
 N MWLCONFIG,SENDIT,X,Y,Z
 S (DIVISION,ITYPNAME,ITYPCODE,CPTIEN,HL7SUBLIST,SENDIT)=0
 I SERVICE D  ; ignore SERVICE if it is null
 . S MWLCONFIG=$$MWLFIND(SERVICE,GMRCIEN)
 . S DIVISION=""
 . I MWLCONFIG D  ; send order
 . . S X=$G(^MAG(2006.5831,MWLCONFIG,0))
 . . S DIVISION=$P(X,"^",5),CPTIEN=$P(X,"^",6),HL7SUBLIST=$P(X,"^",7)
 . . I HL7SUBLIST,$$GET1^DIQ(779.4,HL7SUBLIST,.01)="" S HL7SUBLIST=0 ; absent
 . . I 'HL7SUBLIST D  ; lookup default HL7 subscription list
 . . . N DIC,DO,X,Y
 . . . S DIC=779.4,DIC(0)="BX",X="MAGD DEFAULT" D ^DIC
 . . . S HL7SUBLIST=$P(Y,"^",1) ; Y should equal "<ien>^MAGD DEFAULT"
 . . . Q
 . . ; get specialty index and procedure index (if available, otherwise, use 0)
 . . S Y=$P(X,"^",3)
 . . S ITYPNAME=$P(^MAG(2005.84,Y,0),"^",1)
 . . S ITYPCODE=$P(^MAG(2005.84,Y,2),"^",1)
 . . S Z=$P(X,"^",4)
 . . I Z D  ; get procedure name and code
 . . . S ITYPNAME=ITYPNAME_" -- "_$P(^MAG(2005.85,Z,0),"^",1)
 . . . S ITYPCODE=ITYPCODE_"/"_$P(^MAG(2005.85,Z,2),"^",1)
 . . . Q
 . . S SENDIT=1
 . . Q
 . Q
 Q SENDIT
 ;
MWLFIND(SERVICE,GMRCIEN) ; lookup 2006.5831 entry by service and procedure
 ; ordering a procedure and the 2006.5831 procedure entry are optional
 N PROCEDURE
 S PROCEDURE=+$$GET1^DIQ(123,GMRCIEN,4,"I")
 Q $$IREQUEST(SERVICE,PROCEDURE) ; pointer to modality worklist dictionary file #2006.5831
 ;
IREQUEST(SERVICE,PROCEDURE) ; return the IEN of the consult or procedure for the request service
 N IEN,LIST
 ;
 S SERVICE=$G(SERVICE) I 'SERVICE Q 0
 ;
 ; if this is a lookup for a procedure, just return the "C" cross reference
 S PROCEDURE=$G(PROCEDURE)
 I PROCEDURE Q $O(^MAG(2006.5831,"C",SERVICE,PROCEDURE,""))
 ;
 ; use the "B" cross reference to make a list of all IENs for the request service
 S IEN="" F  S IEN=$O(^MAG(2006.5831,"B",SERVICE,IEN)) Q:IEN=""  S LIST(IEN)=""
 ;
 ; use the "C" cross reference to delete the IENs for the procedures
 S PROCEDURE="" F  S PROCEDURE=$O(^MAG(2006.5831,"C",SERVICE,PROCEDURE)) Q:PROCEDURE=""  D
 . S IEN=$O(^MAG(2006.5831,"C",SERVICE,PROCEDURE,""))
 . K LIST(IEN) ; remove the procedures from the list
 . Q
 ;
 ; return what is left in the list, which should be the consult, if there is one
 Q $O(LIST(""))


text:
using System;

namespace TITcs.SharePoint.SSOM
{
    public interface ISharePointItem
    {
        int Id { get; set; }
        DateTime Created { get; set; }
        Lookup Author { get; set; }
    }
}


text:
using System;

namespace EyeCT4RailsLogic.Exceptions
{
    /// <summary>
    /// An exception that will be caught and rethrown be the FilterCustomException method.
    /// </summary>
    public class CustomException : Exception
    {
        public CustomException(string message) : base(message)
        {

        }

        public CustomException(string message, Exception innerException) : base(message, innerException)
        {

        }
    }
}


text:
package org.lwjgl.util;

/**
 * Readonly interface for Dimensions
 * @author $Author$
 * @version $Revision$
 * $Id$
 */
public interface ReadableDimension {

	/**
	 * Get the width
	 * @return int
	 */
	int getWidth();

	/**
	 * Get the height
	 * @return int
	 */
	int getHeight();

	/**
	 * Copy this ReadableDimension into a destination Dimension
	 * @param dest The destination
	 */
	void getSize(WritableDimension dest);

}


text:
using System;
using System.Globalization;

namespace PowerLib.System
{
	public struct LongRange : IFormattable
	{
		public static readonly LongRange[] Empty = new LongRange[0];
		private long _index;
		private long _count;

		#region Constructors

		public LongRange(long index, long count)
		{
			_index = index;
			_count = count;
		}

		#endregion
		#region Properties

		public long Index
		{
			get
			{
				return _index;
			}
			set
			{
				_index = value ;
			}
		}

		public long Count
		{
			get
			{
				return _count;
			}
			set
			{
				_count = value ;
			}
		}

    #endregion
    #region Methods

    public static LongRange Parse(string s)
    {
      return Parse(s, NumberStyles.Integer, null);
    }

    public static LongRange Parse(string s, NumberStyles styles)
    {
      return Parse(s, styles, null);
    }

    public static LongRange Parse(string s, IFormatProvider formatProvider)
    {
      return Parse(s, NumberStyles.Integer, formatProvider);
    }

    public static LongRange Parse(string s, NumberStyles styles, IFormatProvider formatProvider)
    {
      LongRange result;
      if (!TryParse(s, styles, formatProvider, out result))
        throw new FormatException("Invalid input string");
      return result;
    }

    public static bool TryParse(string s, out LongRange result)
    {
      return TryParse(s, NumberStyles.Integer, null, out result);
    }

    public static bool TryParse(string s, NumberStyles styles, out LongRange result)
    {
      return TryParse(s, styles, null, out result);
    }

    public static bool TryParse(string s, IFormatProvider provider, out LongRange result)
    {
      return TryParse(s, NumberStyles.Integer, provider, out result);
    }

    public static bool TryParse(string s, NumberStyles styles, IFormatProvider provider, out LongRange result)
    {
      return LongRangeParseFormatInfo.Default.TryParse(s, styles, provider, out result);
    }

    public override string ToString()
    {
      return LongRangeParseFormatInfo.Default.Format(this, null, null);
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
      return LongRangeParseFormatInfo.Default.Format(this, format, formatProvider);
    }

    #endregion
  }
}


text:
- ## Teacher: 刘鹏远/Liu Pengyuan
- ## Wechat: ![wechat_me](https://github.com/liupengyuan/python_tutorial/blob/master/pic/wechat_liupengyuan.jpg)
- ## Office: 主南310
- ## Assistant: 竺成浩/Zhu Chenghao(Only for undergraduate)
---
# content
- ## Python fundamental
- ## Statistics fundamental
- ## Pandas basic
- ## Matplotlib basic
- ## Seaborn basic
- ## Linux+vim basic
- ## Web crawler basic
- ## Flask+echarts+nginx+gornicorn basic
---
# course material
- ## This python_tutorial(https://github.com/liupengyuan)
- ## Pandas for Data Analysis(by Wes McKinney)
- ## 统计学(by William Mendenhall)
- ## 爱上统计学(Statistics for people who hate statistics, by Neil J. Salkind)
- ## 可汗学院公开课:统计学
- ## 各类官方文档
---
# Grading standards
- ## Homework(Weekly)                                                   20%
- ## Tutorial of tools or intorduction data and related paper(Monthly)  10%(for computer students)
- ## Introduction of corpus and related paper(Monthly)  10%(for other students)
- ## Team project(visualization platform + E/C document + E/C paper)    70%(3 students/team)

# About the project
- ## Title: Designed by yourself.
- ## Advice: 1. According to your interest. 2. Choosing a Topic from other lesson. 3. Discuss with your classmate. 4. From me.
- ## data
  - ## Available Data(I'll talk it later):
    - ## 1. DCC
    - ## 2. 网络文学语料库
  - ## Data needs to be crawled:
    - ## 1. Diachronic Chinese literature text(Try to find some available website)
    - ## 2. Diachronic Foreign literature text(in Chinese)
    - ## 3. parallel sentences in dict.youdao.com and cn.bing.com/dict/
  - ## Other any data
- ## Presentation and submission
 - ## Introduction and Q/A 15-20 mins /team
 - ## presentation 30 mins /team
 - ## Submission deadline: 2018.01.24  24:00


text:
User
====

.. java:package:: uk.ac.ox.it.cha.auth
   :noindex:

.. java:type:: public class User

   :author: martinfilliau

Constructors
------------
User
^^^^

.. java:constructor:: public User(String username)
   :outertype: User

Methods
-------
getPassword
^^^^^^^^^^^

.. java:method:: public String getPassword()
   :outertype: User

getUsername
^^^^^^^^^^^

.. java:method:: public String getUsername()
   :outertype: User

setPassword
^^^^^^^^^^^

.. java:method:: public void setPassword(String password)
   :outertype: User

setUsername
^^^^^^^^^^^

.. java:method:: public void setUsername(String username)
   :outertype: User


text:
package io.fundrequest.notification;

import io.fundrequest.common.infrastructure.mapping.BaseMapper;
import io.fundrequest.notification.domain.RequestFundedNotification;
import io.fundrequest.notification.dto.RequestFundedNotificationDto;
import org.springframework.stereotype.Component;

@Component
public class RequestFundedNotificationMapper implements BaseMapper<RequestFundedNotificationDto, RequestFundedNotification> {

    @Override
    public RequestFundedNotification map(final RequestFundedNotificationDto notificationDto) {
        return new RequestFundedNotification(notificationDto.getUuid(), notificationDto.getBlockchainEventId(), notificationDto.getDate(), notificationDto.getRequestId(), notificationDto.getFundId());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using HST.Core.Utils;

namespace HST.Converters
{
    public class WeightConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var weight = double.Parse(value.ToString());
            var type = parameter.ToString();

            return HST.Core.Utils.WeightConverter.Convert(weight, type == "kg" ? WeightEnum.KG : WeightEnum.LBS) + " per side";
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}


text:
@import StoreKit;
@import JavaScriptCore;

@protocol JSBNSObject;

@protocol JSBSKProductsResponse <JSExport, JSBNSObject>

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

@property (nonatomic, readonly) NSArray *invalidProductIdentifiers;
@property (nonatomic, assign) id delegate;
@property (nonatomic, readonly) NSArray *products;

#pragma clang diagnostic pop

@end


text:
package notifications

import (
	"fmt"
	"net/http"
	"sync"
	"time"
)

type retryingSink struct {
	mu     sync.Mutex
	sink   Sink
	closed bool

	failures struct {
		threshold int
		recent    int
		last      time.Time
		backoff   time.Duration
	}
}

func newRetryingSink(sink Sink, threshold int, backoff time.Duration) *retryingSink {
	rs := &retryingSink{
		sink: sink,
	}
	rs.failures.threshold = threshold
	rs.failures.backoff = backoff

	return rs
}

func (rs *retryingSink) Write(events ...Event) Error {
	rs.mu.Lock()
	defer rs.mu.Unlock()

retry:
	if rs.closed {
		return Error{ErrSinkClosed, http.StatusInternalServerError}
	}

	if !rs.proceed() {
		return Error{fmt.Errorf("%v encountered too many errors, return", rs.sink), http.StatusInternalServerError}
	}

	err := rs.write(events...)
	if err.Err != nil {
		if err.Err == ErrSinkClosed {
			return Error{ErrSinkClosed, http.StatusInternalServerError}
		}

		fmt.Errorf("retryingsink: error writing events: %v, retrying", err.Err)
		rs.wait(rs.failures.backoff)
		goto retry
	}

	return err
}

func (rs *retryingSink) Close() error {
	rs.mu.Lock()
	defer rs.mu.Unlock()

	if rs.closed {
		return fmt.Errorf("retryingsink: already closed")
	}

	rs.closed = true
	return rs.sink.Close()
}

func (rs *retryingSink) write(events ...Event) Error {
	err := rs.sink.Write(events...)
	if err.Err != nil {
		rs.failure()
		return err
	}
	rs.reset()

	return err
}

func (rs *retryingSink) wait(backoff time.Duration) {
	rs.mu.Unlock()
	defer rs.mu.Lock()

	time.Sleep(backoff)
}

func (rs *retryingSink) reset() {
	rs.failures.recent = 0
	rs.failures.last = time.Time{}
}

func (rs *retryingSink) failure() {
	rs.failures.recent++
	rs.failures.last = time.Now().UTC()
}

func (rs *retryingSink) proceed() bool {
	return rs.failures.recent < rs.failures.threshold
}


text:
<?php
/*
 * Created on Sep 3, 2008
 *
 * Owner: DORU
 */
class notifications_response
	{
	private $response="";

	private $ersArray=array(
		'method'=>array('code'=>'100','desc'=>'Invalid Method','fatal'=>false),
		'headers'=>array('code'=>'101','desc'=>'Incomplete headers','fatal'=>true),
		'post'=>array('code'=>'102','desc'=>'Invalid POST content','fatal'=>false),
		'auth'=>array('code'=>'103','desc'=>'Bad authentification data','fatal'=>true),
		'xml'=>array('code'=>'105','desc'=>'Invalid XML structure','fatal'=>true),
		'api_version'=>array('code'=>'106', 'desc'=>'Invalid Api version please upgrade manually','fatal'=>true),
	);

	private $privateKey;
	private $username;

	private function getAuth()
		{
		include(dirname(__FILE__).'/config.php');
		$this->privateKey=$openinviter_settings['private_key'];
		$this->username=$openinviter_settings['username'];
		global $HTTP_RAW_POST_DATA;
		if ($_SERVER['REQUEST_METHOD']!='POST') $this->error('method');
		if (!isset($_SERVER['HTTP_X_USER'])) $this->error('headers');
		elseif (!isset($_SERVER['HTTP_X_SIGNATURE'])) $this->error('headers');
		if (empty($HTTP_RAW_POST_DATA)) $this->error('post');
		$this->user=htmlentities($_SERVER['HTTP_X_USER'],ENT_QUOTES);
		$xml=trim(gzuncompress($HTTP_RAW_POST_DATA));
		$signature=$_SERVER['HTTP_X_SIGNATURE'];
		if ($this->username!=$this->user) $this->error('auth');
		$signature_check=$this->makeSignature($this->privateKey,$xml);
		if ($signature_check!=$signature) $this->error('auth');
		if ($xml=='<notification>CHECK STATUS</notification>') $this->requestTypes='check';
		elseif ($xml=='<notification>UPDATE</notification>') $this->requestTypes='update';
		else $this->error['xml'];
		return true;
		}

	public function response()
		{
		if ($this->getAuth())
			{
			if ($this->requestTypes=='update') { include('autoupdate.php'); return gzcompress("<response>NOTIFICATIONS OK</response>",9); }
			elseif($this->requestTypes=='check') return gzcompress("<response>WAITING FOR UPDATES</response>",9);
			}
		else return false;
		}

	private function error($errorID,$header="HTTP/1.0 400 Bad Request")
		{
		$error=$this->ersArray[$errorID];
		header($header);echo (gzcompress("<error>{$error['desc']}</error>",9));exit;
		}

	private function makeSignature($var1,$var2)
		{
		return md5(md5($var1).md5($var2));
		}

	}
$notifications=new notifications_response();
echo $notifications->response();
?>


text:
codility-php-solutions
====================
This my contains solutions to the codility training problems

I am currently trying to test my algorithm skills.
Feel free to give suggestions to improve this so that it can become a great learning repository for
people trying to learn php.

##Lesson 1

##Lesson 2

##Lesson 3


text:
import * as assert from 'assert';
import * as fs from 'fs';

import * as rimraf from 'rimraf';

import { stat, statSync, Settings } from '.';

describe('Package', () => {
	before(() => {
		rimraf.sync('fixtures');

		fs.mkdirSync('fixtures');
		fs.mkdirSync('fixtures/a');
		fs.symlinkSync('a', 'fixtures/b', 'junction');
	});

	after(() => {
		rimraf.sync('fixtures');
	});

	describe('.stat', () => {
		it('should work without options or settings', (done) => {
			stat('fixtures/b', (error, stats) => {
				assert.strictEqual(error, null);
				assert.ok(stats);
				done();
			});
		});

		it('should work with options', (done) => {
			stat('fixtures/b', { markSymbolicLink: true }, (error, stats) => {
				assert.strictEqual(error, null);
				assert.strictEqual(stats.isSymbolicLink(), true);
				done();
			});
		});

		it('should work with settings', (done) => {
			const settings = new Settings({ markSymbolicLink: true });

			stat('fixtures/b', settings, (error, stats) => {
				assert.strictEqual(error, null);
				assert.strictEqual(stats.isSymbolicLink(), true);
				done();
			});
		});
	});

	describe('.statSync', () => {
		it('should work without options or settings', () => {
			const actual = statSync('fixtures/b');

			assert.ok(actual);
		});

		it('should work with options', () => {
			const actual = statSync('fixtures/b', { markSymbolicLink: true });

			assert.strictEqual(actual.isSymbolicLink(), true);
		});

		it('should work with settings', () => {
			const settings = new Settings({ markSymbolicLink: true });

			const actual = statSync('fixtures/b', settings);

			assert.strictEqual(actual.isSymbolicLink(), true);
		});
	});
});