text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#if PLATFORM_HAS_BSD_SOCKETS

#include "Core.h"
#include "IPAddress.h"

/**
 * Represents an internet ip address, using the relatively standard SOCKADDR_IN structure. All data is in network byte order
 */
class FInternetAddrBSD : public FInternetAddr
{
protected:
	/** The internet ip address structure */
	sockaddr_in Addr;

public:
	/**
	 * Constructor. Sets address to default state
	 */
	FInternetAddrBSD()
	{
		FMemory::Memzero(&Addr,sizeof(sockaddr_in));
		Addr.sin_family = AF_INET;
	}
	/**
	 * Sets the ip address from a host byte order uint32
	 *
	 * @param InAddr the new address to use (must convert to network byte order)
	 */
	virtual void SetIp(uint32 InAddr) override
	{
		Addr.sin_addr.s_addr = htonl(InAddr);
	}

	/**
	 * Sets the ip address from a string ("A.B.C.D")
	 *
	 * @param InAddr the string containing the new ip address to use
	 */
	virtual void SetIp(const TCHAR* InAddr, bool& bIsValid) override
	{
		int32 A, B, C, D;
		int32 Port = 0;

		FString AddressString = InAddr;

		TArray<FString> PortTokens;
		AddressString.ParseIntoArray(PortTokens, TEXT(":"), true);

		// look for a port number
		if (PortTokens.Num() > 1)
		{
			Port = FCString::Atoi(*PortTokens[1]);
		}

		// now split the part before the : into a.b.c.d
		TArray<FString> AddrTokens;
		PortTokens[0].ParseIntoArray(AddrTokens, TEXT("."), true);

		if (AddrTokens.Num() < 4)
		{
			bIsValid = false;
			return;
		}

		A = FCString::Atoi(*AddrTokens[0]);
		B = FCString::Atoi(*AddrTokens[1]);
		C = FCString::Atoi(*AddrTokens[2]);
		D = FCString::Atoi(*AddrTokens[3]);

		// Make sure the address was valid
		if ((A & 0xFF) == A && (B & 0xFF) == B && (C & 0xFF) == C && (D & 0xFF) == D)
		{
			SetIp((A << 24) | (B << 16) | (C << 8) | (D << 0));

			if (Port != 0)
			{
				SetPort(Port);
			}

			bIsValid = true;
		}
		else
		{
			//debugf(TEXT("Invalid IP address string (%s) passed to SetIp"),InAddr);
			bIsValid = false;
		}
	}

	/**
	 * Sets the ip address using a network byte order ip address
	 *
	 * @param IpAddr the new ip address to use
	 */
	void SetIp(const in_addr& IpAddr)
 	{
 		Addr.sin_addr = IpAddr;
 	}

	/**
	 * Copies the network byte order ip address to a host byte order dword
	 *
	 * @param OutAddr the out param receiving the ip address
	 */
	virtual void GetIp(uint32& OutAddr) const override
	{
		OutAddr = ntohl(Addr.sin_addr.s_addr);
	}

	/**
	 * Copies the network byte order ip address
	 *
	 * @param OutAddr the out param receiving the ip address
	 */
	void GetIp(in_addr& OutAddr) const
 	{
 		OutAddr = Addr.sin_addr;
 	}

	/**
	 * Sets the port number from a host byte order int
	 *
	 * @param InPort the new port to use (must convert to network byte order)
	 */
	virtual void SetPort(int32 InPort) override
	{
		Addr.sin_port = htons(InPort);
	}

	/**
	 * Copies the port number from this address and places it into a host byte order int
	 *
	 * @param OutPort the host byte order int that receives the port
	 */
	virtual void GetPort(int32& OutPort) const override
	{
		OutPort = ntohs(Addr.sin_port);
	}

	/**
	 * Returns the port number from this address in host byte order
	 */
	virtual int32 GetPort(void) const override
	{
		return ntohs(Addr.sin_port);
	}

	/** Sets the address to be any address */
	virtual void SetAnyAddress(void) override
	{
		SetIp(INADDR_ANY);
		SetPort(0);
	}

	/** Sets the address to broadcast */
	virtual void SetBroadcastAddress() override
	{
		SetIp(INADDR_BROADCAST);
		SetPort(0);
	}

	/**
	 * Converts this internet ip address to string form
	 *
	 * @param bAppendPort whether to append the port information or not
	 */
	virtual FString ToString(bool bAppendPort) const override
	{
		uint32 LocalAddr = ntohl(Addr.sin_addr.s_addr);

		// Get the individual bytes
		const int32 A = (LocalAddr >> 24) & 0xFF;
		const int32 B = (LocalAddr >> 16) & 0xFF;
		const int32 C = (LocalAddr >>  8) & 0xFF;
		const int32 D = (LocalAddr >>  0) & 0xFF;
		if (bAppendPort)
		{
			return FString::Printf(TEXT("%i.%i.%i.%i:%i"),A,B,C,D,GetPort());
		}
		else
		{
			return FString::Printf(TEXT("%i.%i.%i.%i"),A,B,C,D);
		}
	}

	/**
	 * Compares two internet ip addresses for equality
	 *
	 * @param Other the address to compare against
	 */
	virtual bool operator==(const FInternetAddr& Other) const override
	{
		FInternetAddrBSD& OtherBSD = (FInternetAddrBSD&)Other;
		return Addr.sin_addr.s_addr == OtherBSD.Addr.sin_addr.s_addr &&
			Addr.sin_port == OtherBSD.Addr.sin_port &&
			Addr.sin_family == OtherBSD.Addr.sin_family;
	}

	/**
	 * Is this a well formed internet address
	 *
	 * @return true if a valid IP, false otherwise
	 */
	virtual bool IsValid() const override
	{
		return Addr.sin_addr.s_addr != 0;
	}

 	operator sockaddr*(void)
 	{
 		return (sockaddr*)&Addr;
 	}

 	operator const sockaddr*(void) const
 	{
 		return (const sockaddr*)&Addr;
 	}
};

#endif	//PLATFORM_HAS_BSD_SOCKETS


text:
ActiveRecord::Schema.define(version: 20151202174320) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "categories", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "links", force: :cascade do |t|
    t.string   "url"
    t.string   "name"
    t.text     "description"
    t.integer  "position"
    t.integer  "user_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "category_id"
  end

  add_index "links", ["category_id"], name: "index_links_on_category_id", using: :btree
  add_index "links", ["user_id"], name: "index_links_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.string   "authentication_token"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree

  add_foreign_key "links", "categories"
  add_foreign_key "links", "users"
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef __TIMER_18XX_43XX_H_
#define __TIMER_18XX_43XX_H_

#ifdef __cplusplus
extern "C" {
#endif

/** @defgroup TIMER_18XX_43XX CHIP: LPC18xx/43xx Timer driver
 * @ingroup CHIP_18XX_43XX_Drivers
 * @{
 */

/**
 * @brief	Initialize a timer
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Nothing
 */
void Chip_TIMER_Init(LPC_TIMER_T *pTMR);

/**
 * @brief	Shutdown a timer
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Nothing
 */
void Chip_TIMER_DeInit(LPC_TIMER_T *pTMR);

/**
 * @brief	Determine if a match interrupt is pending
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match interrupt number to check
 * @return	false if the interrupt is not pending, otherwise true
 * Determine if the match interrupt for the passed timer and match
 * counter is pending.
 */
STATIC INLINE bool Chip_TIMER_MatchPending(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	return IP_TIMER_MatchPending(pTMR, matchnum);
}

/**
 * @brief	Determine if a capture interrupt is pending
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture interrupt number to check
 * @return	false if the interrupt is not pending, otherwise true
 * Determine if the capture interrupt for the passed capture pin is
 * pending.
 */
STATIC INLINE bool Chip_TIMER_CapturePending(LPC_TIMER_T *pTMR, int8_t capnum)
{
	return IP_TIMER_CapturePending(pTMR, capnum);
}

/**
 * @brief	Clears a (pending) match interrupt
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match interrupt number to clear
 * @return	Nothing
 * Clears a pending timer match interrupt.
 */
STATIC INLINE void Chip_TIMER_ClearMatch(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_ClearMatch(pTMR, matchnum);
}

/**
 * @brief	Clears a (pending) capture interrupt
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture interrupt number to clear
 * @return	Nothing
 * Clears a pending timer capture interrupt.
 */
STATIC INLINE void Chip_TIMER_ClearCapture(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_ClearCapture(pTMR, capnum);
}

/**
 * @brief	Enables the timer (starts count)
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Nothing
 * Enables the timer to start counting.
 */
STATIC INLINE void Chip_TIMER_Enable(LPC_TIMER_T *pTMR)
{
	IP_TIMER_Enable(pTMR);
}

/**
 * @brief	Disables the timer (stops count)
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Nothing
 * Disables the timer to stop counting.
 */
STATIC INLINE void Chip_TIMER_Disable(LPC_TIMER_T *pTMR)
{
	IP_TIMER_Disable(pTMR);
}

/**
 * @brief	Returns the current timer count
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Current timer terminal count value
 * Returns the current timer terminal count.
 */
STATIC INLINE uint32_t Chip_TIMER_ReadCount(LPC_TIMER_T *pTMR)
{
	return IP_TIMER_ReadCount(pTMR);
}

/**
 * @brief	Returns the current prescale count
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Current timer prescale count value
 * Returns the current prescale count.
 */
STATIC INLINE uint32_t Chip_TIMER_ReadPrescale(LPC_TIMER_T *pTMR)
{
	return IP_TIMER_ReadPrescale(pTMR);
}

/**
 * @brief	Sets the prescaler value
 * @param	pTMR		: Pointer to timer IP register address
 * @param	prescale	: Prescale value to set the prescale register to
 * @return	Nothing
 * Sets the prescale count value.
 */
STATIC INLINE void Chip_TIMER_PrescaleSet(LPC_TIMER_T *pTMR, uint32_t prescale)
{
	IP_TIMER_PrescaleSet(pTMR, prescale);
}

/**
 * @brief	Sets a timer match value
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer to set match count for
 * @param	matchval	: Match value for the selected match count
 * @return	Nothing
 * Sets ones of the timer match values.
 */
STATIC INLINE void Chip_TIMER_SetMatch(LPC_TIMER_T *pTMR, int8_t matchnum, uint32_t matchval)
{
	IP_TIMER_SetMatch(pTMR, matchnum, matchval);
}

/**
 * @brief	Reads a capture register
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture register to read
 * @return	The selected capture register value
 * Returns the selected capture register value.
 */
STATIC INLINE uint32_t Chip_TIMER_ReadCapture(LPC_TIMER_T *pTMR, int8_t capnum)
{
	return IP_TIMER_ReadCapture(pTMR, capnum);
}

/**
 * @brief	Resets the timer terminal and prescale counts to 0
 * @param	pTMR	: Pointer to timer IP register address
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_Reset(LPC_TIMER_T *pTMR)
{
	IP_TIMER_Reset(pTMR);
}

/**
 * @brief	Enables a match interrupt that fires when the terminal count
 *			matches the match counter value.
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_MatchEnableInt(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_MatchEnableInt(pTMR, matchnum);
}

/**
 * @brief	Disables a match interrupt for a match counter.
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_MatchDisableInt(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_MatchDisableInt(pTMR, matchnum);
}

/**
 * @brief	For the specific match counter, enables reset of the terminal count register when a match occurs
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_ResetOnMatchEnable(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_ResetOnMatchEnable(pTMR, matchnum);
}

/**
 * @brief	For the specific match counter, disables reset of the terminal count register when a match occurs
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_ResetOnMatchDisable(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_ResetOnMatchDisable(pTMR, matchnum);
}

/**
 * @brief	Enable a match timer to stop the terminal count when a
 *			match count equals the terminal count.
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_StopOnMatchEnable(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_StopOnMatchEnable(pTMR, matchnum);
}

/**
 * @brief	Disable stop on match for a match timer. Disables a match timer
 *			to stop the terminal count when a match count equals the terminal count.
 * @param	pTMR		: Pointer to timer IP register address
 * @param	matchnum	: Match timer, 0 to 3
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_StopOnMatchDisable(LPC_TIMER_T *pTMR, int8_t matchnum)
{
	IP_TIMER_StopOnMatchDisable(pTMR, matchnum);
}

/**
 * @brief	Enables capture on on rising edge of selected CAP signal for the
 *			selected capture register, enables the selected CAPn.capnum signal to load
 *			the capture register with the terminal coount on a rising edge.
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureRisingEdgeEnable(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureRisingEdgeEnable(pTMR, capnum);
}

/**
 * @brief	Disables capture on on rising edge of selected CAP signal. For the
 *			selected capture register, disables the selected CAPn.capnum signal to load
 *			the capture register with the terminal coount on a rising edge.
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureRisingEdgeDisable(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureRisingEdgeDisable(pTMR, capnum);
}

/**
 * @brief	Enables capture on on falling edge of selected CAP signal. For the
 *			selected capture register, enables the selected CAPn.capnum signal to load
 *			the capture register with the terminal coount on a falling edge.
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureFallingEdgeEnable(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureFallingEdgeEnable(pTMR, capnum);
}

/**
 * @brief	Disables capture on on falling edge of selected CAP signal. For the
 *			selected capture register, disables the selected CAPn.capnum signal to load
 *			the capture register with the terminal coount on a falling edge.
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureFallingEdgeDisable(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureFallingEdgeDisable(pTMR, capnum);
}

/**
 * @brief	Enables interrupt on capture of selected CAP signal. For the
 *			selected capture register, an interrupt will be generated when the enabled
 *			rising or falling edge on CAPn.capnum is detected.
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureEnableInt(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureEnableInt(pTMR, capnum);
}

/**
 * @brief	Disables interrupt on capture of selected CAP signal
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capnum	: Capture signal/register to use
 * @return	Nothing
 */
STATIC INLINE void Chip_TIMER_CaptureDisableInt(LPC_TIMER_T *pTMR, int8_t capnum)
{
	IP_TIMER_CaptureDisableInt(pTMR, capnum);
}

/**
 * @brief	Sets external match control (MATn.matchnum) pin control
 * @param	pTMR			: Pointer to timer IP register address
 * @param	initial_state	: Initial state of the pin, high(1) or low(0)
 * @param	matchState		: Selects the match state for the pin
 * @param	matchnum		: MATn.matchnum signal to use
 * @return	Nothing
 * For the pin selected with matchnum, sets the function of the pin that occurs on
 * a terminal count match for the match count.
 */
STATIC INLINE void Chip_TIMER_ExtMatchControlSet(LPC_TIMER_T *pTMR, int8_t initial_state,
												 IP_TIMER_PIN_MATCH_STATE_T matchState, int8_t matchnum)
{
	IP_TIMER_ExtMatchControlSet(pTMR, initial_state, matchState, matchnum);
}

/**
 * @brief	Sets timer count source and edge with the selected passed from CapSrc
 * @param	pTMR	: Pointer to timer IP register address
 * @param	capSrc	: timer clock source and edge
 * @param	capnum	: CAPn.capnum pin to use (if used)
 * @return	Nothing
 * If CapSrc selected a CAPn pin, select the specific CAPn pin with the capnum value.
 */
STATIC INLINE void Chip_TIMER_TIMER_SetCountClockSrc(LPC_TIMER_T *pTMR,
													 IP_TIMER_CAP_SRC_STATE_T capSrc,
													 int8_t capnum)
{
	IP_TIMER_SetCountClockSrc(pTMR, capSrc, capnum);
}

/**
 * @}
 */

#ifdef __cplusplus
}
#endif

