text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>Identifier Index</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

[hide private]

[frames] | no frames]

Identifier Index

[
 A
 B
 C
 D
 E
 F
 G
 H
 I
 J
  K
 L
 M
 N
 O
 P
 Q
 R
 S
 T
 U
 V
 W
  X
  Y
  Z
 _
]

A

all

(in TestChartTypes)
APIURL

(in GChartWrapper.GChart')
attribute()

(in GChartWrapper.charts.templatetags.charts)

APIPARAMS

(in GChartWrapper.GChart')
APIURL

(in GChartWrapper.constants)
Axes

(in GChartWrapper.GChart')

APIPARAMS

(in GChartWrapper.constants)
AssertionError

B

bar()

(in GChart)
BUBBLE_LICONS

(in GChartWrapper.constants)
BUBBLE_TYPES

(in GChartWrapper.constants)

Bubble

(in GChartWrapper)
BUBBLE_SICONS

(in GChartWrapper.GChart')
BubbleNode

(in GChartWrapper.charts.templatetags.charts)

bubble()

(in GChartWrapper.charts.templatetags.charts)
BUBBLE_SICONS

(in GChartWrapper.constants)

BUBBLE_LICONS

(in GChartWrapper.GChart')
BUBBLE_TYPES

(in GChartWrapper.GChart')

C

chart()

(in GChartWrapper)
check_type()

(in GChart)
color_args()

(in GChartWrapper.GChart')

ChartExtension

(in GChartWrapper.jinja2)
checksum()

(in GChart)
COLOR_MAP

(in GChartWrapper.GChart')

ChartNode

(in GChartWrapper.charts.templatetags.charts)
cls

(in FancyNode)
COLOR_MAP

(in GChartWrapper.constants)

charts

(in GChartWrapper)
codeset

(in GChartWrapper.encoding)
constants

(in GChartWrapper)

charts

(in GChartWrapper.charts.templatetags)
coding

(in GChartWrapper.encoding)

check_size()

(in GChart)
color()

(in GChart)

D

dataset()

(in GChart)
decode()

(in Encoder)

E

ecoding

(in GChartWrapper.encoding)
encodedata()

(in Encoder)
encoding

(in GChartWrapper)

encode()

(in Encoder)
Encoder

(in GChartWrapper.encoding)
encoding()

(in GChart)

F

FancyNode

(in GChartWrapper.charts.templatetags.charts)
fill()

(in GChart)
fromurl()

(in GChart)

G

GChart

(in GChartWrapper)
GEO

(in GChartWrapper.GChart')
getname()

(in GChart)

GChart'

(in GChartWrapper)
GEO

(in GChartWrapper.constants)
grid()

(in GChart)

GChartWrapper
get_chart()

(in GChartWrapper.tests)

GenericNode

(in GChartWrapper.charts.templatetags.charts)
getdata()

(in GChart)

H

HorizontalBarGroup

(in GChartWrapper)
HorizontalBarStack

(in GChartWrapper)

I

image()

(in GChart)
IMGATTRS

(in GChartWrapper.GChart')

img()

(in GChart)
IMGATTRS

(in GChartWrapper.constants)

J

jinja2

(in GChartWrapper)

L

label()

(in GChart)
LEGEND_POSITIONS

(in GChartWrapper.GChart')
line()

(in GChart)

label()

(in Axes)
LEGEND_POSITIONS

(in GChartWrapper.constants)
LineXY

(in GChartWrapper)

legend()

(in GChart)
level_data()

(in GChart)
lookup_color()

(in GChartWrapper.GChart')

legend_pos()

(in GChart)
Line

(in GChartWrapper)

M

make_chart()

(in GChartWrapper.charts.templatetags.charts)
margin()

(in GChart)
MARKERS

(in GChartWrapper.constants)

Map

(in GChartWrapper)
marker()

(in GChart)
Meter

(in GChartWrapper)

map()

(in GChart)
MARKERS

(in GChartWrapper.GChart')

N

Note

(in GChartWrapper)
NOTE_IMAGES

(in GChartWrapper.constants)
NOTE_WEATHERS

(in GChartWrapper.GChart')

note()

(in GChartWrapper.charts.templatetags.charts)
NOTE_TYPES

(in GChartWrapper.GChart')
NOTE_WEATHERS

(in GChartWrapper.constants)

NOTE_IMAGES

(in GChartWrapper.GChart')
NOTE_TYPES

(in GChartWrapper.constants)
NoteNode

(in GChartWrapper.charts.templatetags.charts)

O

o

(in _AbstractGChart)
orientation()

(in GChart)

o

(in Meter)
output_encoding()

(in GChart)

P

parse()

(in ChartExtension)
PIN_ICONS

(in GChartWrapper.GChart')
PinNode

(in GChartWrapper.charts.templatetags.charts)

Pie

(in GChartWrapper)
PIN_ICONS

(in GChartWrapper.constants)
position()

(in Axes)

Pie3D

(in GChartWrapper)
PIN_SHAPES

(in GChartWrapper.GChart')
post_render()

(in FancyNode)

PieC

(in GChartWrapper)
PIN_SHAPES

(in GChartWrapper.constants)
post_render()

(in GenericNode)

Pin

(in GChartWrapper)
PIN_TYPES

(in GChartWrapper.GChart')
PY_VER

(in GChartWrapper.GChart')

pin()

(in GChartWrapper.charts.templatetags.charts)
PIN_TYPES

(in GChartWrapper.constants)
PY_VER

(in GChartWrapper.constants)

Q

QRCode

(in GChartWrapper)
quote()

(in GChartWrapper.constants)

R

Radar

(in GChartWrapper)
render()

(in Bubble)
render()

(in Pin)

RadarSpline

(in GChartWrapper)
render()

(in GChart)
render()

(in Text)

range()

(in Axes)
render()

(in Axes)
render()

(in ChartNode)

register

(in GChartWrapper.charts.templatetags.charts)
render()

(in Note)
render()

(in GenericNode)

S

save()

(in GChart)
Scatter

(in GChartWrapper)
size()

(in GChart)

saveall()

(in GChartWrapper.tests)
shadow()

(in Bubble)
smart_str()

(in GChartWrapper.constants)

scale()

(in GChart)
shadow()

(in Pin)
Sparkline

(in GChartWrapper)

scalevalue()

(in Encoder)
show()

(in GChart)
style()

(in Axes)

T

t

(in _AbstractGChart)
test_financial()

(in TestChartTypes)
test_markerfill()

(in TestChartTypes)

t

(in HorizontalBarGroup)
test_fromstring()

(in TestChartTypes)
test_markers()

(in TestChartTypes)

t

(in HorizontalBarStack)
test_grid()

(in TestChartTypes)
test_min_max()

(in TestChartTypes)

t

(in Line)
test_guide_bhg()

(in TestChartTypes)
test_multiline()

(in TestChartTypes)

t

(in LineXY)
test_guide_bhs()

(in TestChartTypes)
test_numpy()

(in TestChartTypes)

t

(in Map)
test_guide_bvg()

(in TestChartTypes)
test_omitted_colors()

(in TestChartTypes)

t

(in Meter)
test_guide_bvs()

(in TestChartTypes)
test_packman()

(in TestChartTypes)

t

(in Pie)
test_guide_bvs_scale()

(in TestChartTypes)
test_pie()

(in TestChartTypes)

t

(in Pie3D)
test_guide_chbh_clipped()

(in TestChartTypes)
test_qr_code()

(in TestChartTypes)

t

(in PieC)
test_guide_chbh_size()

(in TestChartTypes)
test_scatter()

(in TestChartTypes)

t

(in Radar)
test_guide_granularity_150()

(in TestChartTypes)
test_simple()

(in TestChartTypes)

t

(in RadarSpline)
test_guide_granularity_20()

(in TestChartTypes)
test_simple_encode()

(in TestChartTypes)

t

(in Scatter)
test_guide_granularity_300()

(in TestChartTypes)
test_small_bubble_icon()

(in TestChartTypes)

t

(in Sparkline)
test_guide_granularity_40()

(in TestChartTypes)
test_sticky_note()

(in TestChartTypes)

t

(in Venn)
test_guide_granularity_80()

(in TestChartTypes)
test_text()

(in TestChartTypes)

t

(in VerticalBarGroup)
test_guide_intro()

(in TestChartTypes)
test_text_encode()

(in TestChartTypes)

t

(in VerticalBarStack)
test_guide_line_lc()

(in TestChartTypes)
test_text_pin()

(in TestChartTypes)

tag

(in GChartWrapper.charts.templatetags.charts)
test_guide_map()

(in TestChartTypes)
test_thought_note()

(in TestChartTypes)

tags

(in ChartExtension)
test_guide_meter()

(in TestChartTypes)
test_tick_marks()

(in TestChartTypes)

templatetags

(in GChartWrapper.charts)
test_guide_radar()

(in TestChartTypes)
test_title()

(in TestChartTypes)

test_adv_icon_pin()

(in TestChartTypes)
test_guide_sparkline()

(in TestChartTypes)
test_venn()

(in TestChartTypes)

test_adv_letter_pin()

(in TestChartTypes)
test_hvz()

(in TestChartTypes)
test_weather_note()

(in TestChartTypes)

test_axes()

(in TestChartTypes)
test_icon_pin()

(in TestChartTypes)
TestChartTypes

(in GChartWrapper.tests)

test_axes_position()

(in TestChartTypes)
test_interval()

(in TestChartTypes)
tests

(in GChartWrapper)

test_bar()

(in TestChartTypes)
test_jacobian()

(in TestChartTypes)
Text

(in GChartWrapper)

test_bar_text()

(in TestChartTypes)
test_large_bubble_icon()

(in TestChartTypes)
text()

(in GChartWrapper.charts.templatetags.charts)

test_bar_zero()

(in TestChartTypes)
test_large_bubble_icon_texts()

(in TestChartTypes)
TextNode

(in GChartWrapper.charts.templatetags.charts)

test_circle_diamonds()

(in TestChartTypes)
test_large_bubble_texts()

(in TestChartTypes)
tick()

(in Axes)

test_concentric_pie()

(in TestChartTypes)
test_legend()

(in TestChartTypes)
title()

(in GChart)

test_currency_bar()

(in TestChartTypes)
test_legend2()

(in TestChartTypes)
TTAGSATTRS

(in GChartWrapper.GChart')

test_czech_and_unicode()

(in TestChartTypes)
test_legend_position()

(in TestChartTypes)
TTAGSATTRS

(in GChartWrapper.constants)

test_extended_encode()

(in TestChartTypes)
test_letter_pin()

(in TestChartTypes)
type()

(in GChart)

test_fancy_radar()

(in TestChartTypes)
test_line()

(in TestChartTypes)
TYPES

(in GChartWrapper.GChart')

test_fill()

(in TestChartTypes)
test_margins()

(in TestChartTypes)
TYPES

(in GChartWrapper.constants)

U

url

(in GChart)
urlopen()

(in GChart)

V

Venn

(in GChartWrapper)
VerticalBarGroup

(in GChartWrapper)
VerticalBarStack

(in GChartWrapper)

W

write()

(in GChart)

_

__call__()

(in Axes)
__init__()

(in QRCode)
__str__()

(in GChart)

__init__()

(in Bubble)
__init__()

(in Text)
_AbstractGChart

(in GChartWrapper.GChart')

__init__()

(in GChart)
__init__()

(in ChartNode)
_chart_support()

(in ChartExtension)

__init__()

(in Axes)
__init__()

(in GenericNode)
_parts()

(in GChart)

__init__()

(in _AbstractGChart)
__init__()

(in Encoder)
_print()

(in GChartWrapper.constants)

__init__()

(in Note)
__init__()

(in TestChartTypes)
_test_a_chart()

(in TestChartTypes)

__init__()

(in Pin)
__repr__()

(in GChart)
_test_encoding()

(in TestChartTypes)

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1
    on Wed Sep 30 14:59:36 2009

      http://epydoc.sourceforge.net


text:
name: cljs.core/HashSetIter
see also:
---

## Summary

## Details

## Examples

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: "Arnold Layne - David Bowie - David Gilmour by Syd Barrett"
tags: [video]
---

http://www.youtube.com/watch?v=wJuCo5M05bU

Det här gör mig glad!


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.sonatype.oss</groupId>
		<artifactId>oss-parent</artifactId>
		<version>9</version>
	</parent>

	<groupId>org.csanchez.kubernetes</groupId>
	<artifactId>kubernetes-java</artifactId>
	<version>0.0.4-SNAPSHOT</version>
	<name>KubernetesAPIJavaClient</name>
	<url>https://github.com/carlossg/KubernetesAPIJavaClient</url>
	<description>Java API Client for Google Kubernetes</description>

	<licenses>
		<license>
			<name>The Apache Software License, Version 2.0</name>
			<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<connection>scm:git:git@github.com:carlossg/KubernetesAPIJavaClient.git</connection>
		<url>git@github.com:carlossg/KubernetesAPIJavaClient.git</url>
		<developerConnection>scm:git:git@github.com:carlossg/KubernetesAPIJavaClient.git</developerConnection>
		<tag>HEAD</tag>
	</scm>

	<developers>
		<developer>
			<id>nirmal070125</id>
			<name>Nirmal Fernando</name>
			<email>nirmal070125@gmail.com</email>
		</developer>
		<developer>
			<id>csanchez</id>
			<name>Carlos Sanchez</name>
			<email>carlos@apache.org</email>
		</developer>
	</developers>

	<properties>
	    <kubernetes.api.endpoint>http://localhost:8080/api/v1beta1/</kubernetes.api.endpoint>
	    <kubernetes.api.username>vagrant</kubernetes.api.username>
	    <kubernetes.api.password>vagrant</kubernetes.api.password>
	    <docker.image>busybox</docker.image>
	    <resteasy.version>3.0.9.Final</resteasy.version>
	    <jackson.version>2.5.0</jackson.version>
  	</properties>

	<dependencies>
		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>jaxrs-api</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>18.0</version>
		</dependency>

		<dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-client</artifactId>
			<version>${resteasy.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.jaxrs</groupId>
			<artifactId>jackson-jaxrs-json-provider</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.datatype</groupId>
			<artifactId>jackson-datatype-joda</artifactId>
			<version>${jackson.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.3</version>
		</dependency>
		<dependency>
			<groupId>org.bouncycastle</groupId>
			<artifactId>bcprov-jdk16</artifactId>
			<version>1.46</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-library</artifactId>
			<version>1.3</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<distributionManagement>
		<snapshotRepository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
		</snapshotRepository>
		<repository>
			<id>ossrh</id>
			<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
		</repository>
	</distributionManagement>

	<prerequisites>
		<maven>3.0.4</maven>
	</prerequisites>

	<build>
		<plugins>
		 	<plugin>
				<groupId>org.sonatype.plugins</groupId>
				<artifactId>nexus-staging-maven-plugin</artifactId>
				<version>1.6.5</version>
				<extensions>true</extensions>
				<configuration>
					<serverId>ossrh</serverId>
					<nexusUrl>https://oss.sonatype.org/</nexusUrl>
					<autoReleaseAfterClose>true</autoReleaseAfterClose>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-release-plugin</artifactId>
				<version>2.5</version>
				<configuration>
					<autoVersionSubmodules>true</autoVersionSubmodules>
					<useReleaseProfile>false</useReleaseProfile>
					<releaseProfiles>release</releaseProfiles>
					<goals>deploy nexus-staging:release</goals>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source />
					<target />
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.18.1</version>
				<configuration>
					<groups>com.github.kubernetes.java.client.UnitTests</groups>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>live</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-surefire-plugin</artifactId>
						<configuration>
							<groups>com.github.kubernetes.java.client.LiveTests</groups>
							<systemPropertyVariables>
								<kubernetes.api.endpoint>${kubernetes.api.endpoint}</kubernetes.api.endpoint>
								<kubernetes.api.username>${kubernetes.api.username}</kubernetes.api.username>
								<kubernetes.api.password>${kubernetes.api.password}</kubernetes.api.password>
								<docker.image>${docker.image}</docker.image>

								<!-- enable for debugging http requests and responses
								<org.apache.commons.logging.Log>org.apache.commons.logging.impl.SimpleLog</org.apache.commons.logging.Log>
								<org.apache.commons.logging.simplelog.showdatetime>true</org.apache.commons.logging.simplelog.showdatetime>
								<org.apache.commons.logging.simplelog.log.org.apache.http>DEBUG</org.apache.commons.logging.simplelog.log.org.apache.http>
								-->
							</systemPropertyVariables>
						</configuration>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>release</id>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-gpg-plugin</artifactId>
						<version>1.6</version>
						<executions>
							<execution>
								<id>sign-artifacts</id>
								<phase>verify</phase>
								<goals>
									<goal>sign</goal>
								</goals>
							</execution>
						</executions>
					</plugin>

					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-source-plugin</artifactId>
						<version>2.2.1</version>
						<executions>
							<execution>
								<id>attach-sources</id>
								<goals>
									<goal>jar-no-fork</goal>
								</goals>
							</execution>
						</executions>
					</plugin>

					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-javadoc-plugin</artifactId>
						<version>2.9.1</version>
						<executions>
							<execution>
								<id>attach-javadocs</id>
								<goals>
									<goal>jar</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
/**
 * @class employeeadmin.model.RoleProxy
 *
 * @classDescription
 * TrueMVC Proxy class object used to control the user roles list
 * of the application.
 *
 * @requires truemvc.proxy.Proxy Proxy
 * @requires truemvc.observer.Notification
 * @requires employeeadmin.model.vo.RoleVO RoleVO
 * @requires employeeadmin.model.vo.UserVO
 * @requires employeeadmin.model.enum.RoleEnum RoleEnum
 * @requires employeeadmin.ApplicationFacade ApplicationFacade
 *
 * @extends truemvc.proxy.Proxy Proxy
 *
 * @constructor
 */
var RoleProxy = Objs("employeeadmin.model.RoleProxy",
	Proxy,
	{

		/**
		 * @constructs
		 * @override
		 *
		 * Initialize a RoleProxy instance.
		 *
		 * @param {String} name
		 * 		Identifier of the Proxy object in the TrueMVC framework.
		 *
		 * @param {Array} roles
		 * 		The list of user roles RoleVO object controlled by the
		 * 		Proxy.
		 */
		initialize: function( name, roles )
		{
			RoleProxy.$super.initialize.call( this, name, roles );

			return this;
		},

		/**
		 * Get the role list.
		 *
		 * @return {Array}
		 * 		The role list.
		 */
		getRoles: function()
		{
			return this.data;
		},

		/**
		 * Add a role to the list.
		 *
		 * @param {RoleVO} role
		 * 		The role to add.
		 */
		addItem: function( role )
		{
			this.getRoles().push( role );
		},

		/**
		 * Remove a role from the list.
		 *
		 * @param {RoleVO} item
		 * 		The role to remove.
		 */
		deleteItem: function( item )
		{
			var roles = this.getRoles();
			for( var i/*Number*/=0; i<roles.length; i++)
			{
				if( roles[i].uname == item.uname )
				{
					roles.splice(i,1);
					break;
				}
			}
		},

		/**
		 * Determine if the user has a given role.
		 *
		 * @param {UserVO} user
		 * 		The user for whom to search for the role.
		 *
		 * @param {RoleEnum} role
		 * 		The role to search for.
		 *
		 * @return {Boolean}
		 * 		The user has the given role.
		 */
		doesUserHaveRole: function( user, role )
		{
			var roles/*Array*/ = this.getRoles();
			var hasRole/*Boolean*/ = false;
			for( var i/*Number*/=0; i<roles.length; i++)
			{
				if( roles[i].uname == user.uname )
				{
					var userRoles/*Array*/ = roles[i].roles;
					for( var j/*Number*/=0; j<userRoles.length; j++ )
					{
						var roleEnum/*RoleEnum*/ = userRoles[j];
						if( roleEnum.equals( role ) )
						{
							hasRole = true;
							break;
						}
					}
					break;
				}
			}
			return hasRole;
		},

		/**
		 * Add a role to a user.
		 *
		 * @param {UserVO} user
		 * 		The user to whom to add a role.
		 *
		 * @param {RoleEnum} role
		 * 		The role to add.
		 */
		addRoleToUser: function( user, role )
		{
			var roles/*Array*/ = this.getRoles();
			var result/*Boolean*/ = false;
			if ( !this.doesUserHaveRole(user, role) )
			{
				for( var i/*Number*/=0; i<roles.length; i++)
				{
					if( roles[i].uname == user.uname )
					{
						var userRoles/*Array*/ = roles[i].roles;
						userRoles.push( role );
						result = true;
						break;
					}
				}
			}
		},

		/**
		 * Remove a role from a user.
		 *
		 * @param {UserVO} user
		 * 		The user to whom remove the role.
		 *
		 * @param {RoleEnum} role
		 * 		The role to remove.
		 */
		removeRoleFromUser: function( user, role )
		{
			var roles/*Array*/ = this.getRoles();
			if( this.doesUserHaveRole( user, role ) )
			{
				for( var i/*Number*/=0; i<roles.length; i++)
				{
					if( roles[i].uname == user.uname )
					{
						var userRoles/*Array*/ = roles[i].roles;
						for( var j/*Number*/=0; j<userRoles.length; j++)
						{
							var roleEnum/*RoleEnum*/ = userRoles[j];
							if( roleEnum.equals( role ) )
							{
								userRoles.splice(j,1);
								break;
							}
						}
						break;
					}
				}
			}
		},

		/**
		 * Get a user's roles.
		 *
		 * @param {String} uname
		 * 		The user unique name.
		 *
		 * @return {Array}
		 * 		The user's role list.
		 */
		getUserRoles: function( uname )
		{
			var roles/*Array*/ = this.getRoles();
			var userRoles/*Array*/ = new Array();
			for( var i/*Number*/=0; i<roles.length; i++)
			{
				if( roles[i].uname == uname )
				{
					userRoles = roles[i].roles;
					break;
				}
			}

			return userRoles;
		}
	}
);


text:
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta name="robots" content="index, follow, all" />
        <title>FFMpeg\Format\FrameInterface | PHP-FFMpeg API</title>
                    <link rel="stylesheet" type="text/css" href="../../stylesheet.css">

Classes

Namespaces

Interfaces

Traits

Index

PHP-FFMpeg API

Interface

FFMpeg\Format\FrameInterface

    interface
    FrameInterface        implements
        FormatInterface

Methods

                    string

                    getPasses()

Returns the number of passes.

                from FormatInterface

                    array()

                    getExtraParams()

Returns an array of extra parameters to add to ffmpeg commandline.

                from FormatInterface

Details

in FormatInterface at line 20

                    public            string
    getPasses()

Returns the number of passes.

Return Value

            string

in FormatInterface at line 27

                    public            array()
    getExtraParams()

Returns an array of extra parameters to add to ffmpeg commandline.

Return Value

            array()

        Generated by Sami, the API Documentation Generator.


text:
#ifndef __TBB_tbb_stddef_H
#define __TBB_tbb_stddef_H

// Marketing-driven product version
#define TBB_VERSION_MAJOR 4
#define TBB_VERSION_MINOR 3

// Engineering-focused interface version
#define TBB_INTERFACE_VERSION 8006
#define TBB_INTERFACE_VERSION_MAJOR TBB_INTERFACE_VERSION/1000

// The oldest major interface version still supported
// To be used in SONAME, manifests, etc.
#define TBB_COMPATIBLE_INTERFACE_VERSION 2

#define __TBB_STRING_AUX(x) #x
#define __TBB_STRING(x) __TBB_STRING_AUX(x)

// We do not need defines below for resource processing on windows
#if !defined RC_INVOKED

// Define groups for Doxygen documentation
/**
 * @defgroup algorithms         Algorithms
 * @defgroup containers         Containers
 * @defgroup memory_allocation  Memory Allocation
 * @defgroup synchronization    Synchronization
 * @defgroup timing             Timing
 * @defgroup task_scheduling    Task Scheduling
 */

// Simple text that is displayed on the main page of Doxygen documentation.
/**
 * \mainpage Main Page
 *
 * Click the tabs above for information about the
 * - Modules (groups of functionality) implemented by the library
 * - Classes provided by the library
 * - Files constituting the library.
 * .
 * Please note that significant part of TBB functionality is implemented in the form of
 * template functions, descriptions of which are not accessible on the Classes
 * tab. Use Modules or Namespace/Namespace Members
 * tabs to find them.
 *
 * Additional pieces of information can be found here
 * - \subpage concepts
 * .
 */

/** \page concepts TBB concepts

    A concept is a set of requirements to a type, which are necessary and sufficient
    for the type to model a particular behavior or a set of behaviors. Some concepts
    are specific to a particular algorithm (e.g. algorithm body), while other ones
    are common to several algorithms (e.g. range concept).

    All TBB algorithms make use of different classes implementing various concepts.
    Implementation classes are supplied by the user as type arguments of template
    parameters and/or as objects passed as function call arguments. The library
    provides predefined  implementations of some concepts (e.g. several kinds of
    \ref range_req "ranges"), while other ones must always be implemented by the user.

    TBB defines a set of minimal requirements each concept must conform to. Here is
    the list of different concepts hyperlinked to the corresponding requirements specifications:
    - \subpage range_req
    - \subpage parallel_do_body_req
    - \subpage parallel_for_body_req
    - \subpage parallel_reduce_body_req
    - \subpage parallel_scan_body_req
    - \subpage parallel_sort_iter_req
**/

// tbb_config.h should be included the first since it contains macro definitions used in other headers
#include "tbb_config.h"

#if _MSC_VER >=1400
    #define __TBB_EXPORTED_FUNC   __cdecl
    #define __TBB_EXPORTED_METHOD __thiscall
#else
    #define __TBB_EXPORTED_FUNC
    #define __TBB_EXPORTED_METHOD
#endif

#if __INTEL_COMPILER || _MSC_VER
#define __TBB_NOINLINE(decl) __declspec(noinline) decl
#elif __GNUC__
#define __TBB_NOINLINE(decl) decl __attribute__ ((noinline))
#else
#define __TBB_NOINLINE(decl) decl
#endif

#if __TBB_NOEXCEPT_PRESENT
#define __TBB_NOEXCEPT(expression) noexcept(expression)
#else
#define __TBB_NOEXCEPT(expression)
#endif

#include <cstddef>      /* Need size_t and ptrdiff_t */

#if _MSC_VER
    #define __TBB_tbb_windef_H
    #include "internal/_tbb_windef.h"
    #undef __TBB_tbb_windef_H
#endif
#if !defined(_MSC_VER) || _MSC_VER>=1600
    #include <stdint.h>
#endif

//! Type for an assertion handler
typedef void(*assertion_handler_type)( const char* filename, int line, const char* expression, const char * comment );

#if __TBBMALLOC_BUILD
namespace rml { namespace internal {
 #define __TBB_ASSERT_RELEASE(predicate,message) ((predicate)?((void)0) : rml::internal::assertion_failure(__FILE__,__LINE__,#predicate,message))
#else
namespace tbb {
 #define __TBB_ASSERT_RELEASE(predicate,message) ((predicate)?((void)0) : tbb::assertion_failure(__FILE__,__LINE__,#predicate,message))
#endif

    //! Set assertion handler and return previous value of it.
    assertion_handler_type __TBB_EXPORTED_FUNC set_assertion_handler( assertion_handler_type new_handler );

    //! Process an assertion failure.
    /** Normally called from __TBB_ASSERT macro.
        If assertion handler is null, print message for assertion failure and abort.
        Otherwise call the assertion handler. */
    void __TBB_EXPORTED_FUNC assertion_failure( const char* filename, int line, const char* expression, const char* comment );

#if __TBBMALLOC_BUILD
}}  // namespace rml::internal
#else
} // namespace tbb
#endif

#if TBB_USE_ASSERT

    //! Assert that x is true.
    /** If x is false, print assertion failure message.
        If the comment argument is not NULL, it is printed as part of the failure message.
        The comment argument has no other effect. */
    #define __TBB_ASSERT(predicate,message) __TBB_ASSERT_RELEASE(predicate,message)

    #define __TBB_ASSERT_EX __TBB_ASSERT

#else /* !TBB_USE_ASSERT */

    //! No-op version of __TBB_ASSERT.
    #define __TBB_ASSERT(predicate,comment) ((void)0)
    //! "Extended" version is useful to suppress warnings if a variable is only used with an assert
    #define __TBB_ASSERT_EX(predicate,comment) ((void)(1 && (predicate)))

#endif /* !TBB_USE_ASSERT */

//! The namespace tbb contains all components of the library.
namespace tbb {

#if _MSC_VER && _MSC_VER<1600
    namespace internal {
        typedef __int8 int8_t;
        typedef __int16 int16_t;
        typedef __int32 int32_t;
        typedef __int64 int64_t;
        typedef unsigned __int8 uint8_t;
        typedef unsigned __int16 uint16_t;
        typedef unsigned __int32 uint32_t;
        typedef unsigned __int64 uint64_t;
    } // namespace internal
#else /* Posix */
    namespace internal {
        using ::int8_t;
        using ::int16_t;
        using ::int32_t;
        using ::int64_t;
        using ::uint8_t;
        using ::uint16_t;
        using ::uint32_t;
        using ::uint64_t;
    } // namespace internal
#endif /* Posix */

    using std::size_t;
    using std::ptrdiff_t;

//! The function returns the interface version of the TBB shared library being used.
/**
 * The version it returns is determined at runtime, not at compile/link time.
 * So it can be different than the value of TBB_INTERFACE_VERSION obtained at compile time.
 */
extern "C" int __TBB_EXPORTED_FUNC TBB_runtime_interface_version();

/**
 * @cond INTERNAL
 * @brief Identifiers declared inside namespace internal should never be used directly by client code.
 */
namespace internal {

//! Compile-time constant that is upper bound on cache line/sector size.
/** It should be used only in situations where having a compile-time upper
    bound is more useful than a run-time exact answer.
    @ingroup memory_allocation */
const size_t NFS_MaxLineSize = 128;

/** Label for data that may be accessed from different threads, and that may eventually become wrapped
    in a formal atomic type.

    Note that no problems have yet been observed relating to the definition currently being empty,
    even if at least "volatile" would seem to be in order to avoid data sometimes temporarily hiding
    in a register (although "volatile" as a "poor man's atomic" lacks several other features of a proper
    atomic, some of which are now provided instead through specialized functions).

    Note that usage is intentionally compatible with a definition as qualifier "volatile",
    both as a way to have the compiler help enforce use of the label and to quickly rule out
    one potential issue.

    Note however that, with some architecture/compiler combinations, e.g. on IA-64 architecture, "volatile"
    also has non-portable memory semantics that are needlessly expensive for "relaxed" operations.

    Note that this must only be applied to data that will not change bit patterns when cast to/from
    an integral type of the same length; tbb::atomic must be used instead for, e.g., floating-point types.

    TODO: apply wherever relevant **/
#define __TBB_atomic // intentionally empty, see above

template<class T, size_t S, size_t R>
struct padded_base : T {
    char pad[S - R];
};
template<class T, size_t S> struct padded_base<T, S, 0> : T {};

//! Pads type T to fill out to a multiple of cache line size.
template<class T, size_t S = NFS_MaxLineSize>
struct padded : padded_base<T, S, sizeof(T) % S> {};

//! Extended variant of the standard offsetof macro
/** The standard offsetof macro is not sufficient for TBB as it can be used for
    POD-types only. The constant 0x1000 (not NULL) is necessary to appease GCC. **/
#define __TBB_offsetof(class_name, member_name) \
    ((ptrdiff_t)&(reinterpret_cast<class_name*>(0x1000)->member_name) - 0x1000)

//! Returns address of the object containing a member with the given name and address
#define __TBB_get_object_ref(class_name, member_name, member_addr) \
    (*reinterpret_cast<class_name*>((char*)member_addr - __TBB_offsetof(class_name, member_name)))

//! Throws std::runtime_error with what() returning error_code description prefixed with aux_info
void __TBB_EXPORTED_FUNC handle_perror( int error_code, const char* aux_info );

#if TBB_USE_EXCEPTIONS
    #define __TBB_TRY try
    #define __TBB_CATCH(e) catch(e)
    #define __TBB_THROW(e) throw e
    #define __TBB_RETHROW() throw
#else /* !TBB_USE_EXCEPTIONS */
    inline bool __TBB_false() { return false; }
    #define __TBB_TRY
    #define __TBB_CATCH(e) if ( tbb::internal::__TBB_false() )
    #define __TBB_THROW(e) ((void)0)
    #define __TBB_RETHROW() ((void)0)
#endif /* !TBB_USE_EXCEPTIONS */

//! Report a runtime warning.
void __TBB_EXPORTED_FUNC runtime_warning( const char* format, ... );

#if TBB_USE_ASSERT
static void* const poisoned_ptr = reinterpret_cast<void*>(-1);

//! Set p to invalid pointer value.
//  Also works for regular (non-__TBB_atomic) pointers.
template<typename T>
inline void poison_pointer( T* __TBB_atomic & p ) { p = reinterpret_cast<T*>(poisoned_ptr); }

/** Expected to be used in assertions only, thus no empty form is defined. **/
template<typename T>
inline bool is_poisoned( T* p ) { return p == reinterpret_cast<T*>(poisoned_ptr); }
#else
template<typename T>
inline void poison_pointer( T* __TBB_atomic & ) {/*do nothing*/}
#endif /* !TBB_USE_ASSERT */

//! Cast between unrelated pointer types.
/** This method should be used sparingly as a last resort for dealing with
    situations that inherently break strict ISO C++ aliasing rules. */
// T is a pointer type because it will be explicitly provided by the programmer as a template argument;
// U is a referent type to enable the compiler to check that "ptr" is a pointer, deducing U in the process.
template<typename T, typename U>
inline T punned_cast( U* ptr ) {
    uintptr_t x = reinterpret_cast<uintptr_t>(ptr);
    return reinterpret_cast<T>(x);
}

//! Base class for types that should not be assigned.
class no_assign {
    // Deny assignment
    void operator=( const no_assign& );
public:
#if __GNUC__
    //! Explicitly define default construction, because otherwise gcc issues gratuitous warning.
    no_assign() {}
#endif /* __GNUC__ */
};

//! Base class for types that should not be copied or assigned.
class no_copy: no_assign {
    //! Deny copy construction
    no_copy( const no_copy& );
public:
    //! Allow default construction
    no_copy() {}
};

#if TBB_DEPRECATED_MUTEX_COPYING
class mutex_copy_deprecated_and_disabled {};
#else
// By default various implementations of mutexes are not copy constructible
// and not copy assignable.
class mutex_copy_deprecated_and_disabled : no_copy {};
#endif

//! A function to check if passed in pointer is aligned on a specific border
template<typename T>
inline bool is_aligned(T* pointer, uintptr_t alignment) {
    return 0==((uintptr_t)pointer & (alignment-1));
}

//! A function to check if passed integer is a power of 2
template<typename integer_type>
inline bool is_power_of_two(integer_type arg) {
    return arg && (0 == (arg & (arg - 1)));
}

//! A function to compute arg modulo divisor where divisor is a power of 2.
template<typename argument_integer_type, typename divisor_integer_type>
inline argument_integer_type modulo_power_of_two(argument_integer_type arg, divisor_integer_type divisor) {
    // Divisor is assumed to be a power of two (which is valid for current uses).
    __TBB_ASSERT( is_power_of_two(divisor), "Divisor should be a power of two" );
    return (arg & (divisor - 1));
}

//! A function to determine if "arg is a multiplication of a number and a power of 2".
// i.e. for strictly positive i and j, with j a power of 2,
// determines whether i==j<<k for some nonnegative k (so i==j yields true).
template<typename argument_integer_type, typename divisor_integer_type>
inline bool is_power_of_two_factor(argument_integer_type arg, divisor_integer_type divisor) {
    // Divisor is assumed to be a power of two (which is valid for current uses).
    __TBB_ASSERT( is_power_of_two(divisor), "Divisor should be a power of two" );
    return 0 == (arg & (arg - divisor));
}

//! Utility template function to prevent "unused" warnings by various compilers.
template<typename T1> void suppress_unused_warning( const T1& ) {}
template<typename T1, typename T2> void suppress_unused_warning( const T1&, const T2& ) {}
template<typename T1, typename T2, typename T3> void suppress_unused_warning( const T1&, const T2&, const T3& ) {}

// Struct to be used as a version tag for inline functions.
/** Version tag can be necessary to prevent loader on Linux from using the wrong
    symbol in debug builds (when inline functions are compiled as out-of-line). **/
struct version_tag_v3 {};

typedef version_tag_v3 version_tag;

} // internal

//! Dummy type that distinguishes splitting constructor from copy constructor.
/**
 * See description of parallel_for and parallel_reduce for example usages.
 * @ingroup algorithms
 */
class split {
};

//! Type enables transmission of splitting proportion from partitioners to range objects
/**
 * In order to make use of such facility Range objects must implement
 * splitting constructor with this type passed and initialize static
 * constant boolean field 'is_splittable_in_proportion' with the value
 * of 'true'
 */
class proportional_split: internal::no_assign {
public:
    proportional_split(size_t _left = 1, size_t _right = 1) : my_left(_left), my_right(_right) { }

    size_t left() const { return my_left; }
    size_t right() const { return my_right; }

    // used when range does not support proportional split
    operator split() const { return split(); }

#if __TBB_ENABLE_RANGE_FEEDBACK
    void set_proportion(size_t _left, size_t _right) {
        my_left = _left;
        my_right = _right;
    }
#endif
private:
    size_t my_left, my_right;
};

} // tbb

// Following is a set of classes and functions typically used in compile-time "metaprogramming".
// TODO: move all that to a separate header

#if __TBB_ALLOCATOR_TRAITS_PRESENT
#include <memory> //for allocator_traits
#endif

#if __TBB_CPP11_RVALUE_REF_PRESENT || _LIBCPP_VERSION
#include <utility> // for std::move
#endif

namespace tbb {
namespace internal {

//! Class for determining type of std::allocator<T>::value_type.
template<typename T>
struct allocator_type {
    typedef T value_type;
};

#if _MSC_VER
//! Microsoft std::allocator has non-standard extension that strips const from a type.
template<typename T>
struct allocator_type<const T> {
    typedef T value_type;
};
#endif

// Ad-hoc implementation of true_type & false_type
// Intended strictly for internal use! For public APIs (traits etc), use C++11 analogues.
template <bool v>
struct bool_constant {
    static /*constexpr*/ const bool value = v;
};
typedef bool_constant<true> true_type;
typedef bool_constant<false> false_type;

#if __TBB_ALLOCATOR_TRAITS_PRESENT
using std::allocator_traits;
#else
template<typename allocator>
struct allocator_traits{
    typedef tbb::internal::false_type propagate_on_container_move_assignment;
};
#endif

//! A template to select either 32-bit or 64-bit constant as compile time, depending on machine word size.
template <unsigned u, unsigned long long ull >
struct select_size_t_constant {
    //Explicit cast is needed to avoid compiler warnings about possible truncation.
    //The value of the right size,   which is selected by ?:, is anyway not truncated or promoted.
    static const size_t value = (size_t)((sizeof(size_t)==sizeof(u)) ? u : ull);
};

#if __TBB_CPP11_RVALUE_REF_PRESENT
using std::move;
using std::forward;
#elif defined(_LIBCPP_NAMESPACE)
// libc++ defines "pre-C++11 move and forward" similarly to ours; use it to avoid name conflicts in some cases.
using std::_LIBCPP_NAMESPACE::move;
using std::_LIBCPP_NAMESPACE::forward;
#else
// It is assumed that cv qualifiers, if any, are part of the deduced type.
template <typename T>
T& move( T& x ) { return x; }
template <typename T>
T& forward( T& x ) { return x; }
#endif /* __TBB_CPP11_RVALUE_REF_PRESENT */

// Helper macros to simplify writing templates working with both C++03 and C++11.
#if __TBB_CPP11_RVALUE_REF_PRESENT
#define  __TBB_FORWARDING_REF(A) A&&
#else
// It is assumed that cv qualifiers, if any, are part of a deduced type.
// Thus this macro should not be used in public interfaces.
#define  __TBB_FORWARDING_REF(A) A&
#endif
#if __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT
#define __TBB_PARAMETER_PACK ...
#define __TBB_PACK_EXPANSION(A) A...
#else
#define __TBB_PARAMETER_PACK
#define __TBB_PACK_EXPANSION(A) A
#endif /* __TBB_CPP11_VARIADIC_TEMPLATES_PRESENT */

#if __TBB_CPP11_DECLTYPE_PRESENT
#if __TBB_CPP11_DECLVAL_BROKEN
// Ad-hoc implementation of std::declval
template <class T> __TBB_FORWARDING_REF(T) declval() /*noexcept*/;
#else
using std::declval;
#endif
#endif

template <bool condition>
struct STATIC_ASSERTION_FAILED;

template <>
struct STATIC_ASSERTION_FAILED<false> { enum {value=1};};

template<>
struct STATIC_ASSERTION_FAILED<true>; //intentionally left undefined to cause compile time error

//! @endcond
}} // namespace tbb::internal

#if    __TBB_STATIC_ASSERT_PRESENT
#define __TBB_STATIC_ASSERT(condition,msg) static_assert(condition,msg)
#else
//please note condition is intentionally inverted to get a bit more understandable error msg
#define __TBB_STATIC_ASSERT_IMPL1(condition,msg,line)       \
    enum {static_assert_on_line_##line = tbb::internal::STATIC_ASSERTION_FAILED<!(condition)>::value}

#define __TBB_STATIC_ASSERT_IMPL(condition,msg,line) __TBB_STATIC_ASSERT_IMPL1(condition,msg,line)
//! Verify at compile time that passed in condition is hold
#define __TBB_STATIC_ASSERT(condition,msg) __TBB_STATIC_ASSERT_IMPL(condition,msg,__LINE__)
#endif

#endif /* RC_INVOKED */
#endif /* __TBB_tbb_stddef_H */


text:
from django.db.models.signals import pre_delete, post_save
from django.dispatch import receiver
from django.conf import settings

from niwi.photo.models import Photo
import os

@receiver(post_save, sender=Photo)
def photo_post_save(sender, instance, created, **kwargs):
    """ Create resized images for photo instance. """
    if created:
        instance.rehash_thumbnails(commit=True)

@receiver(pre_delete, sender=Photo)
def photo_pre_delete(sender, instance, **kwargs):
    if instance.large and os.path.exists(instance.large.path):
        os.remove(instance.large.path)
    if instance.medium and os.path.exists(instance.medium.path):
        os.remove(instance.medium.path)
    if instance.small and os.path.exists(instance.small.path):
        os.remove(instance.small.path)
    if instance.square and os.path.exists(instance.square.path):
        os.remove(instance.square.path)


text:
package com.codedx.bytefrog.util;

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;

import com.esotericsoftware.minlog.Log;

public class Logger extends Log.Logger {
	private FileWriter out;
	private final String lineSeperator = System.lineSeparator();

	public Logger(File file) {
		try {
			out = new FileWriter(file, true);
		} catch (IOException e) {
			System.err.println(String.format("[bytefrog] cannot open %s for logging:", file));
			e.printStackTrace();
			out = null;
		}
	}

	@Override protected void print(String message) {
		if (out != null) {
			try {
				synchronized(out) {
					out.write(message);
					out.write(lineSeperator);
					out.flush();
				}
			} catch (IOException e) {
				System.err.println("[bytefrog] failure writing to log file:");
				e.printStackTrace();
				out = null;
			}
		}
	}
}


text:
<?php
namespace Hyperframework\Cli;

use Hyperframework\Common\Config;
use Hyperframework\Cli\Test\TestCase as Base;

class MultipleCommandAppTest extends Base {
    protected function setUp() {
        parent::setUp();
        Config::set(
            'hyperframework.cli.command_config_path', 'global_command.php'
        );
    }

    public function createApp(
        $shouldCallConstructor = true, $subcommandNames = ['child']
    ) {
        $mock = $this->getMockBuilder('Hyperframework\Cli\MultipleCommandApp')
            ->setMethods([
                'initializeConfig',
                'initializeErrorHandler',
                'getCommandConfig'
            ])
            ->disableOriginalConstructor()
            ->getMock();
        $commandConfig = $this->getMockBuilder('Hyperframework\Cli\CommandConfig')
            ->setMethods(['getSubcommandNames'])->getMock();
        $commandConfig->method('getSubcommandNames')->willReturn($subcommandNames);
        $mock->method('getCommandConfig')->willReturn($commandConfig);
        if ($shouldCallConstructor) {
            $mock->__construct(dirname(__DIR__));
            $this->callProtectedMethod(
                $mock, 'setElements', [$this->callProtectedMethod(
                    $mock, 'parseCommand', $_SERVER['argv']
                )]
            );
        }
        return $mock;
    }

    public function testExecuteGlobalCommand() {
        $this->expectOutputString(
            "Usage: test [-t] [-h|--help] [--version] <subcommand>" . PHP_EOL
                . PHP_EOL . 'Subcommands:' . PHP_EOL . ' child' . PHP_EOL
        );
        $_SERVER['argv'] = ['run', '-t'];
        $app = $this->createApp();
        $this->callProtectedMethod($app, 'executeCommand');
        $this->assertEquals($app->getGlobalOptions(), ['t' => true]);
    }

    public function testExecuteSubcommand() {
        $this->expectOutputString(
            'Hyperframework\Cli\Test\Subcommands\ChildCommand::execute'
        );
        $_SERVER['argv'] = ['run', 'child', '-c', 'arg'];
        $app = $this->createApp();
        $this->callProtectedMethod($app, 'executeCommand');
        $this->assertEquals(['c' => true], $app->getOptions());
        $this->assertEquals(['arg'], $app->getArguments());
    }

    public function testConstruct() {
        $_SERVER['argv'] = ['run', '-t', 'child', '-c', 'arg'];
        $app = $this->createApp();
        $this->assertEquals($app->getGlobalOptions(), ['t' => true]);
        $this->assertEquals($app->getOptions(), ['c' => true]);
        $this->assertEquals($app->getArguments(), ['arg']);
    }

    public function testHasGlobalOption() {
        $_SERVER['argv'] = ['run', '-t', 'child', '-c', 'arg'];
        $app = $this->createApp();
        $this->assertEquals($app->hasGlobalOption('t'),  true);
        $this->assertEquals($app->hasGlobalOption('c'),  false);
    }

    public function testGetGlobalOption() {
        $_SERVER['argv'] = ['run', '-t', 'child', '-c', 'arg'];
        $app = $this->createApp();
        $this->assertEquals($app->getGlobalOption('t'),  true);
        $this->assertEquals($app->hasGlobalOption('c'),  null);
    }

    public function testRenderHelp() {
        $this->expectOutputString(
            "Usage: test [-t] [-h|--help] [--version] <subcommand>" . PHP_EOL
                . PHP_EOL . 'Subcommands:' . PHP_EOL . ' child' . PHP_EOL
        );
        $_SERVER['argv'] = ['run', '-h'];
        $app = $this->createApp(false);
        $app->__construct(dirname(__DIR__));
        $this->callProtectedMethod(
            $app, 'setElements', [$this->callProtectedMethod(
                $app, 'parseCommand', $_SERVER['argv']
            )]
        );
        $this->callProtectedMethod($app, 'executeCommand', [dirname(__dir__)]);
    }

    public function testRenderSubcommandHelp() {
        $this->expectOutputString(
            "Usage: test child [-c] [-h|--help] <arg>" . PHP_EOL
        );
        $_SERVER['argv'] = ['run', 'child', '-h'];
        $app = $this->createApp(false);
        $app->__construct(dirname(__DIR__));
        $this->callProtectedMethod(
            $app, 'setElements', [$this->callProtectedMethod(
                $app, 'parseCommand', $_SERVER['argv']
            )]
        );
        $this->callProtectedMethod($app, 'executeCommand', [dirname(__dir__)]);
    }

    public function testRenderVersion() {
        $this->expectOutputString("1.0.0" . PHP_EOL);
        $_SERVER['argv'] = ['run', '--version'];
        $app = $this->createApp(false);
        $app->__construct(dirname(__DIR__));
        $this->callProtectedMethod(
            $app, 'setElements', [$this->callProtectedMethod(
                $app, 'parseCommand', $_SERVER['argv']
            )]
        );
        $this->callProtectedMethod($app, 'executeCommand', [dirname(__dir__)]);
    }

    /**
     * @expectedException Hyperframework\Common\ClassNotFoundException
     */
    public function testSubcommandClassNotFound() {
        $_SERVER['argv'] = ['run', 'invalid-class-child'];
        $app = $this->createApp(true, ['invalid-class-child']);
        $this->callProtectedMethod($app, 'executeCommand');
    }

    public function testGetSubcommandName() {
        $_SERVER['argv'] = ['run', 'child', 'arg'];
        $app = $this->createApp();
        $this->assertEquals($app->getSubcommandName(), 'child');
        $_SERVER['argv'] = ['run'];
        $app = $this->createApp();
        $this->assertNull($app->getSubcommandName());
    }

    public function testHasSubcommand() {
        $_SERVER['argv'] = ['run', 'child', 'arg'];
        $app = $this->createApp();
        $this->assertTrue($app->hasSubcommand());
        $_SERVER['argv'] = ['run'];
        $app = $this->createApp();
        $this->assertFalse($app->hasSubcommand());
    }
}


text:
copyright:
  years: 2017
lastupdated: "2017-03-17"

---
{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Plug-in do SDK Generator
{: #sdk-cli}

O plug-in do {{site.data.keyword.IBM}} SDK Generator pode ser instalado no [{{site.data.keyword.Bluemix_notm}} CLI ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](/docs/cli/reference/bluemix_cli/index.html).

Como um desenvolvedor no {{site.data.keyword.Bluemix_notm}}, é possível usar esse plug-in para gerar os SDKs de sua definição de API de REST compatível com a [Especificação da Open API ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](https://www.openapis.org/). À medida que você faz mudanças na definição de API de REST, é possível usar esse plug-in para gerar novamente apenas o SDK, em vez de gerar novamente o projeto inteiro.

Também será possível ver se os apps Cloud Foundry em um determinado espaço possuírem definições de API de REST que são válidas para geração de SDK. Finalmente, é possível usar o plug-in do {{site.data.keyword.IBM_notm}} SDK Generator para validar quaisquer definições de API de REST para assegurar-se de que obedeçam aos requisitos do gerador de SDK.

Esse plug-in do {{site.data.keyword.IBM_notm}} SDK Generator permite integrar facilmente seus serviços de backend ao app com um SDK gerado. Quando ocorrer uma mudança em uma API de REST, será possível gerar novamente o SDK e substituir o antigo para um upgrade ininterrupto de SDK. Também será possível integrar a CLI a um pipeline devops e assegurar-se de que o SDK esteja sempre consistente com a especificação de API sempre que o app for construído.

A definição de API de REST deve ser válida e hospedada em um end point do servidor em tempo real ou em um arquivo local no sistema. Se a definição de API de REST for hospedada, a URL relativa deverá ser definida na variável de ambiente `OPENAPI_SPEC`.

## Requisitos
{: #prereqs}

Assegure-se de satisfazer os requisitos a seguir.

* Você tem uma conta do [{{site.data.keyword.Bluemix_notm}} ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](http://bluemix.net)
* Uma definição de API válida que é adequada à especificação de [Open API ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](https://www.openapis.org/)

## Instalação
{: #installation}

1. [Instale o {{site.data.keyword.Bluemix}} CLI ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](http://clis.ng.bluemix.net/ui/home.html).

2. [Instale o plug-in ![Ícone de link externo](../icons/launch-glyph.svg "Ícone de link externo")](/docs/cli/reference/bluemix_cli/index.html#install_plug-in).

	```
	bx plugin install sdk-gen -r Bluemix
	```
	{: codeblock}

## Comandos
{: #commands}

Use os comandos a seguir para gerar um SDK, validar os arquivos de definição da Open API ou listar apps do Cloud Foundry.

### Gerando um SDK
{: #gen}

Use `bluemix sdk generate [arguments...][command options]`.

#### Argumentos
{: #gen-args}

* `APP_NAME` - o nome do app Cloud Foundry em seu espaço atual
* `OPENAPI_DOC_LOCATION` - uma URL ou um caminho de arquivo relativo para a definição de API de REST bruta JSON ou Yaml
* `GENERATED_SDK_NAME` (opcional) - o nome do SDK gerado

#### opções
{: #gen-options}

* `PLATFORM` (necessário)
   * `--android` - gerar um SDK do Android
   * `--ios` - gerar um SDK do iOS Swift
   * `--swift` - gerar um SDK do servidor Swift
* `--output "YOUR_RELATIVE_PATH"` (opcional) - coloca o SDK gerado no diretório especificado por `YOUR_RELATIVE_PATH` (será sobrescrito se o SDK existente estiver presente)
* `--unzip` (opcional) - extrai o SDK gerado (será sobrescrito se artefatos SDK existentes estiverem presentes)

#### Uso
{: #gen-usage}

Para gerar um SDK de um app Cloud Foundry que está em execução no {{site.data.keyword.Bluemix_notm}}, é possível usar o nome do app como um parâmetro para a CLI. O comando a seguir usa o nome do app como o `SDK_Name`.

```
bluemix sdk generate [APP_NAME] [PLATFORM]
```
{: codeblock}

Para gerar um SDK de uma URL para um arquivo de definição de Open API ou um arquivo JSON ou Yaml local, use o comando a seguir.

```
bluemix sdk generate [OPENAPI_DOC_LOCATION] [SDK_Name] [Platform]
```
{: codeblock}

### Validando definições da Open API
{: #validating}

Use `bluemix sdk validate [argument]`.

#### Argumentos
{: #val-args}

* `APP_NAME` - o nome do app Cloud Foundry em seu espaço atual
* `OPENAPI_DOC_LOCATION` - uma URL ou um caminho de arquivo relativo para a definição de API de REST bruta JSON ou Yaml

#### Uso
{: #val-usage}

Para validar uma especificação de API do app Cloud Foundry que está em execução no {{site.data.keyword.Bluemix_notm}}, é possível usar o nome do app como um parâmetro para a CLI.

```
bluemix sdk validate [APP_NAME]
```
{: codeblock}

Para validar um SDK da URL para um documento de especificação de API ou um arquivo JSON ou Yaml local, use o comando a seguir.

```
bluemix sdk validate [OPENAPI_DOC_LOCATION]
```
{: codeblock}

### Listar apps (Cloud Foundry)
{: #list-apps}

Use `bluemix sdk list [argument][option]` para listar apps e validar especificações de API. Deve-se ter a variável de ambiente `OPENAPI_SPEC` configurada para o caminho da URL relativa que hospeda sua especificação.

#### Argumentos
{: #list-args}

* `SPACE_NAME` (opcional) - o nome do espaço do Cloud Foundry em sua organização atual na qual você deseja procurar apps. Se não fornecido, o espaço atual será procurado.

#### opções
{: #list-options}

* `--url` (opcional) - para exibir uma URL completamente formada para a definição de Open API para cada app na lista

#### Uso
{: #list-usage}

Para listar apps no espaço atual, use o comando a seguir.

```
bluemix sdk list
```
{: codeblock}

Para listar apps no espaço atual e exibir a URL de especificação de API, use o comando a seguir.

```
bluemix sdk list --url
```
{: codeblock}

Para listar apps em um espaço específico, use o comando a seguir.

```
bluemix sdk list [SPACE_NAME]
```
{: codeblock}

Para listar apps em um espaço específico e exibir a URL de especificação de API, use o comando a seguir.

```
bluemix sdk list [SPACE_NAME] --url
```
{: codeblock}


text:
<?php

defined('_JEXEC') or die;

/**
 * View for the component configuration
 *
 * @since  3.2
 */
class ConfigViewComponentHtml extends ConfigViewCmsHtml
{
	public $state;

	public $form;

	public $component;

	/**
	 * Display the view
	 *
	 * @return  string  The rendered view.
	 *
	 * @since   3.2
	 *
	 */
	public function render()
	{
		$form = null;
		$component = null;

		try
		{
			$component = $this->model->getComponent();

			if (!$component->enabled)
			{
				return false;
			}

			$form = $this->model->getForm();
			$user = JFactory::getUser();
		}
		catch (Exception $e)
		{
			JFactory::getApplication()->enqueueMessage($e->getMessage(), 'error');

			return false;
		}

		// Bind the form to the data.
		if ($form && $component->params)
		{
			$form->bind($component->params);
		}

		$this->fieldsets   = $form ? $form->getFieldsets() : null;
		$this->formControl = $form ? $form->getFormControl() : null;

		// Don't show permissions fieldset if not authorised.
		if (!$user->authorise('core.admin', $component->option) && isset($this->fieldsets['permissions']))
		{
			unset($this->fieldsets['permissions']);
		}

		$this->form = &$form;
		$this->component = &$component;

		$this->components = ConfigHelperConfig::getComponentsWithConfig();

		$this->userIsSuperAdmin = $user->authorise('core.admin');
		$this->currentComponent = JFactory::getApplication()->input->get('component');
		$this->return = JFactory::getApplication()->input->get('return', '', 'base64');

		$this->addToolbar();

		return parent::render();
	}

	/**
	 * Add the page title and toolbar.
	 *
	 * @return  void
	 *
	 * @since   3.2
	 */
	protected function addToolbar()
	{
		JToolbarHelper::title(JText::_($this->component->option . '_configuration'), 'equalizer config');
		JToolbarHelper::apply('config.save.component.apply');
		JToolbarHelper::save('config.save.component.save');
		JToolbarHelper::divider();
		JToolbarHelper::cancel('config.cancel.component');
		JToolbarHelper::divider();
		JToolbarHelper::help('JHELP_COMPONENTS_' . $this->currentComponent . '_OPTIONS');
	}
}


text:
package org.apache.commons.pool;

/**
 * A simple base implementation of KeyedObjectPool.
 * Optional operations are implemented to either do nothing, return a value
 * indicating it is unsupported or throw {@link UnsupportedOperationException}.
 *
 * @author Rodney Waldhoff
 * @author Sandy McArthur
 * @version $Revision: 1085933 $ $Date: 2011-03-27 06:40:20 -0700 (Sun, 27 Mar 2011) $
 * @since Pool 1.0
 */
public abstract class BaseKeyedObjectPool implements KeyedObjectPool {

    /**
     * {@inheritDoc}
     */
    public abstract Object borrowObject(Object key) throws Exception;

    /**
     * {@inheritDoc}
     */
    public abstract void returnObject(Object key, Object obj) throws Exception;

    /**
     *
Invalidates an object from the pool.

     *
     *
By contract, obj must have been obtained
     * using {@link #borrowObject borrowObject} using a key that is
     * equivalent to the one used to borrow the Object in the first place.

     *
     *
This method should be used when an object that has been borrowed
     * is determined (due to an exception or other problem) to be invalid.

     *
     * @param key the key used to obtain the object
     * @param obj a {@link #borrowObject borrowed} instance to be returned.
     * @throws Exception
     */
    public abstract void invalidateObject(Object key, Object obj) throws Exception;

    /**
     * Not supported in this base implementation.
     * Always throws an {@link UnsupportedOperationException},
     * subclasses should override this behavior.
     * @param key ignored
     * @throws UnsupportedOperationException
     */
    public void addObject(Object key) throws Exception, UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
     * Not supported in this base implementation.
     * @return a negative value.
     * @param key ignored
     */
    public int getNumIdle(Object key) throws UnsupportedOperationException {
        return -1;
    }

    /**
     * Not supported in this base implementation.
     * @return a negative value.
     * @param key ignored
     */
    public int getNumActive(Object key) throws UnsupportedOperationException {
        return -1;
    }

    /**
     * Not supported in this base implementation.
     * @return a negative value.
     */
    public int getNumIdle() throws UnsupportedOperationException {
        return -1;
    }

    /**
     * Not supported in this base implementation.
     * @return a negative value.
     */
    public int getNumActive() throws UnsupportedOperationException {
        return -1;
    }

    /**
     * Not supported in this base implementation.
     * @throws UnsupportedOperationException
     */
    public void clear() throws Exception, UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
     * Not supported in this base implementation.
     * @param key ignored
     * @throws UnsupportedOperationException
     */
    public void clear(Object key) throws Exception, UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
     * Close this pool.
     * This affects the behavior of isClosed and assertOpen.
     */
    public void close() throws Exception {
        closed = true;
    }

    /**
     * Not supported in this base implementation.
     * Always throws an {@link UnsupportedOperationException},
     * subclasses should override this behavior.
     * @param factory the new KeyedPoolableObjectFactory
     * @deprecated to be removed in pool 2.0
     */
    public void setFactory(KeyedPoolableObjectFactory factory) throws IllegalStateException, UnsupportedOperationException {
        throw new UnsupportedOperationException();
    }

    /**
     * Has this pool instance been closed.
     * @return true when this pool has been closed.
     * @since Pool 1.4
     */
    protected final boolean isClosed() {
        return closed;
    }

    /**
     * Throws an IllegalStateException when this pool has been closed.
     * @throws IllegalStateException when this pool has been closed.
     * @see #isClosed()
     * @since Pool 1.4
     */
    protected final void assertOpen() throws IllegalStateException {
        if(isClosed()) {
            throw new IllegalStateException("Pool not open");
        }
    }

    /** Whether or not the pool is close */
    private volatile boolean closed = false;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="cancel">Cancel</string>
    <string name="finish">Finish</string>
    <string name="sharing">Sharing operation is working in the background…</string>
    <string name="share_to">Share to </string>
	<string name="share">Share</string>
	<string name="multi_share">Photo Sharing</string>
	<string name="share_completed">Operation succeeded</string>
	<string name="share_canceled">Operation canceled</string>
	<string name="select_one_plat_at_least">Please select a target platform</string>
	<string name="list_friends">Friends on %s</string>
	<string name="share_failed">Operation failed</string>
	<string name="pull_to_refresh">Pull down to refresh</string>
	<string name="release_to_refresh">Release to refresh</string>
	<string name="refreshing">Refreshing…</string>
	<string name="shake2share">Shake your phone!</string>
</resources>


text:
package com.safecharge.test.workflow;

import java.io.IOException;

import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import com.safecharge.model.MerchantInfo;
import com.safecharge.request.GetOrderDetailsRequest;
import com.safecharge.request.GetSessionTokenRequest;
import com.safecharge.request.OpenOrderRequest;
import com.safecharge.request.PaymentCCRequest;
import com.safecharge.request.SafechargeBaseRequest;
import com.safecharge.request.UpdateOrderRequest;
import com.safecharge.response.OpenOrderResponse;
import com.safecharge.response.SafechargeResponse;
import com.safecharge.response.UpdateOrderResponse;
import com.safecharge.test.BaseTest;
import com.safecharge.util.Constants;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CreditCardWorkflowTest extends BaseTest {

    // All static field values will be shared between tests
    private static String sessionToken;
    private static String orderId;
    private static MerchantInfo merchantInfo;

    @Before
    public void init() {
        super.init();
        merchantInfo = new MerchantInfo("2QMy87kirFbtdkl6Ubk9xCqhNICYNCewiOCm19DhJp3lqAI6lp7Oh2rZsn61LVw9", "2885023999185468261",
                "http://192.168.102.155:8080/ppp/", "5612", Constants.HashAlgorithm.SHA256);

    }

    @Test
    public void test1_getSessionTokenTest() throws IOException {
        SafechargeBaseRequest safechargeRequest = GetSessionTokenRequest.builder()
                .addMerchantInfo(merchantInfo)
                .build();
        SafechargeResponse response = (SafechargeResponse)safechargeRequestExecutor.executeRequest(safechargeRequest);

        Assert.assertTrue(response != null);
        Assert.assertTrue(Constants.APIResponseStatus.SUCCESS.equals(response.getStatus()));
        sessionToken = response.getSessionToken();
    }

    @Test
    public void test2_openOrder() {
        SafechargeBaseRequest openOrderRequest = new OpenOrderRequest.Builder().addMerchantInfo(merchantInfo)
                .addCurrency("EUR")
                .addAmount("2")
                .addSessionToken(sessionToken)
                .addItem("test_item_1", "1", "1")
                .addItem("test_item_2", "1", "1")
                .addUserDetails("Test street 1", "Sofia", "BG", "test@test.com", "Test",
                        "Testov", "0884123456", null, "1000", "1990-01-01","county usr")
                .addBillingDetails("Test", "Testov", "test@test.com", "0884123456",
                        "Test street 1", "Sofia", "BG", null, "1000", "0884123456","county billing")
                .addShippingDetails("Test", "Testov", "test@test.com", "0884123456",
                        "Test street 1", "Sofia", "BG", null, "1000", "0884123456","county shipping")
                .addAmountDetails("1.5", "1.0", "1.0", "0.5")
                .build();
        OpenOrderResponse openOrderResponse = (OpenOrderResponse) safechargeRequestExecutor.executeRequest(openOrderRequest);

        Assert.assertTrue(openOrderResponse != null);
        Assert.assertTrue(Constants.APIResponseStatus.SUCCESS.equals(openOrderResponse.getStatus()));

        orderId = openOrderResponse.getOrderId();
        Assert.assertTrue(orderId != null && !orderId.isEmpty());
    }

    @Test
    public void test3_updateOrder() {
        SafechargeBaseRequest updateOrderRequest = UpdateOrderRequest.builder()
                .addMerchantInfo(merchantInfo)
                .addCurrency("EUR")
                .addAmount("2")
                .addSessionToken(sessionToken)
                .addItem("test_item_1", "1", "1")
                .addItem("test_item_2", "1", "1")
                .addUserDetails("Test street 1", "Sofia", "BG", "test@test.com", "Test", "Testov",
                        "0884123456", null, "1000", "1990-01-01", "county usr")
                .addBillingDetails("Test", "Testov", "test@test.com", "0884123456", "Test street 1",
                        "Sofia", "BG", null, "1000", "0884123456","county billing")
                .addShippingDetails("Test", "Testov", "test@test.com", "0884123456", "Test street 1",
                        "Sofia", "BG", null, "1000", "0884123456","county shipping")
                .addAmountDetails("1.5", "1.0", "1.0", "0.5")
                .addOrderId(orderId)
                .build();

        UpdateOrderResponse updateOrderResponse = (UpdateOrderResponse) safechargeRequestExecutor.executeRequest(updateOrderRequest);

        Assert.assertTrue(updateOrderResponse != null);
        Assert.assertTrue(Constants.APIResponseStatus.SUCCESS.equals(updateOrderResponse.getStatus()));
    }

    @Test
    public void test4_getOrderDetails() {
        SafechargeBaseRequest safechargeRequest = GetOrderDetailsRequest.builder()
                .addMerchantInfo(merchantInfo)
                .addOrderId(orderId)
                .addSessionToken(sessionToken)
                .build();
        SafechargeResponse response = (SafechargeResponse)safechargeRequestExecutor.executeRequest(safechargeRequest);

        Assert.assertTrue(response != null);
        Assert.assertTrue(Constants.APIResponseStatus.SUCCESS.equals(response.getStatus()));
    }

    @Test
    public void test5_paymentCC() {
        SafechargeBaseRequest request = PaymentCCRequest.builder()
                .addMerchantInfo(merchantInfo)
                .addCurrency("EUR")
                .addAmount("2")
                .addSessionToken(sessionToken)
                .addItem("test_item_1", "1", "1")
                .addItem("test_item_2", "1", "1")
                .addUserDetails("Test street 1", "Sofia", "BG", "test@test.com", "Test", "Testov", "0884123456",
                        null, "1000", "1990-01-01","county usr")
                .addBillingDetails("Test", "Testov", "test@test.com", "0884123456", "Test street 1", "Sofia",
                        "BG", null, "1000", "0884123456", "county billing")
                .addShippingDetails("Test", "Testov", "test@test.com", "0884123456", "Test street 1", "Sofia",
                        "BG", null, "1000", "0884123456", "county shipping")
                .addAmountDetails("1.5", "1.0", "1.0", "0.5")
                .addOrderId(orderId)
                .addCardData("4111111111111111", "Test Testov", "10", "2022", null, "123")
                .addTransactionType(Constants.TransactionType.Sale)
                .build();
        SafechargeResponse response = safechargeRequestExecutor.executeRequest(request);

        Assert.assertTrue(response != null);
        Assert.assertTrue(Constants.APIResponseStatus.SUCCESS.equals(response.getStatus()));

    }

}


text:
This is an adapter to be used in conjunction with the AdMob or DFP Android SDK.

## Requirements

* Google Mobile Ads SDK version 15.0.1.
* Avocarrot Android SDK v4.10.3.

## Instructions

### Integrating Avocarrot Android SDK

Add the compile dependency with the latest version of the **Avocarrot** adapter in the `build.gradle` file:

```
repositories {
  maven { url  "https://s3.amazonaws.com/avocarrot-android-builds/dist" }
}

dependencies {
  compile 'com.avocarrot.sdk:adapter-admob-interstitial:1.4.15'
}
```

The Avocarrot SDK should be initialised and started before requiring for ads. To ensure that the metrics are not over-counted, it is highly recommended
that the Avocarrot SDK be called in the `Application` class.

```java
public class YourApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        Avocarrot.onApplicationCreated(this);
        //...
    }
    //...
}
```

Don't forget to add application name to your `AndroidManifest.xml` file.

```xml
<application android:name=".YourApplication">
  <!-- activities goes here -->
</application>
```


text:
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import

import datetime

def ParseBool(value):
  """Parse a string representation into a True/False value."""
  if value is None:
    return None
  value_lower = value.lower()
  if value_lower in ('true', '1'):
    return True
  if value_lower in ('false', '0'):
    return False
  raise ValueError(value)

def ParseISO8601(s):
  if s is None:
    return None
  # ISO8601 specifies many possible formats. The dateutil library is much more
  # flexible about parsing all of the possible formats, but it would be annoying
  # to third_party it just for this. A few formats should cover enough users.
  try:
    return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
  except ValueError:
    return datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')


text:
package com.lightbend.lagom.api.tools.tests.javadsl;

import akka.NotUsed;
import com.lightbend.lagom.javadsl.api.ServiceCall;

public class NoAclServiceImpl implements NoAclService {

    @Override
    public ServiceCall<NotUsed, NotUsed> getMock(String id) {
        return request -> null;
    }
}


text:
//
//  ReadingActionFunnel.h
//  Wikipedia
//
//  Created by Brion on 5/28/14.
//  Copyright (c) 2014 Wikimedia Foundation. Some rights reserved.
//

#import "EventLoggingFunnel.h"

@interface ReadingActionFunnel : EventLoggingFunnel

@property NSString* appInstallID;

/**
 * Note this method is not actually used; the appInstallID key is instead
 * sent with the 'action=mobileview' API request on a fresh page read.
 */
- (void)logSomethingHappened;

@end


text:
var patientDetails = angular.module("patientDetails").component('patientDetails', {
    templateUrl: 'views/patient-details/patient-details.template.html',
    controller: ['$routeParams', 'Patients', 'PatientSummary', function PatientsController($routeParams, Patients, PatientSummary) {
        var self = this;
        self.patientId = $routeParams.patientId;

        Patients.query().$promise.then(function(oData){
            self.patient = oData.find(function(oPatient){
                return oPatient.id == self.patientId;
            });
            self.patient.age = parseInt((new Date() - new Date(self.patient.birthDate))*3.1709791983765E-11);
        });

        // PatientSummary.query({ patientId: self.patient.id }).$promise.then(function (oPatientSummary) {

        // });
    }]
});


text:
import numpy as np
import pandas as pd
from scipy import sparse
import pytest

import anndata as ad

def test_amgibuous_keys():
    """Tests that an error is raised if obs_vector or var_vector is ambiguous."""
    var_keys = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
    obs_keys = [
        "Lorem",
        "ipsum",
        "dolor",
        "sit",
        "amet",
        "consectetur",
        "adipiscing",
        "elit",
    ]
    adata = ad.AnnData(
        X=sparse.random(len(obs_keys), len(var_keys), format="csr"),
        layers={"layer": sparse.random(len(obs_keys), len(var_keys), format="csr")},
        obs=pd.DataFrame(
            np.random.randn(len(obs_keys), len(obs_keys) + len(var_keys)),
            index=obs_keys,
            columns=obs_keys + var_keys,
        ),
        var=pd.DataFrame(
            np.random.randn(len(var_keys), len(obs_keys) + len(var_keys)),
            index=var_keys,
            columns=var_keys + obs_keys,
        ),
    )

    adata.raw = adata

    for k in var_keys:
        # These are mostly to check that the test is working
        assert k in adata.var_names
        assert k in adata.obs.columns
        # Now the actual checks:
        with pytest.raises(ValueError, match=r".*var_names.*obs\.columns.*"):
            adata.obs_vector(k)
        with pytest.raises(ValueError, match=r".*var_names.*obs\.columns.*"):
            adata.obs_vector(k, layer="layer")

        # Should uniquely select column from in adata.var
        assert list(adata.var[k]) == list(adata.var_vector(k))
        assert list(adata.var[k]) == list(adata.var_vector(k, layer="layer"))

        assert list(adata.raw.var[k]) == list(adata.raw.var_vector(k))

    for k in obs_keys:
        assert k in adata.obs_names
        assert k in adata.var.columns
        with pytest.raises(ValueError, match=r".*obs_names.*var\.columns"):
            adata.var_vector(k)
        with pytest.raises(ValueError, match=r".*obs_names.*var\.columns"):
            adata.var_vector(k, layer="layer")

        assert list(adata.obs[k]) == list(adata.obs_vector(k))
        assert list(adata.obs[k]) == list(adata.obs_vector(k, layer="layer"))

        with pytest.raises(ValueError, match=r".*obs_names.*var\.columns*"):
            adata.raw.var_vector(k)


text:
#ifndef HEADER_CURL_HTTP2_H
#define HEADER_CURL_HTTP2_H

#include "curl_setup.h"

#ifdef USE_NGHTTP2
#include "http.h"

/* value for MAX_CONCURRENT_STREAMS we use until we get an updated setting
   from the peer */
#define DEFAULT_MAX_CONCURRENT_STREAMS 13

/*
 * Store nghttp2 version info in this buffer, Prefix with a space.  Return
 * total length written.
 */
int Curl_http2_ver(char *p, size_t len);

CURLcode Curl_http2_init(struct connectdata *conn);
CURLcode Curl_http2_send_request(struct connectdata *conn);
CURLcode Curl_http2_request_upgrade(Curl_send_buffer *req,
                                    struct connectdata *conn);
CURLcode Curl_http2_setup(struct connectdata *conn);
CURLcode Curl_http2_switched(struct connectdata *conn,
                             const char *data, size_t nread);
/* called from Curl_http_setup_conn */
void Curl_http2_setup_conn(struct connectdata *conn);
#else /* USE_NGHTTP2 */
#define Curl_http2_init(x) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_send_request(x) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_request_upgrade(x,y) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_setup(x) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_switched(x,y,z) CURLE_UNSUPPORTED_PROTOCOL
#define Curl_http2_setup_conn(x)
#endif

#endif /* HEADER_CURL_HTTP2_H */


text:
<form class="form form-shipping-address" id="co-shipping-form" data-bind="attr: {'data-hasrequired': $t('* Required Fields')}">

            <input type="checkbox" class="checkbox" id="shipping-save-in-address-book" data-bind="checked: saveInAddressBook" />

</form>


text:
<?php

namespace Movibe\BackendBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CritiqueType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('presse','entity',array(
                'class' => 'Movibe\BackendBundle\Entity\Presse',
                'empty_value' => '',
                'empty_data' => null,
                'property' => 'nom',
                'expanded' => false,
                'multiple' => false,
            ))
            ->add('note','choice',array(
                'choices' => array(1 => ' ', 2 => ' ', 3 => ' ', 4 => ' ', 5 => ' '),
                'expanded' => true,
                'multiple' => false,
            ))
            ->add('commentaire','textarea')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Movibe\BackendBundle\Entity\Critique'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'movibe_backendbundle_critique';
    }
}


text:
SYNONYM

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

#### Published in
Fl. ins. austr. 37. 1786

#### Original name
null

### Remarks
null


text:
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawerLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#aaa"
    android:fitsSystemWindows="true">

    <!-- your content layout -->

    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/menu_drawer_items"/>

</android.support.v4.widget.DrawerLayout>


text:
package org.apache.storm.topology;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.windowing.TimestampExtractor;
import org.apache.storm.windowing.TupleWindow;

import java.util.Map;

/**
 * A bolt abstraction for supporting time and count based sliding & tumbling windows.
 */
public interface IWindowedBolt extends IComponent {
    /**
     * This is similar to the {@link org.apache.storm.task.IBolt#prepare(Map, TopologyContext, OutputCollector)} except
     * that while emitting, the tuples are automatically anchored to the tuples in the inputWindow.
     */
    void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector);

    /**
     * Process the tuple window and optionally emit new tuples based on the tuples in the input window.
     */
    void execute(TupleWindow inputWindow);

    void cleanup();

    /**
     * Return a {@link TimestampExtractor} for extracting timestamps from a
     * tuple for event time based processing, or null for processing time.
     *
     * @return the timestamp extractor
     */
    TimestampExtractor getTimestampExtractor();
}


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

namespace Patternizer
{

	internal class RepeatStep : Step
	{
		private int _repeatCount;
		private Expression<Func<StepPattern, StepPattern>> _pattern;

        /// <summary>
        /// Initializes a new instance of the <see cref="RepeatStep"/> class.
        /// </summary>
        /// <param name="repeatCount">The repeat count, if > 0 then it must be an exact match. Otherwise 1-* matches is ok</param>
        /// <param name="pattern">Pattern.</param>
        public RepeatStep (int repeatCount, Expression<Func<StepPattern, StepPattern>> pattern)
		{
			_repeatCount = repeatCount;
			_pattern = pattern;
		}

		public override StepPatternEvaluationResult Evaluate (Point? lastStepEndPoint, List<Line> lines, StepContext context)
		{
			if (_repeatCount > 0) {
				throw new NotImplementedException ("Repeat count is not implemented yet");
			}

			var preEvaluationList = new List<Line> (lines);

			var func = _pattern.Compile ();
			var isValid = false;
			PatternResult lastResult = null;
			var lastValidCount = preEvaluationList.Count;

			bool control = true;
			while (control) {
				if (preEvaluationList.Count == 0) {
					control = false;
					continue;
				}

				var pattern = func.Invoke (new StepPattern());
				var result = pattern.Evaluate (preEvaluationList, context);
				if (result.IsValid) {
					isValid = true;
					lastValidCount = preEvaluationList.Count;
				} else {
					control = false;
				}

				lastResult = result;
			}

			if (isValid) {
				lines.RemoveRange(0, lines.Count - lastValidCount);
			}

			return new StepPatternEvaluationResult (isValid, lastResult.LastPointInPattern);
		}
	}
}


text:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use yii\jui\DatePicker;
/* @var $this yii\web\View */
/* @var $model app\models\Requisicao */
/* @var $form yii\widgets\ActiveForm */
?>

	<?php $form=ActiveForm::begin(); ?>

	<?=$model->isNewRecord ? $form->field($model, 'cancelada')->hiddenInput(['value' => 0])->label(false) : $form->field($model, 'cancelada')->dropDownList(['0'=>'não', '1'=>'sim'], ['autofocus' => true]) ?>
	<?=$model->isNewRecord ? $form->field($model, 'executada')->hiddenInput(['value' => 0])->label(false) : $form->field($model, 'executada')->dropDownList(['0'=>'não', '1'=>'sim']) ?>
	<?=$form->field($model, 'id_sipac')->textInput() ?>
	<?=$form->field($model, 'id_secao')->dropDownList(ArrayHelper::map(\app\models\Secao::find()->all(), 'id_secao', 'nome_secao'), ['prompt' => 'Selecione']) ?>

	<?=$form->field($model, 'id_servico')->dropDownList(ArrayHelper::map(\app\models\Servico::find()->all(), 'id_servico', 'nome_servico'), ['prompt' => 'Selecione']) ?>

	<?=$form->field($model, 'id_veic')->dropDownList(ArrayHelper::map(\app\models\Veiculo::find()->where(['ativo' => 1])->all(), 'id_veiculo', 'placa'), ['prompt' => 'Selecione']) ?>

	<?=$form->field($model, 'id_mot')->dropDownList(ArrayHelper::map(\app\models\Motorista::find()->where(['ativo' => 1])->all(), 'id_mot', 'nome_mot'), ['prompt' => 'Selecione']) ?>

	<?=$form->field($model, 'data_util')->widget(DatePicker::className(), ['language' => 'pt_BR', 'dateFormat' => 'yyyy-MM-dd']) ?>

	<?=$form->field($model, 'hora_ini')->textInput() ?>

	<?=$form->field($model, 'hora_fim')->textInput() ?>

	<?=$form->field($model, 'anota')->textarea() ?>

	<?=$model->isNewRecord ? null : $form->field($model, "hora_saida")->textInput(); ?>

	<?=$model->isNewRecord ? null : $form->field($model, "hora_chegada")->textInput(); ?>

	<?=$model->isNewRecord ? null : $form->field($model, "km_saida")->textInput(); ?>

	<?=$model->isNewRecord ? null : $form->field($model, "km_chegada")->textInput(); ?>

		<?=Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

	<?php ActiveForm::end(); ?>


text:
package com.clubobsidian.obsidianengine.command.engine;

import com.clubobsidian.obsidianengine.command.Command;
import com.clubobsidian.obsidianengine.command.CommandExecutor;
import com.clubobsidian.obsidianengine.user.User;

public class GCCommand implements CommandExecutor {

	@Override
	public boolean onCommand(User sender, Command cmd, String[] args)
	{
		Runtime runtime = Runtime.getRuntime();
		runtime.gc();
		sender.sendMessage("Max memory: " + (runtime.maxMemory() / 1024) + "Kb");
		sender.sendMessage("Total memory: " + (runtime.totalMemory() / 1024) + "kb");
		sender.sendMessage("Free Memory: " + (runtime.freeMemory() / 1024) + "Kb");
		return true;
	}
}


text:
package com.github.jonathanxd.kores.test;

import com.github.jonathanxd.kores.Instruction;
import com.github.jonathanxd.kores.Instructions;
import com.github.jonathanxd.kores.Types;
import com.github.jonathanxd.kores.base.ClassDeclaration;
import com.github.jonathanxd.kores.base.KoresModifier;
import com.github.jonathanxd.kores.base.ConstructorDeclaration;
import com.github.jonathanxd.kores.base.TypeDeclaration;
import com.github.jonathanxd.kores.factory.Factories;
import com.github.jonathanxd.kores.factory.VariableFactory;
import com.github.jonathanxd.kores.helper.Predefined;
import com.github.jonathanxd.kores.type.LoadedKoresType;
import com.github.jonathanxd.kores.type.KoresTypes;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;

import static com.github.jonathanxd.kores.literal.Literals.INT;
import static com.github.jonathanxd.kores.literal.Literals.STRING;
import static kotlin.collections.CollectionsKt.listOf;

public class CommonGen {

    public static final String name = CommonGen.class.getCanonicalName() + "_Generated";

    public static TypeDeclaration gen() {
        Instruction[] values = {
                STRING("A"), STRING("B"),
                STRING("C"), STRING("D"),
                STRING("E")
        };

        Instruction[] values2 = {
                STRING("F"), STRING("G"),
                STRING("H"), STRING("I"),
                STRING("J")
        };

        Instruction[] values3 = {
                INT(1)
        };

        LoadedKoresType<String[][]> stringArrayType = KoresTypes.getKoresType(String[][].class);

        TypeDeclaration typeDeclaration =
                ClassDeclaration.Builder.builder()
                        .modifiers(KoresModifier.PUBLIC)
                        .name(name)
                        .constructors(
                                ConstructorDeclaration.Builder.builder()
                                        .modifiers(KoresModifier.PUBLIC)
                                        .body(Instructions.fromVarArgs(
                                                VariableFactory.variable(stringArrayType,
                                                        "array",
                                                        Factories.createArray(stringArrayType, listOf(INT(2), INT(5)),
                                                                listOf(
                                                                        Factories.createArray(Types.STRING.toArray(1), listOf(INT(5)), Arrays.asList(values)),
                                                                        Factories.createArray(Types.STRING.toArray(1), listOf(INT(5)), Arrays.asList(values2))
                                                                )
                                                        )),

                                                VariableFactory.variable(Types.STRING.toArray(1),
                                                        "array2",
                                                        Factories.createArray(Types.STRING.toArray(1), listOf(INT(0)), Collections.emptyList())
                                                ),

                                                VariableFactory.variable(Types.OBJECT.toArray(1),
                                                        "array3",
                                                        Factories.createArray(Types.OBJECT.toArray(1), listOf(INT(1)), Arrays.asList(values3))
                                                ),

                                                Predefined.invokePrintln(
                                                        Factories.accessArrayValue(Types.STRING.toArray(1),
                                                                Factories.accessArrayValue(Types.STRING.toArray(2),
                                                                        Factories.accessVariable(
                                                                                Types.STRING.toArray(2),
                                                                                "array"
                                                                        ),
                                                                        INT(0),
                                                                        Types.STRING.toArray(1)
                                                                ),
                                                                INT(0),
                                                                Types.STRING))

                                        ))
                                        .build()
                        )
                        .build();

        return typeDeclaration;
    }

    @Test
    public void test() {
        gen();
    }

}


text:
package torrent

import (
	"crypto/tls"
	"net"
	"net/http"
	"net/url"
	"time"

	"golang.org/x/time/rate"

	"github.com/anacrolix/dht"
	"github.com/anacrolix/missinggo"
	"github.com/anacrolix/missinggo/expect"
	"github.com/anacrolix/torrent/iplist"
	"github.com/anacrolix/torrent/storage"
)

var DefaultHTTPClient = &http.Client{
	Timeout: time.Second * 15,
	Transport: &http.Transport{
		Dial: (&net.Dialer{
			Timeout: 15 * time.Second,
		}).Dial,
		TLSHandshakeTimeout: 15 * time.Second,
		TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
	},
}
var DefaultHTTPUserAgent = "Go-Torrent/1.0"

// Override Client defaults.
type Config struct {
	// Store torrent file data in this directory unless .DefaultStorage is
	// specified.
	DataDir string `long:"data-dir" description:"directory to store downloaded torrent data"`
	// The address to listen for new uTP and TCP bittorrent protocol
	// connections. DHT shares a UDP socket with uTP unless configured
	// otherwise.
	ListenHost              func(network string) string
	ListenPort              int
	NoDefaultPortForwarding bool
	// Don't announce to trackers. This only leaves DHT to discover peers.
	DisableTrackers bool `long:"disable-trackers"`
	DisablePEX      bool `long:"disable-pex"`

	// Don't create a DHT.
	NoDHT            bool `long:"disable-dht"`
	DhtStartingNodes dht.StartingNodesGetter
	// Never send chunks to peers.
	NoUpload bool `long:"no-upload"`
	// Disable uploading even when it isn't fair.
	DisableAggressiveUpload bool `long:"disable-aggressive-upload"`
	// Upload even after there's nothing in it for us. By default uploading is
	// not altruistic, we'll upload slightly more than we download from each
	// peer.
	Seed bool `long:"seed"`
	// Only applies to chunks uploaded to peers, to maintain responsiveness
	// communicating local Client state to peers. Each limiter token
	// represents one byte. The Limiter's burst must be large enough to fit a
	// whole chunk, which is usually 16 KiB (see TorrentSpec.ChunkSize).
	UploadRateLimiter *rate.Limiter
	// Rate limits all reads from connections to peers. Each limiter token
	// represents one byte. The Limiter's burst must be bigger than the
	// largest Read performed on a the underlying rate-limiting io.Reader
	// minus one. This is likely to be the larger of the main read loop buffer
	// (~4096), and the requested chunk size (~16KiB, see
	// TorrentSpec.ChunkSize).
	DownloadRateLimiter *rate.Limiter

	// User-provided Client peer ID. If not present, one is generated automatically.
	PeerID string
	// For the bittorrent protocol.
	DisableUTP bool
	// For the bittorrent protocol.
	DisableTCP bool `long:"disable-tcp"`
	// Called to instantiate storage for each added torrent. Builtin backends
	// are in the storage package. If not set, the "file" implementation is
	// used.
	DefaultStorage storage.ClientImpl

	EncryptionPolicy

	// Sets usage of Socks5 Proxy. Authentication should be included in the url if needed.
	// Example of setting: "socks5://demo:demo@192.168.99.100:1080"
	ProxyURL string

	IPBlocklist      iplist.Ranger
	DisableIPv6      bool `long:"disable-ipv6"`
	DisableIPv4      bool
	DisableIPv4Peers bool
	// Perform logging and any other behaviour that will help debug.
	Debug bool `help:"enable debugging"`

	// HTTP client used to query the tracker endpoint. Default is DefaultHTTPClient
	HTTP *http.Client
	// HTTPUserAgent changes default UserAgent for HTTP requests
	HTTPUserAgent string `long:"http-user-agent"`
	// Updated occasionally to when there's been some changes to client
	// behaviour in case other clients are assuming anything of us. See also
	// `bep20`.
	ExtendedHandshakeClientVersion string // default  "go.torrent dev 20150624"
	// Peer ID client identifier prefix. We'll update this occasionally to
	// reflect changes to client behaviour that other clients may depend on.
	// Also see `extendedHandshakeClientVersion`.
	Bep20 string // default "-GT0001-"

	NominalDialTimeout         time.Duration // default  time.Second * 30
	MinDialTimeout             time.Duration // default  5 * time.Second
	EstablishedConnsPerTorrent int           // default 80
	HalfOpenConnsPerTorrent    int           // default  80
	TorrentPeersHighWater      int           // default 200
	TorrentPeersLowWater       int           // default 50

	// Limit how long handshake can take. This is to reduce the lingering
	// impact of a few bad apples. 4s loses 1% of successful handshakes that
	// are obtained with 60s timeout, and 5% of unsuccessful handshakes.
	HandshakesTimeout time.Duration // default  20 * time.Second

	PublicIp4 net.IP
	PublicIp6 net.IP
}

func (cfg *Config) SetListenAddr(addr string) *Config {
	host, port, err := missinggo.ParseHostPort(addr)
	expect.Nil(err)
	cfg.ListenHost = func(string) string { return host }
	cfg.ListenPort = port
	return cfg
}

func (cfg *Config) setDefaults() {
	if cfg.HTTP == nil {
		cfg.HTTP = DefaultHTTPClient
		if cfg.ProxyURL != "" {
			cfg.setProxyURL()
		}
	}
	if cfg.HTTPUserAgent == "" {
		cfg.HTTPUserAgent = DefaultHTTPUserAgent
	}
	if cfg.ExtendedHandshakeClientVersion == "" {
		cfg.ExtendedHandshakeClientVersion = "go.torrent dev 20150624"
	}
	if cfg.Bep20 == "" {
		cfg.Bep20 = "-GT0001-"
	}
	if cfg.NominalDialTimeout == 0 {
		cfg.NominalDialTimeout = 30 * time.Second
	}
	if cfg.MinDialTimeout == 0 {
		cfg.MinDialTimeout = 5 * time.Second
	}
	if cfg.EstablishedConnsPerTorrent == 0 {
		cfg.EstablishedConnsPerTorrent = 50
	}
	if cfg.HalfOpenConnsPerTorrent == 0 {
		cfg.HalfOpenConnsPerTorrent = (cfg.EstablishedConnsPerTorrent + 1) / 2
	}
	if cfg.TorrentPeersHighWater == 0 {
		// Memory and freshness are the concern here.
		cfg.TorrentPeersHighWater = 500
	}
	if cfg.TorrentPeersLowWater == 0 {
		cfg.TorrentPeersLowWater = 2 * cfg.HalfOpenConnsPerTorrent
	}
	if cfg.HandshakesTimeout == 0 {
		cfg.HandshakesTimeout = 20 * time.Second
	}
	if cfg.DhtStartingNodes == nil {
		cfg.DhtStartingNodes = dht.GlobalBootstrapAddrs
	}
	if cfg.ListenHost == nil {
		cfg.ListenHost = func(string) string { return "" }
	}
}

func (cfg *Config) setProxyURL() {
	fixedURL, err := url.Parse(cfg.ProxyURL)
	if err != nil {
		return
	}

	cfg.HTTP.Transport = &http.Transport{
		Proxy:               http.ProxyURL(fixedURL),
		TLSHandshakeTimeout: 15 * time.Second,
		TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
	}
}

type EncryptionPolicy struct {
	DisableEncryption  bool
	ForceEncryption    bool // Don't allow unobfuscated connections.
	PreferNoEncryption bool
}