text:
import logging
import math

from fooltrader.api.esapi import esapi
from fooltrader.domain.business.es_account import Account, Position
from fooltrader.utils.es_utils import es_get_latest_record, es_delete, es_index_mapping
from fooltrader.utils.utils import fill_doc_type

ORDER_TYPE_LONG = 0
ORDER_TYPE_SHORT = 1
ORDER_TYPE_CLOSE_LONG = 2
ORDER_TYPE_CLOSE_SHORT = 3

class AccountService(object):

    def __init__(self, bot_name, timestamp,
                 base_capital=1000000,
                 buy_cost=0.001,
                 sell_cost=0.001,
                 slippage=0.001,
                 stock_fuquan='hfq'):
        self.logger = logging.getLogger(__name__)

        self.base_capital = base_capital
        self.buy_cost = buy_cost
        self.sell_cost = sell_cost
        self.slippage = slippage
        self.stock_fuquan = stock_fuquan
        self.bot_name = bot_name

        account = es_get_latest_record(index='account', query={"term": {"botName": bot_name}})

        if account:
            self.logger.warning("bot:{} has run before,old result would be deleted".format(bot_name))
            es_delete(index='account', query={"term": {"botName": bot_name}})

        es_index_mapping('account', Account)

        self.account = Account()
        self.account.botName = bot_name
        self.account.cash = self.base_capital
        self.account.positions = []
        self.account.value = self.base_capital
        self.account.timestamp = timestamp
        self.account.save()

    def get_account(self, refresh=True):
        if refresh:
            account_json = es_get_latest_record(index='account', query={"term": {"botName": self.bot_name}})
            self.account = Account()
            fill_doc_type(self.account, account_json)

        return self.account

    def get_current_position(self, security_id):
        account = self.get_account()
        for position in account.positions:
            if position.securityId == security_id:
                return position
        return Position(security_id=security_id)

    # 计算收盘账户
    def calculate_closing_account(self, the_date):
        account = self.get_account()
        for position in account.positions:
            kdata = esapi.es_get_kdata(security_item=position['securityId'], the_date=the_date)
            closing_price = kdata['hfqClose']
            position.availableLong = position.longAmount
            position.availableShort = position.shortAmount

            # 做多导致的市值变化体现了value里
            # 做空导致的市值变化体现在value和cash里
            position.value = position.longAmount * closing_price + position.shortAmount * closing_price

            account.cash += 2 * (position.shortAmount * (position.averageShortPrice - closing_price))

            position.averageShortPrice = closing_price
            position.averageLongPrice = closing_price

    # 两种情况下会被调用:
    # 1)操作导致账户更新
    # 2)当日收盘
    def save_account(self):
        self.account.save()

    def update_account(self, security_id, new_position):
        # 先去掉之前的position
        positions = [position for position in self.account.positions if position.securityId != security_id]
        # 更新为新的position
        positions.append(new_position)
        self.account.positions = positions
        self.account.save()

    def update_position(self, current_position, order_amount, current_price, order_type):
        if order_type == ORDER_TYPE_LONG:
            # 计算平均价
            long_amount = current_position.longAmount + order_amount
            current_position.averageLongPrice = (current_position.averageLongPrice *
                                                 current_position.longAmount + current_price * current_price) / long_amount

            current_position.longAmount = long_amount

            if current_position.tradingT == 0:
                current_position.availableLong += order_amount
        elif order_type == ORDER_TYPE_SHORT:
            short_amount = current_position.shortAmount + order_amount
            current_position.averageShortPrice = (current_position.averageShortPrice *
                                                  current_position.shortAmount + current_price * current_price) / short_amount

            current_position.shortAmount = short_amount

            if current_position.tradingT == 0:
                current_position.availableShort += order_amount

    # 开多,对于某些品种只能开多,比如中国股票
    def buy(self, security_id, current_price, order_amount=0, order_pct=1.0, order_price=0):
        self.order(security_id, current_price, order_amount, order_pct, order_price, order_type=ORDER_TYPE_LONG)

    # 开空
    def sell(self, security_id, current_price, order_amount=0, order_pct=1.0, order_price=0):
        self.order(security_id, current_price, order_amount, order_pct, order_price, order_type=ORDER_TYPE_SHORT)

    # 平多
    def close_long(self, security_id, current_price, order_amount=0, order_pct=1.0, order_price=0):
        self.order(security_id, current_price, order_amount, order_pct, order_price, order_type=ORDER_TYPE_CLOSE_LONG)

    # 平空
    def close_short(self, security_id, current_price, order_amount=0, order_pct=1.0, order_price=0):
        self.order(security_id, current_price, order_amount, order_pct, order_price, order_type=ORDER_TYPE_CLOSE_SHORT)

    def order(self, security_id, current_price, order_amount=0, order_pct=1.0, order_price=0,
              order_type=ORDER_TYPE_LONG):
        """
        对每个投资标的开多.

        Parameters
        ----------
        security_id : str
            交易标的id

        current_price : float
            当前价格

        order_amount : int
            数量

        order_pct : float
            使用可用现金的百分比,0.0-1.0

        order_price : float
            用于限价交易

        order_type : {ORDER_TYPE_LONG,ORDER_TYPE_SHORT,ORDER_TYPE_CLOSE_LONG,ORDER_TYPE_CLOSE_SHORT}
            交易类型

        Returns
        -------

        """

        # 市价交易,就是买卖是"当时"并"一定"能成交的
        # 简单起见,目前只支持这种方式
        if order_price == 0:
            current_position = self.get_current_position(security_id=security_id)

            # 按数量交易
            if order_amount > 0:
                # 开多
                if order_type == ORDER_TYPE_LONG:
                    need_money = (order_amount * current_price) * (1 + self.slippage + self.buy_cost)
                    if self.account.cash >= need_money:
                        self.account.cash -= need_money
                        self.update_position(current_position, order_amount, current_price, order_type)
                    else:
                        raise Exception("not enough money")
                # 开空
                elif order_type == ORDER_TYPE_SHORT:
                    need_money = (order_amount * current_price) * (1 + self.slippage + self.buy_cost)
                    if self.account.cash >= need_money:
                        self.account.cash -= need_money
                        self.update_position(current_position, order_amount, current_price, order_type)
                    else:
                        raise Exception("not enough money")
                # 平多
                elif order_type == ORDER_TYPE_CLOSE_LONG:
                    if current_position.availableLong >= order_amount:
                        self.account.cash += (order_amount * current_price)
                        current_position.availableLong -= order_amount
                        current_position.longAmount -= order_amount
                    else:
                        raise Exception("not enough position")
                # 平空
                elif order_type == ORDER_TYPE_CLOSE_SHORT:
                    if current_position.availableShort >= order_amount:
                        self.account.cash += (order_amount * current_price)
                        current_position.availableShort -= order_amount
                        current_position.shortAmount -= order_amount
                    else:
                        raise Exception("not enough position")

            # 按仓位比例交易
            elif 0 < order_pct <= 1:
                # 开多
                if order_type == ORDER_TYPE_LONG:
                    cost = current_price * (1 + self.slippage + self.buy_cost)
                    want_buy = self.account.cash * order_pct
                    if want_buy >= cost:
                        # 买的数量
                        order_amount = want_buy // cost
                        # 使用的现金
                        self.account.cash -= (want_buy - want_buy % cost)
                        self.update_position(current_position, order_amount, current_price, order_type)
                    else:
                        raise Exception("not enough money")
                # 开空
                elif order_type == ORDER_TYPE_SHORT:
                    need_money = (order_amount * current_price) * (1 + self.slippage + self.buy_cost)
                    if self.account.cash >= need_money:
                        self.account.cash -= need_money
                        self.update_position(current_position, order_amount, current_price, order_type)
                    else:
                        raise Exception("not enough money")
                # 平多
                elif order_type == ORDER_TYPE_CLOSE_LONG:
                    if current_position.availableLong > 1:
                        order_amount = math.floor(current_position.availableLong * order_pct)
                        if order_amount != 0:
                            self.account.cash += (order_amount * current_price)
                            current_position.availableLong -= order_amount
                            current_position.longAmount -= order_amount
                        else:
                            self.logger.warning("{} availableLong:{} order_pct:{} order_amount:{}", security_id,
                                                current_position.availableLong, order_pct, order_amount)
                    else:
                        raise Exception("not enough position")
                # 平空
                elif order_type == ORDER_TYPE_CLOSE_SHORT:
                    if current_position.availableShort > 1:
                        order_amount = math.floor(current_position.availableShort * order_pct)
                        if order_amount != 0:
                            self.account.cash += (order_amount * current_price)
                            current_position.availableLong -= order_amount
                            current_position.longAmount -= order_amount
                        else:
                            self.logger.warning("{} availableLong:{} order_pct:{} order_amount:{}", security_id,
                                                current_position.availableLong, order_pct, order_amount)
                    else:
                        raise Exception("not enough position")

            self.update_account(security_id, current_position)


text:
$(document).ready(function() {
    $(".statusLoggedIn").hide();
    $(".statusNotLoggedIn").hide();

    checkLogin();
});

function checkLogin() {
    $("#loginForm :input").prop("disabled", true);
    $.get(URLSessionTest, function(data) {
        if (data != "") {
            var splitUsername = data.split(" ");
            $("#statusLoggedInUsername").html(splitUsername[1]);
            $(".statusNotLoggedIn").slideUp(250, function() {
                $(".statusLoggedIn").slideDown(250);
            });

            // Offer to log out.
            $("#logged-username").html(splitUsername[1]);
            $("#logout-container-slider").slideDown();
            $("#login-container-slider").slideUp();
            $("#loginForm :input").prop("disabled", true);
        }
        else if (data == "") {
            $(".statusLoggedIn").slideUp(250, function() {
                $(".statusNotLoggedIn").slideDown(250);
            });

            // OK.
            $("#logout-container-slider").slideUp();
            $("#login-container-slider").slideDown();
            $("#loginForm :input").prop("disabled", false);
        }
    });
}

function logout() {
    $.get(URLLogout, function() {
        $(".statusLoggedIn").slideUp(250, function() {
            $(".statusNotLoggedIn").slideDown(250);
        });
        $("#loginForm :input").prop("disabled", false);
        $("#logout-container-slider").slideUp();
        $("#login-container-slider").slideDown();

        setNotifier("You have successfully logged out.", true, false);
        if (statusTimer) clearTimeout(statusTimer);
        statusTimer = setTimeout(function() {
            setNotifier("You have successfully logged out.", false, false);
        }, 2500);
    });
}

function checkForm(form) {
    setNotifier("Logging in.", true, true);
    // Disable form
    $("#loginForm :input").prop("disabled", true);
    var loginPost = $.post(URLLoginPost, { username: form.username.value, password: form.password.value });
    loginPost.success(function(data) {
        console.log(data);
        if (data == "ok") {
            checkLogin();
            validationFeedback("You have successfully logged in.");
        }
        else if (data == "wrong") {
            validationFeedback("Wrong username/password combination.");
        }
        else {
            validationFeedback("Can not reach login server, please try again later.");
        }
        $("#loginForm :input").prop("disabled", false);
    });
    loginPost.fail(function(data) {
        // Re-enable form
        validationFeedback("Can not reach login server, please try again later.");
        $("#loginForm :input").prop("disabled", false);
    });
    return false;
}

var statusTimer = null;
function setNotifier(text, show, spinner) {
    $("#status-notifier-container").slideUp(250, function () {
        text = typeof text !== 'undefined' ? text : "Logging in";
        show = typeof show !== 'undefined' ? show : true;
        spinner = typeof spinner !== 'undefined' ? spinner : true;
        $("#status-notifier").html(" " + text);
        if (show == true) {
            $("#status-notifier-container").slideDown(250);
        }
        else {
            $("#status-notifier-container").slideUp(250);
        }
        if (spinner == true) {
            $("#spinner").show();
        }
        else {
            $("#spinner").hide();
        }
    });
}