#endif /* __TIMER_18XX_43XX_H_ */


text:
#ifndef FVP_PRIVATE_H
#define FVP_PRIVATE_H

#include <plat/arm/common/plat_arm.h>

/*******************************************************************************
 * Function and variable prototypes
 ******************************************************************************/

void fvp_config_setup(void);

void fvp_interconnect_init(void);
void fvp_interconnect_enable(void);
void fvp_interconnect_disable(void);
void fvp_timer_init(void);
void tsp_early_platform_setup(void);

#endif /* FVP_PRIVATE_H */


text:
class OutputFormatter
  def print_array_table(result_list, keys)
    table = Terminal::Table.new
    table.headings = keys.map(&:capitalize)

    result_list.each do |row|
      table.add_row(row.values)
    end
    puts table
  end

  def print_hash_table(result_hash)
    table = Terminal::Table.new do |t|
      t.headings = result_hash.keys.map(&:capitalize)
      t << result_hash.values
    end

    puts table
  end
end


text:
package com.ernestomancebo.ds_algorightms.sort;

public class QuickSort<T extends Comparable<T>> implements Sorter<T> {

	public T[] sort(T[] data) {
		return sort(data, 0, data.length - 1);
	}

	/*
	 * Implement the Quick sort algorithm from the pseudo code shown in the
	 * lectures.
	 */
	public T[] sort(T[] data, int startIndex, int endIndex) {
		if (startIndex < endIndex) {
			int pivotIndex = quickSortPartition(data, startIndex, endIndex);
			sort(data, startIndex, pivotIndex - 1);
			sort(data, pivotIndex + 1, endIndex);
		}

		return data;
	}

	/*
	 * Implement the Shell sort algorithm.
	 */

	private int quickSortPartition(T[] data, int startIndex, int endIndex) {
		T pivot = data[endIndex];
		int rightIndex = startIndex;
		T tmp = null;

		for (int left = startIndex; left < endIndex; left++) {
			if (data[left].compareTo(pivot) < 0) {
				tmp = data[rightIndex];
				data[rightIndex] = data[left];
				data[left] = tmp;

				rightIndex++;
			}
		}

		tmp = data[rightIndex];
		data[rightIndex] = pivot;
		data[endIndex] = tmp;

		return rightIndex;
	}

}


text:
require 'fcntl'
require 'etc'
require 'stringio'
require 'rack'
require 'kgio'

# :stopdoc:
# Unicorn module containing all of the classes (include C extensions) for
# running a Unicorn web server.  It contains a minimalist HTTP server with just
# enough functionality to service web application requests fast as possible.
# :startdoc:

# \Unicorn exposes very little of an user-visible API and most of its
# internals are subject to change.  \Unicorn is designed to host Rack
# applications, so applications should be written against the Rack SPEC
# and not \Unicorn internals.
module Unicorn

  # Raised inside TeeInput when a client closes the socket inside the
  # application dispatch.  This is always raised with an empty backtrace
  # since there is nothing in the application stack that is responsible
  # for client shutdowns/disconnects.  This exception is visible to Rack
  # applications unless PrereadInput middleware is loaded.
  class ClientShutdown < EOFError
  end

  # :stopdoc:

  # This returns a lambda to pass in as the app, this does not "build" the
  # app (which we defer based on the outcome of "preload_app" in the
  # Unicorn config).  The returned lambda will be called when it is
  # time to build the app.
  def self.builder(ru, op)
    # allow Configurator to parse cli switches embedded in the ru file
    op = Unicorn::Configurator::RACKUP.merge!(:file => ru, :optparse => op)

    # Op is going to get cleared before the returned lambda is called, so
    # save this value so that it's still there when we need it:
    no_default_middleware = op[:no_default_middleware]

    # always called after config file parsing, may be called after forking
    lambda do ||
      inner_app = case ru
      when /\.ru$/
        raw = File.read(ru)
        raw.sub!(/^__END__\n.*/, '')
        eval("Rack::Builder.new {(\n#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru)
      else
        require ru
        Object.const_get(File.basename(ru, '.rb').capitalize)
      end

      pp({ :inner_app => inner_app }) if $DEBUG

      return inner_app if no_default_middleware

      # return value, matches rackup defaults based on env
      # Unicorn does not support persistent connections, but Rainbows!
      # and Zbatery both do.  Users accustomed to the Rack::Server default
      # middlewares will need ContentLength/Chunked middlewares.
      case ENV["RACK_ENV"]
      when "development"
        Rack::Builder.new do
          use Rack::ContentLength
          use Rack::Chunked
          use Rack::CommonLogger, $stderr
          use Rack::ShowExceptions
          use Rack::Lint
          run inner_app
        end.to_app
      when "deployment"
        Rack::Builder.new do
          use Rack::ContentLength
          use Rack::Chunked
          use Rack::CommonLogger, $stderr
          run inner_app
        end.to_app
      else
        inner_app
      end
    end
  end

  # returns an array of strings representing TCP listen socket addresses
  # and Unix domain socket paths.  This is useful for use with
  # Raindrops::Middleware under Linux: http://raindrops.bogomips.org/
  def self.listener_names
    Unicorn::HttpServer::LISTENERS.map do |io|
      Unicorn::SocketHelper.sock_name(io)
    end + Unicorn::HttpServer::NEW_LISTENERS
  end

  def self.log_error(logger, prefix, exc)
    message = exc.message
    message = message.dump if /[[:cntrl:]]/ =~ message
    logger.error "#{prefix}: #{message} (#{exc.class})"
    exc.backtrace.each { |line| logger.error(line) }
  end

  # remove this when we only support Ruby >= 2.0
  def self.pipe # :nodoc:
    Kgio::Pipe.new.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) }
  end
  # :startdoc:
end
# :enddoc:
require 'unicorn/const'
require 'unicorn/socket_helper'
require 'unicorn/stream_input'
require 'unicorn/tee_input'
require 'unicorn/http_request'
require 'unicorn/configurator'
require 'unicorn/tmpio'
require 'unicorn/util'
require 'unicorn/http_response'
require 'unicorn/worker'
require 'unicorn/http_server'


text:
package controllers

import "github.com/oal/beego-pongo2"

type IndexController struct {
	BaseController
}

func (this *IndexController) Get() {
	pongo2.Render(this.Ctx, "index.html", pongo2.Context{
		"APP":   this.Data,
		"Title": "抛弃世俗之浮躁,留我钻研之刻苦",
	})
}


text:
static char* lines[MAX_LINES];
static int total_lines = 0;

static
void print_profile(fhash_profile_data* data)
{
    printf("[index]: used: %u, total: %u, usage rate: %f\n",
           data->index_used,
           data->index_size,
           data->index_size > 0
            ? (double)(data->index_used) / (double)(data->index_size)
            : 0.0);

    printf("[slots]: used: %zu, total: %zu, usage rate: %f\n",
           data->used_slots,
           data->total_slots,
           data->total_slots > 0
            ? (double)data->used_slots / (double)data->total_slots
            : 0.0);
}

