text:
using namespace std;
using namespace sf;

namespace fe
{

// =============================================================================
//	CONSTRUCTORS, COPY CONSTRUCTOR, DESTRUCTOR, ASSIGNMENT OPERATOR
// =============================================================================
WordViewer::WordViewer(const UI32 width, const UI32 height, const TFontPtr& font,
	const TTexturePtr& lUndTexture) :
	m_Word(InvalidWord),
	m_Size(width, height),
	m_Position(0, 0),
	m_Callback(nullptr),
	m_LetterFont(font),
	m_LetterSize(0, 0),
	m_LetterPadding(5, 0, 5, 0),
	m_UnderlineMargin(5),
	m_UnderlineTexture(lUndTexture)
{
}

WordViewer::~WordViewer()
{
}

// =============================================================================
//	PRIVATE AND PROTECTED METHODS
// =============================================================================
void WordViewer::GenerateLetters()
{
	m_UnderlineSprites.clear();

	auto letterCount = StringUtils::U8Length(m_Word.GetString());
	auto txSize = m_UnderlineTexture->getSize();

	Vector2f drawableArea(
		m_Size.x - (m_LetterPadding.left + m_LetterPadding.width) * letterCount,
		m_Size.y - txSize.y - m_UnderlineMargin - m_LetterPadding.top - m_LetterPadding.height);

	m_LetterSize.x = drawableArea.x / static_cast<F32>(letterCount);
	m_LetterSize.y = drawableArea.y;

	Vector2f curPos(m_LetterPadding.left + m_Position.x,
					m_LetterPadding.top  + m_Position.y);

	// Get the UTF-8 individual codepoints to iterate over them
	auto utf8letters = StringUtils::U8Split(m_Word.GetString());

	for (UI32 i = 0; i < letterCount; ++i)
	{
		if (utf8letters[i] == " ")
		{
			curPos.x += m_LetterSize.x + m_LetterPadding.left + m_LetterPadding.width;
			continue;
		}

		Sprite undSprite(*m_UnderlineTexture);
		LetterButton letter(utf8letters[i], m_LetterFont, m_LetterSize);

		letter.SetPosition(curPos);
		letter.SetLetterColor(Color::Black);
		letter.SetButtonColor(Color(0, 0, 0, 0));

		undSprite.setPosition(curPos.x,
			curPos.y + m_LetterSize.y + m_LetterPadding.top + m_LetterPadding.height + m_UnderlineMargin);

		auto txSize = m_UnderlineTexture->getSize();

		// Adjust the underline sprite's width
		if (txSize.x != m_LetterSize.x)
		{
			auto scale = m_LetterSize.x / static_cast<F32>(txSize.x);
			undSprite.setScale(scale, 1.0);
		}

		m_HiddenLetterList.push_back(letter);
		m_UnderlineSprites.push_back(undSprite);

		curPos.x += m_LetterSize.x + m_LetterPadding.left + m_LetterPadding.width;
	}
}

// =============================================================================
//	REGULAR METHODS
// =============================================================================
bool WordViewer::TryLetter(const std::string& letter)
{
	list<TLetterButtonList::iterator> toErase;

	for (auto it = m_HiddenLetterList.begin(); it != m_HiddenLetterList.end(); ++it)
	{
		if (it->GetLetter() == letter)
		{
			toErase.push_back(it);
			m_VisibleLetterList.push_back(*it);
		}
	}

	if (toErase.empty())
		return false;

	for (auto& letter : toErase)
		m_HiddenLetterList.erase(letter);

	return true;
}

void WordViewer::HideWord()
{
	for (auto& visible : m_VisibleLetterList)
		m_HiddenLetterList.push_back(visible);

	m_VisibleLetterList.clear();
}

void WordViewer::RevealWord()
{
	for (auto& hidden : m_HiddenLetterList)
		m_VisibleLetterList.push_back(hidden);

	m_HiddenLetterList.clear();
}

void WordViewer::Draw(RenderWindow& window) const
{
	for (auto& underline : m_UnderlineSprites)
		window.draw(underline);

	for (auto& letter : m_VisibleLetterList)
		letter.Draw(window);
}

// =============================================================================
//	GETTERS & SETTERS
// =============================================================================
UI32 WordViewer::GetRemainingLetters() const
{
	return m_HiddenLetterList.size();
}

void WordViewer::SetWord(const Word& word)
{
	m_Word = word;

	m_VisibleLetterList.clear();
	m_HiddenLetterList.clear();

	GenerateLetters();
}

// =============================================================================
//	QUESTION METHODS
// =============================================================================
bool WordViewer::IsWordVisible() const
{
	return m_HiddenLetterList.empty();
}

}


text:
{% extends 'popup/encounter.html' %}
{% with original as o %}

{% block title %}
{{ o }}
{% endblock %}

{% block encounterdetails %}

    {{ o.get_deployment_status_display }}

{% if o.comments %}

    {{ o.comments }}

{% endif %}
{% endblock %}

{% endwith %}

redpajama_set_name: RedPajamaGithub


text:
<?php
    require ('vendor/autoload.php');
    require ('settings.php');

    $settings['redirectUrl'] .= $_SERVER['SCRIPT_NAME'];

    /*
     * replace the following with the configuration code from the Braintree Control Panel, which
     * will contain your unique API keys
     */
    Braintree_Configuration::environment($settings['environment']);
    Braintree_Configuration::merchantId($settings['merchantId']);
    Braintree_Configuration::publicKey($settings['publicKey']);
    Braintree_Configuration::privateKey($settings['privateKey']);

    $status = '';
    $formValues = [
      'first_name' => '',
      'last_name' => '',
      'email' => '',
      'color' => ''
    ];

    if(isset($_GET['http_status']) && $_GET['http_status'] == '200') {

        try {
            $result = Braintree_TransparentRedirect::confirm($_SERVER['QUERY_STRING']);
            if ($result->success) {
                /*
                 *  Braintree_Result_Success has a "transaction" property, which is an object
                 *  with details of the transaction
                 */
                $customer = $result->transaction->customer;
                $customFields = $result->transaction->customFields;
                if ($customer['email'] == '') {
                    Braintree_Transaction::void($result->transaction->id);
                    $status = 'Email address is a required field';

                } else {
                    $status = 'Your transaction was processed successfully.';
                }
            } else {
                $status = $result->message;
                /*
                 *  Braintree_Result_Error has a "params" property, which contains the form data
                 *  in array format
                 */
                $customer = $result->params['transaction']['customer'];
                $customFields = $result->params['transaction']['customFields'];
            }
            $formValues['first_name'] = $customer['firstName'];
            $formValues['last_name'] = $customer['lastName'];
            $formValues['email'] = $customer['email'];
            $formValues['color'] = $customFields['color'];
        } catch (Braintree_Exception_NotFound $e) {
            $status = 'Due to security reasons, the reload button has been disabled on this page.';
        }

    }

    $tr_data = Braintree_TransparentRedirect::transactionData([
            'transaction' => [
                'type' => Braintree_Transaction::SALE,
                'amount' => '100.00',
                'options' => [
                    'submitForSettlement' => true
                ]
            ],
        'redirectUrl' => $settings['redirectUrl']
    ]);

?>
<!doctype html>

    <meta charset="UTF-8">
    <title>Braintree Payment Solutions Transparent Redirect Demonstration</title>
    <link href="style.css" type="text/css" rel="stylesheet">

        <?php if ($status):?>

<?= $status?>

        <?php endif;?>
        <form method="post" action="<?= Braintree_TransparentRedirect::url()?>" autocomplete="off">
            Customer First Name: <input type="text" name="transaction[customer][first_name]" value="<?= $formValues['first_name']?>">

            Customer Last Name: <input type="text" name="transaction[customer][last_name]" value="<?= $formValues['last_name']?>">

            Customer Email: <input type="text" name="transaction[customer][email]" value="<?= $formValues['email']?>">

            Customer Favorite Color: <input type="text" name="transaction[custom_fields][color]" value="<?= $formValues['color']?>">

            Name on Card: <input type="text" name="transaction[credit_card][cardholder_name]">

            Card Number: <input type="text" name="transaction[credit_card][number]">

            CVV: <input type="text" name="transaction[credit_card][cvv]" class="short">

            Expiration Date (MM/YYYY): <input type="text" name="transaction[credit_card][expiration_date]" class="short">

            <input type="submit" value="submit payment">

            <input type="hidden" name="tr_data" value="<?=$tr_data?>">
        </form>


text:
<?php

/**
 * @author Julien Maulny
 * @license MIT
 * @link https://github.com/alcalyn/twig-extension-onpath
 */
namespace Alcalyn\Extension\Twig\Exception;