function validationFeedback(text) {
    setNotifier(text, true, false);
    if (statusTimer) clearTimeout(statusTimer);
    statusTimer = setTimeout(function() {
        setNotifier(text, false, false);
    }, 3000);
}

redpajama_set_name: RedPajamaGithub


text:
package com.hhandoko.play.pdf

import java.io._
import scala.collection.mutable.ArrayBuffer

import com.google.inject.Singleton
import com.lowagie.text.pdf.BaseFont
import nu.validator.htmlparser.dom.HtmlDocumentBuilder
import org.apache.commons.io.{FilenameUtils, IOUtils}
import org.w3c.tidy.Tidy
import org.xhtmlrenderer.pdf.ITextRenderer

import play.api.Play
import play.api.mvc.{Result, Results}
import play.twirl.api.Html

/**
 * PDF generator service.
 *
 * @param xhtml true to set XHTML strict parsing (i.e. leave disabled for HTML5 templates).
 */
@Singleton
class PdfGenerator(val xhtml: Boolean = false) {

  /** HTML tidy checker / prettyprinter instance for XHTML strict parsing */
  private lazy val tidyParser = {
    val t = new Tidy()
    t.setXHTML(true)
    t
  }

  /** Default fonts */
  private var defaultFonts = ArrayBuffer[String]()

  /**
   * Load a list of fonts as temporary fonts (will be deleted when application exits) for PDF generation.
   * @note Existing default fonts collection will be cleared / emptied.
   *
   * @param fonts the list of font filenames to load.
   */
  def loadTemporaryFonts(fonts: Seq[String]): Unit = {
    defaultFonts.clear()
    addTemporaryFonts(fonts)
  }

  /**
   * Add a list of fonts as temporary fonts (will be deleted when application exits) for PDF generation.
   *
   * @param fonts the list of font filenames to add.
   */
  def addTemporaryFonts(fonts: Seq[String]): Unit = {
    fonts.foreach { font =>
      val stream = Play.current.resourceAsStream(font)

      stream.map { s =>
        val file = File.createTempFile("tmp_" + FilenameUtils.getBaseName(font), "." + FilenameUtils.getExtension(font))
        file.deleteOnExit()
        val output = new FileOutputStream(file)
        IOUtils.copy(s, output)
        defaultFonts += file.getAbsolutePath
      }
    }
  }

  /**
   * Load a list of local fonts for PDF generation.
   * @note Existing default fonts collection will be cleared / emptied.
   *
   * @param fonts the list of font filenames to load.
   */
  def loadLocalFonts(fonts: Seq[String]): Unit = {
    defaultFonts.clear()
    addLocalFonts(fonts)
  }

  /**
   * Add a list of local fonts for PDF generation.
   *
   * @param fonts the list of font filenames to load.
   */
  def addLocalFonts(fonts: Seq[String]): Unit = defaultFonts ++= fonts

  /**
   * Returns PDF result from Twirl HTML.
   *
   * @param html the Twirl HTML.
   * @param documentBaseUrl the document / page base URL.
   * @param fonts the external / additional fonts to load.
   * @return Generated PDF result (with "application/pdf" MIME type).
   */
  def ok(html: Html, documentBaseUrl: String, fonts: Seq[String] = defaultFonts): Result = {
    Results.Ok(toBytes(parseString(html), documentBaseUrl, fonts)).as("application/pdf")
  }

  /**
   * Generate PDF bytearray given Twirl HTML.
   *
   * @param html the Twirl HTML.
   * @param documentBaseUrl the document / page base URL.
   * @param fonts the external / additional fonts to load.
   * @return Generated PDF as bytearray.
   */
  def toBytes(html: Html, documentBaseUrl: String, fonts: Seq[String]): Array[Byte] = {
    // NOTE: Use default value assignment in method body,
    //       as Scala compiler does not like overloaded methods with default params
    val loadedFonts = if (fonts.isEmpty) defaultFonts else fonts
    toBytes(parseString(html), documentBaseUrl, loadedFonts)
  }

  /**
   * Generate PDF bytearray given HTML string.
   *
   * @param string the HTML string.
   * @param documentBaseUrl the document / page base URL.
   * @param fonts the external / additional fonts to load.
   * @return Generated PDF as bytearray.
   */
  def toBytes(string: String, documentBaseUrl: String, fonts: Seq[String]): Array[Byte] = {
    // NOTE: Use default value assignment in method body,
    //       as Scala compiler does not like overloaded methods with default params
    val loadedFonts = if (fonts.isEmpty) defaultFonts else fonts
    val output = new ByteArrayOutputStream()
    toStream(output)(string, documentBaseUrl, loadedFonts)
    output.toByteArray
  }

  /**
   * Generate and write PDF to an existing OutputStream given HTML string.
   *
   * @param output the OutputStream to write the generated PDF to.
   * @param string the HTML string.
   * @param documentBaseUrl the document / page base URL.
   * @param fonts the external / additional fonts to load.
   */
  def toStream(output: OutputStream)(string: String, documentBaseUrl: String, fonts: Seq[String] = defaultFonts): Unit = {
    val input = new ByteArrayInputStream(string.getBytes("UTF-8"))
    val renderer = new ITextRenderer()
    fonts.foreach { font => renderer.getFontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED) }
    val userAgent = new PdfUserAgent(renderer.getOutputDevice)
    userAgent.setSharedContext(renderer.getSharedContext)
    renderer.getSharedContext.setUserAgentCallback(userAgent)
    val document = new HtmlDocumentBuilder().parse(input)
    renderer.setDocument(document, documentBaseUrl)
    renderer.layout()
    renderer.createPDF(output)
  }

  /**
   * Parse Twirl HTML into HTML string.
   *
   * @param html the generated Twirl HTML.
   * @return HTML as string.
   */
  def parseString(html: Html): String = {
    if (xhtml) {
      val reader = new StringReader(html.body)
      val writer = new StringWriter()
      tidyParser.parse(reader, writer)
      writer.getBuffer.toString
    } else html.body
  }

}


text:
If you believe you have found a security vulnerability in Next.js, we encourage you to let us know right away.

We will investigate all legitimate reports and do our best to quickly fix the problem.

Email `security@vercel.com` to disclose any security vulnerabilities.

https://vercel.com/security


text:
import {
  report,
  ruleMessages,
  cssStatementHasEmptyBlock,
  validateOptions
} from "../../utils"

export const ruleName = "rule-trailing-semicolon"

export const messages = ruleMessages(ruleName, {
  expected: `Expected a trailing semicolon`,
  rejected: `Unexpected trailing semicolon`,
})

export default function (expectation) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: expectation,
      possible: [
        "always",
        "never",
      ],
    })
    if (!validOptions) { return }

    root.walkRules(rule => {
      // Return early if an empty rule
      if (cssStatementHasEmptyBlock(rule)) { return }

      if (!rule.last || rule.last.type !== "decl") { return }

      let errorIndex
      let message
      if (expectation === "always") {
        if (rule.raws.semicolon) { return }
        errorIndex = rule.toString().length - rule.raws.after.length - 1
        message = messages.expected
      }
      if (expectation === "never") {
        if (!rule.raws.semicolon) { return }
        errorIndex = rule.toString().length - rule.raws.after.length - 2
        message = messages.rejected
      }

      report({
        message,
        node: rule,
        index: errorIndex,
        result,
        ruleName,
      })
    })
  }
}


text:
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <syslog.h>
#include <pthread.h>
#include <json-c/json.h>
#include <wiringPi.h>

#include "oregon_radio.h"

//Receiver Vars
static volatile int oregon_latch = 0;
static volatile int oregon_start = 0;
static volatile oregon_msg_t oregon_message;

/*
  Global
*/

void rf_oregon_recv_clean(){
  oregon_message.sync_count = 0;
  //Fixed Message
  oregon_message.sensor_id = 0;
  oregon_message.channel = 0;
  oregon_message.rolling_code = 0;
  oregon_message.flags = 0;
  oregon_message.checksum = 0;
  //Variable Message
  oregon_message.var_content = 0;
  oregon_message.temperature = 0;
  oregon_message.temperature_sign = 0;
  oregon_message.humidity = 0;
  oregon_message.pressure = 0;
}

void _rf_oregon_recv_validate(){
}

void rf_oregon_print(oregon_msg_t *msg){

}

/*
  Receive Oregon Scentific sensor values
*/

int rf_oregon_recv(int state, int delta, int micro){
  if(oregon_latch > 0 & (micro - oregon_start) >  467200){
    rf_oregon_recv_clean();
    oregon_latch = 0;
    printf("Oregon Reset");
    return 0;
  }

  if(oregon_latch == 0 && state == 1 && delta > 396 && delta < 884){
    oregon_message.sync_count += 1;
  }

  if(oregon_latch == 0 && state == 0 && delta > 581 && delta < 1069){
    oregon_start = micro;
    oregon_latch = 1;
    printf("Oregon Sync Count: %d\n", oregon_message.sync_count);
  }

  return 0;
}
void rf_oregon_recv_process(oregon_msg_t *msg){

}
int rf_oregon_recv_json(oregon_msg_t *msg, char *buffer){
  return 0;
}


text:
{% extends base_template %}

{% block title %}
Fancy people talking about fancy dances
{% endblock title %}

{% block content %}
    The truth
    {% block fragment%}
        Loneliness, violence, and peanut butter
    {% endblock %}
{% endblock content %}


text:
package v1

// ImageLabelApplyConfiguration represents an declarative configuration of the ImageLabel type for use
// with apply.
type ImageLabelApplyConfiguration struct {
	Name  *string `json:"name,omitempty"`
	Value *string `json:"value,omitempty"`
}

// ImageLabelApplyConfiguration constructs an declarative configuration of the ImageLabel type for use with
// apply.
func ImageLabel() *ImageLabelApplyConfiguration {
	return &ImageLabelApplyConfiguration{}
}

// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *ImageLabelApplyConfiguration) WithName(value string) *ImageLabelApplyConfiguration {
	b.Name = &value
	return b
}

// WithValue sets the Value field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Value field is set to the value of the last call.
func (b *ImageLabelApplyConfiguration) WithValue(value string) *ImageLabelApplyConfiguration {
	b.Value = &value
	return b
}


text:
using System;
using UnityEngine;

namespace GameEngine
{
    public class WallBuilder : MonoBehaviour
    {
        public const float WallWidth = 0.1f;

        [SerializeField]
        private Ray[] halfrays;

        private Action _onComplete;
        private Action _onFail;

        private void Awake()
        {
            halfrays[0].OnHit += _CB_OnHalfRayIsHit;
            halfrays[1].OnHit += _CB_OnHalfRayIsHit;

            halfrays[0].OnReachAWall += _CB_OnHalfRayIsOver;
            halfrays[1].OnReachAWall += _CB_OnHalfRayIsOver;
        }

        public void DrawRay(Vector3 startingPos, RayLauncher.RayDirection direction, Action onComplete, Action onFail)
        {
            _onComplete = onComplete;
            _onFail = onFail;
            if (direction == RayLauncher.RayDirection.Horizontal)
            {
                halfrays[0].DrawRay(startingPos, Ray.RayDirection.Left);
                halfrays[1].DrawRay(startingPos, Ray.RayDirection.Right);
            }
            else
            {
                halfrays[0].DrawRay(startingPos, Ray.RayDirection.Up);
                halfrays[1].DrawRay(startingPos, Ray.RayDirection.Down);
            }
        }