static
int load_key_values(const char* file, char** line_bufs, int max_lines)
{
    FILE* fp = NULL;
    size_t len = 0;
    ssize_t read;
    fp = fopen(file, "r");
    if (!fp) {
        printf("cannot open %s\n", file);
        exit(1);
    }

    int i = 0;
    lines[i] = NULL;
    while ((read = getline(&line_bufs[i], &len, fp)) != -1 && i < max_lines) {
        line_bufs[++i] = NULL;
    }

    return i;
}

static
void unload_key_values(char** line_bufs, int max_lines)
{
    for (int i = 0; i < max_lines; i++) {
        free(line_bufs[i]);
    }
}

static
int hash_core_compare(const void* key1, key_sz_t key_sz1,
                      const void* key2, key_sz_t key_sz2)
{
    if (key_sz1 != key_sz2) {
        return 1;
    }

    return memcmp(key1, key2, (size_t)key_sz1);
}

static
void test_without_autorehash()
{
    printf("========= fhash testing without auto rehash =========\n");

    fhash_opt opt;
    opt.hash_alg = NULL;
    opt.compare = hash_core_compare;

    fhash* phash = fhash_create(0, opt, FHASH_MASK_NONE);

    // test set
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_set(phash, lines[i], (key_sz_t)strlen(lines[i]),
                      lines[i], (value_sz_t)strlen(lines[i]));
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_set x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    // test get
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_get(phash, lines[i], (key_sz_t)strlen(lines[i]), NULL);
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_get x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    // test iteration
    {
        unsigned long long start = ftime_gettime();
        fhash_iter iter = fhash_iter_new(phash);
        char* data = NULL;
        int iter_count = 0;
        while ((data = fhash_next(&iter))) {
            iter_count++;
        }
        fhash_iter_release(&iter);
        unsigned long long end = ftime_gettime();

        printf("fhash_next x%d spend time: %llu usec\n",
               iter_count, end -start);
    }

    // test rehash
    {
        unsigned long long start = ftime_gettime();
        int ret = fhash_rehash(phash, (uint32_t)total_lines);
        unsigned long long end = ftime_gettime();
        printf("fhash_rehash (index double), ret: %d, spend time: %llu usec\n",
               ret, end -start);
    }

    fhash_profile_data profile_data;
    fhash_profile(phash, 0, &profile_data);
    print_profile(&profile_data);

    // test delete
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_del(phash, lines[i], (key_sz_t)strlen(lines[i]));
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_del x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    fhash_delete(phash);
}

static
void test_with_autorehash()
{
    printf("========= fhash testing with auto rehash =========\n");

    fhash_opt opt;
    opt.hash_alg = NULL;
    opt.compare = hash_core_compare;

    fhash* phash = fhash_create(0, opt, FHASH_MASK_AUTO_REHASH);

    // test set
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_set(phash, lines[i], (key_sz_t)strlen(lines[i]),
                      lines[i], (value_sz_t)strlen(lines[i]));
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_set x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    // test get
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_get(phash, lines[i], (key_sz_t)strlen(lines[i]), NULL);
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_get x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    // test iteration
    {
        unsigned long long start = ftime_gettime();
        fhash_iter iter = fhash_iter_new(phash);
        char* data = NULL;
        int iter_count = 0;
        while ((data = fhash_next(&iter))) {
            iter_count++;
        }
        fhash_iter_release(&iter);
        unsigned long long end = ftime_gettime();

        printf("fhash_next x%d spend time: %llu usec\n",
               iter_count, end -start);
    }

    // test rehash
    {
        unsigned long long start = ftime_gettime();
        int ret = fhash_rehash(phash, (uint32_t)total_lines);
        unsigned long long end = ftime_gettime();
        printf("fhash_rehash (index double), ret: %d, spend time: %llu usec\n",
               ret, end -start);
    }

    fhash_profile_data profile_data;
    fhash_profile(phash, 0, &profile_data);
    print_profile(&profile_data);

    // test delete
    {
        unsigned long long start = ftime_gettime();
        for (int i = 0; i < total_lines; i++) {
            fhash_del(phash, lines[i], (key_sz_t)strlen(lines[i]));
        }
        unsigned long long end = ftime_gettime();
        printf("fhash_del x%d spend time: %llu usec\n",
               total_lines, end - start);
    }

    fhash_delete(phash);
}

int main(int argc, char** argv)
{
    total_lines = load_key_values("/tmp/fhash_kv.txt", lines, MAX_LINES);
    test_without_autorehash();
    test_with_autorehash();
    unload_key_values(lines, total_lines);
    return 0;
}


text:
Pupcake --- a micro framework for PHP 5.3+
=======================================

##About Pupcake Framework
+ Pupcake is a minimal but extensible microframework for PHP 5.3+
+ Pupcake can be run in traditional web server such as Apache.
+ For more detail usages on using pupcake in general and on traditional web servers, please see https://github.com/superjimpupcake/Pupcake/wiki/_pages

##Installation:

###If you plan to use it on Apache
#### install package "Pupcake/Pupcake" using composer (http://getcomposer.org/)
####.htaccess File for Apache
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php/$1 [L]

###Simple requests when running on Apache
#### For more details on running Pupcake in general and in traditional web server, please see https://github.com/superjimpupcake/Pupcake/wiki/_pages
```php
<?php
//Assuming this is public/index.php and the composer vendor directory is ../vendor

require_once __DIR__.'/../vendor/autoload.php';

$app = new Pupcake\Pupcake();

$app->get("date/:year/:month/:day", function($req, $res){
    $output = $req->params('year').'-'.$req->params('month').'-'.$req->params('day');
    $res->send($output);
});

$app->get("/hello/:name", function($req, $res){
  $res->send("hello ".$req->params('name')." in get");
});

$app->post("/hello/:name", function($req, $res){
  $res->send("hello ".$req->params('name')." in post");
});

$app->put("/hello/:name", function($req, $res){
  $res->send("hello ".$req->params('name')." in put");
});

$app->delete("/hello/:name", function($req, $res){
  $res->send("hello ".$req->params('name')." in delete");
});

/**
 * Multiple request methods for one route
 */
$app->map("/api/hello/:action", function($req, $res){
  $res->send("hello ".$req->params('action')." in get and post");
})->via('GET','POST');

$app->run();
```


text:
package org.lowcostair.util.parser;

import org.w3c.dom.Document;

import java.io.InputStream;

public interface HtmlParser {

    Document parseHtml(InputStream htmlInputStream) throws HtmlParserException;

}


text:
package de.ust.skill.common.java.internal.fieldTypes;

import java.util.ArrayList;

import de.ust.skill.common.java.internal.FieldType;
import de.ust.skill.common.jvm.streams.InStream;

public final class VariableLengthArray<T> extends SingleArgumentType<ArrayList<T>, T> {

    /**
     * @see SKilL V1.0 reference manual §G
     */
    public static final int typeID = 17;

    public VariableLengthArray(FieldType<T> groundType) {
        super(typeID, groundType);
    }

    @Override
    public ArrayList<T> readSingleField(InStream in) {
        int i = in.v32();
        ArrayList<T> rval = new ArrayList<>(i);
        while (i-- != 0)
            rval.add(groundType.readSingleField(in));
        return rval;
    }

    @Override
    public String toString() {
        return groundType.toString() + "[]";
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof VariableLengthArray<?>)
            return groundType.equals(((VariableLengthArray<?>) obj).groundType);
        return false;
    }
}


text:
/**
 * Entrypoint for the Openapi handler
 */

import { Context } from "@azure/functions";

import * as express from "express";
import * as winston from "winston";

import { setAppContext } from "io-functions-commons/dist/src/utils/middlewares/context_middleware";

import { configureAzureContextTransport } from "io-functions-commons/dist/src/utils/logging";

import createAzureFunctionHandler from "io-functions-express/dist/src/createAzureFunctionsHandler";

import { GetOpenapi } from "./controllers/openapi";

import { specs as adminApiSpecs } from "./api/admin_api";
import { specs as publicApiV1Specs } from "./api/public_api_v1";

// Whether we're in a production environment
const isProduction = process.env.NODE_ENV === "production";

// Setup Express

const app = express();

app.get("/specs/api/v1/swagger.json", GetOpenapi(publicApiV1Specs));
app.get("/specs/adm/swagger.json", GetOpenapi(adminApiSpecs));

const azureFunctionHandler = createAzureFunctionHandler(app);

// Binds the express app to an Azure Function handler
export function index(context: Context): void {
  const logLevel = isProduction ? "info" : "debug";
  configureAzureContextTransport(context, winston, logLevel);
  setAppContext(app, context);
  azureFunctionHandler(context);
}


text:
package 'mosh'
#package 'python'
package 'libssl0.9.8'
package 'erlang'
#package 'libdigest-hmac-perl' # this is hacky, but needed for scm_helper in opsworks/s3curl.pl
package 'redis-server'

#python/pip tips
#https://forums.aws.amazon.com/thread.jspa?messageID=468626
include_recipe 'python'

%w(boto awscli).each do |pkg|
  python_pip "#{pkg}"
end

#service "akronym-runner" do
#action :nothing
#
#supports :restart => true, :start => true, :stop => true
# /opt/akronym4/rel/akronym/package/bin/akronym


text:
from pythonforandroid.toolchain import CythonRecipe
from os.path import join

class KiventPolygenRecipe(CythonRecipe):
    name = 'kivent_polygen'

    depends = ['kivent_core']

    subbuilddir = False

    def get_recipe_env(self, arch, with_flags_in_cc=True):
        env = super(KiventPolygenRecipe, self).get_recipe_env(
            arch, with_flags_in_cc=with_flags_in_cc)
        kivy = self.get_recipe('kivy', self.ctx).get_build_dir(arch.arch)
        kivent = self.get_recipe('kivent_core',
                                 self.ctx).get_build_dir(arch.arch, sub=True)
        env['CYTHONPATH'] = ':'.join((kivy, kivent))
        return env

    def prepare_build_dir(self, arch):
        '''No need to prepare, we'll use kivent_core'''
        return

    def get_build_dir(self, arch):
        builddir = self.get_recipe('kivent_core', self.ctx).get_build_dir(arch)
        return join(builddir, 'modules', 'polygen')

recipe = KiventPolygenRecipe()


text:
{-|
Module      : Graphics.Sudbury.CABI.Common
Description : C ABI
Copyright   : (c) Auke Booij, 2015-2017
License     : MIT
Maintainer  : auke@tulcod.com
Stability   : experimental

We attempt to implement the ABI of the libwayland C library.
This implements some common tools to implement this ABI.
-}
module Graphics.Sudbury.CABI.Common where

import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Builder as BB
import Data.Fixed
import Data.Char
import Data.Word
import Data.Monoid
import Control.Concurrent.STM
import Foreign.Ptr
import Foreign.StablePtr
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Array (peekArray0)
import Foreign.Marshal.Utils (with)
import System.Posix.Types

import Graphics.Sudbury.WireMessages
import Graphics.Sudbury.WirePackages
import Graphics.Sudbury.Argument

import Graphics.Sudbury.CABI.Structs