use Exception;

/**
 * Twig extension to print a string depending on current route
 *
 * @author Julien Maulny
 * @license MIT
 * @link https://github.com/alcalyn/twig-extension-onpath
 */
class OnPathException extends Exception
{
    /**
     * @param string $message
     */
    public function __construct($message)
    {
        parent::__construct($message, 0, null);
    }
}


text:
package uk.co.epii.stephenson.parser;

import org.junit.Before;
import org.junit.Test;
import uk.co.epii.stephenson.cif.IntermediateLocation;
import uk.co.epii.stephenson.cif.NationalRailTime;
import uk.co.epii.stephenson.cif.OriginLocation;

import static org.junit.Assert.assertEquals;

/**
 * User: James Robinson
 * Date: 17/08/2014
 * Time: 15:05
 */
public class IntermediateLocationParserTest {

  private static final String EXAMPLE_INTERMEDIATE_LOCATION = "LIPSEA    2211 2212      221122121  UML   T";
  private static final String EXAMPLE_THROUGH_INTERMEDIATE_LOCATION = "LIPCRKJN            2220 00000000";

  private IntermediateLocationParser intermediateLocationParser;

  @Before
  public void setUp() {
    intermediateLocationParser = new IntermediateLocationParser(new NationalRailTimeParser(), new NationalRailTimeParser());
  }

  @Test
  public void parsesExampleIntermediateLocationTest() {
    IntermediateLocation actual = intermediateLocationParser.parse(EXAMPLE_INTERMEDIATE_LOCATION);
    assertEquals("Record Identity","LI",actual.getRecordIdentity());
    assertEquals("Location","PSEA    ",actual.getLocation());
    assertEquals("Scheduled Arrival",new NationalRailTimeImpl(0,22,11,0),actual.getScheduledArrival());
    assertEquals("Scheduled Departure",new NationalRailTimeImpl(0,22,12,0),actual.getScheduledDeparture());
    assertEquals("Scheduled Pass",null,actual.getScheduledPass());
    assertEquals("Public Arrival",new NationalRailTimeImpl(0,22,11,0),actual.getPublicArrival());
    assertEquals("Public Departure",new NationalRailTimeImpl(0,22,12,0),actual.getPublicDeparture());
    assertEquals("Platform","1  ",actual.getPlatform());
    assertEquals("Line","UML",actual.getLine());
    assertEquals("Path","   ",actual.getPath());
    assertEquals("Activity","T           ",actual.getActivity());
    assertEquals("Engineering Allowance","  ",actual.getEngineeringAllowance());
    assertEquals("Pathing Allowance","  ",actual.getPathingAllowance());
    assertEquals("Performance Allowance","  ",actual.getPerformanceAllowance());
    assertEquals("Spare","                    ",actual.getSpare());
  }

  @Test
  public void parsesExampleIntermediateThroughLocationTest() {
    IntermediateLocation actual = intermediateLocationParser.parse(EXAMPLE_THROUGH_INTERMEDIATE_LOCATION);
    assertEquals("Record Identity","LI",actual.getRecordIdentity());
    assertEquals("Location","PCRKJN  ",actual.getLocation());
    assertEquals("Scheduled Arrival",null,actual.getScheduledArrival());
    assertEquals("Scheduled Departure",null,actual.getScheduledDeparture());
    assertEquals("Scheduled Pass",new NationalRailTimeImpl(0,22,20,0),actual.getScheduledPass());
    assertEquals("Public Arrival",null,actual.getPublicArrival());
    assertEquals("Public Departure",null,actual.getPublicDeparture());
    assertEquals("Platform","   ",actual.getPlatform());
    assertEquals("Line","   ",actual.getLine());
    assertEquals("Path","   ",actual.getPath());
    assertEquals("Activity","            ",actual.getActivity());
    assertEquals("Engineering Allowance","  ",actual.getEngineeringAllowance());
    assertEquals("Pathing Allowance","  ",actual.getPathingAllowance());
    assertEquals("Performance Allowance","  ",actual.getPerformanceAllowance());
    assertEquals("Spare","                    ",actual.getSpare());
  }

}


text:
'use strict';

angular.module('myProfile.photo').directive('myProfilePhoto', function(){
    return {
        restrict: 'EA',
        templateUrl: 'photo/photo.template.html',
        scope: true //can also take {} isolate value
    }
});


text:
In a currency pair, the value of the base currency is displayed relative to the quote currency. The currency pair is
priced in terms of the quote currency and the price indicates how much of the quote currency is required to buy one
unit of the base currency. For example, a price of $110 for XBT/USD means that $110 USD is required to purchase 1
XBT. In currency pair trading on Kraken, a pair can effectively be a single trading instrument that is opened as a
position by buying (going long) or selling (going short) the pair.

# Maker Take
From the email: What is a maker taker model? In a maker taker model, reduced fees are given to the market "makers"
who provide liquidity to the market "takers". The maker fee applies when you add liquidity to the order book by
placing a limit buy below market price or a limit sell above market price. The maker fee is paid only when such
orders are taken by new incoming orders. The taker fee applies when you remove liquidity from the book by placing a
market or limit order that executes immediately against a limit order already on the book. All advanced orders
trigger either market or limit orders and the triggered market or limit order will be maker or taker as described
above.


text:
/**
 * Created by cnfi on 2016/12/6.
 */
import React, {Component} from 'react'
import {render} from "react-dom"

class App extends Component {
    constructor(props, context) {
        super(props, context);

        this.handleClickChild = this.handleClickChild.bind(this);
        this.handleClickParent = this.handleClickParent.bind(this);
    }

    handleClickChild(e) {
        e.stopPropagation();
        e.preventDefault();
        console.log('do click child');
    }

    handleClickParent(e) {
        e.stopPropagation();
        e.preventDefault();
        console.log('do click parent');
    }

    componentDidMount() {

        document.body.addEventListener("click", function (e) {
            console.log("click-body");
        }, false);

        // this.refs.parent.addEventListener("click", function (e) {
        //     console.log("click-parent");
        // }, false);

        // this.refs.child.addEventListener("click", function (e) {
        //     //e.stopPropagation();
        //     console.log("click-child");
        // }, false);
        this.refs.grandchild.addEventListener("click", function (e) {
            //e.stopPropagation();
            console.log("click-grandchild");
        }, false);
    }

    render() {
        console.log('render');
        return (

                    父

                        子

                            孙

        )
    }
}

render(
    <App />,
    document.querySelector('#appContainer')
);


text:
{% extends 'base.html' %} {% load pipeline %} {% load widget_tweaks %}

{% block title %} ;) {% endblock %}

{% block head %}
  {% stylesheet 'new' %}
{% endblock head %}

{% block content %}

          {% if metatype == 'question' %}
            Ask a Question?
          {% else %}
            Start a Discussion!
          {% endif %}

          Ayyy there superuser! ;)

      {% if regform.errors %}

        <button class="delete" v-on:click="triggerDelete"></button>
          {{ regform.title.errors }}
          {{ regform.confirm_password.errors }}

      {% endif %}

         <form action="{% url 'random_submit' %}" method="POST"> {% csrf_token %}

          Username

            <input type="text" class="input" placeholder="A random username" name="username" />

          The user's bio

            <input type="text" class="input" placeholder="Blah Blah Blah" name="bio" />

           Title (Speak your mind)

               {% render_field form.title type="text" class+="input" %}

                 title

              Description

                {% render_field form.description type="textarea" class+="textarea" placeholder="A title is required, but expanding further here could be of clarity." %}

              Channels (optional)

                    {% render_field form.channels class+="input" %}

                  view_carousel

               <button class="button is-success" value="submit" name="submit" v-on:click="toggleLoading" v-bind:class="{'is-loading': isActive}">
                 Post
               </button>

         </form>

{% endblock content %}

{% block js %}
  {% javascript 'new' %}
{% endblock js %}


text:
import Action from './Action.js'
import ActionType from './ActionType.js'

class HomeAction extends Action {
  constructor(device) {
    super(ActionType.HOME)
    this._device = device
  }

  async fire() {
    await this._device.home()
  }

  toCommand() {
    return this.type
  }

  equals(otherAction) {
    if (this === otherAction) {
      return true
    }

    if (otherAction === null) {
      return false
    }

    if (!(otherAction instanceof HomeAction)) {
      return false
    }

    if (this.type !== otherAction.type) {
      return false
    }
    return true
  }
}

export default HomeAction


text:
from setuptools import setup, find_packages