        private void _CB_OnHalfRayIsOver()
        {
            if (halfrays[0].isOver && halfrays[1].isOver)
            {
                halfrays[0].OnHit -= _CB_OnHalfRayIsHit;
                halfrays[1].OnHit -= _CB_OnHalfRayIsHit;
                Destroy(halfrays[0]);
                Destroy(halfrays[1]);

                halfrays[0].gameObject.layer = LayerMask.NameToLayer("Wall");
                halfrays[1].gameObject.layer = LayerMask.NameToLayer("Wall");

                if (_onComplete != null)
                    _onComplete();
            }
        }

        private void _CB_OnHalfRayIsHit()
        {
            if (_onFail != null)
                _onFail();
            Destroy(this.gameObject);
        }
    }
}


text:
package main;

/**
 * @author Tony Liang
 *
 */
public class Rational extends Number implements Comparable<Object>
{
	private long numerator = 0;
	private long denominator = 1;

	/**
	 * Creates a new default Rational.
	 */
	public Rational()
	{
		this(0, 1);
	}

	/**
	 * Creates a new Rational given the numerator and denominator.
	 *
	 * @param numerator		numerator
	 * @param denominator	denominator
	 */
	public Rational(long numerator, long denominator)
	{
		long gcd = gcd(numerator, denominator);
		this.numerator = ((denominator > 0) ? 1 : -1) * numerator / gcd;
		this.denominator = Math.abs(denominator) / gcd;
	}

	private static long gcd(long n, long d)
	{
		long n1 = Math.abs(n);
		long n2 = Math.abs(d);
		int gcd = 1;

		for (int k = 1; k <= n1 && k <= n2; k++)
		{
			if (n1 % k == 0 && n2 % k == 0)
			{
				gcd = k;
			}
		}

		return gcd;
	}

	public long getNumerator()
	{
		return numerator;
	}

	public long getDenominator()
	{
		return denominator;
	}

	public Rational add(Rational secondRational)
	{
		long n = numerator * secondRational.getDenominator() + denominator * secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		return new Rational(n, d);
	}

	public Rational subtract(Rational secondRational)
	{
		long n = numerator * secondRational.getDenominator() - denominator * secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		return new Rational(n, d);
	}

	public Rational multiply(Rational secondRational)
	{
		long n = numerator * secondRational.getNumerator();
		long d = denominator * secondRational.getDenominator();
		return new Rational(n, d);
	}

	public Rational divide(Rational secondRational)
	{
		long n = numerator * secondRational.getDenominator();
		long d = denominator * secondRational.getNumerator();
		return new Rational(n, d);
	}

	@Override
	public String toString()
	{
		if (denominator == 1)
		{
			return numerator + "";
		}
		else
		{
			return numerator + "/" + denominator;
		}
	}

	@Override
	public boolean equals(Object param1)
	{
		if ((this.subtract((Rational)(param1))).getNumerator() == 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	@Override
	public int intValue()
	{
		return (int)doubleValue();
	}

	@Override
	public float floatValue()
	{
		return (float)doubleValue();
	}

	@Override
	public double doubleValue()
	{
		return numerator * 1.0 / denominator;
	}

	@Override
	public long longValue()
	{
		return (long)doubleValue();
	}

	@Override
	public int compareTo(Object o)
	{
		if (this.subtract((Rational)o).getNumerator() > 0)
		{
			return 1;
		}
		else if (this.subtract((Rational)o).getNumerator() < 0)
		{
			return -1;
		}
		else
		{
			return 0;
		}
	}
}


text:
<!doctype html>

    <title>drag and drop sequence should end when dropping over a plugin</title>

Use your pointing device to drag the orange square onto the blue square, and release it. The drag placeholder should disappear after releasing (or as the pointer moves over the blue square). Try dragging the orange square again. Fail if it does not respond when trying to drag it.

<object data="../resources/boxnavy.swf"></object>


text:
published: true
title: XXIIe dimanche après la Pentecôte
---
**Dimanche 5 novembre 2017, messe de 19h**

![Si iniquitates.jpg]({{site.baseurl}}/images/Si iniquitates.jpg)

*Ego clamavi, quoniam exaudisti me, Deus*
Je t'appelle, puisque tu m'écoutes, mon Dieu.

**Introït : Si iniquitates**

**Graduel : Ecce quam bonum**
faux-bourdon parisien du Ier ton

**Alleluia : Qui timent Dominum**

**Offertoire : Benedicamus in laude**
anonyme XVe - ms de Trente

**Communion : O sacrum convivium**
d'après anonyme XVe - ms de Trente

**Au dernier évangile : Salve Regina**

**Sortie : Salve Regina misericordiae**
anonyme XVe - ms de Trente


text:
using System;

namespace Azure.ResourceManager.StorageSync.Models
{
    /// <summary> Server endpoint cloud tiering status object. </summary>
    public partial class CloudTieringCachePerformance
    {
        /// <summary> Initializes a new instance of CloudTieringCachePerformance. </summary>
        internal CloudTieringCachePerformance()
        {
        }

        /// <summary> Initializes a new instance of CloudTieringCachePerformance. </summary>
        /// <param name="lastUpdatedOn"> Last updated timestamp. </param>
        /// <param name="cacheHitBytes"> Count of bytes that were served from the local server. </param>
        /// <param name="cacheMissBytes"> Count of bytes that were served from the cloud. </param>
        /// <param name="cacheHitBytesPercent"> Percentage of total bytes (hit + miss) that were served from the local server. </param>
        internal CloudTieringCachePerformance(DateTimeOffset? lastUpdatedOn, long? cacheHitBytes, long? cacheMissBytes, int? cacheHitBytesPercent)
        {
            LastUpdatedOn = lastUpdatedOn;
            CacheHitBytes = cacheHitBytes;
            CacheMissBytes = cacheMissBytes;
            CacheHitBytesPercent = cacheHitBytesPercent;
        }

        /// <summary> Last updated timestamp. </summary>
        public DateTimeOffset? LastUpdatedOn { get; }
        /// <summary> Count of bytes that were served from the local server. </summary>
        public long? CacheHitBytes { get; }
        /// <summary> Count of bytes that were served from the cloud. </summary>
        public long? CacheMissBytes { get; }
        /// <summary> Percentage of total bytes (hit + miss) that were served from the local server. </summary>
        public int? CacheHitBytesPercent { get; }
    }
}


text:
module Emma
  module API
    module Fields
      # Gets a list of this account's defined fields.
      def my_fields(params = {})
        get("/fields", params)
      end

      # Gets the detailed information about a particular field.
      def get_field_by_id(id, params = {})
        get("/fields/#{id}", params)
      end

      # Create a new field
      def add_field(params = {})
        post("/fields", params)
      end

      # Delete a field
      def remove_field(id)
        delete("/fields/#{id}")
      end

      # Clear the member data for the specified field.
      def remove_member_data_for_field(id)
        post("/fields/#{id}/clear")
      end

      # Updates an existing field.
      def update_field(id, params = {})
        put("/fields/#{id}", params)
      end
    end
  end
end


text:
var EditorSaveButtonView = Ember.View.extend({
    templateName: 'editor-save-button',
    tagName: 'section',
    classNames: ['splitbtn', 'js-publish-splitbutton'],

    // Tracks whether we're going to change the state of the post on save
    isDangerous: Ember.computed('controller.isPublished', 'controller.willPublish', function () {
        return this.get('controller.isPublished') !== this.get('controller.willPublish');
    }),

    publishText: Ember.computed('controller.isPublished', function () {
        return this.get('controller.isPublished') ? 'Update Post' : 'Publish Now';
    }),

    draftText: Ember.computed('controller.isPublished', function () {
        return this.get('controller.isPublished') ? 'Unpublish' : 'Save Draft';
    }),

    saveText: Ember.computed('controller.willPublish', function () {
        return this.get('controller.willPublish') ? this.get('publishText') : this.get('draftText');
    })
});

export default EditorSaveButtonView;


text:
package com.hotf.client.action.result;

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

import net.customware.gwt.dispatch.shared.Result;

/**
 * @author Jeff
 *
 */
public class CharacterGeneralSkillResult implements Result {

	private GameGeneralSkillResult gameGeneralSkill;
	private Integer ranks;
	private Integer level;
	private Integer modifier;
	private List<CharacterSkillResult> skills = new ArrayList<CharacterSkillResult>();

	public CharacterGeneralSkillResult() {
		super();
	}

	public GameGeneralSkillResult getGameGeneralSkill() {
		return gameGeneralSkill;
	}

	public void setGameGeneralSkill(GameGeneralSkillResult gameGeneralSkill) {
		this.gameGeneralSkill = gameGeneralSkill;
	}

	public Integer getRanks() {
		return ranks;
	}

	public void setRanks(Integer ranks) {
		this.ranks = ranks;
	}

	public Integer getLevel() {
		return level;
	}

	public void setLevel(Integer level) {
		this.level = level;
	}

	public Integer getModifier() {
		return modifier;
	}

	public void setModifier(Integer modifier) {
		this.modifier = modifier;
	}

	public List<CharacterSkillResult> getSkills() {
		return skills;
	}

	public void setSkills(List<CharacterSkillResult> skills) {
		this.skills = skills;
	}

}


text:
package com.secdec.bytefrog.agent.control.test

import org.scalatest.FunSpec
import org.scalatest._
import org.scalatest.Matchers._
import org.scalamock.scalatest.MockFactory

import com.codedx.codepulse.agent.control.ModeChangeListener
import com.codedx.codepulse.agent.control.StateManager
import com.secdec.bytefrog.agent.util.ErrorEnforcement
import com.secdec.bytefrog.agent.util.MockHelpers
import com.secdec.bytefrog.agent.util.StateManagerHelpers
import com.codedx.codepulse.agent.common.message.AgentOperationMode

class StateManagerSuite extends FunSpec with MockFactory with Matchers with ErrorEnforcement with MockHelpers with StateManagerHelpers {
	describe("state manager") {
		it("should start in initialization mode") {
			enforceNoErrors

			val sm = new StateManager

			sm.getCurrentMode should be(AgentOperationMode.Initializing)
		}

		it("should properly add mode change listeners") {
			val listener = mock[ModeChangeListener]
			(listener.onModeChange _).expects(*, *).once

			val sm = new StateManager

			sm.withListener(listener) {
				sm.triggerShutdown();
			}
		}

		it("should properly remove mode change listeners") {
			val listener = mock[ModeChangeListener]
			(listener.onModeChange _).expects(*, *).never

			val sm = new StateManager

			sm.withListener(listener) {
				sm.removeListener(listener)
				sm.triggerShutdown();
			}
		}

		it("should change to shutdown mode upon triggerShutdown()") {
			enforceNoErrors

			val sm = new StateManager
			sm.triggerShutdown()

			sm.getCurrentMode should be(AgentOperationMode.Shutdown)
		}

		describe("control message handler from getControlMessageHandler()") {
			it("should handle onStart properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once

				sm.withListener(listener) {
					cmh.onStart
				}

				sm.getCurrentMode should be(AgentOperationMode.Tracing)
			}

			it("should handle onStart properly (while suspended)") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Suspended).once

				sm.withListener(listener) {
					cmh.onSuspend
					cmh.onStart
				}

				sm.getCurrentMode should be(AgentOperationMode.Suspended)
			}

			it("should handle onStop properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once
				(listener.onModeChange _).expects(AgentOperationMode.Tracing, AgentOperationMode.Shutdown).once

				sm.withListener(listener) {
					cmh.onStart
					cmh.onStop
				}

				sm.getCurrentMode should be(AgentOperationMode.Shutdown)
			}

			it("should handle onPause properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once
				(listener.onModeChange _).expects(AgentOperationMode.Tracing, AgentOperationMode.Paused).once

				sm.withListener(listener) {
					cmh.onStart
					cmh.onPause
				}

				sm.getCurrentMode should be(AgentOperationMode.Paused)

				// pause is only valid when tracing, so calling pause again should error
				enforceError("pause control message is only valid when tracing")
				cmh.onPause
			}

			it("should handle onUnpause properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once
				(listener.onModeChange _).expects(AgentOperationMode.Tracing, AgentOperationMode.Paused).once
				(listener.onModeChange _).expects(AgentOperationMode.Paused, AgentOperationMode.Tracing).once

				sm.withListener(listener) {
					cmh.onStart
					cmh.onPause
					cmh.onUnpause
				}

				sm.getCurrentMode should be(AgentOperationMode.Tracing)

				// unpause is only valid when paused, so calling unpause again should error
				enforceError("unpause control message is only valid when paused")
				cmh.onUnpause
			}

			it("should handle onSuspend properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once
				(listener.onModeChange _).expects(AgentOperationMode.Tracing, AgentOperationMode.Suspended).once

				sm.withListener(listener) {
					cmh.onStart
					cmh.onSuspend
				}

				sm.getCurrentMode should be(AgentOperationMode.Suspended)

				// suspend is only valid when tracing, so calling suspend again should error
				enforceError("suspend control message is only valid when tracing or initializing")
				cmh.onSuspend
			}

			it("should handle onUnsuspend properly") {
				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				val listener = mock[ModeChangeListener]
				(listener.onModeChange _).expects(AgentOperationMode.Initializing, AgentOperationMode.Tracing).once
				(listener.onModeChange _).expects(AgentOperationMode.Tracing, AgentOperationMode.Suspended).once
				(listener.onModeChange _).expects(AgentOperationMode.Suspended, AgentOperationMode.Tracing).once

				sm.withListener(listener) {
					cmh.onStart
					cmh.onSuspend
					cmh.onUnsuspend
				}

				sm.getCurrentMode should be(AgentOperationMode.Tracing)

				// unsuspend is only valid when suspended, so calling unsuspend again should error
				enforceError("unsuspend control message is only valid when suspended or initializing")
				cmh.onUnsuspend
			}

			it("should defer to ErrorHandler onError") {
				val errorMessage = "error message"
				val expectedError = s"received error from HQ: $errorMessage"

				enforceNoErrors

				val sm = new StateManager
				val cmh = sm.getControlMessageHandler

				enforceError(expectedError)
				cmh.onError(errorMessage)
			}
		}
	}
}