-- | A specific implementation (ie for one opcode) is some abstract function
-- pointer. Since libffi doesn't care anyway, we'll make it something trivial.
type Implementation = FunPtr ()
-- | Listeners are structs of function pointers, so essentially (C-style) arrays
type Listener = Ptr Implementation
type UserData = Ptr ()
type DispatcherData = Ptr ()

{-
 * A dispatcher takes five arguments:  The first is the dispatcher-specific
 * implementation data associated with the target object.  The second is the
 * object on which the callback is being invoked (either wl_proxy or
 * wl_resource).  The third and fourth arguments are the opcode the wl_messsage
 * structure corresponding to the callback being emitted.  The final argument
 * is an array of arguments received from the other process via the wire
 * protocol.
typedef int (*wl_dispatcher_func_t)(const void *, void *, uint32_t,
				    const struct wl_message *,
				    union wl_argument *);
-}
-- the return value is ignored (even by libwayland)
-- | dispatcher function. we represent the second argument (wl_proxy or wl_resource)
-- by an untyped StablePtr which we can later cast to the right type. sorry.
type DispatcherFunc = FunPtr (DispatcherData -> StablePtr () -> CUInt -> Ptr WL_message -> Ptr WL_arg -> IO CInt)

type CDispatcher = (DispatcherFunc, DispatcherData)

type HaskDispatcher = Word16 -> [CArgBox] -> IO ()

charToArgType :: Char -> ArgTypeBox
charToArgType c =
  case c of
       'i' -> ArgTypeBox SIntWAT
       'u' -> ArgTypeBox SUIntWAT
       'f' -> ArgTypeBox SFixedWAT
       's' -> ArgTypeBox SStringWAT
       'o' -> ArgTypeBox SObjectWAT
       'n' -> ArgTypeBox SNewIdWAT
       'a' -> ArgTypeBox SArrayWAT
       'h' -> ArgTypeBox SFdWAT
       o   -> error ("Unexpected argument '" ++ [o] ++ "' encountered")

-- TODO The filter in the following is probably a hack. We should probably use more information of the signature.
signatureToTypes :: CString -> IO [ArgTypeBox]
signatureToTypes sig = map charToArgType . filter isAlpha . map castCCharToChar <$> peekArray0 0 sig

-- | See `convert_arguments_to_ffi` in connection.c in libwayland
type family CArgument (t :: ArgumentType) where
  CArgument 'IntWAT = CInt
  CArgument 'UIntWAT = CUInt
  CArgument 'FixedWAT = CInt
  CArgument 'StringWAT = CString
  CArgument 'ObjectWAT = Ptr ()
  CArgument 'NewIdWAT = Ptr () -- NOTE this should be CUInt server-side
  CArgument 'ArrayWAT = Ptr WL_array
  CArgument 'FdWAT = Fd

data CArgBox = forall t. CArgBox (SArgumentType t) (CArgument t)

data CMessage = CMessage
  { cMessageSender :: Word32
  , cMessageOpcode :: Word16
  , cMessageArguments :: [CArgBox]
  }

type MessageQueue = TQueue WireMessage
type FdQueue = TQueue Fd

handleWireCArg :: (Word32 -> Ptr ()) -> FdQueue -> (CArgBox -> IO a) ->  WireArgBox -> IO a
handleWireCArg _ _   f (WireArgBox SIntWAT n)    = f (CArgBox SIntWAT (fromIntegral n))
handleWireCArg _ _   f (WireArgBox SUIntWAT n)   = f (CArgBox SUIntWAT (fromIntegral n))
handleWireCArg _ _   f (WireArgBox SFixedWAT (MkFixed n)) = f (CArgBox SFixedWAT (fromIntegral n))
handleWireCArg _ _   f (WireArgBox SStringWAT s) = B.useAsCString s $ \cstr -> f (CArgBox SStringWAT cstr)
handleWireCArg _ _   f (WireArgBox SObjectWAT 0) = f (CArgBox SObjectWAT nullPtr)
handleWireCArg _ _   f (WireArgBox SNewIdWAT 0)  = f (CArgBox SNewIdWAT nullPtr)
handleWireCArg om _  f (WireArgBox SObjectWAT o) = f (CArgBox SObjectWAT (om o))
handleWireCArg om _  f (WireArgBox SNewIdWAT n)  = f (CArgBox SNewIdWAT (om n))
handleWireCArg _ _   f (WireArgBox SArrayWAT a)  = B.useAsCStringLen a $ \(cstr, len) -> with (WL_array (fromIntegral len) (fromIntegral len) cstr) $ \ptr -> f (CArgBox SArrayWAT ptr)
handleWireCArg _ queue f (WireArgBox SFdWAT _)  = do
  Fd fd <- atomically $ readTQueue queue
  f (CArgBox SFixedWAT fd)

takeFds :: FdQueue -> STM [Fd]
takeFds queue = do
  x <- tryReadTQueue queue
  case x of
    Nothing -> return []
    Just fd -> do
      fds <- takeFds queue
      return $ fd : fds

serializeQueue1 :: MessageQueue -> BB.Builder -> STM BB.Builder
serializeQueue1 queue bs = do
  msg <- tryReadTQueue queue
  case msg of
    Nothing -> return bs
    Just x -> serializeQueue1 queue (bs <> wirePack (messageToPackage x))

serializeQueue :: MessageQueue -> STM B.ByteString
serializeQueue queue = BL.toStrict . BB.toLazyByteString <$> serializeQueue1 queue mempty

withStablePtr :: StablePtr a -> (a -> IO b) -> IO b
withStablePtr = flip withStablePtr'

withStablePtr' :: (a -> IO b) -> StablePtr a  -> IO b
withStablePtr' f ptr = deRefStablePtr ptr >>= f


text:
define(['tb.component/formbuilder/form/element/Element'], function (ElementConstructor) {
    'use strict';

    describe('Testing FormElement', function () {

        var formTag = '1Zvze';

        it('Testing FormElement constructor error (Missing key or config)', function () {
            var element;

            try {
                element = new ElementConstructor();
                expect(false).toBe(true);
            } catch (e) {
                expect(e).toEqual('Error n 500 BadTypeException: The key of element must be a string');
            }

            try {
                element = new ElementConstructor('foo');
                expect(false).toBe(true);
            } catch (e) {
                expect(e).toEqual('Error n 500 MissingConfigException: Config must be set');
            }

            try {
                element = new ElementConstructor('foo', {});
                expect(false).toBe(true);
            } catch (e) {
                expect(e).toEqual('Error n 500 BadTypeException: The formTag of element must be a string');
            }

            expect(element).not.toBeDefined();
        });

        it('Testing FormElement constructor error (Missing type)', function () {
            var config = {
                    label: 'My label'
                },
                element;

            try {
                element = new ElementConstructor('foo', config, formTag);
                expect(false).toBe(true);
            } catch (e) {
                expect(e).toEqual('Error n 500 MissingPropertyException: Property "type" not found of element: foo');
            }

            expect(element).not.toBeDefined();
        });

        it('Testing FormElement constructor lite', function () {
            var config = {
                    type: 'text'
                },
                element = new ElementConstructor('name', config, formTag);

            expect(element.getKey()).toEqual('name');
            expect(element.getConfig()).toEqual(config);
            expect(element.getPlaceholder()).toEqual('');
            expect(element.getValue()).toEqual('');
            expect(element.getLabel()).toEqual('');
            expect(element.isDisabled()).toEqual(false);
            expect(element.getType()).toEqual('text');
        });

        it('Testing FormElement constructor full', function () {
            var config = {
                    type: 'text',
                    placeholder: 'Foo',
                    value: 'Bar',
                    label: 'Jean pierre',
                    disabled: true
                },
                element = new ElementConstructor('name', config, formTag);

            expect(element.getKey()).toEqual('name');
            expect(element.getConfig()).toEqual(config);
            expect(element.getPlaceholder()).toEqual('Foo');
            expect(element.getValue()).toEqual('Bar');
            expect(element.getLabel()).toEqual('Jean pierre');
            expect(element.isDisabled()).toEqual(true);
            expect(element.getType()).toEqual('text');
        });
    });
});


text:
import collections
from .models import Schema
from .helpers import *

color_names = Schema(collections.OrderedDict([
    ("Color Name", (str, str)),
    ("Hex Value", (str, str)),
]))

# each row maps to a variant of a product.
left_to_sell_items = Schema(collections.OrderedDict([
    ("Style", (int, int)),
    ("Color", (str, str)),
    ("Color Desc", (str, str)),
    ("Size Desc", (int, int)),
    ("Left to Sell", (int, int)),
    ("price", (int_from_str, int)),
]))

# each row maps to a product with lists of options.
js_group_dresses = Schema(collections.OrderedDict([
    ("Style Number", (int, int)),
    ("Dress Name", (str, str)),
    ("Handle", (str, str)),
    ("Dress Description", (str, str)),
    ("Collection", (str, str)),
    ("Layout Format", (str, str)),
    ("Oversell", (bool_from_str, str_from_bool)),
    ("Waitlist", (bool_from_str, str_from_bool)),
    ("Fulfillment", (str, str)),
    ("Sizes", (list_of_int_from_str, str_from_list)),
    ("Colors", (list_split_strip, str_from_list)),
    ("Price (USD)", (int_from_str, int)),
    ("Sale Price", (int_from_str, int)),
    ("On Sale", (bool_from_str, str_from_bool)),
    ("Permanent Markdown", (bool_from_str, str_from_bool)),
    ("Never Markdown", (bool_from_str, str_from_bool)),
    ("Tags", (list_or_none_from_string, str_from_list)),
]))

shopify_product = Schema(collections.OrderedDict([
    ("Handle", (str, str)),
    ("Title", (str, str)),
    ("Body (HTML)", (str, str)),
    ("Vendor", (str, str)),
    ("Type", (str, str)),
    ("Tags", (list_split_strip, str_from_list)),
    ("Collection", (str, str)),
    ("Published", (bool_from_str_blank_true, str_from_bool)),
    ("Image Src", (str, str)),
    ("Image Alt Text", (str, str)),
    ("SEO Title", (str, str)),
    ("SEO Description", (str, str)),
    ("Option1 Name", (str, str)),
    ("Option1 Value", (str, str)),
    ("Option2 Name", (str, str)),
    ("Option2 Value", (str, str)),
    ("Option3 Name", (str, str)),
    ("Option3 Value", (str, str)),
    ("Variant SKU", (str, str)),
    ("Variant Grams", (int, int)),
    ("Variant Inventory Tracker", (str, str)),
    ("Variant Inventory Qty", (int, int)),
    ("Variant Inventory Policy", (str, str)),
    ("Variant Fulfillment Service", (str, str)),
    ("Variant Price", (two_place_float_from_str, None)),
    ("Variant Compare At Price", (two_place_float_from_str, None)),
    ("Variant Requires Shipping", (bool_from_str, str_from_bool)),
    ("Variant Taxable", (bool_from_str, str_from_bool)),
    ("Variant Barcode", (str, str)),
    ("Variant Image", (str, str)),
    ("Variant Weight Unit", (None, None)),
    ("Gift Card", (None, None)),
    ("Google Shopping / MPN", (None, None)),
    ("Google Shopping / Age Group", (None, None)),
    ("Google Shopping / Gender", (None, None)),
    ("Google Shopping / Google Product Category", (None, None)),
    ("Google Shopping / AdWords Grouping", (None, None)),
    ("Google Shopping / AdWords Labels", (None, None)),
    ("Google Shopping / Condition", (None, None)),
    ("Google Shopping / Custom Product", (None, None)),
    ("Google Shopping / Custom Label 0", (None, None)),
    ("Google Shopping / Custom Label 1", (None, None)),
    ("Google Shopping / Custom Label 2", (None, None)),
    ("Google Shopping / Custom Label 3", (None, None)),
    ("Google Shopping / Custom Label 4", (None, None))
]))