setup(
    name='django-contrib-postgres',
    version='0.0.1',
    description='Backport of django.contrib.postgres',
    long_description=open('README.rst').read(),
    author='Mikko Hellsing',
    author_email='mikko@aino.se',
    license='BSD',
    url='https://github.com/sorl/django-contrib-postgres',
    packages=find_packages(exclude=['tests', 'tests.*']),
    zip_safe=False,
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Environment :: Web Environment',
        'Framework :: Django',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
        'Topic :: Internet :: WWW/HTTP :: WSGI',
        'Topic :: Software Development :: Libraries :: Application Frameworks',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],
)


text:
module OneviewCookbook
  module API300
    module Synergy
      # Enclosure API300 Synergy provider
      class EnclosureProvider < API200::EnclosureProvider
      end
    end
  end
end


text:
from django.template import Library, Node, Variable, VariableDoesNotExist, TemplateSyntaxError
from django.contrib.contenttypes.models import ContentType

from tagging.models import Tag

from courant.core.news.models import Article

from datetime import date, timedelta

register = Library()

class CountThisNode(Node):

    def __init__(self, object, url=None):
        self.object = object
        self.url = url

    def render(self, context):
        object = Variable(self.object).resolve(context)
        if not self.url:
            url = object.get_absolute_url()
        else:
            url = Variable(self.url).resolve(context)

        #Make sure the variable exists so we can add to it
        if not 'countthis' in context['request'].META:
            context['request'].META['countthis'] = []

        #Add the object's path, model name, and id, each object is separated by a ;
        context['request'].META['countthis'].append("%s~%s~%s" % (url, ContentType.objects.get_for_model(object).pk, object.id))

        return ''

def countthis(parser, token):
    """
    Send request to update the count of the object.
    Takes an object and an optional URL. If a URL is not provided, then
    get_absolute_url will be called on the object. If the object does not
    have this function defined, then an error will be thrown.

    Example usage:
        {% countthis object %}
        {% countthis object url %}
    """
    bits = token.contents.split()
    if len(bits) == 2:
        return CountThisNode(bits[1])
    elif len(bits) == 3:
        return CountThisNode(bits[1], bits[2])
    else:
        raise TemplateSyntaxError
countthis = register.tag(countthis)

class MostPopularNode(Node):

    def __init__(self, appmodel, type, limit, days, varname, force=False):
        self.appmodel = appmodel
        self.limit = limit
        self.days = days
        self.varname = varname
        self.force = force

        if type == 'viewed':
            self.type = 'view_count'
        elif type == 'emailed':
            self.type = 'email_count'
        elif type == 'commented':
            self.type = 'comment_count'
        else:
            raise TemplateSyntaxError('The only supported types for this template tag are viewed, emailed, and commented.')

    def render(self, context):
        from courant.core.countthis.models import Statistic
        from datetime import timedelta, datetime

        try:
            self.appmodel = Variable(self.appmodel).resolve(context)
        except VariableDoesNotExist:
            pass #Just leave it alone

        #These are numbers, so either they'll resolve to a variable or resolve will return the number
        self.limit = Variable(self.limit).resolve(context)
        self.days = Variable(self.days).resolve(context)

        #We have to get the ContentType from the app.model string
        appmodel = self.appmodel.split('.')
        content_object = ContentType.objects.get(app_label=appmodel[0], model=appmodel[1])
        content_object_model = content_object.model_class()

        content_type_list = [content_object.pk]
        for related_object in content_object_model._meta.get_all_related_objects():
            if issubclass(related_object.model, content_object_model):
                content_type_list.append(ContentType.objects.get_for_model(related_object.model).pk)

        #Get the right objects
        while True:
            statistics_objects = Statistic.objects.filter(content_type__in=content_type_list, created_at__gte=datetime.now() - timedelta(days=self.days)).order_by('-' + self.type)

            #Do we have enough?
            if self.force and statistics_objects.count() < self.limit:
                self.days = self.days + 7
                continue

            #We have enough!
            statistics_objects = statistics_objects[:self.limit]
            break

        #Create a dictionary of just the content_objects and view_counts, so they don't get Statistic models back and have to do object.content_object
        context[self.varname] = [{appmodel[1]: obj.content_object, 'count': getattr(obj, self.type)} for obj in statistics_objects]
        return ''

def get_bits(bits):
    return {
        'appmodel': bits[2],
        'type': bits[1],
        'limit': bits[-3],
        'days': bits[5],
        'varname': bits[-1],
    }

def get_most_popular(parser, token, force=False):
    """
    Format is get_most_popular viewed/emailed/commented APP.MODEL from last X days limit Y as VARIABLE.
    The day range, limit, and app.model name may be context variables.
    """
    bits = token.contents.split()
    bits = get_bits(bits)
    return MostPopularNode(bits['appmodel'], bits['type'], bits['limit'], bits['days'], bits['varname'])
register.tag('get_most_popular', get_most_popular)

def smart_get_most_popular(parser, token):
    """
    Same format as get_most_popular, but if there aren't enough stories in the days given, it will add seven days and try again.
    """
    bits = token.contents.split()
    bits = get_bits(bits)
    return MostPopularNode(bits['appmodel'], bits['type'], bits['limit'], bits['days'], bits['varname'], force=True)
register.tag('smart_get_most_popular', smart_get_most_popular)

class MostPopularTagsNode(Node):

    def __init__(self, days, limit, varname):
        self.days = int(days)
        self.limit = int(limit)
        self.varname = varname

    def render(self, context):
        first_day = date.today() + timedelta(-self.days)
        articles_in_period = Article.objects.filter(published_at__gte=first_day)
        tags = Tag.objects.usage_for_queryset(articles_in_period, counts=True)
        tags.sort(reverse=True, key=lambda t: t.count)
        context[self.varname] = tags[:self.limit]
        return ''

def get_most_popular_tags(parser, token):
    """
    For the given time period, finds the tags which have been used the most (had the most content tagged with them).

    Example:
        {% get_most_popular_tags from last X days limit Y as VARNAME %}
    """

    bits = token.contents.split()
    if len(bits) != 9:
        raise TemplateSyntaxError, "get_most_popular_tags: invalid parameters"
    return MostPopularTagsNode(bits[3], bits[6], bits[8])
register.tag('get_most_popular_tags', get_most_popular_tags)


text:
package mesosphere.marathon.core.storage.store.impl.zk

import akka.Done
import akka.util.ByteString
import org.apache.curator.RetryPolicy
import org.apache.curator.framework.api.{ BackgroundPathable, Backgroundable, Pathable }
import org.apache.curator.framework.{ CuratorFramework, CuratorFrameworkFactory }
import org.apache.zookeeper.CreateMode
import org.apache.zookeeper.data.{ ACL, Stat }

import scala.collection.JavaConverters._
import scala.collection.immutable.Seq
import scala.concurrent.Future
import scala.util.control.NonFatal

/**
  * Extensions to CuratorFramework that give a more friendly API to scala (everything executes in the background
  * and returns futures instead of the blocking form).
  *
  * While an implicit conversion is provided, the compiler doesn't appear to be able to resolve it automatically
  * if named parameters are given. Instead, it is advisable to create it explicitly.
  *
  * @param client The underlying Curator client.
  */
class RichCuratorFramework(val client: CuratorFramework) extends AnyVal {
  def usingNamespace(namespace: String): RichCuratorFramework = {
    new RichCuratorFramework(client.usingNamespace(namespace))
  }

  def create(
    path: String,
    data: Option[ByteString] = None,
    compress: Boolean = false,
    `protected`: Boolean = false,
    acls: Seq[ACL] = Nil,
    createMode: CreateMode = CreateMode.PERSISTENT,
    creatingParentsIfNeeded: Boolean = false,
    creatingParentContainersIfNeeded: Boolean = false): Future[String] =
    build(client.create(), ZkFuture.create) { builder =>
      if (compress) builder.compressed()
      if (`protected`) builder.withProtection()
      if (creatingParentsIfNeeded) builder.creatingParentsIfNeeded()
      if (creatingParentContainersIfNeeded) builder.creatingParentContainersIfNeeded()
      if (acls.nonEmpty) builder.withACL(acls.asJava)
      builder.withMode(createMode)
      data.fold(builder.forPath(path)) { bytes =>
        builder.forPath(path, bytes.toArray)
      }
    }

  def delete(
    path: String,
    version: Option[Int] = None,
    guaranteed: Boolean = false,
    deletingChildrenIfNeeded: Boolean = false): Future[String] =
    build(client.delete(), ZkFuture.delete) { builder =>
      if (deletingChildrenIfNeeded) builder.deletingChildrenIfNeeded()
      if (guaranteed) builder.guaranteed()
      if (deletingChildrenIfNeeded) builder.deletingChildrenIfNeeded()
      version.foreach(builder.withVersion)
      builder.forPath(path)
    }