text:
package tagsvc

import (
	"fmt"
	"log"
	"net"

	"github.com/pgm/pliant/v2"
	"github.com/pgm/pliant/v2/s3"
	//"net/http"
	"net/rpc"
	//	"strconv"
	"bytes"
	"crypto/md5"
	"crypto/rand"
	"errors"
	"time"
)

const CHALLENGE_SIZE int = 64
const GREETING string = "minion_v1\n"

func RandomChallenge() []byte {
	b := make([]byte, CHALLENGE_SIZE)
	rand.Read(b)
	return b
}

func ComputeResponse(secret []byte, client []byte, server []byte) []byte {
	buf := bytes.NewBuffer(make([]byte, 0, 100))
	buf.Write(secret)
	buf.Write(client)
	buf.Write(server)
	response := md5.Sum(buf.Bytes())

	return response[:]
}

var NO_SUCH_KEY error = errors.New("No such key")

type Config struct {
	AccessKeyId     string
	SecretAccessKey string
	Endpoint        string
	Bucket          string
	MasterPort      int
	Prefix          string
	PersistPath     string
	AuthSecret      string
}

type Master struct {
	roots  *Roots
	config *Config
}

type SetArgs struct {
	Label string
	Key   *v2.Key
}

type AddLeaseArgs struct {
	Timeout uint64
	Key     *v2.Key
}

func (t *Master) Set(args *SetArgs, reply *bool) error {
	t.roots.Set(args.Label, args.Key)

	*reply = true

	return nil
}

func (t *Master) Get(label *string, reply *v2.Key) error {
	replyPtr := t.roots.Get(*label)
	if replyPtr == nil {
		return NO_SUCH_KEY
	}
	*reply = *replyPtr

	return nil
}

func (t *Master) GetAll(ignored *string, reply *[]NameAndKey) error {
	*reply = t.roots.GetNamedRoots()

	return nil
}

func (t *Master) AddLease(args *AddLeaseArgs, reply *bool) error {
	now := uint64(time.Now().Unix())
	t.roots.AddLease(args.Timeout+now, args.Key)

	*reply = true

	return nil
}

func (t *Master) GC(label *string, reply *v2.Key) error {
	panic("todo: update code to pass in bolt db ref")
	cache, _ := v2.NewFilesystemCacheDB("cache", nil)
	chunkService := s3.NewS3ChunkService(t.config.AccessKeyId, t.config.SecretAccessKey, t.config.Endpoint, t.config.Bucket, t.config.Prefix, cache.AllocateTempFilename)
	dirService := v2.NewLeafDirService(chunkService)
	t.roots.GC(dirService, chunkService, chunkService.Delete)

	return nil
}

func (t *Master) GetConfig(nothing *string, reply *Config) error {
	fmt.Printf("reply=%s\nconfig=%s\n", reply, t.config)
	*reply = *t.config

	return nil
}

/*	clientChallenge := RandomChallenge()

	conn.Write([]byte(GREETING))
	conn.Write(clientChallenge)

	serverChallenge := make([]byte, CHALLENGE_SIZE)
	n, err := conn.Read(serverChallenge)
	if n != CHALLENGE_SIZE {
		log.Fatalf("expecting challenge but read %d", n)
	}

	response := ComputeResponse([]byte(authSecret), clientChallenge, serverChallenge)
	conn.Write(response)
*/

func handleConnection(config *Config, conn net.Conn) {
	serverChallenge := RandomChallenge()
	clientChallenge := make([]byte, CHALLENGE_SIZE)

	greetingBuffer := make([]byte, len([]byte(GREETING)))
	conn.Read(greetingBuffer)
	n, _ := conn.Read(clientChallenge)
	if n != CHALLENGE_SIZE {
		log.Fatalf("expecting challenge but read %d", n)
	}

	conn.Write(serverChallenge)

	expected := ComputeResponse([]byte(config.AuthSecret), clientChallenge, serverChallenge)
	response := make([]byte, len(expected))
	conn.Read(response)
	if bytes.Compare(expected, response) == 0 {
		fmt.Printf("Auth succeeded!\n")
		rpc.ServeConn(conn)
	} else {
		fmt.Printf("Auth failed!\n")
		conn.Close()
	}
}

func listenForever(config *Config, l net.Listener) {
	for {
		log.Printf("Serve starting")

		conn, err := l.Accept()
		if err != nil {
			fmt.Printf("Accept failed %s", err)
			break
		}

		go handleConnection(config, conn)
	}
}

func StartServer(config *Config) (net.Listener, error) {
	ac := &Master{config: config, roots: NewRoots(config.PersistPath)}
	rpc.Register(ac)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", fmt.Sprintf("localhost:%d", config.MasterPort))
	if e != nil {
		log.Fatal("listen error:", e)
		return nil, e
	}

	go listenForever(config, l)

	return l, nil
}

type Client struct {
	client *rpc.Client
}

func (c *Client) GetConfig() (*Config, error) {
	var config Config
	param := "nil"
	err := c.client.Call("Master.GetConfig", param, &config)
	if err != nil {
		return nil, err
	}
	return &config, nil
}

func (c *Client) Get(label string) (*v2.Key, error) {
	var key v2.Key
	err := c.client.Call("Master.Get", label, &key)
	if err != nil {
		return nil, err
	}
	return &key, nil
}

type NameAndKey struct {
	Name string
	Key  *v2.Key
}

func (c *Client) GetAll() ([]NameAndKey, error) {
	var input = ""
	var result []NameAndKey
	err := c.client.Call("Master.GetAll", &input, &result)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func (c *Client) Set(label string, key *v2.Key) error {
	err := c.client.Call("Master.Set", &SetArgs{label, key}, nil)
	return err
}

func (c *Client) AddLease(Timeout uint64, Key *v2.Key) error {
	err := c.client.Call("Master.AddLease", &AddLeaseArgs{Timeout, Key}, nil)
	return err
}

func NewClient(address string, authSecret []byte) *Client {
	conn, err := net.Dial("tcp", address)
	if err != nil {
		log.Fatal("dialing:", err)
	}

	clientChallenge := RandomChallenge()

	conn.Write([]byte(GREETING))
	conn.Write(clientChallenge)

	serverChallenge := make([]byte, CHALLENGE_SIZE)
	n, err := conn.Read(serverChallenge)
	if n != CHALLENGE_SIZE {
		log.Fatalf("expecting challenge but read %d", n)
	}

	response := ComputeResponse([]byte(authSecret), clientChallenge, serverChallenge)
	conn.Write(response)

	client := rpc.NewClient(conn)
	return &Client{client: client}
}

type TagService struct {
	client *Client
}

func (t *TagService) Put(name string, key *v2.Key) error {
	return t.client.Set(name, key)
}

func (t *TagService) Get(name string) (*v2.Key, error) {
	key, err := t.client.Get(name)
	if err != nil {
		if err.Error() == NO_SUCH_KEY.Error() {
			return nil, nil
		}
		return nil, err
	}
	return key, nil
}

func (t *TagService) ForEach(callback func(name string, key *v2.Key)) {
	result, err := t.client.GetAll()
	if err != nil {
		panic(err.Error())
	}
	for _, nameAndKey := range result {
		callback(nameAndKey.Name, nameAndKey.Key)
	}
}

func NewTagService(c *Client) v2.TagService {
	return &TagService{client: c}
}


text:
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
#include <wchar.h>

#include "termbox.h"

#include "bytebuffer.inl"
#include "term.inl"
#include "input.inl"

struct cellbuf {
	int width;
	int height;
	struct tb_cell *cells;
};

#define CELL(buf, x, y) (buf)->cells[(y) * (buf)->width + (x)]
#define IS_CURSOR_HIDDEN(cx, cy) (cx == -1 || cy == -1)
#define LAST_COORD_INIT -1

static struct termios orig_tios;

static struct cellbuf back_buffer;
static struct cellbuf front_buffer;
static struct bytebuffer output_buffer;
static struct bytebuffer input_buffer;

static int termw = -1;
static int termh = -1;

static int inputmode = TB_INPUT_ESC;
static int outputmode = TB_OUTPUT_NORMAL;

static int inout;
static int winch_fds[2];

static int lastx = LAST_COORD_INIT;
static int lasty = LAST_COORD_INIT;
static int cursor_x = -1;
static int cursor_y = -1;

static uint16_t background = TB_DEFAULT;
static uint16_t foreground = TB_DEFAULT;

static void write_cursor(int x, int y);
static void write_sgr(uint16_t fg, uint16_t bg);

static void cellbuf_init(struct cellbuf *buf, int width, int height);
static void cellbuf_resize(struct cellbuf *buf, int width, int height);
static void cellbuf_clear(struct cellbuf *buf);
static void cellbuf_free(struct cellbuf *buf);

static void update_size(void);
static void update_term_size(void);
static void send_attr(uint16_t fg, uint16_t bg);
static void send_char(int x, int y, uint32_t c);
static void send_clear(void);
static void sigwinch_handler(int xxx);
static int wait_fill_event(struct tb_event *event, struct timeval *timeout);

/* may happen in a different thread */
static volatile int buffer_size_change_request;

/* -------------------------------------------------------- */

int tb_init_fd(int inout_)
{
	inout = inout_;
	if (inout == -1) {
		return TB_EFAILED_TO_OPEN_TTY;
	}

	if (init_term() < 0) {
		close(inout);
		return TB_EUNSUPPORTED_TERMINAL;
	}

	if (pipe(winch_fds) < 0) {
		close(inout);
		return TB_EPIPE_TRAP_ERROR;
	}

	struct sigaction sa;
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = sigwinch_handler;
	sa.sa_flags = 0;
	sigaction(SIGWINCH, &sa, 0);

	tcgetattr(inout, &orig_tios);

	struct termios tios;
	memcpy(&tios, &orig_tios, sizeof(tios));

	tios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                           | INLCR | IGNCR | ICRNL | IXON);
	tios.c_oflag &= ~OPOST;
	tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
	tios.c_cflag &= ~(CSIZE | PARENB);
	tios.c_cflag |= CS8;
	tios.c_cc[VMIN] = 0;
	tios.c_cc[VTIME] = 0;
	tcsetattr(inout, TCSAFLUSH, &tios);

	bytebuffer_init(&input_buffer, 128);
	bytebuffer_init(&output_buffer, 32 * 1024);

	bytebuffer_puts(&output_buffer, funcs[T_ENTER_CA]);
	bytebuffer_puts(&output_buffer, funcs[T_ENTER_KEYPAD]);
	bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]);
	send_clear();

	update_term_size();
	cellbuf_init(&back_buffer, termw, termh);
	cellbuf_init(&front_buffer, termw, termh);
	cellbuf_clear(&back_buffer);
	cellbuf_clear(&front_buffer);

	return 0;
}