# each row maps to a product with lists of options.
dresses_missing_images = Schema(collections.OrderedDict([
    ("Style Number", (int, int)),
    ("Dress Name", (str, str)),
    ("Collection", (str, str)),
]))


text:
'''

Wraps shell commands and sends the result to Datadog as events. Ex:

dogwrap -n test-job -k $API_KEY --submit_mode all "ls -lah"

Note that you need to enclose your command in quotes to prevent python
from thinking the command line arguments belong to the python command
instead of the wrapped command.

You can also have the script only send events if they fail:

dogwrap -n test-job -k $API_KEY --submit_mode errors "ls -lah"

And you can give the command a timeout too:

dogwrap -n test-job -k $API_KEY --timeout=1 "sleep 3"

'''

import sys
import subprocess
import time
from StringIO import StringIO
from optparse import OptionParser

from dogapi import dog_http_api as dog
from dogapi.common import get_ec2_instance_id

SUCCESS = 'success'
ERROR = 'error'

class Timeout(Exception): pass

def poll_proc(proc, sleep_interval, timeout):
    start_time = time.time()
    returncode = None
    while returncode is None:
        returncode = proc.poll()
        if time.time() - start_time > timeout:
            raise Timeout()
        else:
            time.sleep(sleep_interval)
    return returncode