  def exists(
    path: String,
    creatingParentContainersIfNeeded: Boolean = false): Future[ExistsResult] =
    build(client.checkExists(), ZkFuture.exists) { builder =>
      if (creatingParentContainersIfNeeded) builder.creatingParentContainersIfNeeded()
      builder.forPath(path)
    }

  def data(
    path: String,
    decompressed: Boolean = false): Future[GetData] =
    build(client.getData, ZkFuture.data) { builder =>
      if (decompressed) builder.decompressed()
      builder.forPath(path)
    }

  def setData(
    path: String,
    data: ByteString,
    compressed: Boolean = false,
    version: Option[Int] = None): Future[SetData] =
    build(client.setData(), ZkFuture.setData) { builder =>
      version.foreach(builder.withVersion)
      if (compressed) builder.compressed()
      builder.forPath(path, data.toArray)
    }

  def children(path: String): Future[Children] =
    build(client.getChildren, ZkFuture.children) { builder =>
      builder.forPath(path)
    }

  def sync(path: String): Future[Option[Stat]] =
    build(client.sync(), ZkFuture.sync) { builder =>
      builder.forPath(path)
    }

  def acl(path: String): Future[Seq[ACL]] =
    build(client.getACL, ZkFuture.acl) { builder =>
      builder.forPath(path)
    }

  @SuppressWarnings(Array("AsInstanceOf"))
  def setAcl(path: String, acls: Seq[ACL],
    version: Option[Int] = None): Future[Done] = {
    val builder = client.setACL()
    // sadly, the builder doesn't export BackgroundPathable, but the impl is.
    build(builder.asInstanceOf[BackgroundPathable[_]], ZkFuture.setAcl) { _ =>
      version.foreach(builder.withVersion)
      builder.withACL(acls.asJava)
      // it doesn't export Pathable either?
      builder.asInstanceOf[Pathable[_]].forPath(path)
    }
  }

  private def build[A <: Backgroundable[_], B](builder: A, future: ZkFuture[B])(f: A => Unit): Future[B] = {
    try {
      builder.inBackground(future)
      f(builder)
      future
    } catch {
      case NonFatal(e) =>
        future.fail(e)
    }
  }

  override def toString: String =
    s"CuratorFramework(${client.getZookeeperClient.getCurrentConnectionString}/${client.getNamespace})"
}