int tb_init_file(const char* name){
	return tb_init_fd(open(name, O_RDWR));
}

int tb_init(void)
{
	return tb_init_file("/dev/tty");
}

void tb_shutdown(void)
{
	if (termw == -1) {
		fputs("tb_shutdown() should not be called twice.", stderr);
		abort();
	}

	bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]);
	bytebuffer_puts(&output_buffer, funcs[T_SGR0]);
	bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]);
	bytebuffer_puts(&output_buffer, funcs[T_EXIT_CA]);
	bytebuffer_puts(&output_buffer, funcs[T_EXIT_KEYPAD]);
	bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]);
	bytebuffer_flush(&output_buffer, inout);
	tcsetattr(inout, TCSAFLUSH, &orig_tios);

	shutdown_term();
	close(inout);
	close(winch_fds[0]);
	close(winch_fds[1]);

	cellbuf_free(&back_buffer);
	cellbuf_free(&front_buffer);
	bytebuffer_free(&output_buffer);
	bytebuffer_free(&input_buffer);
	termw = termh = -1;
}

void tb_present(void)
{
	int x,y,w,i;
	struct tb_cell *back, *front;

	/* invalidate cursor position */
	lastx = LAST_COORD_INIT;
	lasty = LAST_COORD_INIT;

	if (buffer_size_change_request) {
		update_size();
		buffer_size_change_request = 0;
	}

	for (y = 0; y < front_buffer.height; ++y) {
		for (x = 0; x < front_buffer.width; ) {
			back = &CELL(&back_buffer, x, y);
			front = &CELL(&front_buffer, x, y);
			w = wcwidth(back->ch);
			if (w < 1) w = 1;
			if (memcmp(back, front, sizeof(struct tb_cell)) == 0) {
				x += w;
				continue;
			}
			memcpy(front, back, sizeof(struct tb_cell));
			send_attr(back->fg, back->bg);
			if (w > 1 && x >= front_buffer.width - (w - 1)) {
				// Not enough room for wide ch, so send spaces
				for (i = x; i < front_buffer.width; ++i) {
					send_char(i, y, ' ');
				}
			} else {
				send_char(x, y, back->ch);
				for (i = 1; i < w; ++i) {
					front = &CELL(&front_buffer, x + i, y);
					front->ch = 0;
					front->fg = back->fg;
					front->bg = back->bg;
				}
			}
			x += w;
		}
	}
	if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
		write_cursor(cursor_x, cursor_y);
	bytebuffer_flush(&output_buffer, inout);
}

void tb_set_cursor(int cx, int cy)
{
	if (IS_CURSOR_HIDDEN(cursor_x, cursor_y) && !IS_CURSOR_HIDDEN(cx, cy))
		bytebuffer_puts(&output_buffer, funcs[T_SHOW_CURSOR]);

	if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y) && IS_CURSOR_HIDDEN(cx, cy))
		bytebuffer_puts(&output_buffer, funcs[T_HIDE_CURSOR]);

	cursor_x = cx;
	cursor_y = cy;
	if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
		write_cursor(cursor_x, cursor_y);
}

void tb_put_cell(int x, int y, const struct tb_cell *cell)
{
	if ((unsigned)x >= (unsigned)back_buffer.width)
		return;
	if ((unsigned)y >= (unsigned)back_buffer.height)
		return;
	CELL(&back_buffer, x, y) = *cell;
}

void tb_change_cell(int x, int y, uint32_t ch, uint16_t fg, uint16_t bg)
{
	struct tb_cell c = {ch, fg, bg};
	tb_put_cell(x, y, &c);
}

void tb_blit(int x, int y, int w, int h, const struct tb_cell *cells)
{
	if (x + w < 0 || x >= back_buffer.width)
		return;
	if (y + h < 0 || y >= back_buffer.height)
		return;
	int xo = 0, yo = 0, ww = w, hh = h;
	if (x < 0) {
		xo = -x;
		ww -= xo;
		x = 0;
	}
	if (y < 0) {
		yo = -y;
		hh -= yo;
		y = 0;
	}
	if (ww > back_buffer.width - x)
		ww = back_buffer.width - x;
	if (hh > back_buffer.height - y)
		hh = back_buffer.height - y;

	int sy;
	struct tb_cell *dst = &CELL(&back_buffer, x, y);
	const struct tb_cell *src = cells + yo * w + xo;
	size_t size = sizeof(struct tb_cell) * ww;

	for (sy = 0; sy < hh; ++sy) {
		memcpy(dst, src, size);
		dst += back_buffer.width;
		src += w;
	}
}

struct tb_cell *tb_cell_buffer(void)
{
	return back_buffer.cells;
}

int tb_poll_event(struct tb_event *event)
{
	return wait_fill_event(event, 0);
}

int tb_peek_event(struct tb_event *event, int timeout)
{
	struct timeval tv;
	tv.tv_sec = timeout / 1000;
	tv.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000;
	return wait_fill_event(event, &tv);
}

int tb_width(void)
{
	return termw;
}

int tb_height(void)
{
	return termh;
}

void tb_clear(void)
{
	if (buffer_size_change_request) {
		update_size();
		buffer_size_change_request = 0;
	}
	cellbuf_clear(&back_buffer);
}

int tb_select_input_mode(int mode)
{
	if (mode) {
		if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == 0)
			mode |= TB_INPUT_ESC;

		/* technically termbox can handle that, but let's be nice and show here
		   what mode is actually used */
		if ((mode & (TB_INPUT_ESC | TB_INPUT_ALT)) == (TB_INPUT_ESC | TB_INPUT_ALT))
			mode &= ~TB_INPUT_ALT;

		inputmode = mode;
		if (mode&TB_INPUT_MOUSE) {
			bytebuffer_puts(&output_buffer, funcs[T_ENTER_MOUSE]);
			bytebuffer_flush(&output_buffer, inout);
		} else {
			bytebuffer_puts(&output_buffer, funcs[T_EXIT_MOUSE]);
			bytebuffer_flush(&output_buffer, inout);
		}
	}
	return inputmode;
}

int tb_select_output_mode(int mode)
{
	if (mode)
		outputmode = mode;
	return outputmode;
}

void tb_set_clear_attributes(uint16_t fg, uint16_t bg)
{
	foreground = fg;
	background = bg;
}

/* -------------------------------------------------------- */

static int convertnum(uint32_t num, char* buf) {
	int i, l = 0;
	int ch;
	do {
		buf[l++] = '0' + (num % 10);
		num /= 10;
	} while (num);
	for(i = 0; i < l / 2; i++) {
		ch = buf[i];
		buf[i] = buf[l - 1 - i];
		buf[l - 1 - i] = ch;
	}
	return l;
}

#define WRITE_LITERAL(X) bytebuffer_append(&output_buffer, (X), sizeof(X)-1)
#define WRITE_INT(X) bytebuffer_append(&output_buffer, buf, convertnum((X), buf))

static void write_cursor(int x, int y) {
	char buf[32];
	WRITE_LITERAL("\033[");
	WRITE_INT(y+1);
	WRITE_LITERAL(";");
	WRITE_INT(x+1);
	WRITE_LITERAL("H");
}

static void write_sgr(uint16_t fg, uint16_t bg) {
	char buf[32];

	if (fg == TB_DEFAULT && bg == TB_DEFAULT)
		return;

	switch (outputmode) {
	case TB_OUTPUT_256:
	case TB_OUTPUT_216:
	case TB_OUTPUT_GRAYSCALE:
		WRITE_LITERAL("\033[");
		if (fg != TB_DEFAULT) {
			WRITE_LITERAL("38;5;");
			WRITE_INT(fg);
			if (bg != TB_DEFAULT) {
				WRITE_LITERAL(";");
			}
		}
		if (bg != TB_DEFAULT) {
			WRITE_LITERAL("48;5;");
			WRITE_INT(bg);
		}
		WRITE_LITERAL("m");
		break;
	case TB_OUTPUT_NORMAL:
	default:
		WRITE_LITERAL("\033[");
		if (fg != TB_DEFAULT) {
			WRITE_LITERAL("3");
			WRITE_INT(fg - 1);
			if (bg != TB_DEFAULT) {
				WRITE_LITERAL(";");
			}
		}
		if (bg != TB_DEFAULT) {
			WRITE_LITERAL("4");
			WRITE_INT(bg - 1);
		}
		WRITE_LITERAL("m");
		break;
	}
}

static void cellbuf_init(struct cellbuf *buf, int width, int height)
{
	buf->cells = (struct tb_cell*)malloc(sizeof(struct tb_cell) * width * height);
	assert(buf->cells);
	buf->width = width;
	buf->height = height;
}

static void cellbuf_resize(struct cellbuf *buf, int width, int height)
{
	if (buf->width == width && buf->height == height)
		return;

	int oldw = buf->width;
	int oldh = buf->height;
	struct tb_cell *oldcells = buf->cells;

	cellbuf_init(buf, width, height);
	cellbuf_clear(buf);

	int minw = (width < oldw) ? width : oldw;
	int minh = (height < oldh) ? height : oldh;
	int i;

	for (i = 0; i < minh; ++i) {
		struct tb_cell *csrc = oldcells + (i * oldw);
		struct tb_cell *cdst = buf->cells + (i * width);
		memcpy(cdst, csrc, sizeof(struct tb_cell) * minw);
	}

	free(oldcells);
}

static void cellbuf_clear(struct cellbuf *buf)
{
	int i;
	int ncells = buf->width * buf->height;

	for (i = 0; i < ncells; ++i) {
		buf->cells[i].ch = ' ';
		buf->cells[i].fg = foreground;
		buf->cells[i].bg = background;
	}
}

static void cellbuf_free(struct cellbuf *buf)
{
	free(buf->cells);
}

static void get_term_size(int *w, int *h)
{
	struct winsize sz;
	memset(&sz, 0, sizeof(sz));

	ioctl(inout, TIOCGWINSZ, &sz);

	if (w) *w = sz.ws_col;
	if (h) *h = sz.ws_row;
}

static void update_term_size(void)
{
	struct winsize sz;
	memset(&sz, 0, sizeof(sz));

	ioctl(inout, TIOCGWINSZ, &sz);

	termw = sz.ws_col;
	termh = sz.ws_row;
}