def execute(cmd, cmd_timeout, sigterm_timeout, sigkill_timeout,
            proc_poll_interval):
    start_time = time.time()
    returncode = -1
    stdout = ''
    stderr = ''
    try:
        proc = subprocess.Popen(u' '.join(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    except Exception:
        print >> sys.stderr, u"Failed to execute %s" % (repr(cmd))
        raise
    try:
        returncode = poll_proc(proc, proc_poll_interval, cmd_timeout)
        stdout, stderr = proc.communicate()
        duration = time.time() - start_time
    except Timeout:
        duration = time.time() - start_time
        try:
            proc.terminate()
            sigterm_start = time.time()
            try:
                print >> sys.stderr, "Command timed out after %.2fs, killing with SIGTERM" % (time.time() - start_time)
                poll_proc(proc, proc_poll_interval, sigterm_timeout)
                returncode = Timeout
            except Timeout:
                print >> sys.stderr, "SIGTERM timeout failed after %.2fs, killing with SIGKILL" % (time.time() - sigterm_start)
                proc.kill()
                poll_proc(proc, proc_poll_interval, sigkill_timeout)
                returncode = Timeout
        except OSError as e:
            # Ignore OSError 3: no process found.
            if e.errno != 3:
                raise
    return returncode, stdout, stderr, duration

def main():
    parser = OptionParser()
    parser.add_option('-n', '--name', action='store', type='string', help="The name of the event")
    parser.add_option('-k', '--api_key', action='store', type='string')
    parser.add_option('-m', '--submit_mode', action='store', type='choice', default='errors', choices=['errors', 'all'])
    parser.add_option('-t', '--timeout', action='store', type='int', default=60*60*24)
    parser.add_option('--sigterm_timeout', action='store', type='int', default=60*2)
    parser.add_option('--sigkill_timeout', action='store', type='int', default=60)
    parser.add_option('--proc_poll_interval', action='store', type='float', default=0.5)
    parser.add_option('--notify_success', action='store', type='string', default='')
    parser.add_option('--notify_error', action='store', type='string', default='')

    options, args = parser.parse_args()

    dog.api_key = options.api_key

    cmd = []
    for part in args:
        cmd.extend(part.split(' '))
    returncode, stdout, stderr, duration = execute(cmd, options.timeout,
        options.sigterm_timeout, options.sigkill_timeout,
        options.proc_poll_interval)

    host = get_ec2_instance_id()
    if returncode == 0:
        alert_type = SUCCESS
        event_title = u'[%s] %s succeeded in %.2fs' % (host, options.name,
                                                       duration)
    elif returncode is Timeout:
        alert_type = ERROR
        event_title = u'[%s] %s timed out after %.2fs' % (host, options.name,
                                                          duration)
        returncode = -1
    else:
        alert_type = ERROR
        event_title = u'[%s] %s failed in %.2fs' % (host, options.name,
                                                    duration)
    event_body = [u'%%%\n',
        u'commmand:\n```\n', u' '.join(cmd), u'\n```\n',
        u'exit code: %s\n\n' % returncode,
    ]
    if stdout:
        event_body.extend([u'stdout:\n```\n', stdout, u'\n```\n'])
    if stderr:
        event_body.extend([u'stderr:\n```\n', stderr, u'\n```\n'])

    notifications = ""
    if alert_type == SUCCESS and options.notify_success:
        notifications = options.notify_success
    elif alert_type == ERROR and options.notify_error:
        notifications = options.notify_error

    if notifications:
        event_body.extend([u'notifications: %s\n' % (notifications)])

    event_body.append(u'%%%\n')

    # ensure all strings are parsed as utf-8
    event_body = [x.decode('utf-8') for x in event_body]

    event_body = u''.join(event_body)
    event = {
        'alert_type': alert_type,
        'aggregation_key': options.name,
        'host': host,
    }

    print >> sys.stderr, stderr.strip()
    print >> sys.stdout, stdout.strip()

    if options.submit_mode == 'all' or returncode != 0:
        dog.event(event_title, event_body, **event)

    sys.exit(returncode)

if __name__ == '__main__':
    main()


text:
@extends('layouts.master')
@section('tituloWeb')
Actulizar Descuentos
@stop
@section('contenido')

Farmacias Bys | Registro de promociones

        <a href="<?php echo url('admin/'); ?>/promociones/">Volver

Actualizar promoción

        <form method="post" class="form-vertical" id="registrar-form" enctype="multipart/form-data">

                @if($errors->has())
                Ocurrieron los siguientes errores al procesar el formulario

                    @foreach($errors->all() as $message)

{{ $message }}

                    @endforeach

                @endif

<input type='hidden' name='csrfmiddlewaretoken' value='IrZwy4iuA1VPBcD8NBnCrMHiOUlcdtZO' />

                Nombre

                    <input id="id_nombre" type="text" class="" name="nombre" value="{{$promocion->nombre}}" required/>

                Descripción

                    <input id="id_descripcion" type="text" class="" name="descripcion" value="{{$promocion->descripcion}}" required/>

                Tipo

                     {{Form::select('tipoPromocion',array('home-principal'=>'HOME Principal','home-inferior-grande'=>'HOME Inferior grande',
                    'home-inferior-peque1'=>'HOME inferior pequeño arriba','home-inferior-peque2'=>'HOME inferior pequeño abajo',
                    'dctos-superior-grande1'=>'Descuentos superior grande izquierdo','dctos-superior-grande2'=>'Descuentos superior grande derecho',
                    'dctos-superior-pequenos1'=>'Descuentos superior pequeño derecho arriba','dctos-superior-pequenos2'=>'Descuentos superior pequeño derecho abajo',
                    'dctos-superior-pequenos3'=>'Descuentos superior pequeño izquieda arriba','dctos-superior-pequenos4'=>'Descuentos superior pequeño izquieda abajo',
                    'dctos-inferior-grande1'=>'Descuentos inferior grande izquierdo','dctos-inferior-grande2'=>'Descuentos inferior grande derecho'
                    ),$promocion->tipo,array('required'=>''));}}

                Imagen de la promoción

                    {{HTML::image('/upload-images/'.$promocion->ruta)}}

                Cambiar imagen de la promoción

                    <input id="imagen" type="file" class="" name="imagen"/>

                Fecha de vencimiento

                    <input id="fechaVencimiento" type="text" class="" value="{{$promocion->vencimiento}}" name="fechaVencimiento" required/>

            <button class='btn btn-info' type="submit">Guardar</button>
        </form>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

@stop


text:
<?php

namespace Rougin\Slytherin\Routing;

/**
 * Router Test Cases
 *
 * @package Slytherin
 * @author  Rougin Gutib <rougingutib@gmail.com>
 */
class RouterTestCases extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Rougin\Slytherin\Routing\RouterInterface
     */
    protected $router;

    /**
     * @var array
     */
    protected $routes = array(array('GET', '/', 'Rougin\Slytherin\Fixture\Classes\NewClass@index'));

    /**
     * Sets up the router.
     *
     * @return void
     */
    public function setUp()
    {
        $this->markTestSkipped('No implementation style defined.');
    }

    /**
     * Tests RouterInterface::add.
     *
     * @return void
     */
    public function testAddMethod()
    {
        $this->exists(get_class($this->router));

        $this->router->prefix('', 'Rougin\Slytherin\Fixture\Classes');

        $this->router->add('POST', '/store', 'NewClass@store');

        $this->assertTrue($this->router->has('POST', '/store'));
    }

    /**
     * Tests RouterInterface::__call.
     *
     * @return void
     */
    public function testCallMagicMethod()
    {
        $this->exists(get_class($this->router));

        $this->router->post('/posts', 'PostsController@store');

        $this->assertTrue($this->router->has('POST', '/posts'));
    }

    /**
     * Tests RouterInterface::__call with an exception.
     *
     * @return void
     */
    public function testCallMagicMethodWithException()
    {
        $this->setExpectedException('BadMethodCallException');

        $this->exists(get_class($this->router));

        $this->router->test('/test', 'PostsController@test');
    }

    /**
     * Tests RouterInterface::has.
     *
     * @return void
     */
    public function testHasMethod()
    {
        $this->exists(get_class($this->router));

        $result = $this->router->has('GET', '/');

        $this->assertTrue((boolean) $result);
    }

    /**
     * Tests RouterInterface::retrieve.
     *
     * @return void
     */
    public function testRetrieveMethod()
    {
        $this->exists(get_class($this->router));

        $expected = 'Rougin\Slytherin\Fixture\Classes\NewClass@index';

        $route = $this->router->retrieve('GET', '/');

        $result = implode('@', $route[2]);

        $this->assertEquals($expected, $result);
    }

    /**
     * Tests RouterInterface::retrieve with null as the result.
     *
     * @return void
     */
    public function testRetrieveMethodWithNull()
    {
        $this->exists(get_class($this->router));

        $route = $this->router->retrieve('GET', '/test');

        $this->assertNull($route);
    }

    /**
     * Tests RouterInterface::prefix.
     *
     * @return void
     */
    public function testPrefixMethod()
    {
        $this->exists(get_class($this->router));

        $this->router->prefix((string) '/v1/slytherin');

        $this->router->get('/hello', (string) 'HelloController@hello');

        $exists = $this->router->has('GET', '/v1/slytherin/hello');

        $this->assertTrue($exists);
    }

    /**
     * Tests RouterInterface::prefix with multiple prefixes.
     *
     * @return void
     */
    public function testPrefixMethodWithMultiplePrefixes()
    {
        $this->exists(get_class($this->router));

        $this->router->prefix('', 'Acme\Http\Controllers');

        $this->router->get('/home', 'HomeController@index');

        $this->router->prefix('/v1/auth');

        $this->router->post('/login', 'AuthController@login');

        $this->router->post('/logout', 'AuthController@logout');

        $this->router->prefix('/v1/test');

        $this->router->get('/hello', 'TestController@hello');

        $this->router->get('/test', 'TestController@test');

        $home = $this->router->retrieve('GET', '/home');

        $home = 'Acme\Http\Controllers\HomeController' === $home[2][0];

        $login = $this->router->retrieve('POST', '/v1/auth/login');

        $login = 'Acme\Http\Controllers\AuthController' === $login[2][0];

        $hello = $this->router->retrieve('GET', '/v1/test/hello');

        $hello = 'Acme\Http\Controllers\TestController' === $hello[2][0];

        $this->assertTrue($home && $login && $hello);
    }

    /**
     * Tests RouterInterface::merge.
     *
     * @return void
     */
    public function testMergeMethod()
    {
        $this->exists(get_class($this->router));

        $router = new Router;

        $router->get('/test', 'TestController@test');

        $this->router->merge($router->routes());

        $exists = $this->router->has('GET', '/test');

        $this->assertTrue($exists);
    }

    /**
     * Verifies the specified router if it exists.
     *
     * @param  string $router
     * @return void
     */
    protected function exists($router)
    {
        if ($router === 'Rougin\Slytherin\Routing\FastRouteRouter') {
            $exists = class_exists('FastRoute\RouteCollector');

            $message = (string) 'FastRoute is not installed.';

            $exists || $this->markTestSkipped((string) $message);
        }

        if ($router === 'Rougin\Slytherin\Routing\PhrouteRouter') {
            $exists = class_exists('Phroute\Phroute\RouteCollector');

            $message = (string) 'Phroute is not installed.';

            $exists || $this->markTestSkipped((string) $message);
        }
    }
}


text:
from plenum.server.consensus.ordering_service import OrderingService
from plenum.server.node import Node
from plenum.server.replica import Replica
from plenum.server.suspicion_codes import Suspicions
from plenum.test.delayers import ppgDelay
from plenum.test.node_request.test_propagate.helper import sum_of_request_propagates
from plenum.test.stasher import delay_rules
from stp_core.common.log import getlogger
from plenum.test.helper import sdk_send_random_and_check
from plenum.test.checkpoints.conftest import chkFreqPatched
from plenum.test.replica.helper import register_pp_ts

logger = getlogger()
CHK_FREQ = 1

def test_replica_received_preprepare_with_ordered_request(looper,
                                                          txnPoolNodeSet,
                                                          sdk_pool_handle,
                                                          sdk_wallet_steward,
                                                          chkFreqPatched):
    sdk_send_random_and_check(looper, txnPoolNodeSet,
                              sdk_pool_handle, sdk_wallet_steward, 1)

    replica = txnPoolNodeSet[1].master_replica
    params = replica._ordering_service.spylog.getLastParams(OrderingService.process_preprepare)
    pp = params["pre_prepare"]
    sender = params["sender"]
    start_request_propagate_count = replica.node.spylog.count(Node.request_propagates)

    def discard(offendingMsg, reason, logger, cliOutput=False):
        assert offendingMsg == pp
        assert Suspicions.PPR_WITH_ORDERED_REQUEST.reason == reason

    replica.node.discard = discard

    register_pp_ts(replica, pp, sender)
    replica._ordering_service.process_preprepare(pp, sender)

    assert 0 == replica.node.spylog.count(Node.request_propagates) - start_request_propagate_count
    assert (pp, sender, set(pp.reqIdr)) not in replica._ordering_service.prePreparesPendingFinReqs

def test_replica_received_preprepare_with_unknown_request(looper,
                                                          txnPoolNodeSet,
                                                          sdk_pool_handle,
                                                          sdk_wallet_steward,
                                                          chkFreqPatched,
                                                          tconf):
    sdk_send_random_and_check(looper, txnPoolNodeSet,
                              sdk_pool_handle, sdk_wallet_steward, 1)
    slow_nodes = txnPoolNodeSet[2:]
    nodes_stashers = [n.nodeIbStasher for n in slow_nodes]
    slow_replica_1 = txnPoolNodeSet[2].master_replica
    slow_replica_2 = txnPoolNodeSet[3].master_replica
    with delay_rules(nodes_stashers, ppgDelay()):
        sdk_send_random_and_check(looper, txnPoolNodeSet,
                                  sdk_pool_handle, sdk_wallet_steward, 1)

    params1 = slow_replica_1._ordering_service.spylog.getLastParams(OrderingService.process_preprepare)
    pp1 = params1["pre_prepare"]
    sender1 = params1["sender"]
    params2 = slow_replica_2._ordering_service.spylog.getLastParams(OrderingService.process_preprepare)
    pp2 = params2["pre_prepare"]
    sender2 = params2["sender"]
    looper.runFor(tconf.PROPAGATE_REQUEST_DELAY)
    assert (pp1, sender1, set(pp1.reqIdr)) not in slow_replica_1._ordering_service.prePreparesPendingFinReqs
    assert (pp2, sender2, set(pp2.reqIdr)) not in slow_replica_2._ordering_service.prePreparesPendingFinReqs


text:
from multiprocessing import Pool
from sqlalchemy import desc
from base import Base
from schema import Session, Feed, Post
from datetime import datetime as dt
from datetime import timedelta

from config import max_post_age
from parser import parse_one

class Index(Base):
    def get(self):
        posts = Session.query(Post).filter_by(read=False).order_by(
            desc(Post.published))
        return self.render('index.html', posts=posts)

class FeedDelete(Base):
    # TODO: rewrite to post or better: delete (if that is possible?)
    def get(self, id):
        # sqlite won't cascade-delete the posts
        Session.query(Post).filter_by(feed_id=id).delete()
        Session.query(Feed).filter_by(id=id).delete()
        Session.commit()
        Session.close()
        return self.redirect('/')

class FeedEdit(Base):
    def get(self, id):
        feed = Session.query(Feed).filter_by(id=id).one()
        return self.render('feed_edit.html', feed=feed)

    def post(self, id):
        feed = Session.query(Feed).filter_by(id=id).one()
        feed.title = self.get_argument('name')
        feed.url = self.get_argument('url')
        Session.commit()
        Session.close()
        return self.redirect('/')

class FeedAdd(Base):
    def get(self):
        return self.render('feed_add.html')

    def post(self):
        name = self.get_argument('name')
        url = self.get_argument('url')
        feed = Feed()
        feed.title = name
        feed.url = url
        Session.add(feed)
        Session.commit()
        return self.render('index.html')

class MarkAsRead(Base):
    def get(self):
        for post in Session.query(Post).filter_by(read=False):
            post.read = True
        Session.commit()
        Session.close()
        return self.redirect('/')

class Refresh(Base):
    def get(self):
        Session.query(Post).filter(
            Post.updated <= dt.now() - timedelta(days=max_post_age)).delete()
        feeds = Session.query(Feed.id).all()
        Session.close()
        p = Pool(10)
        p.map_async(parse_one, (f.id for f in feeds))
        p.close()
        p.join()
        self.redirect('/')
        return


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Bootstrap 101 Template</title>

    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="http://rawgit.com/FezVrasta/bootstrap-material-design/master/dist/css/bootstrap-material-design.min.css">
    <link rel="stylesheet" href="http://rawgit.com/FezVrasta/bootstrap-material-design/master/dist/css/ripples.min.css">

                <form>

                            Email address
                            <input type="email" class="form-control" id="exampleInputEmail1">

                        Password
                        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">

                        File input
                        <input type="file" id="exampleInputFile">

Example block-level help text here.

                            <input type="checkbox"> Check me out

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

.col-md-6


text:
lanes = require "lanes"
lanes.configure{with_timers = false}

local function a_lane()
		print "IN A LANE"
    -- To require 'math' we still actually need to have it initialized for
    -- the lane.
    --
    require "math"
    assert( math and math.sqrt )
    assert( math.sqrt(4)==2 )

    assert( lanes==nil )
    local lanes = require "lanes".configure{with_timers = false}
    assert( lanes and lanes.gen )

    local h= lanes.gen( function() return 42 end ) ()
    local v= h[1]

    return v==42
end

local gen= lanes.gen( "math,package,string,table", {package={}},a_lane )

local h= gen()
local ret= h[1]
assert( ret==true )


text:
TOP_DIR = ..

# Standard definitions are found in the following file.

include $(TOP_DIR)/MakeDefs

SRCLIBDIR = $(TOP_DIR)/src/lib

# Subdirectories to build
#
# libGeoTiff isn't yet supported on Windows.

LINUXSUBS   = libGeotrans libTiff libGTiff
WINSUBS     = libGeotrans libTiff libGTiff
OTHERCLEANS = clean-Marsbin

ifeq ($(MARS_OS),linux)
    SUBS = $(LINUXSUBS)
else ifeq ($(MARS_OS),win)
    SUBS = $(WINSUBS)
else
    SUBS =
endif

.PHONY: all

all: $(SRCLIBDIR) subs Marsbin

#---------------------------------------------------------------------
# Target: <subdir> -- Rebuilds individual subdirectories

.PHONY: $(SUBS) Marsbin clean-Marsbin

$(SUBS):
	cd $@ ; make clean ; make

Marsbin:
	cd $@ ; chmod +x configure ; ./configure --with-tcl=$(MARS_TCL_HOME)/lib --prefix $(realpath $(TOP_DIR)) --exec-prefix $(realpath $(TOP_DIR))
	cd $@ ; make clean ; make ; make install

clean-Marsbin:
	cd Marsbin ; if test -f Makefile ; then make clean ; fi

#---------------------------------------------------------------------
# Target: lib -- creates the lib directory

$(SRCLIBDIR):
	mkdir $(SRCLIBDIR)

#---------------------------------------------------------------------
# Standard Rules

include $(TOP_DIR)/MakeRules

#---------------------------------------------------------------------
# Making Subdirectories

include MakeSubs


text:
require("angular");
require("angular-route");
var routes_1 = require("./configs/routes");
var PageTweetsComponent_1 = require("./components/pageTweets/PageTweetsComponent");
var TweetContentComponent_1 = require("./components/tweetContent/TweetContentComponent");
var TweetMainComponent_1 = require("./components/tweetMain/TweetMainComponent");
var TweetSidebarComponent_1 = require("./components/tweetSidebar/TweetSidebarComponent");
var TweetTopbarComponent_1 = require("./components/tweetTopbar/TweetTopbarComponent");
var ContentModel_1 = require("../core/models/impl/ContentModel");
var SharedModel_1 = require("../core/models/impl/SharedModel");
var SidebarModel_1 = require("../core/models/impl/SidebarModel");
var TopbarModel_1 = require("../core/models/impl/TopbarModel");
var TweetService_1 = require("../core/services/impl/TweetService");
angular.module("app.tweets", ["ngRoute"])
    .service("IContentModel", ContentModel_1.ContentModel)
    .service("ISharedModel", SharedModel_1.SharedModel)
    .service("ISidebarModel", SidebarModel_1.SidebarModel)
    .service("ITopbarModel", TopbarModel_1.TopbarModel)
    .service("ITweetService", TweetService_1.TweetService)
    .directive("pageTweets", function () { return new PageTweetsComponent_1.PageTweetsComponent(); })
    .directive("tweetContent", function () { return new TweetContentComponent_1.TweetContentComponent(); })
    .directive("tweetMain", function () { return new TweetMainComponent_1.TweetMainComponent(); })
    .directive("tweetSidebar", function () { return new TweetSidebarComponent_1.TweetSidebarComponent(); })
    .directive("tweetTopbar", function () { return new TweetTopbarComponent_1.TweetTopbarComponent(); })
    .config(routes_1.config);
//# sourceMappingURL=index.js.map


text:
class TcpDummy

  attr_accessor :last_send

  def initialize *args

  end

  def send *args
    @last_send = args
  end
end


text:
*+ENMFIL

       SUBROUTINE ENMFIL (MAP_NAME, FILE_NAME, STATUS)
C      -----------------------------------------------

C     Returns the full file name for a given map.
C
C     Given:
C         Abbreviated map name
              CHARACTER*(*)       MAP_NAME
C     Returned:
C         Full map file name
              CHARACTER*(*)       FILE_NAME
C         Status variable - must be zero on entry - otherwise error
              INTEGER             STATUS
C
C     Returns the full file name matching a given map name, using the
C     default map directory if not explicitly specified.  Case sensitivity
C     is relaxed when matching existing file names.  If no match is found
C     a new file name is constructed using the given name, and a NO_FILE
C     status is returned.
C
C     The STATUS value should be zero on entry.
C
C     DJT, 28 July 1994.
C-
C
      include '/mrao/include/iolib_errors.inc'
      include '/mrao/include/chrlib_functions.inc'
C
      character*64  temp_name, file
      character*32  def_dir
      integer       iobjx, count
      integer       ls, n
C
      if ( status .ne. 0 ) return
C
C  Add default directory to the given name
C
      temp_name = map_name
      call enmdir(def_dir, status)
      if ( map_name(1:1).ne.'/' .and. def_dir.ne.' ' ) then
         ls = chr_lenb(def_dir)
         if (def_dir(ls:ls).eq.'/') then
            temp_name = def_dir(1:ls) // map_name
         else
            temp_name = def_dir(1:ls) // '/' // map_name
         endif
      endif
      file_name = temp_name
C
C  Search the directory for a match to the given name
C
      n = 0
      count = 0
      ls = chr_ilstc(temp_name,'/')
      temp_name(ls+1:) = '*'
      do while (status.eq.0)
        call io_nxtfil(temp_name,file,iobjx,count,status)
        if ( status.eq.0 ) then
           if ( chr_fmatch(map_name, file)) then
             file_name = file
             n = n + 1
           endif
        endif
      enddo
      if ( n.eq.0 ) then
        call io_makfil(def_dir,map_name,'map',file_name,ls)
        status = NO_FILE
      elseif ( n.eq.1 ) then
        status = 0
      elseif ( n.gt.1 ) then
        status = AMB_FILE
      endif
C
      end


text:
from msrest.serialization import Model

class TopologyResource(Model):
    """The network resource topology information for the given resource group.

    :param name: Name of the resource.
    :type name: str
    :param id: ID of the resource.
    :type id: str
    :param location: Resource location.
    :type location: str
    :param associations: Holds the associations the resource has with other
     resources in the resource group.
    :type associations:
     list[~azure.mgmt.network.v2017_08_01.models.TopologyAssociation]
    """

    _attribute_map = {
        'name': {'key': 'name', 'type': 'str'},
        'id': {'key': 'id', 'type': 'str'},
        'location': {'key': 'location', 'type': 'str'},
        'associations': {'key': 'associations', 'type': '[TopologyAssociation]'},
    }

    def __init__(self, *, name: str=None, id: str=None, location: str=None, associations=None, **kwargs) -> None:
        super(TopologyResource, self).__init__(**kwargs)
        self.name = name
        self.id = id
        self.location = location
        self.associations = associations


text:
<md-dialog aria-label="Project" ng-cloak>
  <form>
    <md-toolbar>

{{project.name}}

    </md-toolbar>
    <md-dialog-content>

    </md-dialog-content>
    <md-dialog-actions layout="row">

      <md-button ng-click="hide()" style="margin-right:20px;">
        Скрыть
      </md-button>
    </md-dialog-actions>
  </form>
</md-dialog>


text: Count:


text:
import { Conduct, fillConductFromJson } from "./conduct";
import { GazouLabel } from "./gazou-label";
import { FullConductShinryou, jsonToFullConductShinryou } from "./full-conduct-shinryou";
import { FullConductDrug, jsonToFullConductDrug } from "./full-conduct-drug";
import { FullConductKizai, jsonToFullConductKizai } from "./full-conduct-kizai";

export class FullConduct extends Conduct {
	gazouLabel: string | null;
	drugs: FullConductDrug[];
	shinryouList: FullConductShinryou[];
	kizaiList: FullConductKizai[];
}

export function jsonToFullConduct(src: any){
	let conduct = new FullConduct();
	fillConductFromJson(conduct, src);
	conduct.gazouLabel = src.gazou_label;
	let drugs = src.drugs || [];
	conduct.drugs = drugs.map(jsonToFullConductDrug);
	let shinryouList = src.shinryou_list || [];
	conduct.shinryouList = shinryouList.map(jsonToFullConductShinryou);
	let kizaiList = src.kizai_list || [];
	conduct.kizaiList = kizaiList.map(jsonToFullConductKizai);
	return conduct;
}

/**
export function validateFullConduct(conduct: FullConduct): string[] {
	let errs = validateConduct(conduct);
	V.validate("画像ラベル", conduct.gazouLabel, errs, [
		V.isDefined, V.isOptionalString
	]);
	conduct.drugs.forEach(s => {
		errs = errs.concat(validateFullConductDrug(s));
	})
	conduct.shinryouList.forEach(s => {
		errs = errs.concat(validateFullConductShinryou(s));
	})
	conduct.kizaiList.forEach(s => {
		errs = errs.concat(validateFullConductKizai(s));
	})
	return errs;
}

export function fromJsonToFullConduct(src: any): FullConduct | V.ValidationError {
	let gazouLabel: string | null;
	{
		let val = src.gazou_label;
		if( typeof val === "string" ){
			gazouLabel = val;
		} else if( val === undefined || val === null ){
			gazouLabel = null;
		} else {
			return new V.ValidationError(["invalid gazou_label"]);
		}
	}
	let drugs: FullConductDrug[];
	{
		let result = V.mapConvert(src.drugs, fromJsonToFullConductDrug);
		if( result instanceof V.ValidationError ){
			return result;
		} else {
			drugs = result;
		}
	}
	let shinryouList: FullConductShinryou[];
	{
		let result = V.mapConvert(src.shinryou_list, fromJsonToFullConductShinryou);
		if( result instanceof V.ValidationError ){
			return result;
		} else {
			shinryouList = result;
		}
	}
	let kizaiList: FullConductKizai[];
	{
		let result = V.mapConvert(src.kizai_list, fromJsonToFullConductKizai);
		if( result instanceof V.ValidationError ){
			return result;
		} else {
			kizaiList = result;
		}
	}
	let conduct = new FullConduct(src.id, src.visit_id, src.kind, gazouLabel,
		drugs, shinryouList, kizaiList);
	let errs = validateFullConduct(conduct);
	if( errs.length > 0 ){
		return new V.ValidationError(errs);
	} else {
		return conduct;
	}
}

**/


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

namespace MVC_Azure_Explorer.Models
{
    public class MensajeView
    {
        public MensajeView()
        {
        }
        public bool GrowlStyle { get; set; }
        public string Mensaje { get; set; }
        public bool IsError { get; set; }
        public string ClaseCSS { get; set; }
    }

    public class ActionMensaje
    {
        public ActionMensaje()
        {
        }
        public string Msg { get; set; }
        public object DataObject { get; set; }
        public bool Success { get; set; }

    }
    public class MensajeUpload
    {
        public MensajeUpload()
        {
        }
        public string message { get; set; }
        public object DataObject { get; set; }
        public bool success { get; set; }

    }

}


text:
app.factory("KeyExistsFactory",function($q, fbUrl){
  return function(listName, shouldHaveSomeKey, keyString){
    var deferred = $q.defer();
    var ref = new Firebase(fbUrl+'/'+listName).orderByChild(keyString);
    var query;
    if (shouldHaveSomeKey) {
      query = ref.startAt(!null);
      // or:
      // query = ref.startAt(true);
    } else {
      query = ref.equalTo(null);
      // or:
      // query = ref.endAt(!null);
      // query = ref.endAt(true);
    }
    query.once("value", function(dataSnapshot){
      deferred.resolve(dataSnapshot.val());
    }, function (error) {
      deferred.reject(error);
    });
    return deferred.promise;
  }
});


text:
from fabric.api import (
    hide,
    lcd,
    local,
    quiet,
    task,
    warn_only)

@task
def clean():
    local('rm -rf wheelhouse')
    local('rm -rf dist')
    local('rm -rf build')

    with lcd('doc'):
        local('make clean')

@task
def docs():
    with lcd('doc'):
        local('make html')

@task
def lint():
    with warn_only():
        local('pylint --rcfile .pylintrc warthog')

@task
def coverage():
    with quiet():
        local('coverage run --source warthog ./.env/bin/py.test test')

    with hide('running'):
        local("coverage report  --omit 'warthog/packages*' --show-missing")

@task
def push():
    local('git push origin')

@task
def push_tags():
    local('git push --tags origin')

@task
def pypi():
    local('python setup.py sdist bdist_wheel')
    local('twine upload dist/*')


text:
- no arguments
- simple json.db for persistent storage.
- basic httpd with get and 8 file caching mechanism.
- levelized across single protocol.
- cookies.js is amazing.
- organized files, terrible codel
- chat was decent, had good tracking, fixed to 256 messages.

# basic.js (unreleased)

- arguments
- telnet and full-featured www.
- never worked?
- stage 2 advanced sql-like database. ( a mess. )
- chat server with built in learning talk bot


text:
<!DOCTYPE html>
<!--
    @license
    Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
    This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
    The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
    The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
    Code distributed by Google as part of the polymer project is also
    subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
  <head>
    <title>HTMLImportsLoaded, native</title>
    <script>
      WCT = {
        waitFor: function (cb) {
          cb();
        },
      };
    </script>
    <script src="../../node_modules/@webcomponents/html-imports/html-imports.min.js"></script>
    <script src="../../node_modules/wct-browser-legacy/browser.js"></script>
  </head>
  <body>
    <script>
      test('HTMLLinkElement has import property defined', function () {
        var link = document.createElement('link');
        assert.isTrue('import' in link);
        assert.isNull(link.import);
      });
    </script>
  </body>
</html>


text:
package basicauth_test

import (
	"fmt"
	"testing"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/httptest"
	"github.com/kataras/iris/v12/middleware/basicauth"
)

func TestBasicAuthUseRouter(t *testing.T) {
	app := iris.New()
	users := map[string]string{
		"usr":   "pss",
		"admin": "admin",
	}

	auth := basicauth.New(basicauth.Options{
		Allow:    basicauth.AllowUsers(users),
		Realm:    basicauth.DefaultRealm,
		MaxTries: 1,
	})

	app.UseRouter(auth)

	app.Get("/user_json", func(ctx iris.Context) {
		ctx.JSON(ctx.User())
	})

	app.Get("/user_string", func(ctx iris.Context) {
		user := ctx.User()

		authorization, _ := user.GetAuthorization()
		username, _ := user.GetUsername()
		password, _ := user.GetPassword()
		ctx.Writef("%s\n%s\n%s", authorization, username, password)
	})

	app.Get("/", func(ctx iris.Context) {
		username, _, _ := ctx.Request().BasicAuth()
		ctx.Writef("Hello, %s!", username)
	})

	app.Subdomain("static").Get("/", func(ctx iris.Context) {
		username, _, _ := ctx.Request().BasicAuth()
		ctx.Writef("Static, %s", username)
	})

	resetWithUseRouter := app.Subdomain("reset_with_use_router").ResetRouterFilters()
	resetWithUseRouter.UseRouter(func(ctx iris.Context) {
		ctx.Record()
		ctx.Writef("with use router\n")
		ctx.Next()
	})
	resetWithUseRouter.Get("/", func(ctx iris.Context) {
		username, _, _ := ctx.Request().BasicAuth()
		ctx.Writef("%s", username) // username should be empty.
	})
	// ^ order of these should not matter.
	app.Subdomain("reset").ResetRouterFilters().Get("/", func(ctx iris.Context) {
		username, _, _ := ctx.Request().BasicAuth()
		ctx.Writef("%s", username) // username should be empty.
	})

	e := httptest.New(t, app.Configure(
		iris.WithFireMethodNotAllowed,
		iris.WithResetOnFireErrorCode,
	))

	for username, password := range users {
		// Test pass authentication and route found.
		e.GET("/").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusOK).Body().Equal(fmt.Sprintf("Hello, %s!", username))
		e.GET("/user_json").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusOK).JSON().Object().ContainsMap(iris.Map{
			"username": username,
		})
		e.GET("/user_string").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusOK).Body().
			Equal(fmt.Sprintf("%s\n%s\n%s", "Basic Authentication", username, password))

		// Test empty auth.
		e.GET("/").Expect().Status(httptest.StatusUnauthorized).Body().Equal("Unauthorized")
		// Test invalid auth.
		e.GET("/").WithBasicAuth(username, "invalid_password").Expect().
			Status(httptest.StatusForbidden)
		e.GET("/").WithBasicAuth("invaid_username", password).Expect().
			Status(httptest.StatusForbidden)

		// Test different method, it should pass the authentication (no stop on 401)
		// but it doesn't fire the GET route, instead it gives 405.
		e.POST("/").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusMethodNotAllowed).Body().Equal("Method Not Allowed")

		// Test pass the authentication but route not found.
		e.GET("/notfound").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusNotFound).Body().Equal("Not Found")

		// Test empty auth.
		e.GET("/notfound").Expect().Status(httptest.StatusUnauthorized).Body().Equal("Unauthorized")
		// Test invalid auth.
		e.GET("/notfound").WithBasicAuth(username, "invalid_password").Expect().
			Status(httptest.StatusForbidden)
		e.GET("/notfound").WithBasicAuth("invaid_username", password).Expect().
			Status(httptest.StatusForbidden)

		// Test subdomain inherited.
		sub := e.Builder(func(req *httptest.Request) {
			req.WithURL("http://static.mydomain.com")
		})

		// Test pass and route found.
		sub.GET("/").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusOK).Body().Equal(fmt.Sprintf("Static, %s", username))

		// Test empty auth.
		sub.GET("/").Expect().Status(httptest.StatusUnauthorized)
		// Test invalid auth.
		sub.GET("/").WithBasicAuth(username, "invalid_password").Expect().
			Status(httptest.StatusForbidden)
		sub.GET("/").WithBasicAuth("invaid_username", password).Expect().
			Status(httptest.StatusForbidden)

		// Test pass the authentication but route not found.
		sub.GET("/notfound").WithBasicAuth(username, password).Expect().
			Status(httptest.StatusNotFound).Body().Equal("Not Found")

		// Test empty auth.
		sub.GET("/notfound").Expect().Status(httptest.StatusUnauthorized).Body().Equal("Unauthorized")
		// Test invalid auth.
		sub.GET("/notfound").WithBasicAuth(username, "invalid_password").Expect().
			Status(httptest.StatusForbidden)
		sub.GET("/notfound").WithBasicAuth("invaid_username", password).Expect().
			Status(httptest.StatusForbidden)

		// Test a reset-ed Party with a single one UseRouter
		// which writes on matched routes and reset and send the error on errors.
		// (all should pass without auth).
		sub = e.Builder(func(req *httptest.Request) {
			req.WithURL("http://reset_with_use_router.mydomain.com")
		})
		sub.GET("/").Expect().Status(httptest.StatusOK).Body().Equal("with use router\n")
		sub.POST("/").Expect().Status(httptest.StatusMethodNotAllowed).Body().Equal("Method Not Allowed")
		sub.GET("/notfound").Expect().Status(httptest.StatusNotFound).Body().Equal("Not Found")

		// Test a reset-ed Party (all should pass without auth).
		sub = e.Builder(func(req *httptest.Request) {
			req.WithURL("http://reset.mydomain.com")
		})
		sub.GET("/").Expect().Status(httptest.StatusOK).Body().Empty()
		sub.POST("/").Expect().Status(httptest.StatusMethodNotAllowed).Body().Equal("Method Not Allowed")
		sub.GET("/notfound").Expect().Status(httptest.StatusNotFound).Body().Equal("Not Found")
	}
}