object RichCuratorFramework {
  def apply(client: CuratorFramework): RichCuratorFramework = new RichCuratorFramework(client)
  def apply(uri: String, retryPolicy: RetryPolicy): RichCuratorFramework = {
    val c = CuratorFrameworkFactory.newClient(uri, retryPolicy)
    c.start()
    new RichCuratorFramework(c)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using KSP;
using Contracts;
using Strategies;
using Strategies.Effects;
using ContractConfigurator;

namespace Strategia
{
    /// <summary>
    /// Special CurrencyOperation that gives a modifier for specific trait.
    /// </summary>
    public class CurrencyOperationByTrait : StrategyEffect
    {
        List<Currency> currencies;
        string effectDescription;
        List<TransactionReasons> affectReasons;
        List<float> multipliers;
        string trait;

        private Vessel cachedVessel;
        private float cacheTime;

        public CurrencyOperationByTrait(Strategy parent)
            : base(parent)
        {
        }

        protected override string GetDescription()
        {
            float multiplier = Parent.GetLeveledListItem(multipliers);
            string multiplierStr = ToPercentage(multiplier);

            string currencyStr = currencies.Count() > 1 ? "" : (currencies.First() + " ");

            return multiplierStr + " " + currencyStr + effectDescription +
                " when " + StringUtil.ATrait(trait) + " is present.";
        }

        protected override void OnLoadFromConfig(ConfigNode node)
        {
            base.OnLoadFromConfig(node);

            currencies = ConfigNodeUtil.ParseValue<List<Currency>>(node, "currency");
            effectDescription = ConfigNodeUtil.ParseValue<string>(node, "effectDescription");
            affectReasons = ConfigNodeUtil.ParseValue<List<TransactionReasons>>(node, "AffectReason");
            multipliers = ConfigNodeUtil.ParseValue<List<float>>(node, "multiplier");
            trait = ConfigNodeUtil.ParseValue<string>(node, "trait");
        }

        protected override void OnRegister()
        {
            if (Parent.IsActive)
            {
                GameEvents.Modifiers.OnCurrencyModifierQuery.Add(new EventData<CurrencyModifierQuery>.OnEvent(OnEffectQuery));
                GameEvents.onVesselRecovered.Add(new EventData<ProtoVessel, bool>.OnEvent(OnVesselRecovered));
                GameEvents.onGameSceneLoadRequested.Add(new EventData<GameScenes>.OnEvent(OnGameSceneLoadRequested));
            }
        }

        protected override void OnUnregister()
        {
            GameEvents.Modifiers.OnCurrencyModifierQuery.Remove(new EventData<CurrencyModifierQuery>.OnEvent(OnEffectQuery));
            GameEvents.onVesselRecovered.Add(new EventData<ProtoVessel, bool>.OnEvent(OnVesselRecovered));
            GameEvents.onGameSceneLoadRequested.Add(new EventData<GameScenes>.OnEvent(OnGameSceneLoadRequested));
        }

        private void OnGameSceneLoadRequested(GameScenes scene)
        {
            cachedVessel = null;
        }

        private void OnVesselRecovered(ProtoVessel vessel, bool quick)
        {
            cachedVessel = vessel.vesselRef;
            cacheTime = Time.fixedTime;
        }

        private void OnEffectQuery(CurrencyModifierQuery qry)
        {
            // Check the reason is a match
            if (!affectReasons.Contains(qry.reason))
            {
                return;
            }

            // Check if it's non-zero
            float total = 0.0f;
            foreach (Currency currency in currencies)
            {
                total += Math.Abs(qry.GetInput(currency));
            }
            if (total < 0.01f)
            {
                return;
            }

            // Figure out the vessel to look at
            Vessel vessel = null;
            if (FlightGlobals.ActiveVessel != null)
            {
                vessel = FlightGlobals.ActiveVessel;
            }
            else if (cachedVessel != null && cacheTime < Time.fixedTime + 5.0f)
            {
                vessel = cachedVessel;
            }

            // Check for matching crew
            if (vessel != null)
            {
                bool crewFound = false;
                foreach (ProtoCrewMember pcm in VesselUtil.GetVesselCrew(vessel))
                {
                    if (pcm.experienceTrait.Config.Name == trait)
                    {
                        crewFound = true;
                        break;
                    }
                }
                if (!crewFound)
                {
                    return;
                }
            }

            float multiplier = Parent.GetLeveledListItem(multipliers);
            foreach (Currency currency in currencies)
            {
                qry.AddDelta(currency, multiplier * qry.GetInput(currency) - qry.GetInput(currency));
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>jCarousel Examples</title>
<link href="../style.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="../lib/jquery.jcarousel.css" />

<link rel="stylesheet" type="text/css" href="../skins/tango/skin.css" />

jCarousel

Riding carousels with jQuery

Carousel illustrating the callback functions

    This carousel has registered all available callback functions and displays
    information about the state of the items and buttons. Additionally the width
    of the carousel is set to auto. Resize the browser window and see what happens.


text:
package edu.cmu.cs.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.util.Map;

/**
 * Created by junjuew on 3/4/16.
 */
public abstract class GenericEditTextAlertDialog {
    protected DialogEditTextResultListener delegate;
    protected Context mContext;

    public interface DialogEditTextResultListener {
        void onDialogEditTextResult(String... result);
    }

    public GenericEditTextAlertDialog(Context m, DialogEditTextResultListener delegate){
        this.mContext=m;
        this.delegate=delegate;
    }

//    public abstract Dialog createDialog(String title, String[] msg, String[] hints);
}

//    /**
//     * Create and return an example alert dialog with an edit text box.
//     */
//    public Dialog createDialog(String title,
//                               String msg,
//                               String hint){
//        AlertDialog.Builder builder = new AlertDialog.Builder(this.mContext);
//        builder.setTitle(title);
//        builder.setMessage(msg);
//
//        // Use an EditText view to get user input.
//        final EditText input = new EditText(this.mContext);
//        input.setText(hint);
//        dialogInputTextEdit = input;
//        inputDialogResult = null;
//        builder.setView(input);
//
//        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int whichButton) {
//            }
//        });
//
//        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                return;
//            }
//        });
//
//
//        AlertDialog alertDialog = builder.create();
//        alertDialog.show();
//        Button customOkButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
//        customOkButton.setOnClickListener(new OKReturnTextListener(alertDialog));
//        return alertDialog;
//    }
//
//    class OKReturnTextListener implements View.OnClickListener {
//        private final Dialog dialog;
//        public OKReturnTextListener(Dialog dialog) {
//            this.dialog = dialog;
//        }
//        @Override
//        public void onClick(View v) {
//            inputDialogResult = dialogInputTextEdit.getText().toString();
//            Log.d(TAG, "user input: " + inputDialogResult);
//            if (null != delegate){
//                delegate.onDialogEditTextResult(inputDialogResult);
//            }
//            this.dialog.dismiss();
//            return;
//        }
//    }


text:
layout: default
title: Policies
---

{{ page.title }}

Bylaws

Cola Makerspace Bylaws

Policies

Code of Conduct

Anti-Harassment Policy

Guest Policy

Minor Policy

Non-Discrimination Policy

Liability Waivers

Liability Waiver

Liability Waiver for Minors

Corporate Sponsor Liability Waiver


text:
<?php
/**
 * Created by PhpStorm.
 * User: laogui
 * Date: 17/3/30
 * Time: 下午2:07
 */
namespace Sukui\Task;

class AsyncSleep implements Async {
    public function begin(callable $cc){
        swoole_timer_after(1000,$cc);
    }
}


text:
<?php namespace RabbitORM;

use Countable;
use ArrayIterator;
use IteratorAggregate;
use RabbitORM\Row;

class Result implements Countable, IteratorAggregate {

	protected $model = null;
	protected $query = null;

	protected $rows;

	function __construct(Model $model, QueryBuilder $query = null)
	{
		$this->model = $model;
		$this->query = $query->get();
	}

	function row()
	{
		if($this->query->num_rows() == 0) return;
		$rowData = $this->query->row_array();
		$this->model->setData($rowData);
		return $this->model;
	}

	function rows()
	{
		$this->rows = array();
		if($this->query->num_rows() == 0) return $this;

		$class = get_class($this->model);

		foreach($this->query->result_array() as $rowData)
		{
			$model = new $class;
			$model->exists = true;
			$model->setData($rowData);
			$this->rows[] = $model;
		}

		return $this;
	}

	// Alias for row();
	function first()
	{
		return $this->row();
	}

	function pluck($field)
	{
		$first = $this->row();

		return $first->$field;
	}

	// Eager loading
	function load($method)
	{
		if(!is_callable(array($this->model, $method))) return false;

		$relation = call_user_func(array($this->model, $method));

		$primaries = array();

		foreach($this->rows as $row)
			$primaries[] = $row->getData( $row->getPrimaryKey() );

		$this->rows = $relation->eagerLoad( $this->rows, $primaries, $method );
	}

	function toArray()
	{
		$array = array();

		foreach($this->rows as $row) $array[] = $row->toArray();

		return $array;
	}

	function json()
	{
		return json_encode( $this->toArray() );
	}

	// Implements IteratorAggregate function
	public function getIterator()
	{
		return new ArrayIterator($this->rows);
	}

	// Implements Countable function
	public function count()
	{
		return count($this->rows);
	}
}


text:
#ifndef _UAPI_LINUX_HW_BREAKPOINT_H
#define _UAPI_LINUX_HW_BREAKPOINT_H
enum {
 HW_BREAKPOINT_LEN_1 = 1,
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 HW_BREAKPOINT_LEN_2 = 2,
 HW_BREAKPOINT_LEN_4 = 4,
 HW_BREAKPOINT_LEN_8 = 8,
};
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
enum {
 HW_BREAKPOINT_EMPTY = 0,
 HW_BREAKPOINT_R = 1,
 HW_BREAKPOINT_W = 2,
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
 HW_BREAKPOINT_RW = HW_BREAKPOINT_R | HW_BREAKPOINT_W,
 HW_BREAKPOINT_X = 4,
 HW_BREAKPOINT_INVALID = HW_BREAKPOINT_RW | HW_BREAKPOINT_X,
};
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
enum bp_type_idx {
 TYPE_INST = 0,
 TYPE_DATA = 1,
 TYPE_MAX
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
};
#endif


text:
package tools.devnull.cafeina.annotations.sentimento;

import java.lang.annotation.Documented;

/**
 * Anotação usada para indicar que você não foi o responsável por nenhuma
 * cagada, apenas corrigiu algum bug (geralmente um carinhoso NPE) ou
 * implementou alguma funcionalidade exótica.
 *
 * Esta anotação automaticamente valida qualquer tipo de gambiarra maquiavélica.
 *
 * @author Marcelo Guimarães
 */
@Documented
public @interface EuSoEstouDandoManutencao {

  /**
   * Indica os infelizes mantenedores que já se contaminaram com o código.
   *
   * @return os infelizes mantenedores que já se contaminaram com o código.
   */
  String[] passouPorAqui() default {};

}


text:
wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.3.2.deb
sudo dpkg -i elasticsearch-1.3.2.deb
sudo service elasticsearch restart

if [ -n "$NOBRAINER" ]; then
  source /etc/lsb-release && echo "deb http://download.rethinkdb.com/apt $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list
  wget -qO- http://download.rethinkdb.com/apt/pubkey.gpg | sudo apt-key add -
  sudo apt-get update -q
  sudo apt-get install rethinkdb
  sudo cp /etc/rethinkdb/default.conf.sample /etc/rethinkdb/instances.d/instance1.conf
  sudo service rethinkdb restart
fi


text:
/* tslint:disable:no-unused-variable */
import { SolrZkcliOptions, SolrZkCliCommand, SolrZkcliResult } from './main';
import * as path from 'path';
import * as util from 'util';

// describe('SolrZkCliCommand', () => {
//   it('upconfig', (done) => {
//     const solrZkcliOptions = new SolrZkcliOptions(
//         /* cmd */ 'upconfig',
//         /* currentWorkingDirectory */  undefined,
//         /* zkhost */ 'zookeeper-ap-southeast-2-1:2181/my_new_config',
//         /* confname */ 'my_new_config',
//         /* confdir */ '/fleetmake/ebs/solr-fmlogs-ap-southeast-2-1-1/for_upconfig/fmlogs/conf',
//         /* clusterprop*/ undefined,
//         /* solrhome */ undefined,
//         /* solrdockerimage */ 'quobjectio/solr:7.2.1',
//         /* machineName */ 'localhost',
//         /* network */ 'fm-net',
//     );

//     return Promise.resolve().then(() => {
//       return SolrZkCliCommand(solrZkcliOptions);
//     }).then((data: SolrZkcliResult) => {
//       console.log('data = ', util.inspect(data, { depth: 10 }));
//       expect(data.ok).toBeTruthy();
//       done();
//     });
//   }, 1000000); //1000 seconds timeout
//  });

//  describe('SolrZkCliCommand', () => {
//   it('upconfig', (done) => {
//     const solrZkcliOptions = new SolrZkcliOptions(
//         /* cmd */ 'upconfig',
//         /* currentWorkingDirectory */  undefined,
//         /* zkhost */ 'zookeeper-ap-southeast-2-1:2181/my_new_config',
//         /* confname */ 'my_new_config',
//         /* confdir */ '/fleetmake/ebs/solr-fmlogs-ap-southeast-2-1-1/for_upconfig/fmlogs/conf',
//         /* clusterprop*/ undefined,
//         /* solrhome */ undefined,
//         /* solrdockerimage */ 'quobjectio/solr:7.2.1',
//         /* machineName */ 'machine.2.ap-southeast-2.0.0.1',
//         /* network */ 'fm-net',
//     );

//     return Promise.resolve().then(() => {
//       return SolrZkCliCommand(solrZkcliOptions);
//     }).then((data: SolrZkcliResult) => {
//       console.log('data = ', util.inspect(data, { depth: 10 }));
//       expect(data.ok).toBeTruthy();
//       done();
//     });
//   }, 1000000); //1000 seconds timeout
//  });

//  describe('SolrZkCliCommand', () => {
//    it('mkroot', (done) => {
//      const solrZkcliOptions = new SolrZkcliOptions(
//        /* cmd */ 'mkroot',
//        /* currentWorkingDirectory */  undefined,
//        /* zkhost */ 'zookeeper-ap-southeast-2-1:2181',
//        /* confname */ 'my_new_config',
//        /* confdir */ undefined,
//        /* clusterprop*/ undefined,
//        /* solrhome */ undefined,
//        /* solrdockerimage */ 'quobjectio/solr:7.2.1',
//        /* machineName */ 'localhost',
//        /* network */ 'fm-net',

//      );

//      return Promise.resolve().then(() => {
//        return SolrZkCliCommand(solrZkcliOptions);
//      }).then((data: SolrZkcliResult) => {
//        console.log('data = ', util.inspect(data, { depth: 10 }));
//        expect(data.ok).toBeTruthy();
//        done();
//      });
//    });
//  });

 describe('SolrZkCliCommand', () => {
   it('mkroot', (done) => {
     const solrZkcliOptions = new SolrZkcliOptions(
       /* cmd */ 'mkroot',
       /* currentWorkingDirectory */  undefined,
       /* zkhost */ 'zookeeper-ap-southeast-2-1:2181',
       /* confname */ 'my_new_config',
       /* confdir */ undefined,
       /* clusterprop*/ undefined,
       /* solrhome */ undefined,
       /* solrdockerimage */ 'quobjectio/solr:7.2.1',
        /* machineName */ 'machine.2.ap-southeast-2.0.0.1',
        /* network */ 'fm-net',

     );

     return Promise.resolve().then(() => {
       return SolrZkCliCommand(solrZkcliOptions);
     }).then((data: SolrZkcliResult) => {
       console.log('data = ', util.inspect(data, { depth: 10 }));
       expect(data.ok).toBeTruthy();
       done();
     });
   });
 });


text:
'use strict';

// MODULES //

var gammaln = require( 'math-gammaln' );
var PINF = require( 'const-pinf-float32' );

// BETALN //

/**
* FUNCTION: betaln( x, y )
*	Evaluates the natural logarithm of the beta function of two numeric values.
*
* @param {Number} x - input value
* @param {Number} y - second input value
* @returns {Number} function value
*/
function betaln( x , y  ) {
	// Special cases: NaN
	if ( x !== x || y !== y ) {
		return NaN;
	}
	// Special cases: negative numbers
	if ( x < 0 || y < 0 ) {
		return NaN;
	}
	// Special cases: 0
	if ( x === 0 || y === 0 ) {
		return PINF;
	}
	return gammaln( x ) + gammaln( y ) - gammaln( x + y );
} // end FUNCTION betaln()

// EXPORTS //

module.exports = betaln;


text:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace Ets2Map.Demo
{
    public partial class Ets2MapDemo : Form
    {
        private Ets2Mapper map;
        private MapRenderer render;

        private Ets2Point navigatePoint;
        private Ets2NavigationRoute route;

        private Timer refresh;

        private float mapScale = 1000.0f;

        private Point? dragPoint;
        private Ets2Point location = new Ets2Point(1000, 0, -1000, 0);

        public Ets2MapDemo()
        {
            var projectMap = @"C:\Projects\Software\ets2-map\";

            map = new Ets2Mapper(
                projectMap + @"SCS\europe\",
                projectMap + @"SCS\prefab",
                projectMap + @"SCS\LUT1.19",
                projectMap + @"LUT\LUT1.19");
            map.Parse(true);

            render = new MapRenderer(map, new SimpleMapPalette());

            InitializeComponent();

            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            refresh = new Timer();
            refresh.Interval = 250;
            refresh.Tick += (sender, args) => Invalidate();
            refresh.Start();

            // Panning around
            MouseDown += (s, e) => dragPoint = e.Location;
            MouseUp += (s, e) => dragPoint = null;
            MouseMove += (s, e) =>
            {
                if (dragPoint.HasValue)
                {
                    var spd = mapScale/Math.Max(this.Width, this.Height);
                    location = new Ets2Point(location.X - (e.X - dragPoint.Value.X)*spd,
                        0,
                        location.Z - (e.Y - dragPoint.Value.Y)*spd,
                        0);
                    dragPoint = e.Location;
                }
            };

            // Zooming in
            MouseWheel += Ets2MapDemo_MouseWheel;

            // Navigation
            MouseDoubleClick += Ets2MapDemo_MouseDoubleClick;

            Resize += Ets2MapDemo_Resize;
        }

        private void Ets2MapDemo_MouseWheel(object sender, MouseEventArgs e)
        {
            mapScale -= e.Delta;
            mapScale = Math.Max(100, Math.Min(30000, mapScale));
        }

        private void Ets2MapDemo_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            navigatePoint = render.CalculatePointFromMap(e.X, e.Y);
        }

        private void Ets2MapDemo_Resize(object sender, EventArgs e)
        {
            Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (navigatePoint != null)
            {
                route = map.NavigateTo(location, navigatePoint);
                navigatePoint = null;
            }
            if (route != null && route.Loading == false)
                render.SetNavigation(route);

            render.Render(e.Graphics, e.ClipRectangle, mapScale, location);

            base.OnPaint(e);
        }
    }
}


text:
<Record>
<Term>Picloxydine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Topical Anti-Infective Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Anti-Infective Agent/Topical Anti-Infective Agent/Picloxydine</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Anti-Infective Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<BroaderTerm>Picloxydine</BroaderTerm>
<BroaderTerm>Topical Anti-Infective Agent</BroaderTerm>
<Synonym>PICLOXYDINE</Synonym>
<Synonym>Picloxydine</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
Pre-build SQLSN distribution as it is meant to be used.

## module dependencies

* sqlsn-core
* sqlsn-stack
* sqlsn-run


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class GraphicDimensions extends AbstractTag
{

    protected $Id = '0070,0020';

    protected $Name = 'GraphicDimensions';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Graphic Dimensions';

}


text:
define(['i18nTokens'], function(tokens) {
  'use strict';
  // This should be wrapped with key missing safe methods.
  return tokens;
});


text:
package com.consol.citrus.integration.runner;

import com.consol.citrus.annotations.CitrusTest;
import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;
import org.springframework.core.io.ClassPathResource;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
@Test
public class GroovyActionTestRunnerIT extends TestNGCitrusTestRunner {

    /** OS new line */
    private static final String NEWLINE = System.getProperty("line.separator");

    @CitrusTest
    public void groovyAction() {
        variable("date", "citrus:currentDate()");
        variable("greetingText", "Hello Citrus!");

        groovy(builder -> builder.script("println 'Hello Citrus'"));

        groovy(builder -> builder.script("println 'Current date is ${date}!'"));

        groovy(builder -> builder.script("import com.consol.citrus.*" + NEWLINE +
                "import com.consol.citrus.variable.*" + NEWLINE +
                "import com.consol.citrus.context.TestContext" + NEWLINE +
                "import com.consol.citrus.script.GroovyAction.ScriptExecutor" + NEWLINE +
                "import org.testng.Assert" + NEWLINE +
                "public class GScript implements ScriptExecutor {" + NEWLINE +
                "public void execute(TestContext context) {" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"Hello Citrus!\")" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"${greetingText}\")" + NEWLINE +
                "}" + NEWLINE +
                "}"));

        groovy(builder -> builder.script("println context.getVariable(\"date\")" + NEWLINE +
                "assert context.getVariable(\"greetingText\").equals(\"Hello Citrus!\")" + NEWLINE +
                "assert context.getVariable(\"greetingText\").equals(\"${greetingText}\")"));

        groovy(builder -> builder.script("println 'Hello Citrus'")
                .skipTemplate());

        groovy(builder -> builder.script("Assert.assertEquals(context.getVariable(\"scriptTemplateVar\"), \"It works!\")" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"Hello Citrus!\")" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"${greetingText}\")")
                .template("classpath:com/consol/citrus/script/custom-script-template.groovy"));

        groovy(builder -> builder.script("import org.testng.Assert" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"scriptTemplateVar\"), \"It works!\")" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"Hello Citrus!\")" + NEWLINE +
                "Assert.assertEquals(context.getVariable(\"greetingText\"), \"${greetingText}\")"));

        groovy(builder -> builder.script("public class MyCustomClass {" + NEWLINE +
                "public void run() {" + NEWLINE +
                "println 'Just executed a custom class with run method!'" + NEWLINE +
                "}" + NEWLINE +
                "}"));

        groovy(builder -> builder.script(new ClassPathResource("com/consol/citrus/script/example.groovy")));
    }
}


text:
package org.txazo.java.concurrency.thread;

import java.io.IOException;
import java.util.concurrent.locks.LockSupport;

/**
 * 线程状态
 *

 * 1) NEW: 初始状态
 * 2) RUNNABLE: 运行状态, 包括运行(RUNNING)和就绪(READY)两种状态
 * 3) BLOCKED: 阻塞状态
 *      1) synchronized
 * 4) WAITING: 等待状态
 *      1) Object.wait()
 *      2) Thread.join()
 *      3) LockSupport.park()
 * 5) TIMED_WAITING: 超时等待状态
 *      1) Object.wait(timeout)
 *      2) Thread.join(timeout)
 *      3) Thread.sleep(timeout)
 *      4) LockSupport.parkNanos(timeout)
 *      5) LockSupport.parkUntil(timeout)
 * 6) TERMINATED: 终止状态
 *

 *

 * 1) 可通过jstack工具查看运行时的线程状态
 *

 *
 * @see Thread.State
 * @see Thread#getState()
 */
public class ThreadStatusTest {

//    jstack

//    RUNNING
//    runnable
//    java.lang.Thread.State: RUNNABLE

//    READY
//    waiting on condition
//    java.lang.Thread.State: RUNNABLE

//    synchronized
//    waiting for monitor entry
//    java.lang.Thread.State: BLOCKED (on object monitor)

//    Object.wait()或Thread.join()
//    in Object.wait()
//    java.lang.Thread.State: WAITING (on object monitor)

//    LockSupport.park()
//    waiting on condition
//    java.lang.Thread.State: WAITING (parking)

//    Thread.sleep(timeout)
//    waiting on condition
//    java.lang.Thread.State: TIMED_WAITING (sleeping)

//    Object.wait(timeout)或Thread.join(timeout)
//    in Object.wait()
//    java.lang.Thread.State: TIMED_WAITING (on object monitor)

//    LockSupport.parkNanos(timeout)或LockSupport.parkUntil(timeout)
//    waiting on condition
//    java.lang.Thread.State: TIMED_WAITING (parking)

    public static void main(String[] args) throws IOException, InterruptedException {
//        new Thread(new Runnable() {
//
//            @Override
//            public void run() {
//            }
//
//        }, "NEW");

//        for (int i = 0; i < 8; i++) {
//            startThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    int i = 0;
//                    for (; ; ) {
//                        i++;
//                    }
//                }
//
//            }, "RUNNABLE " + i);
//        }

//        Thread t = startThread(new Runnable() {
//
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                synchronized (this) {
//                    System.out.println("This is a BLOCKED Thread");
//                }
//            }
//
//        }, "BLOCKED");
//
//        synchronized (t) {
//            Thread.sleep(10000000);
//        }

//        Thread t = startThread(new Runnable() {
//
//            @Override
//            public void run() {
//                Object lock = new Object();
//                synchronized (lock) {
//                    try {
//                        lock.wait();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//
//        }, "WAITING 1");
//
//        startThread(new Runnable() {
//
//            @Override
//            public void run() {
//                try {
//                    t.join();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//
//        }, "WAITING 2");
//
//        startThread(new Runnable() {
//
//            @Override
//            public void run() {
//                LockSupport.park(this);
//            }
//
//        }, "WAITING 3");

        startThread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(100000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "TIMED_WAITING 1");

                Thread t = startThread(new Runnable() {

            @Override
            public void run() {
                Object lock = new Object();
                synchronized (lock) {
                    try {
                        lock.wait(100000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "TIMED_WAITING 2");

        startThread(new Runnable() {

            @Override
            public void run() {
                try {
                    t.join(100000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "TIMED_WAITING 3");

        startThread(new Runnable() {

            @Override
            public void run() {
                LockSupport.parkUntil(this,System.currentTimeMillis() + 100000);
            }

        }, "TIMED_WAITING 4");

        System.in.read();
    }

    private static Thread startThread(Runnable runnable, String name) {
        Thread t = new Thread(runnable, name);
        t.start();
        return t;
    }

}


text:
namespace Azure.ResourceManager.AppService.Models
{
    ///  Site config properties dictionary.
    public partial class SiteConfigPropertiesDictionary
    {
        ///  Initializes a new instance of SiteConfigPropertiesDictionary.
        internal SiteConfigPropertiesDictionary()
        {
        }

        ///  Initializes a new instance of SiteConfigPropertiesDictionary.
        /// <param name="use32BitWorkerProcess"> true if use32BitWorkerProcess should be set to true for the stack; otherwise, false. </param>
        /// <param name="linuxFxVersion"> LinuxFxVersion configuration setting. </param>
        /// <param name="javaVersion"> JavaVersion configuration setting. </param>
        /// <param name="powerShellVersion"> PowerShellVersion configuration setting. </param>
        internal SiteConfigPropertiesDictionary(bool? use32BitWorkerProcess, string linuxFxVersion, string javaVersion, string powerShellVersion)
        {
            Use32BitWorkerProcess = use32BitWorkerProcess;
            LinuxFxVersion = linuxFxVersion;
            JavaVersion = javaVersion;
            PowerShellVersion = powerShellVersion;
        }

        ///  true if use32BitWorkerProcess should be set to true for the stack; otherwise, false.
        public bool? Use32BitWorkerProcess { get; }
        ///  LinuxFxVersion configuration setting.
        public string LinuxFxVersion { get; }
        ///  JavaVersion configuration setting.
        public string JavaVersion { get; }
        ///  PowerShellVersion configuration setting.
        public string PowerShellVersion { get; }
    }
}


text:
package com.mongodb.internal.operation;

import com.mongodb.ExplainVerbosity;
import com.mongodb.MongoNamespace;
import com.mongodb.WriteConcern;
import com.mongodb.client.model.Collation;
import com.mongodb.connection.ConnectionDescription;
import com.mongodb.internal.async.SingleResultCallback;
import com.mongodb.internal.binding.AsyncWriteBinding;
import com.mongodb.internal.binding.WriteBinding;
import com.mongodb.internal.connection.AsyncConnection;
import com.mongodb.internal.connection.Connection;
import com.mongodb.internal.operation.CommandOperationHelper.CommandWriteTransformer;
import com.mongodb.internal.operation.CommandOperationHelper.CommandWriteTransformerAsync;
import org.bson.BsonBoolean;
import org.bson.BsonDocument;
import org.bson.BsonJavaScript;
import org.bson.BsonString;
import org.bson.codecs.BsonDocumentCodec;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.mongodb.assertions.Assertions.isTrue;
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback;
import static com.mongodb.internal.operation.CommandOperationHelper.executeCommand;
import static com.mongodb.internal.operation.CommandOperationHelper.executeCommandAsync;
import static com.mongodb.internal.operation.DocumentHelper.putIfNotNull;
import static com.mongodb.internal.operation.DocumentHelper.putIfNotZero;
import static com.mongodb.internal.operation.DocumentHelper.putIfTrue;
import static com.mongodb.internal.operation.OperationHelper.AsyncCallableWithConnection;
import static com.mongodb.internal.operation.OperationHelper.CallableWithConnection;
import static com.mongodb.internal.operation.OperationHelper.LOGGER;
import static com.mongodb.internal.operation.OperationHelper.releasingCallback;
import static com.mongodb.internal.operation.OperationHelper.withAsyncConnection;
import static com.mongodb.internal.operation.OperationHelper.withConnection;
import static com.mongodb.internal.operation.ServerVersionHelper.serverIsAtLeastVersionFourDotFour;
import static com.mongodb.internal.operation.WriteConcernHelper.appendWriteConcernToCommand;
import static com.mongodb.internal.operation.WriteConcernHelper.throwOnWriteConcernError;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

/**
 * Operation that runs a Map Reduce against a MongoDB instance.  This operation does not support "inline" results, i.e. the results will
 * be output into the collection represented by the MongoNamespace provided.
 *
 *
To run a map reduce operation and receive the results inline (i.e. as a response to running the command) use {@code
 * MapReduceToCollectionOperation}.

 *
 *
This class is not part of the public API and may be removed or changed at any time

 */
public class
MapReduceToCollectionOperation implements AsyncWriteOperation<MapReduceStatistics>, WriteOperation<MapReduceStatistics> {
    private final MongoNamespace namespace;
    private final BsonJavaScript mapFunction;
    private final BsonJavaScript reduceFunction;
    private final String collectionName;
    private final WriteConcern writeConcern;
    private BsonJavaScript finalizeFunction;
    private BsonDocument scope;
    private BsonDocument filter;
    private BsonDocument sort;
    private int limit;
    private boolean jsMode;
    private boolean verbose;
    private long maxTimeMS;
    private String action = "replace";
    private String databaseName;
    private boolean sharded;
    private boolean nonAtomic;
    private Boolean bypassDocumentValidation;
    private Collation collation;
    private static final List<String> VALID_ACTIONS = asList("replace", "merge", "reduce");

    public MapReduceToCollectionOperation(final MongoNamespace namespace, final BsonJavaScript mapFunction,
                                          final BsonJavaScript reduceFunction, final String collectionName) {
        this(namespace, mapFunction, reduceFunction, collectionName, null);
    }

    public MapReduceToCollectionOperation(final MongoNamespace namespace, final BsonJavaScript mapFunction,
                                          final BsonJavaScript reduceFunction, final String collectionName,
                                          final WriteConcern writeConcern) {
        this.namespace = notNull("namespace", namespace);
        this.mapFunction = notNull("mapFunction", mapFunction);
        this.reduceFunction = notNull("reduceFunction", reduceFunction);
        this.collectionName = notNull("collectionName", collectionName);
        this.writeConcern = writeConcern;
    }

    public MongoNamespace getNamespace() {
        return namespace;
    }

    public BsonJavaScript getMapFunction() {
        return mapFunction;
    }

    public BsonJavaScript getReduceFunction() {
        return reduceFunction;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public WriteConcern getWriteConcern() {
        return writeConcern;
    }

    public BsonJavaScript getFinalizeFunction() {
        return finalizeFunction;
    }

    public MapReduceToCollectionOperation finalizeFunction(final BsonJavaScript finalizeFunction) {
        this.finalizeFunction = finalizeFunction;
        return this;
    }

    public BsonDocument getScope() {
        return scope;
    }

    public MapReduceToCollectionOperation scope(final BsonDocument scope) {
        this.scope = scope;
        return this;
    }

    public BsonDocument getFilter() {
        return filter;
    }

    public MapReduceToCollectionOperation filter(final BsonDocument filter) {
        this.filter = filter;
        return this;
    }

    public BsonDocument getSort() {
        return sort;
    }

    public MapReduceToCollectionOperation sort(final BsonDocument sort) {
        this.sort = sort;
        return this;
    }

    public int getLimit() {
        return limit;
    }

    public MapReduceToCollectionOperation limit(final int limit) {
        this.limit = limit;
        return this;
    }

    public boolean isJsMode() {
        return jsMode;
    }

    public MapReduceToCollectionOperation jsMode(final boolean jsMode) {
        this.jsMode = jsMode;
        return this;
    }

    public boolean isVerbose() {
        return verbose;
    }

    public MapReduceToCollectionOperation verbose(final boolean verbose) {
        this.verbose = verbose;
        return this;
    }

    public long getMaxTime(final TimeUnit timeUnit) {
        notNull("timeUnit", timeUnit);
        return timeUnit.convert(maxTimeMS, TimeUnit.MILLISECONDS);
    }

    public MapReduceToCollectionOperation maxTime(final long maxTime, final TimeUnit timeUnit) {
        notNull("timeUnit", timeUnit);
        this.maxTimeMS = TimeUnit.MILLISECONDS.convert(maxTime, timeUnit);
        return this;
    }

    public String getAction() {
        return action;
    }

    public MapReduceToCollectionOperation action(final String action) {
        notNull("action", action);
        isTrue("action must be one of: \"replace\", \"merge\", \"reduce\"", VALID_ACTIONS.contains(action));
        this.action = action;
        return this;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public MapReduceToCollectionOperation databaseName(final String databaseName) {
        this.databaseName = databaseName;
        return this;
    }

    public boolean isSharded() {
        return sharded;
    }

    public MapReduceToCollectionOperation sharded(final boolean sharded) {
        this.sharded = sharded;
        return this;
    }

    public boolean isNonAtomic() {
        return nonAtomic;
    }

    public MapReduceToCollectionOperation nonAtomic(final boolean nonAtomic) {
        this.nonAtomic = nonAtomic;
        return this;
    }

    public Boolean getBypassDocumentValidation() {
        return bypassDocumentValidation;
    }

    public MapReduceToCollectionOperation bypassDocumentValidation(final Boolean bypassDocumentValidation) {
        this.bypassDocumentValidation = bypassDocumentValidation;
        return this;
    }

    public Collation getCollation() {
        return collation;
    }

    public MapReduceToCollectionOperation collation(final Collation collation) {
        this.collation = collation;
        return this;
    }

    @Override
    public MapReduceStatistics execute(final WriteBinding binding) {
        return withConnection(binding, new CallableWithConnection<MapReduceStatistics>() {
            @Override
            public MapReduceStatistics call(final Connection connection) {
                return executeCommand(binding, namespace.getDatabaseName(), getCommand(connection.getDescription()),
                        connection, transformer());
            }
        });
    }

    @Override
    public void executeAsync(final AsyncWriteBinding binding, final SingleResultCallback<MapReduceStatistics> callback) {
        withAsyncConnection(binding, new AsyncCallableWithConnection() {
            @Override
            public void call(final AsyncConnection connection, final Throwable t) {
                SingleResultCallback<MapReduceStatistics> errHandlingCallback = errorHandlingCallback(callback, LOGGER);
                if (t != null) {
                    errHandlingCallback.onResult(null, t);
                } else {
                    executeCommandAsync(binding, namespace.getDatabaseName(),
                            getCommand(connection.getDescription()), connection, transformerAsync(),
                            releasingCallback(errHandlingCallback, connection));

                }
            }
        });
    }

    /**
     * Gets an operation whose execution explains this operation.
     *
     * @param explainVerbosity the explain verbosity
     * @return a read operation that when executed will explain this operation
     */
    public ReadOperation<BsonDocument> asExplainableOperation(final ExplainVerbosity explainVerbosity) {
        return createExplainableOperation(explainVerbosity);
    }

    /**
     * Gets an operation whose execution explains this operation.
     *
     * @param explainVerbosity the explain verbosity
     * @return a read operation that when executed will explain this operation
     */
    public AsyncReadOperation<BsonDocument> asExplainableOperationAsync(final ExplainVerbosity explainVerbosity) {
        return createExplainableOperation(explainVerbosity);
    }

    private CommandReadOperation<BsonDocument> createExplainableOperation(final ExplainVerbosity explainVerbosity) {
        return new CommandReadOperation<BsonDocument>(namespace.getDatabaseName(),
                                                      ExplainHelper.asExplainCommand(getCommand(null), explainVerbosity),
                                                      new BsonDocumentCodec());
    }

    private CommandWriteTransformer<BsonDocument, MapReduceStatistics> transformer() {
        return new CommandWriteTransformer<BsonDocument, MapReduceStatistics>() {
            @SuppressWarnings("unchecked")
            @Override
            public MapReduceStatistics apply(final BsonDocument result, final Connection connection) {
                throwOnWriteConcernError(result, connection.getDescription().getServerAddress(),
                        connection.getDescription().getMaxWireVersion());
                return MapReduceHelper.createStatistics(result);
            }
        };
    }

    private CommandWriteTransformerAsync<BsonDocument, MapReduceStatistics> transformerAsync() {
        return new CommandWriteTransformerAsync<BsonDocument, MapReduceStatistics>() {
            @Override
            public MapReduceStatistics apply(final BsonDocument result, final AsyncConnection connection) {
                throwOnWriteConcernError(result, connection.getDescription().getServerAddress(),
                        connection.getDescription().getMaxWireVersion());
                return MapReduceHelper.createStatistics(result);
            }
        };
    }

    private BsonDocument getCommand(final ConnectionDescription description) {
        BsonDocument outputDocument = new BsonDocument(getAction(), new BsonString(getCollectionName()));
        if (description != null && !serverIsAtLeastVersionFourDotFour(description)) {
            putIfTrue(outputDocument, "sharded", isSharded());
            putIfTrue(outputDocument, "nonAtomic", isNonAtomic());
        }
        if (getDatabaseName() != null) {
            outputDocument.put("db", new BsonString(getDatabaseName()));
        }
        BsonDocument commandDocument = new BsonDocument("mapreduce", new BsonString(namespace.getCollectionName()))
                                           .append("map", getMapFunction())
                                           .append("reduce", getReduceFunction())
                                           .append("out", outputDocument);

        putIfNotNull(commandDocument, "query", getFilter());
        putIfNotNull(commandDocument, "sort", getSort());
        putIfNotNull(commandDocument, "finalize", getFinalizeFunction());
        putIfNotNull(commandDocument, "scope", getScope());
        putIfTrue(commandDocument, "verbose", isVerbose());
        putIfNotZero(commandDocument, "limit", getLimit());
        putIfNotZero(commandDocument, "maxTimeMS", getMaxTime(MILLISECONDS));
        putIfTrue(commandDocument, "jsMode", isJsMode());
        if (bypassDocumentValidation != null && description != null) {
            commandDocument.put("bypassDocumentValidation", BsonBoolean.valueOf(bypassDocumentValidation));
        }
        if (description != null) {
            appendWriteConcernToCommand(writeConcern, commandDocument);
        }
        if (collation != null) {
            commandDocument.put("collation", collation.asDocument());
        }
        return commandDocument;
    }
}


text:
module Fasterer
  class Token
    def initialize(name)
      @name = name
    end

    def method_definition?
      name == :def
    end

    def method_call?
      name == :call
    end

    def command_call?
      name == :command
    end

    def parallel_assignment?
      name == :massign
    end

    def for_loop?
      name == :for
    end
  end
end