static void send_attr(uint16_t fg, uint16_t bg)
{
#define LAST_ATTR_INIT 0xFFFF
	static uint16_t lastfg = LAST_ATTR_INIT, lastbg = LAST_ATTR_INIT;
	if (fg != lastfg || bg != lastbg) {
		bytebuffer_puts(&output_buffer, funcs[T_SGR0]);

		uint16_t fgcol;
		uint16_t bgcol;

		switch (outputmode) {
		case TB_OUTPUT_256:
			fgcol = fg & 0xFF;
			bgcol = bg & 0xFF;
			break;

		case TB_OUTPUT_216:
			fgcol = fg & 0xFF; if (fgcol > 215) fgcol = 7;
			bgcol = bg & 0xFF; if (bgcol > 215) bgcol = 0;
			fgcol += 0x10;
			bgcol += 0x10;
			break;

		case TB_OUTPUT_GRAYSCALE:
			fgcol = fg & 0xFF; if (fgcol > 23) fgcol = 23;
			bgcol = bg & 0xFF; if (bgcol > 23) bgcol = 0;
			fgcol += 0xe8;
			bgcol += 0xe8;
			break;

		case TB_OUTPUT_NORMAL:
		default:
			fgcol = fg & 0x0F;
			bgcol = bg & 0x0F;
		}

		if (fg & TB_BOLD)
			bytebuffer_puts(&output_buffer, funcs[T_BOLD]);
		if (bg & TB_BOLD)
			bytebuffer_puts(&output_buffer, funcs[T_BLINK]);
		if (fg & TB_UNDERLINE)
			bytebuffer_puts(&output_buffer, funcs[T_UNDERLINE]);
		if ((fg & TB_REVERSE) || (bg & TB_REVERSE))
			bytebuffer_puts(&output_buffer, funcs[T_REVERSE]);

		write_sgr(fgcol, bgcol);

		lastfg = fg;
		lastbg = bg;
	}
}

static void send_char(int x, int y, uint32_t c)
{
	char buf[7];
	int bw = tb_utf8_unicode_to_char(buf, c);
	if (x-1 != lastx || y != lasty)
		write_cursor(x, y);
	lastx = x; lasty = y;
	if(!c) buf[0] = ' '; // replace 0 with whitespace
	bytebuffer_append(&output_buffer, buf, bw);
}

static void send_clear(void)
{
	send_attr(foreground, background);
	bytebuffer_puts(&output_buffer, funcs[T_CLEAR_SCREEN]);
	if (!IS_CURSOR_HIDDEN(cursor_x, cursor_y))
		write_cursor(cursor_x, cursor_y);
	bytebuffer_flush(&output_buffer, inout);

	/* we need to invalidate cursor position too and these two vars are
	 * used only for simple cursor positioning optimization, cursor
	 * actually may be in the correct place, but we simply discard
	 * optimization once and it gives us simple solution for the case when
	 * cursor moved */
	lastx = LAST_COORD_INIT;
	lasty = LAST_COORD_INIT;
}

static void sigwinch_handler(int xxx)
{
	(void) xxx;
	const int zzz = 1;
	write(winch_fds[1], &zzz, sizeof(int));
}

static void update_size(void)
{
	update_term_size();
	cellbuf_resize(&back_buffer, termw, termh);
	cellbuf_resize(&front_buffer, termw, termh);
	cellbuf_clear(&front_buffer);
	send_clear();
}

static int read_up_to(int n) {
	assert(n > 0);
	const int prevlen = input_buffer.len;
	bytebuffer_resize(&input_buffer, prevlen + n);

	int read_n = 0;
	while (read_n <= n) {
		ssize_t r = 0;
		if (read_n < n) {
			r = read(inout, input_buffer.buf + prevlen + read_n, n - read_n);
		}
#ifdef __CYGWIN__
		// While linux man for tty says when VMIN == 0 && VTIME == 0, read
		// should return 0 when there is nothing to read, cygwin's read returns
		// -1. Not sure why and if it's correct to ignore it, but let's pretend
		// it's zero.
		if (r < 0) r = 0;
#endif
		if (r < 0) {
			// EAGAIN / EWOULDBLOCK shouldn't occur here
			assert(errno != EAGAIN && errno != EWOULDBLOCK);
			return -1;
		} else if (r > 0) {
			read_n += r;
		} else {
			bytebuffer_resize(&input_buffer, prevlen + read_n);
			return read_n;
		}
	}
	assert(!"unreachable");
	return 0;
}

static int wait_fill_event(struct tb_event *event, struct timeval *timeout)
{
	// ;-)
#define ENOUGH_DATA_FOR_PARSING 64
	fd_set events;
	memset(event, 0, sizeof(struct tb_event));

	// try to extract event from input buffer, return on success
	event->type = TB_EVENT_KEY;
	if (extract_event(event, &input_buffer, inputmode))
		return event->type;

	// it looks like input buffer is incomplete, let's try the short path,
	// but first make sure there is enough space
	int n = read_up_to(ENOUGH_DATA_FOR_PARSING);
	if (n < 0)
		return -1;
	if (n > 0 && extract_event(event, &input_buffer, inputmode))
		return event->type;

	// n == 0, or not enough data, let's go to select
	while (1) {
		FD_ZERO(&events);
		FD_SET(inout, &events);
		FD_SET(winch_fds[0], &events);
		int maxfd = (winch_fds[0] > inout) ? winch_fds[0] : inout;
		int result = select(maxfd+1, &events, 0, 0, timeout);
		if (!result)
			return 0;

		if (FD_ISSET(inout, &events)) {
			event->type = TB_EVENT_KEY;
			n = read_up_to(ENOUGH_DATA_FOR_PARSING);
			if (n < 0)
				return -1;

			if (n == 0)
				continue;

			if (extract_event(event, &input_buffer, inputmode))
				return event->type;
		}
		if (FD_ISSET(winch_fds[0], &events)) {
			event->type = TB_EVENT_RESIZE;
			int zzz = 0;
			read(winch_fds[0], &zzz, sizeof(int));
			buffer_size_change_request = 1;
			get_term_size(&event->w, &event->h);
			return TB_EVENT_RESIZE;
		}
	}
}


text:
namespace AjaxControlToolkit.Design {

    class MultiHandleSliderExtenderDesigner : ExtenderControlBaseDesigner<MultiHandleSliderExtender> {
    }

}


text:
require 'rails_helper'

describe 'English Search Search', js: true do
  let(:main_entries) { create_list(:generic_main_entry, 26) }
  let(:keywords) { create_list(:generic_keyword, 2) }
  let(:keyword_groups) { create_list(:generic_keyword_group, 5) }

  before do
    main_entries
  end

  context "English Empty Search" do
    it "executes a solr search and displays results if found" do
      visit root_path
      page.find_field('q').send_keys('notfound')
      choose("Search in English")
      click_button 'Search'
      expect(page).to have_content 'Your search yielded no results'
    end
  end

  context "English Non Empty Search" do
    it "executes a solr search and displays found results" do
      allow_any_instance_of(BuildSolrSearchService).to receive(:build_search) { Keywords.all }
      visit root_path
      page.find_field('q').send_keys('word')
      choose("Search in English")
      click_button 'Search'
      expect(page).to have_content 'word'
    end
  end
end


text:
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from packets.djinni

#import "IXNMuseDataPacketType.h"
#import <Foundation/Foundation.h>
@class IXNSenderInformation;

/**
 * Provides access to information about packet.
 * This packet can represent different data: eeg,
 * accelerometer, quantization, etc. Look at MuseDataPacketType enum
 * for all possible types. Look at specific type enum for information
 * 'values' field mapping.
 */

@interface IXNMuseDataPacket : NSObject
- (id)initWithMuseDataPacket:(IXNMuseDataPacket *)museDataPacket;
- (id)initWithPacketType:(IXNMuseDataPacketType)packetType timestamp:(int64_t)timestamp source:(IXNSenderInformation *)source values:(NSArray *)values;

/** Specifies what kind of values are stored in the packet. */
@property (nonatomic, readonly) IXNMuseDataPacketType packetType;

/** Microseconds since epoch (usually Jan 1, 1970). */
@property (nonatomic, readonly) int64_t timestamp;

/** Information about the %Muse which sent the packet. */
@property (nonatomic, readonly) IXNSenderInformation *source;

/**
 * Contains the actual data. Elements of the array have "double" data type.
 * Size of the array and the meaning of its elemetns depend on packet type.
 * Some types have enum which provides access to the data mapping.
 */
@property (nonatomic, readonly) NSArray *values;

@end


text:
<?php

namespace Warlords\GameBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PlayerStatsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PlayerStatsRepository extends EntityRepository
{