text:
import numpy as np
import pytest
from numpy.testing import assert_equal

from expyfun import ExperimentController, __version__
from expyfun.io import read_tab, reconstruct_tracker, reconstruct_dealer
from expyfun._utils import _TempDir
from expyfun.stimuli import TrackerUD, TrackerBinom, TrackerDealer

temp_dir = _TempDir()
std_args = ['test']  # experiment name
std_kwargs = dict(output_dir=temp_dir, full_screen=False, window_size=(1, 1),
                  participant='foo', session='01', stim_db=0.0, noise_db=0.0,
                  verbose=True, version='dev')

@pytest.mark.timeout(10)
def test_parse_basic(hide_window, tmpdir):
    """Test .tab parsing."""
    with ExperimentController(*std_args, **std_kwargs) as ec:
        ec.identify_trial(ec_id='one', ttl_id=[0])
        ec.start_stimulus()
        ec.write_data_line('misc', 'trial one')
        ec.stop()
        ec.trial_ok()
        ec.write_data_line('misc', 'between trials')
        ec.identify_trial(ec_id='two', ttl_id=[1])
        ec.start_stimulus()
        ec.write_data_line('misc', 'trial two')
        ec.stop()
        ec.trial_ok()
        ec.write_data_line('misc', 'end of experiment')

    pytest.raises(ValueError, read_tab, ec.data_fname, group_start='foo')
    pytest.raises(ValueError, read_tab, ec.data_fname, group_end='foo')
    pytest.raises(ValueError, read_tab, ec.data_fname, group_end='trial_id')
    pytest.raises(RuntimeError, read_tab, ec.data_fname, group_end='misc')
    data = read_tab(ec.data_fname)
    keys = list(data[0].keys())
    assert_equal(len(keys), 6)
    for key in ['trial_id', 'flip', 'play', 'stop', 'misc', 'trial_ok']:
        assert key in keys
    assert_equal(len(data[0]['misc']), 1)
    assert_equal(len(data[1]['misc']), 1)
    data, params = read_tab(ec.data_fname, group_end=None, return_params=True)
    assert_equal(len(data[0]['misc']), 2)  # includes between-trials stuff
    assert_equal(len(data[1]['misc']), 2)
    assert_equal(params['version'], 'dev')
    assert_equal(params['version_used'], __version__)
    assert (params['file'].endswith('test_parse.py'))

    # handle old files where the last trial_ok was missing
    bad_fname = str(tmpdir.join('bad.tab'))
    with open(ec.data_fname, 'r') as fid:
        lines = fid.readlines()
        assert 'trial_ok' in lines[-3]
    with open(bad_fname, 'w') as fid:
        # we used to write JSON badly
        fid.write(lines[0].replace('"', "'"))
        # and then sometimes missed the last trial_ok
        for line in lines[1:-3]:
            fid.write(line)
    with pytest.raises(RuntimeError, match='bad bounds'):
        read_tab(bad_fname)
    data, params = read_tab(ec.data_fname, return_params=True)
    data_2, params_2 = read_tab(
        bad_fname, return_params=True, allow_last_missing=True)
    assert params == params_2
    t = data[-1].pop('trial_ok')
    t_2 = data_2[-1].pop('trial_ok')
    assert t != t_2
    assert data_2 == data