	// Get players by Level
	public function getPlayerByLevel($level, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.level <= :player_lvl_up AND p.level >= :player_lvl_down')
				->addOrderBy('p.level','DESC')
				->setParameter('player_lvl_up', ($level + 0) + 2)
				->setParameter('player_lvl_down', ($level + 0) - 2);

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

	// Get players by Gold
	public function getPlayerByGold($gold, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.gold <= :player_gold_up AND p.gold >= :player_gold_down')
				->addOrderBy('p.gold','DESC')
				->setParameter('player_gold_up', ($gold + 0) * 1.5)
				->setParameter('player_gold_down', floor(($gold + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

	// Get players by number of infantry
	public function getPlayerByInfantry($infantry, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.infantry <= :player_infantry_up AND p.infantry >= :player_infantry_down')
				->addOrderBy('p.infantry','DESC')
				->setParameter('player_infantry_up', ($infantry + 0) * 1.5)
				->setParameter('player_infantry_down', floor(($infantry + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

	// Get players by number of knights
	public function getPlayerByKnight($knights, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.knights <= :player_knights_up AND p.knights >= :player_knights_down')
				->addOrderBy('p.knights','DESC')
				->setParameter('player_knights_up', ($knights + 0) * 1.5)
				->setParameter('player_knights_down', floor(($knights + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}
	// Get players by number of calvary
	public function getPlayerByCalvary($calvary, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.calvary <= :player_calvary_up AND p.knights >= :player_calvary_down')
				->addOrderBy('p.calvary','DESC')
				->setParameter('player_calvary_up', ($calvary + 0) * 1.5)
				->setParameter('player_calvary_down', floor(($calvary + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

	// Get players by number of land
	public function getPlayerByLand($land, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.land <= :player_land_up AND p.land >= :player_land_down')
				->addOrderBy('p.land','DESC')
				->setParameter('player_land_up', ($land + 0) * 1.5)
				->setParameter('player_land_down', floor(($land + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}
	// Get players by fame
	public function getPlayerByFame($fame, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->where('p.fame <= :player_fame_up AND p.fame >= :player_fame_down')
				->addOrderBy('p.fame','DESC')
				->setParameter('player_fame_up', ($fame + 0) * 1.5)
				->setParameter('player_fame_down', floor(($fame + 0) * 0.5));

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

	// Get players by username will wildcards
	// return all username start with param $username
	public function getPlayerByUsername($username, $limit = 25)
	{
		$qb = $this->createQueryBuilder('p')
				->select('p')
				->innerjoin('p.user', 'User')
				->where('User.username LIKE :player_username')
				->addOrderBy('User.username','DESC')
				->setParameter('player_username', $username . '%');

		if (false === is_null($limit))
       	 		$qb->setMaxResults($limit);

    		return $qb->getQuery()
              		->getResult();

	}

}


text:
set -x

originalDirectory=$(pwd)


text:
var comb = require("comb-proxy"),
    define = comb.define,
    isUndefined = comb.isUndefined,
    isUndefinedOrNull = comb.isUndefinedOrNull,
    isBoolean = comb.isBoolean,
    isString = comb.isString,
    isHash = comb.isHash,
    when = comb.when,
    isFunction = comb.isFunction,
    isInstanceOf = comb.isInstanceOf,
    Promise = comb.Promise,
    PromiseList = comb.PromiseList,
    array = comb.array,
    toArray = array.toArray,
    isArray = comb.isArray,
    Middleware = comb.plugins.Middleware,
    PatioError = require("../errors").PatioError;

var fetch = {
    LAZY: "lazy",
    EAGER: "eager"
};

/**
 * @class
 * Base class for all associations.
 *
 *

 * NOT to be instantiated directly
 * Its just documented for reference.
 *
 * @constructs
 * @param {Object} options
 * @param {String} options.model a string to look up the model that we are associated with
 * @param {Function} options.filter  a callback to find association if a filter is defined then
 *                                    the association is read only
 * @param {Object} options.key object with left key and right key
 * @param {String|Object} options.orderBy<String|Object> - how to order our association @see Dataset.order
 * @param {fetch.EAGER|fetch.LAZY} options.fetchType the fetch type of the model if fetch.Eager is supplied then
 *                                    the associations are automatically filled, if fetch.Lazy is supplied
 *                                    then a promise is returned and is called back with the loaded models
 * @property {Model} model the model associatied with this association.
 * @name Association
 * @memberOf patio.associations
 * */
define(Middleware, {
    instance: {
        /**@lends patio.associations.Association.prototype*/

        type: "",

        //Our associated model
        _model: null,

        /**
         * Fetch type
         */
        fetchType: fetch.LAZY,

        /**how to order our association*/
        orderBy: null,

        /**Our filter method*/
        filter: null,

        __hooks: null,

        isOwner: true,

        createSetter: true,

        isCascading: false,

        supportsStringKey: true,

        supportsHashKey: true,

        supportsCompositeKey: true,

        supportsLeftAndRightKey: true,

        /**
         *
         *Method to call to look up association,
         *called after the model has been filtered
         **/
        _fetchMethod: "all",

        constructor: function (options, patio, filter) {
            options = options || {};
            if (!options.model) {
                throw new Error("Model is required for " + this.type + " association");
            }
            this._model = options.model;
            this.patio = patio;
            this.__opts = options;
            !isUndefined(options.isCascading) && (this.isCascading = options.isCascading);
            this.filter = filter;
            this.readOnly = isBoolean(options.readOnly) ? options.readOnly : false;
            this.__hooks =
            {before: {add: null, remove: null, "set": null, load: null}, after: {add: null, remove: null, "set": null, load: null}};
            var hooks = ["Add", "Remove", "Set", "Load"];
            ["before", "after"].forEach(function (h) {
                hooks.forEach(function (a) {
                    var hookName = h + a, hook;
                    if (isFunction((hook = options[hookName]))) {
                        this.__hooks[h][a.toLowerCase()] = hook;
                    }
                }, this);
            }, this);
            this.fetchType = options.fetchType || fetch.LAZY;
        },

        _callHook: function (hook, action, args) {
            var func = this.__hooks[hook][action], ret;
            if (isFunction(func)) {
                ret = func.apply(this, args);
            }
            return ret;
        },

        _clearAssociations: function (model) {
            if (!this.readOnly) {
                delete model.__associations[this.name];
            }
        },

        _forceReloadAssociations: function (model) {
            if (!this.readOnly) {
                delete model.__associations[this.name];
                return model[this.name];
            }
        },

        /**
         * @return {Boolean} true if the association is eager.
         */
        isEager: function () {
            return this.fetchType === fetch.EAGER;
        },

        _checkAssociationKey: function (parent) {
            var q = {};
            this._setAssociationKeys(parent, q);
            return Object.keys(q).every(function (k) {
                return q[k] !== null;
            });
        },

        _getAssociationKey: function () {
            var options = this.__opts, key, ret = [], lk, rk;
            if (!isUndefinedOrNull((key = options.key))) {
                if (this.supportsStringKey && isString(key)) {
                    //normalize the key first!
                    ret = [
                        [this.isOwner ? this.defaultLeftKey : key],
                        [this.isOwner ? key : this.defaultRightKey]
                    ];
                } else if (this.supportsHashKey && isHash(key)) {
                    var leftKey = Object.keys(key)[0];
                    var rightKey = key[leftKey];
                    ret = [
                        [leftKey],
                        [rightKey]
                    ];
                } else if (this.supportsCompositeKey && isArray(key)) {
                    ret = [
                        [key],
                        null
                    ];
                }
            } else if (this.supportsLeftAndRightKey && (!isUndefinedOrNull((lk = options.leftKey)) && !isUndefinedOrNull((rk = options.rightKey)))) {
                ret = [
                    toArray(lk), toArray(rk)
                ];
            } else {
                //todo handle composite primary keys
                ret = [
                    [this.defaultLeftKey],
                    [this.defaultRightKey]
                ];
            }
            return ret;
        },

        _setAssociationKeys: function (parent, model, val) {
            var keys = this._getAssociationKey(parent), leftKey = keys[0], rightKey = keys[1], i = leftKey.length - 1;
            if (leftKey && rightKey) {
                for (; i >= 0; i--) {
                    model[rightKey[i]] = !isUndefined(val) ? val : parent[leftKey[i]] ? parent[leftKey[i]] : null;
                }
            } else {
                for (; i >= 0; i--) {
                    var k = leftKey[i];
                    model[k] = !isUndefined(val) ? val : parent[k] ? parent[k] : null;

                }
            }
        },

        _setDatasetOptions: function (ds) {
            var options = this.__opts || {};
            var order, limit, distinct, select, query;
            //allow for multi key ordering
            if (!isUndefined((select = this.select))) {
                ds = ds.select.apply(ds, toArray(select));
            }
            if (!isUndefined((query = options.query)) || !isUndefined((query = options.conditions))) {
                ds = ds.filter(query);
            }
            if (isFunction(this.filter)) {
                var ret = this.filter.apply(this, [ds]);
                if (isInstanceOf(ret, ds._static)) {
                    ds = ret;
                }
            }
            if (!isUndefined((distinct = options.distinct))) {
                ds = ds.limit.apply(ds, toArray(distinct));
            }
            if (!isUndefined((order = options.orderBy)) || !isUndefined((order = options.order))) {
                ds = ds.order.apply(ds, toArray(order));
            }
            if (!isUndefined((limit = options.limit))) {
                ds = ds.limit.apply(ds, toArray(limit));
            }
            return ds;

        },

        /**
         *Filters our associated dataset to load our association.
         *
         *@return {Dataset} the dataset with all filters applied.
         **/
        _filter: function (parent) {
            var options = this.__opts || {};
            var ds, self = this;
            if (!isUndefined((ds = options.dataset)) && isFunction(ds)) {
                ds = ds.apply(parent, [parent]);
            }
            if (!ds) {
                var q = {};
                this._setAssociationKeys(parent, q);
                ds = this.model.dataset.naked().filter(q);
                var recip = this.model._findAssociation(this);
                recip && (recip = recip[1]);
                ds.rowCb = function (item) {
                    var model = self._toModel(item, true);
                    recip && recip.__setValue(model, parent);
                    //call hook to finish other model associations
                    return model._hook("post", "load").chain(function () {
                        return model;
                    });
                };
            } else if (!ds.rowCb && this.model) {
                ds.rowCb = function (item) {
                    var model = self._toModel(item, true);
                    //call hook to finish other model associations
                    return model._hook("post", "load").chain(function () {
                        return model;
                    });
                };
            }

            return this._setDatasetOptions(ds);
        },

        __setValue: function (parent, model) {
            var associations;
            if (this._fetchMethod === "all") {
                associations = !isArray(model) ? [model] : model;
            } else {
                associations = isArray(model) ? model[0] : model;
            }
            parent.__associations[this.name] = associations;
            return parent.__associations[this.name];
        },

        fetch: function (parent) {
            var ret = new Promise();
            if (this._checkAssociationKey(parent)) {
                var self = this;
                return this._filter(parent)[this._fetchMethod]().chain(function (result) {
                    self.__setValue(parent, result);
                    parent = null;
                    return result;
                });
            } else {
                this.__setValue(parent, null);
                ret.callback(null);
            }
            return ret;
        },

        /**
         * Middleware called before a model is removed.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being acted up.
         */
        _preRemove: function (next, model) {
            if (this.isOwner && !this.isCascading) {
                var q = {};
                this._setAssociationKeys(model, q, null);
                model[this.associatedDatasetName].update(q).classic(next);
            } else {
                next();
            }
        },

        /**
         * Middleware called aft era model is removed.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _postRemove: function (next, model) {
            next();
        },

        /**
         * Middleware called before a model is saved.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _preSave: function (next, model) {
            next();
        },

        /**
         * Middleware called after a model is saved.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _postSave: function (next, model) {
            next();
        },

        /**
         * Middleware called before a model is updated.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _preUpdate: function (next, model) {
            next();
        },

        /**
         * Middleware called before a model is updated.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _postUpdate: function (next, model) {
            next();
        },

        /**
         * Middleware called before a model is loaded.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _preLoad: function (next, model) {
            next();
        },

        /**
         * Middleware called after a model is loaded.
         *

         *  This is called in the scope of the model
         * @param {Function} next function to pass control up the middleware stack.
         * @param {_Association} self reference to the Association that is being called.
         */
        _postLoad: function (next, model) {
            next();
        },

        /**
         * Alias used to explicitly set an association on a model.
         * @param {*} val the value to set the association to
         * @param {_Association} self reference to the Association that is being called.
         */
        _setter: function (val, model) {
            model.__associations[this.name] = val;
        },

        associationLoaded: function (model) {
            return model.__associations.hasOwnProperty(this.name);
        },

        getAssociation: function (model) {
            return model.__associations[this.name];
        },

        /**
         * Alias used to explicitly get an association on a model.
         * @param {_Association} self reference to the Association that is being called.
         */
        _getter: function (model) {
            //if we have them return them;
            if (this.associationLoaded(model)) {
                var assoc = this.getAssociation(model);
                return this.isEager() ? assoc : when(assoc);
            } else if (model.isNew) {
                return null;
            } else {
                return this.fetch(model);
            }
        },

        _toModel: function (val, fromDb) {
            var Model = this.model;
            if (!isUndefinedOrNull(Model)) {
                if (!isInstanceOf(val, Model)) {
                    val = new this.model(val, fromDb);
                }
            } else {
                throw new PatioError("Invalid model " + this.name);
            }
            return val;
        },

        /**
         * Method to inject functionality into a model. This method alters the model
         * to prepare it for associations, and initializes all required middleware calls
         * to fulfill requirements needed to loaded the associations.
         *
         * @param {Model} parent the model that is having an associtaion set on it.
         * @param {String} name the name of the association.
         */
        inject: function (parent, name) {
            this.name = name;
            var self = this;
            this.parent = parent;
            var parentProto = parent.prototype;
            parentProto["__defineGetter__"](name, function () {
                return self._getter(this);
            });
            parentProto["__defineGetter__"](this.associatedDatasetName, function () {
                return self._filter(this);
            });

            if (!this.readOnly && this.createSetter) {
                //define a setter because we arent read only
                parentProto["__defineSetter__"](name, function (vals) {
                    self._setter(vals, this);
                });
            }

            //set up all callbacks
            ["pre", "post"].forEach(function (op) {
                ["save", "update", "remove", "load"].forEach(function (type) {
                    parent[op](type, function (next) {
                        return self["_" + op + type.charAt(0).toUpperCase() + type.slice(1)](next, this);
                    });
                }, this);
            }, this);
        },

        getters: {

            select: function () {
                return this.__opts.select;
            },

            defaultLeftKey: function () {
                var ret = "";
                if (this.isOwner) {
                    ret = this.__opts.primaryKey || this.parent.primaryKey[0];
                } else {
                    ret = this.model.tableName + "Id";
                }
                return ret;
            },

            defaultRightKey: function () {
                return this.associatedModelKey;
            },

            //Returns our model
            model: function () {
                return this["__model__"] || (this["__model__"] = this.patio.getModel(this._model, this.parent.db));
            },

            associatedModelKey: function () {
                var ret = "";
                if (this.isOwner) {
                    ret = this.__opts.primaryKey || this.parent.tableName + "Id";
                } else {
                    ret = this.model.primaryKey[0];
                }
                return ret;
            },

            associatedDatasetName: function () {
                return this.name + "Dataset";
            },

            removeAssociationFlagName: function () {
                return "__remove" + this.name + "association";
            }

        }
    },

    static: {
        /**@lends patio.associations.Association*/

        fetch: {

            LAZY: "lazy",

            EAGER: "eager"
        }
    }
}).as(module);


text:
Marketing Survey App
===============

The code in this folder is a Django app written in python.

A working example can be found at: [http://ec2-54-202-248-221.us-west-2.compute.amazonaws.com](http://ec2-54-202-248-221.us-west-2.compute.amazonaws.com)

The admin to this app can be viewed at: [http://ec2-54-202-248-221.us-west-2.compute.amazonaws.com/admin/](http://ec2-54-202-248-221.us-west-2.compute.amazonaws.com/admin/)

Purpose
----------
This app serves two purposes. First we need users to authenticate with the twitter oauth api so that we can use their credentials to download additional data. This method was used to collect over 20GB of tweets from the Skullcandy followers and the followers of similar brands.

Second, this app is a proof of concept for building more engaging marketing campaigns that both collect greater insights about the intended demographic and also provide greater incentives to individuals.


text:
using BranchSwitcher.Web.Utilities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;

namespace BranchSwitcher.Web.Filters
{
	[AttributeUsage(AttributeTargets.Method, Inherited = true)]
	public class NotNullFilterAttribute : ActionFilterAttribute
	{
		private readonly Func<IDictionary<string, object>, bool> m_Validation;

		public NotNullFilterAttribute()
			: this(arguments => arguments.Values.Contains(null))
		{
		}

		public NotNullFilterAttribute(Func<IDictionary<string, object>, bool> validation)
		{
			m_Validation = validation.NotNull();
		}

		public override void OnActionExecuting(ActionExecutingContext context)
		{
			if (m_Validation(context.ActionArguments))
			{
				context.Result = new BadRequestResult();
			}
		}
	}
}


text:
package net.runelite.client.plugins.hunter;

import java.time.Duration;
import java.time.Instant;
import lombok.Getter;
import lombok.Setter;
import net.runelite.api.GameObject;
import net.runelite.api.coords.WorldPoint;

/**
 * Wrapper class for a GameObject that represents a hunter trap.
 */
class HunterTrap
{
	/**
	 * A hunter trap stays up 1 minute before collapsing.
	 */
	static final Duration TRAP_TIME = Duration.ofMinutes(1);

	/**
	 * The time in milliseconds when the trap was placed.
	 */
	@Getter
	private Instant placedOn;

	/**
	 * The state of the trap.
	 */
	@Getter
	@Setter
	private State state;

	/**
	 * The ID of the game object this is representing
	 */
	@Getter
	private int objectId;

	@Getter
	private WorldPoint worldLocation;

	/**
	 * The states a trap can be in.
	 */
	enum State
	{
		/**
		 * A laid out trap.
		 */
		OPEN,
		/**
		 * A trap that is empty.
		 */
		EMPTY,
		/**
		 * A trap that caught something.
		 */
		FULL,
		/**
		 * A trap that is closing.
		 */
		TRANSITION
	}

	/**
	 * Constructor for a HunterTrap object
	 *
	 * @param gameObject The gameobject thats corresponds with this trap.
	 */
	HunterTrap(GameObject gameObject)
	{
		this.state = State.OPEN;
		this.placedOn = Instant.now();
		this.objectId = gameObject.getId();
		this.worldLocation = gameObject.getWorldLocation();
	}

	/**
	 * Calculates how much time is left before the trap is collapsing.
	 *
	 * @return Value between 0 and 1. 0 means the trap was laid moments ago.
	 * 1 is a trap that's about to collapse.
	 */
	public double getTrapTimeRelative()
	{
		Duration duration = Duration.between(placedOn, Instant.now());
		return duration.compareTo(TRAP_TIME) < 0 ? (double) duration.toMillis() / TRAP_TIME.toMillis() : 1;
	}

	/**
	 * Resets the time value when the trap was placed.
	 */
	public void resetTimer()
	{
		placedOn = Instant.now();
	}
}


text:
<?php

require_once __DIR__ . "/includes/core.php";
?>
<!doctype html>

	<title>ContribSize</title>
	<meta charset="utf-8"/>
	<link rel="stylesheet" href="style/core.css"/>

<?php
if ( !isset( $_GET['user'] ) ) { // no username given
	echo "
You haven't entered a username!
";
} else { // so we've got some work to do...
	$size = number_format( getSize( $_GET['user'] ) );
	$user = htmlentities( $_GET['user'] );
	echo "
$user has changed $size bytes on English Wikipedia.
";
}
?>


text:
<list>
  <contact>
    <last__name>New_Test 0</last__name>
    <first__name>TestHelloo 0</first__name>
    <middle__name>TestTest 0</middle__name>
    <nick__name>Test_data_test</nick__name>
    <company__name>Test_High_Technologies</company__name>
    <mobile__phone>89526656583</mobile__phone>
    <email__1>john_swift@yahoo.com</email__1>
    <address>England, Solsbery, Flint str, h 7, fl. 8</address>
    <home__phone>6402780</home__phone>
  </contact>
  <contact>
    <last__name>New_Test 1</last__name>
    <first__name>TestHelloo 1</first__name>
    <middle__name>TestTest 1</middle__name>
    <nick__name>Test_data_test</nick__name>
    <company__name>Test_High_Technologies</company__name>
    <mobile__phone>89526656583</mobile__phone>
    <email__1>john_swift@yahoo.com</email__1>
    <address>England, Solsbery, Flint str, h 7, fl. 8</address>
    <home__phone>6402780</home__phone>
  </contact>
  <contact>
    <last__name>New_Test 2</last__name>
    <first__name>TestHelloo 2</first__name>
    <middle__name>TestTest 2</middle__name>
    <nick__name>Test_data_test</nick__name>
    <company__name>Test_High_Technologies</company__name>
    <mobile__phone>89526656583</mobile__phone>
    <email__1>john_swift@yahoo.com</email__1>
    <address>England, Solsbery, Flint str, h 7, fl. 8</address>
    <home__phone>6402780</home__phone>
  </contact>
</list>


text:
package com.xanderblinov.translator.data;

/**
 * Date: 3/8/2015
 * Time: 4:28 PM
 *
 * @author xanderblinov
 */
public class TranslationResult
{
	private final boolean mPreTranslation;
	private final String mFromText;
	private final String mToText;

	public TranslationResult(final boolean preTranslation, final String fromText, final String toText)
	{
		mPreTranslation = preTranslation;
		mFromText = fromText;
		mToText = toText;
	}

	public boolean isPreTranslation()
	{
		return mPreTranslation;
	}

	public String getFromText()
	{
		return mFromText;
	}

	public String getToText()
	{
		return mToText;
	}
}


text:
<?php
namespace Tattler\Base\Channels;

interface IUser extends IChannel
{
    public function setNameConverter(\Closure $callback): IUser;
    public function setSocketId($socketId): IUser;
	public function getSocketId(): string;
}


text:
class CreateEntry < ActiveRecord::Migration
  def change
    create_table :entries do |t|
      t.string :title
      t.string :url
      t.string :author
      t.text :content
      t.datetime :published
      t.belongs_to :blog
    end
  end
end


text:
#include "benchlet.hpp"
#include "PbMarketDataCodecBench.hpp"

#define MAX_MD_BUFFER (1000*1000)

class PbMarketDataBench : public Benchmark
{
public:
    virtual void setUp(void)
    {
        buffer_ = new char[MAX_MD_BUFFER];
        bench_.runEncode(buffer_);  // set buffer up for decoding runs
    };

    virtual void tearDown(void)
    {
        delete[] buffer_;
    };

    PbMarketDataCodecBench bench_;
    char *buffer_;
};

static struct Benchmark::Config cfg[] = {
    { Benchmark::ITERATIONS, "1000000" },
    { Benchmark::BATCHES, "20" }
};

BENCHMARK_CONFIG(PbMarketDataBench, RunSingleEncode, cfg)
{
    bench_.runEncode(buffer_);
}

BENCHMARK_CONFIG(PbMarketDataBench, RunSingleDecode, cfg)
{
    bench_.runDecode(buffer_);
}

BENCHMARK_CONFIG(PbMarketDataBench, RunSingleEncodeAndDecode, cfg)
{
    bench_.runEncodeAndDecode(buffer_);
}


text:
Simple transform streams useful in creating [good](https://github.com/hapijs/good) data pipelines.

[![Build Status](https://travis-ci.org/hapijs/good-squeeze.svg?branch=master&style=flat)](https://travis-ci.org/hapijs/good-squeeze)
![Current Version](https://img.shields.io/npm/v/good-squeeze.svg?style=flat)

Lead Maintainer: [Adam Bretz](https://github.com/arb)

## Usage

good-squeeze is a collection of small transform streams useful in custom good reporter clients. The `Squeeze` stream is useful for filtering events based on the good event options. The `SafeJson` stream is useful for stringifying objects to prevent circular object errors.

## Methods

### `Squeeze(events, [options])`

Creates a new Squeeze transform stream where:

- `events` an object where each key is a valid good event, and the value is a string or array of strings representing event tags. "\*" indicates no filtering. `null` and `undefined` are assumed to be "\*".
- `options` an optional configuration object that gets passed to the Node [`Stream.Transform`](http://nodejs.org/api/stream.html#stream_class_stream_transform) constructor. **Note** `objectMode` is always `true` for all `Squeeze` objects.

The transform stream only passes on events that satisfy the event filtering based on event name and tags. If the upstream event doesn't satisfy the filter, it is not continued down the pipe line.

### `Squeeze.subscription(events)`

A static method on `Squeeze` that creates a new event subscription map where:

- `events` an object where each key is a valid good event, and the value is a string or array of strings representing event tags. "*" indicates no filtering. `null` and `undefined` are assumed to be "*".

```js
var Squeeze = require('good-squeeze');

Squeeze.subscription({ log: 'user', ops: '*', request: ['hapi', 'foo'] });

// Results in
// {
//     log: [ 'user' ],
//     ops: [],
//     request: [ 'hapi', 'foo', 'hapi', 'foo' ]
// }
```

Useful for creating an event subscription to be used with `Squeeze.filter` if you do not plan on creating a pipeline coming from good and instead want to manage event filtering manually.

### `Squeeze.filter(subscription, data)`

Returns `true` if the supplied `data.event` + `data.tags` should be reported based on `subscription` where:

- `subscription` - a subscription map created by `Squeeze.subscription()`.
- `data` - event object emitted from good/hapi which should contain the following keys:
    - `event` - a string representing the event name of `data`
    - `tags` - an array of strings representing tags associated with this event.

### `SafeJson([options])`

Creates a new SafeJson transform stream where:

- `options` an optional configuration object that gets passed to the Node [`Stream.Transform`](http://nodejs.org/api/stream.html#stream_class_stream_transform) constructor. **Note** `objectMode` is always `true` for all `Squeeze` objects.

The transform stream stringifys the incoming data and pipes it forward. It will not crash in the cases of circular references and will instead include a "~Circular" string in the result.