def test_reconstruct(hide_window):
    """Test Tracker objects reconstruction."""
    # test with one TrackerUD
    with ExperimentController(*std_args, **std_kwargs) as ec:
        tr = TrackerUD(ec, 1, 1, 3, 1, 5, np.inf, 3)
        while not tr.stopped:
            tr.respond(np.random.rand() < tr.x_current)

    tracker = reconstruct_tracker(ec.data_fname)[0]
    assert (tracker.stopped)
    tracker.x_current

    # test with one TrackerBinom
    with ExperimentController(*std_args, **std_kwargs) as ec:
        tr = TrackerBinom(ec, .05, .5, 10)
        while not tr.stopped:
            tr.respond(True)

    tracker = reconstruct_tracker(ec.data_fname)[0]
    assert (tracker.stopped)
    tracker.x_current

    # tracker not stopped
    with ExperimentController(*std_args, **std_kwargs) as ec:
        tr = TrackerUD(ec, 1, 1, 3, 1, 5, np.inf, 3)
        tr.respond(np.random.rand() < tr.x_current)
        assert (not tr.stopped)
    pytest.raises(ValueError, reconstruct_tracker, ec.data_fname)

    # test with dealer
    with ExperimentController(*std_args, **std_kwargs) as ec:
        tr = [TrackerUD(ec, 1, 1, 3, 1, 5, np.inf, 3) for _ in range(3)]
        td = TrackerDealer(ec, tr)

        for _, x_current in td:
            td.respond(np.random.rand() < x_current)

    dealer = reconstruct_dealer(ec.data_fname)[0]
    assert (all(td._x_history == dealer._x_history))
    assert (all(td._tracker_history == dealer._tracker_history))
    assert (all(td._response_history == dealer._response_history))
    assert (td.shape == dealer.shape)
    assert (td.trackers.shape == dealer.trackers.shape)

    # no tracker/dealer in file
    with ExperimentController(*std_args, **std_kwargs) as ec:
        ec.identify_trial(ec_id='one', ttl_id=[0])
        ec.start_stimulus()
        ec.write_data_line('misc', 'trial one')
        ec.stop()
        ec.trial_ok()
        ec.write_data_line('misc', 'end')

    pytest.raises(ValueError, reconstruct_tracker, ec.data_fname)
    pytest.raises(ValueError, reconstruct_dealer, ec.data_fname)