text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>CommandLine.Help (picocli 3.9.6 API)</title>
<meta name="date" content="2019-04-06">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

picocli

Class CommandLine.Help

java.lang.Object

picocli.CommandLine.Help

Enclosing class:

CommandLine

public static class CommandLine.Help
extends java.lang.Object

A collection of methods and inner classes that provide fine-grained control over the contents and layout of
 the usage help message to display to end users when help is requested or invalid input values were specified.

Class Diagram of the CommandLine.Help API

Layered API

The CommandLine.Command annotation and the CommandLine.Model.UsageMessageSpec programmatic API equivalent
 provide the easiest way to configure the usage help message. See
 the Manual for details.

This Help class provides high-level functions to create sections of the usage help message and headings
 for these sections. Instead of calling the CommandLine.usage(PrintStream, CommandLine.Help.ColorScheme)
 method, application authors may want to create a custom usage help message by reorganizing sections in a
 different order and/or adding custom sections.

Finally, the Help class contains inner classes and interfaces that can be used to create custom help messages.

IOptionRenderer and IParameterRenderer

Renders a field annotated with CommandLine.Option or CommandLine.Parameters to an array of CommandLine.Help.Ansi.Text values.
 By default, these values are

mandatory marker character (if the option/parameter is required)

short option name (empty for parameters)

comma or empty (empty for parameters)

long option names (the parameter label for parameters)

description

Other components rely on this ordering.

Layout

Delegates to the renderers to create CommandLine.Help.Ansi.Text values for the annotated fields, and uses a
 CommandLine.Help.TextTable to display these values in tabular format. Layout is responsible for deciding which values
 to display where in the table. By default, Layout shows one option or parameter per table row.

TextTable

Responsible for spacing out CommandLine.Help.Ansi.Text values according to the CommandLine.Help.Column definitions the table was
 created with. Columns have a width, indentation, and an overflow policy that decides what to do if a value is
 longer than the column's width.

Text

Encapsulates rich text with styles and colors in a way that other components like CommandLine.Help.TextTable are
 unaware of the embedded ANSI escape codes.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
CommandLine.Help.Ansi

Provides methods and inner classes to support using ANSI escape codes in usage help messages.

static class
CommandLine.Help.ColorScheme

All usage help message are generated with a color scheme that assigns certain styles and colors to common
 parts of a usage message: the command name, options, positional parameters and option parameters.

static class
CommandLine.Help.Column

Columns define the width, indent (leading number of spaces in a column before the value) and
 Overflow policy of a column in a TextTable.

static interface
CommandLine.Help.IOptionRenderer

When customizing online help for Option details, a custom IOptionRenderer can be
 used to create textual representation of an Option in a tabular format: one or more rows, each containing
 one or more columns.

static interface
CommandLine.Help.IParameterRenderer

When customizing online help for positional parameters details, a custom IParameterRenderer
 can be used to create textual representation of a Parameters field in a tabular format: one or more rows,
 each containing one or more columns.

static interface
CommandLine.Help.IParamLabelRenderer

When customizing online usage help for an option parameter or a positional parameter, a custom
 IParamLabelRenderer can be used to render the parameter name or label to a String.

static class
CommandLine.Help.Layout

Use a Layout to format usage help text for options and parameters in tabular format.

static class
CommandLine.Help.TextTable

Responsible for spacing out CommandLine.Help.Ansi.Text values according to the CommandLine.Help.Column definitions the table was
 created with.

static class
CommandLine.Help.Visibility

Controls the visibility of certain aspects of the usage help message.

Field Summary

Fields

Modifier and Type
Field and Description

protected static java.lang.String
DEFAULT_COMMAND_NAME

Constant String holding the default program name, value defined in CommandLine.Model.CommandSpec.DEFAULT_COMMAND_NAME.

protected static java.lang.String
DEFAULT_SEPARATOR

Constant String holding the default string that separates options from option parameters, value defined in CommandLine.Model.ParserSpec.DEFAULT_SEPARATOR.

Constructor Summary

Constructors

Constructor and Description

Help(CommandLine.Model.CommandSpec commandSpec,
    CommandLine.Help.ColorScheme colorScheme)

Constructs a new Help instance with the specified color scheme, initialized from annotatations
 on the specified class and superclasses.

Help(java.lang.Object command)

Constructs a new Help instance with a default color scheme, initialized from annotatations
 on the specified class and superclasses.

Help(java.lang.Object command,
    CommandLine.Help.Ansi ansi)

Constructs a new Help instance with a default color scheme, initialized from annotatations
 on the specified class and superclasses.

Help(java.lang.Object command,
    CommandLine.Help.ColorScheme colorScheme)

Deprecated.

use picocli.CommandLine.Help#Help(picocli.CommandLine.Model.CommandSpec, picocli.CommandLine.Help.ColorScheme)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods

Modifier and Type
Method and Description

java.lang.String
abbreviatedSynopsis()

Generates a generic synopsis like <command name> [OPTIONS] [PARAM1 [PARAM2]...], omitting parts
 that don't apply to the command (e.g., does not show [OPTIONS] if the command has no options).

CommandLine.Help
addAllSubcommands(java.util.Map<java.lang.String,CommandLine> commands)

Registers all specified subcommands with this Help.

CommandLine.Help
addSubcommand(java.lang.String commandName,
             java.lang.Object command)

Deprecated.

protected java.util.List<java.lang.String>
aliases()

Returns the list of aliases for the command in this Help.

CommandLine.Help.Ansi
ansi()

Returns whether ANSI escape codes are enabled or not.

CommandLine.Help.ColorScheme
colorScheme()

Returns the ColorScheme model that this Help was constructed with.

java.lang.String
commandList()

Returns a 2-column list with command names and the first line of their header or (if absent) description.

java.lang.String
commandListHeading(java.lang.Object... params)

Returns the text displayed before the command list; an empty string if there are no commands,
 otherwise the result of String.format(commandListHeading, params).

CommandLine.Help.Ansi.Text
commandNamesText(java.lang.String separator)

Returns a Text object containing the command name and all aliases, separated with the specified separator.

CommandLine.Model.CommandSpec
commandSpec()

Returns the CommandSpec model that this Help was constructed with.

CommandLine.Help.Layout
createDefaultLayout()

Returns a Layout instance configured with the user preferences captured in this Help instance.

CommandLine.Help.IOptionRenderer
createDefaultOptionRenderer()

Returns a new default OptionRenderer which converts Options to five columns of text to match
  the default TextTable column layout.

CommandLine.Help.IParameterRenderer
createDefaultParameterRenderer()

Returns a new default ParameterRenderer which converts positional parameters to four columns of
 text to match the default TextTable column layout.

CommandLine.Help.IParamLabelRenderer
createDefaultParamLabelRenderer()

Returns a new default param label renderer that separates option parameters from their option name
 with the specified separator string, and, unless CommandLine.Model.ArgSpec.hideParamSyntax() is true,
 surrounds optional parameters with '[' and ']'
 characters and uses ellipses ("...") to indicate that any number of a parameter are allowed.

protected CommandLine.Help.Ansi.Text
createDetailedSynopsisCommandText()

Returns a Text object containing a partial detailed synopsis showing only the subcommands, starting with a " " space.

protected CommandLine.Help.Ansi.Text
createDetailedSynopsisOptionsText(java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                                 boolean clusterBooleanOptions)

Returns a Text object containing a partial detailed synopsis showing only the options, starting with a " " space.

protected CommandLine.Help.Ansi.Text
createDetailedSynopsisPositionalsText()

Returns a Text object containing a partial detailed synopsis showing only the positional parameters, starting with a " " space.

static CommandLine.Help.IOptionRenderer
createMinimalOptionRenderer()

Returns a new minimal OptionRenderer which converts Options to a single row with two columns
 of text: an option name and a description.

static CommandLine.Help.IParameterRenderer
createMinimalParameterRenderer()

Returns a new minimal ParameterRenderer which converts positional parameters
 to a single row with two columns of text: an option name and a description.

static CommandLine.Help.IParamLabelRenderer
createMinimalParamLabelRenderer()

Returns a value renderer that returns the paramLabel if defined or the field name otherwise.

static java.util.Comparator<CommandLine.Model.OptionSpec>
createShortOptionArityAndNameComparator()

Sorts OptionSpecs by their option max arity first, by
 min arity next, and by option name last.

static java.util.Comparator<CommandLine.Model.OptionSpec>
createShortOptionNameComparator()

Sorts OptionSpecs by their option name in case-insensitive alphabetic order.

java.lang.String
customSynopsis(java.lang.Object... params)

Returns command custom synopsis as a string.

static CommandLine.Help.ColorScheme
defaultColorScheme(CommandLine.Help.Ansi ansi)

Creates and returns a new CommandLine.Help.ColorScheme initialized with picocli default values: commands are bold,
  options and parameters use a yellow foreground, and option parameters use italic.

java.lang.String
description(java.lang.Object... params)

Returns command description text as a string.

java.lang.String
descriptionHeading(java.lang.Object... params)

Returns the text displayed before the description text; an empty string if there is no description,
 otherwise the result of String.format(descriptionHeading, params).

java.lang.String
detailedSynopsis(java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                boolean clusterBooleanOptions)

Deprecated.

use detailedSynopsis(int, Comparator, boolean) instead.

java.lang.String
detailedSynopsis(int synopsisHeadingLength,
                java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                boolean clusterBooleanOptions)

Generates a detailed synopsis message showing all options and parameters.

java.lang.String
footer(java.lang.Object... params)

Returns command footer text as a string.

java.lang.String
footerHeading(java.lang.Object... params)

Returns the text displayed before the footer text; the result of String.format(footerHeading, params).

java.lang.String
header(java.lang.Object... params)

Returns the command header text as a string.

java.lang.String
headerHeading(java.lang.Object... params)

Returns the text displayed before the header text; the result of String.format(headerHeading, params).

protected java.lang.String
insertSynopsisCommandName(int synopsisHeadingLength,
                         CommandLine.Help.Ansi.Text optionsAndPositionalsAndCommandsDetails)

Returns the detailed synopsis text by inserting the command name before the specified text with options and positional parameters details.

static java.lang.StringBuilder
join(CommandLine.Help.Ansi ansi,
    int usageHelpWidth,
    java.lang.String[] values,
    java.lang.StringBuilder sb,
    java.lang.Object... params)

Formats each of the specified values and appends it to the specified StringBuilder.

java.lang.String
optionList()

Returns a description of the options supported by the application.

java.lang.String
optionList(CommandLine.Help.Layout layout,
          java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
          CommandLine.Help.IParamLabelRenderer valueLabelRenderer)

Sorts all Options with the specified comparator (if the comparator is non-null),
 then adds all non-hidden options to the
 specified TextTable and returns the result of TextTable.toString().

java.lang.String
optionListHeading(java.lang.Object... params)

Returns the text displayed before the option list; an empty string if there are no options,
 otherwise the result of String.format(optionListHeading, params).

CommandLine.Help.IParamLabelRenderer
parameterLabelRenderer()

Option and positional parameter value label renderer used for the synopsis line(s) and the option list.

java.lang.String
parameterList()

Returns the section of the usage help message that lists the parameters with their descriptions.

java.lang.String
parameterList(CommandLine.Help.Layout layout,
             CommandLine.Help.IParamLabelRenderer paramLabelRenderer)

Returns the section of the usage help message that lists the parameters with their descriptions.

java.lang.String
parameterListHeading(java.lang.Object... params)

Returns the text displayed before the positional parameter list; an empty string if there are no positional
 parameters, otherwise the result of String.format(parameterListHeading, params).

static java.util.Comparator<java.lang.String>
shortestFirst()

Sorts short strings before longer strings.

protected java.util.Map<java.lang.String,CommandLine.Help>
subcommands()

Returns the map of subcommand Help instances for this command Help.

java.lang.String
synopsis()

Deprecated.

use synopsis(int) instead

java.lang.String
synopsis(int synopsisHeadingLength)

Returns a synopsis for the command, reserving the specified space for the synopsis heading.

java.lang.String
synopsisHeading(java.lang.Object... params)

Returns the text displayed before the synopsis text; the result of String.format(synopsisHeading, params).

int
synopsisHeadingLength()

Returns the number of characters the synopsis heading will take on the same line as the synopsis.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

DEFAULT_COMMAND_NAME

protected static final java.lang.String DEFAULT_COMMAND_NAME

Constant String holding the default program name, value defined in CommandLine.Model.CommandSpec.DEFAULT_COMMAND_NAME.

See Also:

Constant Field Values

DEFAULT_SEPARATOR

protected static final java.lang.String DEFAULT_SEPARATOR

Constant String holding the default string that separates options from option parameters, value defined in CommandLine.Model.ParserSpec.DEFAULT_SEPARATOR.

See Also:

Constant Field Values

Constructor Detail

Help

public Help(java.lang.Object command)

Constructs a new Help instance with a default color scheme, initialized from annotatations
 on the specified class and superclasses.

Parameters:

command - the annotated object to create usage help for

Help

public Help(java.lang.Object command,
            CommandLine.Help.Ansi ansi)

Constructs a new Help instance with a default color scheme, initialized from annotatations
 on the specified class and superclasses.

Parameters:

command - the annotated object to create usage help for

ansi - whether to emit ANSI escape codes or not

Help

@Deprecated
public Help(java.lang.Object command,
                         CommandLine.Help.ColorScheme colorScheme)

Deprecated. use picocli.CommandLine.Help#Help(picocli.CommandLine.Model.CommandSpec, picocli.CommandLine.Help.ColorScheme)

Constructs a new Help instance with the specified color scheme, initialized from annotatations
 on the specified class and superclasses.

Parameters:

command - the annotated object to create usage help for

colorScheme - the color scheme to use

Help

public Help(CommandLine.Model.CommandSpec commandSpec,
            CommandLine.Help.ColorScheme colorScheme)

Constructs a new Help instance with the specified color scheme, initialized from annotatations
 on the specified class and superclasses.

Parameters:

commandSpec - the command model to create usage help for

colorScheme - the color scheme to use

Method Detail

commandSpec

public CommandLine.Model.CommandSpec commandSpec()

Returns the CommandSpec model that this Help was constructed with.

Since:

3.9

colorScheme

public CommandLine.Help.ColorScheme colorScheme()

Returns the ColorScheme model that this Help was constructed with.

Since:

3.0

subcommands

protected java.util.Map<java.lang.String,CommandLine.Help> subcommands()

Returns the map of subcommand Help instances for this command Help.

Since:

3.9

aliases

protected java.util.List<java.lang.String> aliases()

Returns the list of aliases for the command in this Help.

Since:

3.9

parameterLabelRenderer

public CommandLine.Help.IParamLabelRenderer parameterLabelRenderer()

Option and positional parameter value label renderer used for the synopsis line(s) and the option list.
 By default initialized to the result of createDefaultParamLabelRenderer(), which takes a snapshot
 of the CommandLine.Model.ParserSpec.separator() at construction time. If the separator is modified after Help construction, you
 may need to re-initialize this field by calling createDefaultParamLabelRenderer() again.

addAllSubcommands

public CommandLine.Help addAllSubcommands(java.util.Map<java.lang.String,CommandLine> commands)

Registers all specified subcommands with this Help.

Parameters:

commands - maps the command names to the associated CommandLine object

Returns:

this Help instance (for method chaining)

See Also:

CommandLine.getSubcommands()

addSubcommand

@Deprecated
public CommandLine.Help addSubcommand(java.lang.String commandName,
                                                   java.lang.Object command)

Deprecated.

Registers the specified subcommand with this Help.

Parameters:

commandName - the name of the subcommand to display in the usage message

command - the CommandSpec or @Command annotated object to get more information from

Returns:

this Help instance (for method chaining)

synopsis

@Deprecated
public java.lang.String synopsis()

Deprecated. use synopsis(int) instead

Returns a synopsis for the command without reserving space for the synopsis heading.

Returns:

a synopsis

See Also:

abbreviatedSynopsis(),
detailedSynopsis(Comparator, boolean)

synopsis

public java.lang.String synopsis(int synopsisHeadingLength)

Returns a synopsis for the command, reserving the specified space for the synopsis heading.

Parameters:

synopsisHeadingLength - the length of the synopsis heading that will be displayed on the same line

Returns:

a synopsis

See Also:

abbreviatedSynopsis(),
detailedSynopsis(Comparator, boolean),
synopsisHeading(java.lang.Object...)

abbreviatedSynopsis

public java.lang.String abbreviatedSynopsis()

Generates a generic synopsis like <command name> [OPTIONS] [PARAM1 [PARAM2]...], omitting parts
 that don't apply to the command (e.g., does not show [OPTIONS] if the command has no options).

Returns:

a generic synopsis

detailedSynopsis

@Deprecated
public java.lang.String detailedSynopsis(java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                                                      boolean clusterBooleanOptions)

Deprecated. use detailedSynopsis(int, Comparator, boolean) instead.

Generates a detailed synopsis message showing all options and parameters. Follows the unix convention of
 showing optional options and parameters in square brackets ([ ]).

Parameters:

optionSort - comparator to sort options or null if options should not be sorted

clusterBooleanOptions - true if boolean short options should be clustered into a single string

Returns:

a detailed synopsis

detailedSynopsis

public java.lang.String detailedSynopsis(int synopsisHeadingLength,
                                         java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                                         boolean clusterBooleanOptions)

Generates a detailed synopsis message showing all options and parameters. Follows the unix convention of
 showing optional options and parameters in square brackets ([ ]).

Parameters:

synopsisHeadingLength - the length of the synopsis heading that will be displayed on the same line

optionSort - comparator to sort options or null if options should not be sorted

clusterBooleanOptions - true if boolean short options should be clustered into a single string

Returns:

a detailed synopsis

Since:

3.0

createDetailedSynopsisOptionsText

protected CommandLine.Help.Ansi.Text createDetailedSynopsisOptionsText(java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                                                                       boolean clusterBooleanOptions)

Returns a Text object containing a partial detailed synopsis showing only the options, starting with a " " space.
 Follows the unix convention of showing optional options and parameters in square brackets ([ ]).

Parameters:

optionSort - comparator to sort options or null if options should not be sorted

clusterBooleanOptions - true if boolean short options should be clustered into a single string

Returns:

the formatted options, starting with a " " space, or an empty Text if this command has no named options

Since:

3.9

createDetailedSynopsisPositionalsText

protected CommandLine.Help.Ansi.Text createDetailedSynopsisPositionalsText()

Returns a Text object containing a partial detailed synopsis showing only the positional parameters, starting with a " " space.
 Follows the unix convention of showing optional options and parameters in square brackets ([ ]).

Returns:

the formatted positional parameters, starting with a " " space, or an empty Text if this command has no positional parameters

Since:

3.9

createDetailedSynopsisCommandText

protected CommandLine.Help.Ansi.Text createDetailedSynopsisCommandText()

Returns a Text object containing a partial detailed synopsis showing only the subcommands, starting with a " " space.
 Follows the unix convention of showing optional elements in square brackets ([ ]).

Returns:

this implementation returns a hard-coded string " [COMMAND]" if this command has subcommands, an empty Text otherwise

Since:

3.9

insertSynopsisCommandName

protected java.lang.String insertSynopsisCommandName(int synopsisHeadingLength,
                                                     CommandLine.Help.Ansi.Text optionsAndPositionalsAndCommandsDetails)

Returns the detailed synopsis text by inserting the command name before the specified text with options and positional parameters details.

Parameters:

synopsisHeadingLength - length of the synopsis heading string to be displayed on the same line as the first synopsis line.
                              For example, if the synopsis heading is "Usage: ", this value is 7.

optionsAndPositionalsAndCommandsDetails - formatted string with options, positional parameters and subcommands.
          Follows the unix convention of showing optional options and parameters in square brackets ([ ]).

Returns:

the detailed synopsis text, in multiple lines if the length exceeds the usage width

synopsisHeadingLength

public int synopsisHeadingLength()

Returns the number of characters the synopsis heading will take on the same line as the synopsis.

Returns:

the number of characters the synopsis heading will take on the same line as the synopsis.

See Also:

detailedSynopsis(int, Comparator, boolean)

optionList

public java.lang.String optionList()

Returns a description of the options supported by the application.
 This implementation sorts options alphabetically, and shows
 only the non-hidden options in a tabular format
 using the default renderer and default layout.

Returns:

the fully formatted option list

See Also:

optionList(Layout, Comparator, IParamLabelRenderer)

optionList

public java.lang.String optionList(CommandLine.Help.Layout layout,
                                   java.util.Comparator<CommandLine.Model.OptionSpec> optionSort,
                                   CommandLine.Help.IParamLabelRenderer valueLabelRenderer)

Sorts all Options with the specified comparator (if the comparator is non-null),
 then adds all non-hidden options to the
 specified TextTable and returns the result of TextTable.toString().

Parameters:

layout - responsible for rendering the option list

optionSort - determines in what order Options should be listed. Declared order if null

valueLabelRenderer - used for options with a parameter

Returns:

the fully formatted option list

Since:

3.0

parameterList

public java.lang.String parameterList()

Returns the section of the usage help message that lists the parameters with their descriptions.

Returns:

the section of the usage help message that lists the parameters

parameterList

public java.lang.String parameterList(CommandLine.Help.Layout layout,
                                      CommandLine.Help.IParamLabelRenderer paramLabelRenderer)

Returns the section of the usage help message that lists the parameters with their descriptions.

Parameters:

layout - the layout to use

paramLabelRenderer - for rendering parameter names

Returns:

the section of the usage help message that lists the parameters

join

public static java.lang.StringBuilder join(CommandLine.Help.Ansi ansi,
                                           int usageHelpWidth,
                                           java.lang.String[] values,
                                           java.lang.StringBuilder sb,
                                           java.lang.Object... params)

Formats each of the specified values and appends it to the specified StringBuilder.

Parameters:

ansi - whether the result should contain ANSI escape codes or not

usageHelpWidth - the width of the usage help message

values - the values to format and append to the StringBuilder

sb - the StringBuilder to collect the formatted strings

params - the parameters to pass to the format method when formatting each value

Returns:

the specified StringBuilder

customSynopsis

public java.lang.String customSynopsis(java.lang.Object... params)

Returns command custom synopsis as a string. A custom synopsis can be zero or more lines, and can be
 specified declaratively with the CommandLine.Command.customSynopsis() annotation attribute or programmatically
 by setting the Help instance's customSynopsis(java.lang.Object...) field.

Parameters:

params - Arguments referenced by the format specifiers in the synopsis strings

Returns:

the custom synopsis lines combined into a single String (which may be empty)

description

public java.lang.String description(java.lang.Object... params)

Returns command description text as a string. Description text can be zero or more lines, and can be specified
 declaratively with the CommandLine.Command.description() annotation attribute or programmatically by
 setting the Help instance's description(java.lang.Object...) field.

Parameters:

params - Arguments referenced by the format specifiers in the description strings

Returns:

the description lines combined into a single String (which may be empty)

header

public java.lang.String header(java.lang.Object... params)

Returns the command header text as a string. Header text can be zero or more lines, and can be specified
 declaratively with the CommandLine.Command.header() annotation attribute or programmatically by
 setting the Help instance's header(java.lang.Object...) field.

Parameters:

params - Arguments referenced by the format specifiers in the header strings

Returns:

the header lines combined into a single String (which may be empty)

footer

public java.lang.String footer(java.lang.Object... params)

Returns command footer text as a string. Footer text can be zero or more lines, and can be specified
 declaratively with the CommandLine.Command.footer() annotation attribute or programmatically by
 setting the Help instance's footer(java.lang.Object...) field.

Parameters:

params - Arguments referenced by the format specifiers in the footer strings

Returns:

the footer lines combined into a single String (which may be empty)

headerHeading

public java.lang.String headerHeading(java.lang.Object... params)

Returns the text displayed before the header text; the result of String.format(headerHeading, params).

Parameters:

params - the parameters to use to format the header heading

Returns:

the formatted header heading

synopsisHeading

public java.lang.String synopsisHeading(java.lang.Object... params)

Returns the text displayed before the synopsis text; the result of String.format(synopsisHeading, params).

Parameters:

params - the parameters to use to format the synopsis heading

Returns:

the formatted synopsis heading

descriptionHeading

public java.lang.String descriptionHeading(java.lang.Object... params)

Returns the text displayed before the description text; an empty string if there is no description,
 otherwise the result of String.format(descriptionHeading, params).

Parameters:

params - the parameters to use to format the description heading

Returns:

the formatted description heading

parameterListHeading

public java.lang.String parameterListHeading(java.lang.Object... params)

Returns the text displayed before the positional parameter list; an empty string if there are no positional
 parameters, otherwise the result of String.format(parameterListHeading, params).

Parameters:

params - the parameters to use to format the parameter list heading

Returns:

the formatted parameter list heading

optionListHeading

public java.lang.String optionListHeading(java.lang.Object... params)

Returns the text displayed before the option list; an empty string if there are no options,
 otherwise the result of String.format(optionListHeading, params).

Parameters:

params - the parameters to use to format the option list heading

Returns:

the formatted option list heading

commandListHeading

public java.lang.String commandListHeading(java.lang.Object... params)

Returns the text displayed before the command list; an empty string if there are no commands,
 otherwise the result of String.format(commandListHeading, params).

Parameters:

params - the parameters to use to format the command list heading

Returns:

the formatted command list heading

footerHeading

public java.lang.String footerHeading(java.lang.Object... params)

Returns the text displayed before the footer text; the result of String.format(footerHeading, params).

Parameters:

params - the parameters to use to format the footer heading

Returns:

the formatted footer heading

commandList

public java.lang.String commandList()

Returns a 2-column list with command names and the first line of their header or (if absent) description.

Returns:

a usage help section describing the added commands

commandNamesText

public CommandLine.Help.Ansi.Text commandNamesText(java.lang.String separator)

Returns a Text object containing the command name and all aliases, separated with the specified separator.
 Command names will use the command style for the color scheme of this Help.

Since:

3.9

createDefaultLayout

public CommandLine.Help.Layout createDefaultLayout()

Returns a Layout instance configured with the user preferences captured in this Help instance.

Returns:

a Layout

createDefaultOptionRenderer

public CommandLine.Help.IOptionRenderer createDefaultOptionRenderer()

Returns a new default OptionRenderer which converts Options to five columns of text to match
  the default TextTable column layout. The first row of values looks like this:

the required option marker

2-character short option name (or empty string if no short option exists)

comma separator (only if both short option and long option exist, empty string otherwise)

comma-separated string with long option name(s)

first element of the CommandLine.Model.OptionSpec.description() array

Following this, there will be one row for each of the remaining elements of the CommandLine.Model.OptionSpec.description() array, and these rows look like {"", "", "", "", option.description()[i]}.

If configured, this option renderer adds an additional row to display the default field value.

Returns:

a new default OptionRenderer

createMinimalOptionRenderer

public static CommandLine.Help.IOptionRenderer createMinimalOptionRenderer()

Returns a new minimal OptionRenderer which converts Options to a single row with two columns
 of text: an option name and a description. If multiple names or descriptions exist, the first value is used.

Returns:

a new minimal OptionRenderer

createDefaultParameterRenderer

public CommandLine.Help.IParameterRenderer createDefaultParameterRenderer()

Returns a new default ParameterRenderer which converts positional parameters to four columns of
 text to match the default TextTable column layout. The first row of values looks like this:

empty string

empty string

parameter(s) label as rendered by the CommandLine.Help.IParamLabelRenderer

first element of the CommandLine.Model.PositionalParamSpec.description() array

Following this, there will be one row for each of the remaining elements of the CommandLine.Model.PositionalParamSpec.description() array, and these rows look like {"", "", "", param.description()[i]}.

If configured, this parameter renderer adds an additional row to display the default field value.

Returns:

a new default ParameterRenderer

createMinimalParameterRenderer

public static CommandLine.Help.IParameterRenderer createMinimalParameterRenderer()

Returns a new minimal ParameterRenderer which converts positional parameters
 to a single row with two columns of text: an option name and a description. If multiple descriptions exist, the first value is used.

Returns:

a new minimal ParameterRenderer

createMinimalParamLabelRenderer

public static CommandLine.Help.IParamLabelRenderer createMinimalParamLabelRenderer()

Returns a value renderer that returns the paramLabel if defined or the field name otherwise.

Returns:

a new minimal ParamLabelRenderer

createDefaultParamLabelRenderer

public CommandLine.Help.IParamLabelRenderer createDefaultParamLabelRenderer()

Returns a new default param label renderer that separates option parameters from their option name
 with the specified separator string, and, unless CommandLine.Model.ArgSpec.hideParamSyntax() is true,
 surrounds optional parameters with '[' and ']'
 characters and uses ellipses ("...") to indicate that any number of a parameter are allowed.

Returns:

a new default ParamLabelRenderer

createShortOptionNameComparator

public static java.util.Comparator<CommandLine.Model.OptionSpec> createShortOptionNameComparator()

Sorts OptionSpecs by their option name in case-insensitive alphabetic order. If an
 option has multiple names, the shortest name is used for the sorting. Help options follow non-help options.

Returns:

a comparator that sorts OptionSpecs by their option name in case-insensitive alphabetic order

createShortOptionArityAndNameComparator

public static java.util.Comparator<CommandLine.Model.OptionSpec> createShortOptionArityAndNameComparator()

Sorts OptionSpecs by their option max arity first, by
 min arity next, and by option name last.

Returns:

a comparator that sorts OptionSpecs by arity first, then their option name

shortestFirst

public static java.util.Comparator<java.lang.String> shortestFirst()

Sorts short strings before longer strings.

Returns:

a comparators that sorts short strings before longer strings

ansi

public CommandLine.Help.Ansi ansi()

Returns whether ANSI escape codes are enabled or not.

Returns:

whether ANSI escape codes are enabled or not

defaultColorScheme

public static CommandLine.Help.ColorScheme defaultColorScheme(CommandLine.Help.Ansi ansi)

Creates and returns a new CommandLine.Help.ColorScheme initialized with picocli default values: commands are bold,
  options and parameters use a yellow foreground, and option parameters use italic.

Parameters:

ansi - whether the usage help message should contain ANSI escape codes or not

Returns:

a new default color scheme

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
TOOMUCHW.IN
===========

TOOMUCHW.IN is an EVE Online instant lottery service.

TOOMUCHW.IN was a EVE project started with a friend mid-2014.
Even if we made everything we could to improve it and advertise (you maybe remember that ad on AT XII), it never really launched and we stopped to keep it alive a few months later.
It has been almost a year now, and no one seems to be interested in buying a lottery service anymore, so I have decided to make it Free.
I hope it can be useful to someone, to break up the betting site monopoly in EVE or learn Python with examples.

redpajama_set_name: RedPajamaGithub


text:
/** @file
 *
 * @defgroup ble_sdk_srv_ias Immediate Alert Service
 * @{
 * @ingroup ble_sdk_srv
 * @brief Immediate Alert Service module.
 *
 * @details This module implements the Immediate Alert Service with the Alert Level characteristic.
 *          During initialization it adds the Immediate Alert Service and Alert Level characteristic
 *          to the BLE stack database.
 *
 *          The application must supply an event handler for receiving Immediate Alert Service
 *          events. Using this handler, the service will notify the application when the
 *          Alert Level characteristic value changes.
 *
 *          The service also provides a function for letting the application poll the current
 *          value of the Alert Level characteristic.
 *
 * @note The application must propagate BLE stack events to the Immediate Alert Service
 *       module by calling ble_ias_on_ble_evt() from the @ref ble_stack_handler callback.
 */

#ifndef BLE_IAS_H__
#define BLE_IAS_H__

#include <stdint.h>
#include "ble.h"

/**@brief Immediate Alert Service event type. */
typedef enum
{
    BLE_IAS_EVT_ALERT_LEVEL_UPDATED                     /**< Alert Level Updated event. */
} ble_ias_evt_type_t;

/**@brief Immediate Alert Service event. */
typedef struct
{
    ble_ias_evt_type_t evt_type;                        /**< Type of event. */
    union
    {
        uint8_t alert_level;                            /**< New Alert Level value. */
    } params;
} ble_ias_evt_t;

// Forward declaration of the ble_ias_t type.
typedef struct ble_ias_s ble_ias_t;

/**@brief Immediate Alert Service event handler type. */
typedef void (*ble_ias_evt_handler_t) (ble_ias_t * p_ias, ble_ias_evt_t * p_evt);

/**@brief Immediate Alert Service init structure. This contains all options and data needed for
 *        initialization of the service. */
typedef struct
{
    ble_ias_evt_handler_t evt_handler;                  /**< Event handler to be called for handling events in the Immediate Alert Service. */
} ble_ias_init_t;

/**@brief Immediate Alert Service structure. This contains various status information for the
 *        service. */
typedef struct ble_ias_s
{
    ble_ias_evt_handler_t     evt_handler;              /**< Event handler to be called for handling events in the Immediate Alert Service. */
    uint16_t                  service_handle;           /**< Handle of Immediate Alert Service (as provided by the BLE stack). */
    ble_gatts_char_handles_t  alert_level_handles;      /**< Handles related to the Alert Level characteristic. */
} ble_ias_t;

/**@brief Function for initializing the Immediate Alert Service.
 *
 * @param[out]  p_ias       Immediate Alert Service structure. This structure will have to be
 *                          supplied by the application. It will be initialized by this function,
 *                          and will later be used to identify this particular service instance.
 * @param[in]   p_ias_init  Information needed to initialize the service.
 *
 * @return      NRF_SUCCESS on successful initialization of service, otherwise an error code.
 */
uint32_t ble_ias_init(ble_ias_t * p_ias, const ble_ias_init_t * p_ias_init);

/**@brief Function for handling the Application's BLE Stack events.
 *
 * @details Handles all events from the BLE stack of interest to the Immediate Alert Service.
 *
 * @param[in]   p_ias      Immediate Alert Service structure.
 * @param[in]   p_ble_evt  Event received from the BLE stack.
 */
void ble_ias_on_ble_evt(ble_ias_t * p_ias, ble_evt_t * p_ble_evt);

/**@brief Function for getting current value of the Alert Level characteristic.
 *
 * @param[in]   p_ias          Immediate Alert Service structure.
 * @param[out]  p_alert_level  Current Alert Level value.
 */
uint32_t ble_ias_alert_level_get(ble_ias_t * p_ias, uint8_t * p_alert_level);

#endif // BLE_IAS_H__

/** @} */


text:
[![Python 3.6+](https://img.shields.io/badge/python-3.6+-blue.svg)](https://www.python.org/downloads/release/python-360/)

## Installation

#### Option 1: Anaconda (new Python users)

Download the Python 3 [Anaconda installer](https://www.anaconda.com/distribution/#download-section) for your OS and open the Anaconda prompt.

Clone this repo using git or download it manually. Then, using the Anaconda prompt, cd into the ml-tutorial directory and move on to [Starting the tutorial](#Starting the tutorial).

#### Option 2: pip & virtual environment (advanced users)

Clone the repo and create a [virtual environment](https://docs.python.org/3/library/venv.html) in the root folder. After activating the environment, install the required packages:

        pip install -r requirements.txt

## Starting the tutorial

Open the `release/1/index.ipynb` Jupyter notebook with the following command:

        jupyter notebook release/1/index.ipynb

## Updating the tutorial

Activate the nbgrader notebook extension as documented [here](https://nbgrader.readthedocs.io/en/stable/user_guide/installation.html#installing-and-activating-extensions).
Change the notebooks in the `source/` folder, any new cells where students have to write code should be set to `Autograded answer` as documented [here](https://nbgrader.readthedocs.io/en/stable/user_guide/creating_and_grading_assignments.html#autograded-answer-cells).

After saving your changes, run:

        sh generate_assignment.sh

This will overwrite the existing `release/` directory.

While creating the notebooks in the `release/` directory, the [nbgrader](https://nbgrader.readthedocs.io/en/stable/) package will alter code segments that look like:

        ### BEGIN SOLUTION
        foo = bar
        ### END SOLUTION

into:

        ##### Implement this part of the code #####
        raise NotImplementedError("Code not implemented, follow the instructions.")

As specified in the `nbgrader_config.py` file.

## JupyterHub (BETA)

If you want to host this workshop you can use the included Dockerfile to build a JupyterHub which you can build and launch with the following commands:

```docker build . -t ml-tutorial```

```docker run -p 8000:80 ml-tutorial```

Surf to `http://localhost:8000` to start the tutorial and log in with `user001` and password `password`.

The docker image is also available on docker hub so running it on a server should work with:
```docker run -d -p 80:80 pbutenee/ml-tutorial```
without the need for downloading the code or building the container. Set the port to 8000 instead of 80 to test it out on local host.
NOTE: ONLY AN OLD VERSION OF THIS CONTAINER IS AVAILABLE ON DOCKER HUB SINCE IT IS NO LONGER FREE


text:
title:  Biblija – autoritativni izvor naše teologije
date:   18/04/2020
---

### Tekstovi za proučavanje u toku sedmice
Marko 7,1-13; Rimljanima 2,4; 1. Jovanova 2,15-17; 2. Korinćanima 10,5.6; Jovan 5,46.47; Jovan 7,38.

>
Tekst za pamćenje

>"Zakon i svjedočanstvo tražite. Ako li ko ne govori tako, njemu nema zore" (Isaija 8,20).

Nema hrišćanske crkve koja ne koristi Sveto pismo kako bi poduprla svoja verovanja. Međutim, uloga i autoritet Pisma u teologiji nisu isti u svim crkvama. Shvatanje uloge Pisma zapravo se uveliko razlikuje od crkve do crkve. To je važan ali veoma složen predmet koji ćemo istražiti proučavajući pet različitih izvora koji snažno utiču na naše tumačenje Pisma – tradiciju, iskustvo, kulturu, razum i samu Bibliju.

Ovi izvori imaju značajnu ulogu u svakoj teologiji i u svakoj crkvi. Svi smo mi deo različitih tradicija i kultura i pod njihovim smo uticajem. Svi imamo iskustva koja oblikuju naše mišljenje i utiču na to kako razumemo stvari. Svi imamo um da bismo razmatrali i procenjivali određene pojave. Svi čitamo Bibliju i služimo se njome da bismo razumeli Boga i Njegovu volju.

Koji od ovih izvora, ili koje kombinacije izvora, predstavljaju krajnji autoritet kad je reč o tome kako tumačimo Bibliju, i kako se oni koriste u svom uzajamnom odnosu? Davanje prednosti jednom ili većem broju izvora vodi do veoma različitih naglasaka i rezultata, i konačno određuje pravac čitave naše teologije.


text:
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.openqa.selenium.devtools.network.model;

import static java.util.Objects.requireNonNull;

import org.openqa.selenium.json.JsonInput;

/**
 * Object for storing Network.loadingFinished response
 */
public class LoadingFinished {

  /**
   * Request identifier
   */
  private final RequestId requestId;

  /**
   * MonotonicTime
   */
  private final MonotonicTime timestamp;

  /**
   * Total number of bytes received for this request
   */
  private final Number encodedDataLength;

  /**
   * Set when 1) response was blocked by Cross-Origin Read Blocking and also 2) this needs to be reported to the DevTools console
   */
  private final Boolean shouldReportCorbBlocking;

  private LoadingFinished(RequestId requestId, MonotonicTime timestamp, Number encodedDataLength,
                          Boolean shouldReportCorbBlocking) {
    this.requestId = requireNonNull(requestId, "'requestId' is required for LoadingFinished");
    this.timestamp = requireNonNull(timestamp, "'timestamp' is required for LoadingFinished");
    this.encodedDataLength =
        requireNonNull(encodedDataLength, "'encodedDataLength' is required for LoadingFinished");
    this.shouldReportCorbBlocking = shouldReportCorbBlocking;
  }

  private static LoadingFinished fromJson(JsonInput input) {
    RequestId requestId = new RequestId(input.nextString());
    MonotonicTime timestamp = null;
    Number encodedDataLength = null;
    Boolean shouldReportCorbBlocking = null;

    while (input.hasNext()) {

      switch (input.nextName()) {
        case "timestamp":
          timestamp = MonotonicTime.parse(input.nextNumber());
          break;

        case "encodedDataLength":
          encodedDataLength = input.nextNumber();
          break;

        case "shouldReportCorbBlocking":
          shouldReportCorbBlocking = input.nextBoolean();
          break;

        default:
          input.skipValue();
          break;
      }
    }

    return new LoadingFinished(requestId, timestamp, encodedDataLength, shouldReportCorbBlocking);
  }

  public RequestId getRequestId() {
    return requestId;
  }

  public MonotonicTime getTimestamp() {
    return timestamp;
  }

  public Number getEncodedDataLength() {
    return encodedDataLength;
  }

  public Boolean getShouldReportCorbBlocking() {
    return shouldReportCorbBlocking;
  }

  @Override
  public String toString() {
    return "LoadingFinished{" +
           "requestId=" + requestId +
           ", timestamp=" + timestamp.getTimeStamp().toString() +
           ", encodedDataLength=" + encodedDataLength +
           ", shouldReportCorbBlocking=" + shouldReportCorbBlocking +
           '}';
  }

}


text:
<?php

class SV_Telemetry_IOintercept
{
    const prefix = 'xfiocount';
    const prefix_full = 'xfiocount://';
    const prefix_full_count = 12;

    protected static function ParsePath($path)
    {
        static $urls = array();

        if (isset($urls[$path]))
        {
            return $urls[$path];
        }

        if (substr($path, 0, self::prefix_full_count) == self::prefix_full)
        {
            $urls[$path] = substr($path, self::prefix_full_count);
            return $urls[$path];
        }
        return False;
    }

    function __construct ()
    {
    }

    function __destruct ()
    {
    }

    protected $dirhandle;

    public function dir_closedir ()
    {
        if (!isset($this->dirhandle))
        {
            return False;
        }
        @closedir($this->dirhandle);
        unset($this->dirhandle);
        return True;
    }

    public function dir_opendir($path, /** @noinspection PhpUnusedParameterInspection */ $options)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return False;
        }

        $this->dirhandle = @opendir($path);
        return $this->dirhandle !== False;
    }

    public function dir_readdir()
    {
        if (!isset($this->dirhandle))
        {
            return False;
        }
        return readdir($this->dirhandle);
    }

    public function dir_rewinddir()
    {
        if (!isset($this->dirhandle))
        {
            return False;
        }
        rewinddir($this->dirhandle);
        return True;
    }

    public function mkdir($path, $mode, $options)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return False;
        }
        $recursive = ($options & STREAM_MKDIR_RECURSIVE) == STREAM_MKDIR_RECURSIVE;
        $queryTime = microtime(true);
        try
        {
            return mkdir($path, $mode, $recursive);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'mkdir'));
        }
    }

    public function rmdir($path, /** @noinspection PhpUnusedParameterInspection */ $options)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return False;
        }
        $queryTime = microtime(true);
        try
        {
            return rmdir($path);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'rmdir'));
        }
    }

    protected $streamhandle;
    protected $fileRequiresUpdate = false;
    protected $parsedPath;

    public function stream_close()
    {
        $queryTime = microtime(true);
        try
        {
            $ret = fclose($this->streamhandle);
            unset($this->streamhandle);
            return $ret;
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'close'));
        }
    }

    public function stream_eof()
    {
        if(!isset($this->streamhandle))
        {
            return true;
        }
        return feof($this->streamhandle);
    }

    public function stream_flush()
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        $queryTime = microtime(true);
        try
        {
            return fflush($this->streamhandle);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'flush'));
        }
    }

    public function stream_metadata($path, $option, $value)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return False;
        }
        $ret = False;
        $queryTime = microtime(true);
        try
        {
            switch($option)
            {
                case STREAM_META_TOUCH:
                    if (isset($value[0]) && isset($value[1]))
                        $ret = touch($path, $value[0], $value[1]);
                    else if (isset($value[0]))
                        $ret = touch($path, $value[0]);
                    else
                        $ret = touch($path);
                    break;
                case STREAM_META_OWNER_NAME:
                case STREAM_META_OWNER:
                    $ret = chown($path, $value);
                    break;
                case STREAM_META_GROUP_NAME:
                case STREAM_META_GROUP:
                    $ret = chgrp($path, $value);
                    break;
                case STREAM_META_ACCESS:
                    $ret = chmod($path, $value);
                    break;
                default:
                    throw new Exception("SV_Telemetry_IOintercept::stream_metadata ". $option ." not implemented");
                    break;
            }
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'metadata'));
        }
        return $ret;
    }

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        $parsedPath = self::ParsePath($path);
        if (!$parsedPath)
        {
            throw new Exception('stream_open() passed an invalid path');
        }
        $queryTime = microtime(true);
        try
        {
            $use_include_path  = ($options & STREAM_USE_PATH) == STREAM_USE_PATH;
            $this->streamhandle = fopen($parsedPath, $mode, $use_include_path);
            if ($this->streamhandle !== False)
            {
                $opened_path = $path;
            }
            else
            {
                throw new Exception('Call to fopen() failed');
            }
            return $this->streamhandle !== False;
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'open'));
        }
    }

    public function stream_read($count)
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        $queryTime = microtime(true);
        try
        {
            return fread($this->streamhandle,$count);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'read'));
        }
    }

    public function stream_seek($offset, $whence  = SEEK_SET)
    {
        if(!isset($this->streamhandle))
        {
            return False;
        }
        return fseek($this->streamhandle, $offset, $whence) == 0;
    }

    public function stream_cast(/** @noinspection PhpUnusedParameterInspection */
        $cast_as)
    {
        return $this->streamhandle;
    }

    public function stream_stat()
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        return fstat($this->streamhandle);
    }

    public function stream_tell()
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        return ftell($this->streamhandle);
    }

    public function stream_truncate($new_size)
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        $queryTime = microtime(true);
        try
        {
            return ftruncate($this->streamhandle, $new_size);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'truncate'));
        }
    }

    public function stream_write($data)
    {
        if(!isset($this->streamhandle))
        {
            return false;
        }
        $queryTime = microtime(true);
        try
        {
            return fwrite($this->streamhandle, $data);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'write'));
        }
    }

    public function unlink($path)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return False;
        }
        $queryTime = microtime(true);
        try
        {
            return @unlink($path);
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'unlink'));
        }
    }

    public function url_stat($path, $flags)
    {
        $path = self::ParsePath($path);
        if (!$path)
        {
            return 0;
        }
        $queryTime = microtime(true);
        try
        {
            if ($flags & STREAM_URL_STAT_LINK)
            {
                return ($flags & STREAM_URL_STAT_QUIET) ? @lstat($path) : lstat($path);
            }
            else
            {
                return ($flags & STREAM_URL_STAT_QUIET) ? @stat($path) : stat($path);
            }
        }
        finally
        {
            SV_Telemetry_Wrapper::stats()->timing('xenforo.io', microtime(true) - $queryTime, 1, array('io' => 'stat'));
        }
        // doesn't actually get here
        return 0;
    }
}


text:
<?php

namespace Oro\Bundle\ApiBundle\Tests\Unit\Processor\Subresource\Shared\JsonApi;

use Oro\Bundle\ApiBundle\Model\Error;
use Oro\Bundle\ApiBundle\Model\ErrorSource;
use Oro\Bundle\ApiBundle\Processor\Subresource\Shared\JsonApi\NormalizeRequestData;
use Oro\Bundle\ApiBundle\Request\DataType;
use Oro\Bundle\ApiBundle\Tests\Unit\Processor\Subresource\ChangeRelationshipProcessorTestCase;

class NormalizeRequestDataTest extends ChangeRelationshipProcessorTestCase
{
    const ASSOCIATION_NAME = 'testAssociation';

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $valueNormalizer;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $entityIdTransformer;

    /** @var NormalizeRequestData */
    protected $processor;

    public function setUp()
    {
        parent::setUp();

        $this->valueNormalizer = $this->getMockBuilder('Oro\Bundle\ApiBundle\Request\ValueNormalizer')
            ->disableOriginalConstructor()
            ->getMock();
        $this->entityIdTransformer = $this->createMock('Oro\Bundle\ApiBundle\Request\EntityIdTransformerInterface');

        $this->processor = new NormalizeRequestData($this->valueNormalizer, $this->entityIdTransformer);
    }

    public function testNormalizeDataForToOneAssociation()
    {
        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->with('entity', DataType::ENTITY_CLASS, $this->context->getRequestType(), false)
            ->willReturn('Test\Class');
        $this->entityIdTransformer->expects($this->once())
            ->method('reverseTransform')
            ->with('Test\Class', 'val')
            ->willReturn('normalizedVal');

        $this->context->setRequestData(['data' => ['type' => 'entity', 'id' => 'val']]);
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(false);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                'id'    => 'normalizedVal',
                'class' => 'Test\Class'
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
    }

    public function testNormalizeEmptyDataForToOneAssociation()
    {
        $this->valueNormalizer->expects($this->never())
            ->method('normalizeValue');
        $this->entityIdTransformer->expects($this->never())
            ->method('reverseTransform');

        $this->context->setRequestData(['data' => null]);
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(false);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => null
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
    }

    public function testNormalizeDataForToManyAssociation()
    {
        $this->valueNormalizer->expects($this->exactly(2))
            ->method('normalizeValue')
            ->willReturnMap(
                [
                    ['entity1', DataType::ENTITY_CLASS, $this->context->getRequestType(), false, 'Test\Class1'],
                    ['entity2', DataType::ENTITY_CLASS, $this->context->getRequestType(), false, 'Test\Class2'],
                ]
            );
        $this->entityIdTransformer->expects($this->exactly(2))
            ->method('reverseTransform')
            ->willReturnMap(
                [
                    ['Test\Class1', 'val1', 'normalizedVal1'],
                    ['Test\Class2', 'val2', 'normalizedVal2'],
                ]
            );

        $this->context->setRequestData(
            [
                'data' => [
                    ['type' => 'entity1', 'id' => 'val1'],
                    ['type' => 'entity2', 'id' => 'val2']
                ]
            ]
        );
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(true);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                [
                    'id'    => 'normalizedVal1',
                    'class' => 'Test\Class1'
                ],
                [
                    'id'    => 'normalizedVal2',
                    'class' => 'Test\Class2'
                ]
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
    }

    public function testNormalizeEmptyDataForToManyAssociation()
    {
        $this->valueNormalizer->expects($this->never())
            ->method('normalizeValue');
        $this->entityIdTransformer->expects($this->never())
            ->method('reverseTransform');

        $this->context->setRequestData(['data' => []]);
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(true);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => []
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
    }

    public function testProcessWithInvalidEntityTypeForToOneAssociation()
    {
        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->willThrowException(new \Exception('cannot normalize entity type'));
        $this->entityIdTransformer->expects($this->never())
            ->method('reverseTransform');

        $this->context->setRequestData(['data' => ['type' => 'entity', 'id' => 'val']]);
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(false);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                'id'    => 'val',
                'class' => 'entity'
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
        $this->assertEquals(
            [
                Error::createValidationError('entity type constraint')
                    ->setInnerException(new \Exception('cannot normalize entity type'))
                    ->setSource(ErrorSource::createByPointer('/data/type'))
            ],
            $this->context->getErrors()
        );
    }

    public function testProcessWithInvalidIdentifierForToOneAssociation()
    {
        $this->valueNormalizer->expects($this->once())
            ->method('normalizeValue')
            ->with('entity', DataType::ENTITY_CLASS, $this->context->getRequestType(), false)
            ->willReturn('Test\Class');
        $this->entityIdTransformer->expects($this->once())
            ->method('reverseTransform')
            ->willThrowException(new \Exception('cannot normalize id'));

        $this->context->setRequestData(['data' => ['type' => 'entity', 'id' => 'val']]);
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(false);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                'id'    => 'val',
                'class' => 'Test\Class'
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
        $this->assertEquals(
            [
                Error::createValidationError('entity identifier constraint')
                    ->setInnerException(new \Exception('cannot normalize id'))
                    ->setSource(ErrorSource::createByPointer('/data/id'))
            ],
            $this->context->getErrors()
        );
    }

    public function testProcessWithInvalidEntityTypesForToManyAssociation()
    {
        $this->valueNormalizer->expects($this->exactly(2))
            ->method('normalizeValue')
            ->willThrowException(new \Exception('cannot normalize entity type'));
        $this->entityIdTransformer->expects($this->never())
            ->method('reverseTransform');

        $this->context->setRequestData(
            [
                'data' => [
                    ['type' => 'entity1', 'id' => 'val1'],
                    ['type' => 'entity2', 'id' => 'val2']
                ]
            ]
        );
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(true);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                [
                    'id'    => 'val1',
                    'class' => 'entity1'
                ],
                [
                    'id'    => 'val2',
                    'class' => 'entity2'
                ]
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
        $this->assertEquals(
            [
                Error::createValidationError('entity type constraint')
                    ->setInnerException(new \Exception('cannot normalize entity type'))
                    ->setSource(ErrorSource::createByPointer('/data/0/type')),
                Error::createValidationError('entity type constraint')
                    ->setInnerException(new \Exception('cannot normalize entity type'))
                    ->setSource(ErrorSource::createByPointer('/data/1/type')),
            ],
            $this->context->getErrors()
        );
    }

    public function testProcessWithInvalidIdentifiersForToManyAssociation()
    {
        $this->valueNormalizer->expects($this->exactly(2))
            ->method('normalizeValue')
            ->willReturnMap(
                [
                    ['entity1', DataType::ENTITY_CLASS, $this->context->getRequestType(), false, 'Test\Class1'],
                    ['entity2', DataType::ENTITY_CLASS, $this->context->getRequestType(), false, 'Test\Class2'],
                ]
            );
        $this->entityIdTransformer->expects($this->exactly(2))
            ->method('reverseTransform')
            ->willThrowException(new \Exception('cannot normalize id'));

        $this->context->setRequestData(
            [
                'data' => [
                    ['type' => 'entity1', 'id' => 'val1'],
                    ['type' => 'entity2', 'id' => 'val2']
                ]
            ]
        );
        $this->context->setAssociationName(self::ASSOCIATION_NAME);
        $this->context->setIsCollection(true);
        $this->processor->process($this->context);

        $expectedData = [
            self::ASSOCIATION_NAME => [
                [
                    'id'    => 'val1',
                    'class' => 'Test\Class1'
                ],
                [
                    'id'    => 'val2',
                    'class' => 'Test\Class2'
                ]
            ]
        ];

        $this->assertEquals($expectedData, $this->context->getRequestData());
        $this->assertEquals(
            [
                Error::createValidationError('entity identifier constraint')
                    ->setInnerException(new \Exception('cannot normalize id'))
                    ->setSource(ErrorSource::createByPointer('/data/0/id')),
                Error::createValidationError('entity identifier constraint')
                    ->setInnerException(new \Exception('cannot normalize id'))
                    ->setSource(ErrorSource::createByPointer('/data/1/id')),
            ],
            $this->context->getErrors()
        );
    }
}


text:
require 'haml'
require 'nokogiri'
require 'ostruct'
require './models/media'

describe 'photo.haml' do
  subject { Nokogiri::HTML.fragment(Haml::Engine.new(File.read('views/photo.haml')).render(OpenStruct.new(locals))) }
  let(:photo) { Media.new(id: '1234', url: 'http://someurl.com/url', thumbnail: 'http://somethumb.com/thumb')}
  let(:locals) { {photo: photo, previous_photo: nil, next_photo: nil} }

  it { expect(subject.css('img')[0][:src]).to eq 'http://someurl.com/url' }
  it { expect(subject.css('a.previous')).to be_empty }
  it { expect(subject.css('a.next')).to be_empty }

  describe 'when there is a previous photo' do
    let(:locals) { {photo: photo, previous_photo: 'http://previousurl.com/previous'} }
    it { expect(subject.css('a.previous')[0][:href]).to eq 'http://previousurl.com/previous' }
  end

  describe 'when there is a next photo' do
    let(:locals) { {photo: photo, next_photo: 'http://nexturl.com/next'} }
    it { expect(subject.css('a.next')[0][:href]).to eq 'http://nexturl.com/next' }
  end
end


text:
require 'faraday'
module TorrentRSS
  class Torrent
    attr_accessor :id, :url, :title, :summary
    def self.from_entry entry
      torrent = new

      [:id, :url, :title, :summary].each do |attr|
        torrent.send "#{attr}=", entry.send("#{attr}")
      end

      torrent
    end

    def initialize
      @connection = Faraday.new do |builder|
        builder.adapter Faraday.default_adapter
      end
    end

    def download directory
      response = @connection.get @url
      if response.success?
        filename = response.headers['content-disposition'].match(/filename=\"(.+)\"/)[1]
        File.write "#{directory}/#{filename}", response.body
      end
      response.success?
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.IO;
using Pulse.Core;
using Pulse.FS;

namespace Pulse.UI
{
    public sealed class UiArchiveExtractor : IDisposable
    {
        private readonly ArchiveListing _listing;
        private readonly ArchiveEntry[] _leafs;
        private readonly IUiExtractionTarget _target;
        private readonly Boolean? _conversion;
        private readonly Dictionary<String, IArchiveEntryExtractor> _extractors;

        public UiArchiveExtractor(ArchiveListing listing, ArchiveEntry[] leafs, bool? conversion, IUiExtractionTarget target)
        {
            _listing = listing;
            _leafs = leafs;
            _target = target;
            _conversion = conversion;
            _extractors = ProvideExtractors();
        }

        public void Dispose()
        {
        }

        public void Extract()
        {
            if (_leafs.Length == 0)
                return;

            String root = InteractionService.WorkingLocation.Provide().ProvideExtractedDirectory();

            byte[] buff = new byte[32 * 1024];
            foreach (ArchiveEntry entry in _leafs)
            {
                String targetExtension;
                IArchiveEntryExtractor extractor = GetExtractor(entry, out targetExtension);
                if (extractor == null)
                    continue;

                String targetPath = Path.Combine(root, PathEx.ChangeMultiDotExtension(entry.Name, targetExtension));
                String directoryPath = Path.GetDirectoryName(targetPath);
                _target.CreateDirectory(directoryPath);

                using (Stream input = _listing.Accessor.ExtractBinary(entry))
                using (StreamSequence output = _target.Create(targetPath))
                    extractor.Extract(entry, output, input, buff);
            }
        }

        private IArchiveEntryExtractor GetExtractor(ArchiveEntry entry, out String targetExtension)
        {
            IArchiveEntryExtractor result;
            targetExtension = PathEx.GetMultiDotComparableExtension(entry.Name);

            if (entry.Name.Contains("_jp") || entry.Name.Contains("_kr"))
                result = DefaultExtractor;
            else if (_extractors.TryGetValue(targetExtension, out result))
                targetExtension = result.TargetExtension;
            else if (_conversion != true)
                result = DefaultExtractor;

            return result;
        }

        private Dictionary<String, IArchiveEntryExtractor> ProvideExtractors()
        {
            return _conversion != false ? Converters : Emptry;
        }

        #region Static

        private static readonly IArchiveEntryExtractor DefaultExtractor = ProvideDefaultExtractor();
        private static readonly Dictionary<String, IArchiveEntryExtractor> Emptry = new Dictionary<String, IArchiveEntryExtractor>(0);
        private static readonly Dictionary<String, IArchiveEntryExtractor> Converters = RegisterConverters();

        private static IArchiveEntryExtractor ProvideDefaultExtractor()
        {
            return new DefaultArchiveEntryExtractor();
        }

        private static Dictionary<String, IArchiveEntryExtractor> RegisterConverters()
        {
            return new Dictionary<String, IArchiveEntryExtractor>
            {
                {".ztr", new ZtrToStringsArchiveEntryExtractor()},
                {".win32.scd", new ScdToWaveArchiveEntryExtractor()}
            };
        }

        #endregion
    }
}


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

using Foundation;
using UIKit;
using XLabs.Forms;

namespace RCBeacon.iOS
{
    // The UIApplicationDelegate for the application. This class is responsible for launching the
    // User Interface of the application, as well as listening (and optionally responding) to
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : XFormsApplicationDelegate
    {
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}


text:
;(function() {
  'use strict';

  const recaptcha = require('recaptcha2');

  module.exports = Extension => class Form extends Extension {
    _constructor() {
      this.show.context = Extension.SECTION;
      this.validate.context = Extension.ROUTER;
    }

    show(ctx) {
      let args = ctx.arg('recaptcha');

      let captcha = args && new recaptcha({
        siteKey: args.siteKey,
        secretKey: args.secretKey
      });

      ctx.content = ctx.render({ recaptcha: captcha && captcha.formElement() });
      return ctx.success();
    }

    validate(ctx) {
      let args = ctx.arg('recaptcha');
      let captcha = new recaptcha({
        siteKey: args.siteKey,
        secretKey: args.secretKey
      });

      captcha.validateRequest(ctx.req)
        .then(() => ctx.success())
        .catch(err => ctx.error(err));
    }
  }
})();


text:
class AP_RangeFinder_MaxsonarI2CXL : public AP_RangeFinder_Backend
{
public:
    // constructor
    AP_RangeFinder_MaxsonarI2CXL(RangeFinder &ranger, uint8_t instance, RangeFinder::RangeFinder_State &_state);

    // static detection function
    static bool detect(RangeFinder &ranger, uint8_t instance);

    // update state
    void update(void);

private:
    // start a reading
    static bool start_reading(void);
    static bool get_reading(uint16_t &reading_cm);
};
#endif  // __AP_RANGEFINDER_MAXSONARI2CXL_H__


text:
<?php

namespace MB\SimpleRestFirewall;

/**
 *
 * @author mickael
 */
interface IUser {

    /**
     * @return integer
     */
    public function getUserId();

    /**
     * @return string
     */
    public function getLogin();

    /**
     * @return string
     */
    public function getToken();

    /**
     * @return \Datetime
     */
    public function getTokenDateExpired();

    /**
     * @return array Authorization\IGroup
     */
    public function getGroups();

}


text:
namespace CPF
{
	namespace MultiCore
	{
		//////////////////////////////////////////////////////////////////////////
		class ContainerBase
		{
		public:
			virtual ~ContainerBase() {}

			virtual void Begin() {}
			virtual void End() {}
		};

		//////////////////////////////////////////////////////////////////////////
		template<typename WORKTYPE>
		class VectorContainer : public ContainerBase
		{
		public:
			using WorkType = WORKTYPE;

			void Acquire();
			void Release();

			size_t GetSize() const;
			void Add(WorkType&& work);
			void Remove(const WorkType& work);

			const WorkType& operator [](const size_t index) const;

		private:
			Threading::Mutex mLock;
			Vector<WorkType> mWork;
		};

		//////////////////////////////////////////////////////////////////////////
		template<typename WORKTYPE>
		void VectorContainer<WORKTYPE>::Acquire()
		{
			mLock.Acquire();
		}

		template<typename WORKTYPE>
		void VectorContainer<WORKTYPE>::Release()
		{
			mLock.Release();
		}

		template<typename WORKTYPE>
		size_t VectorContainer<WORKTYPE>::GetSize() const
		{
			return mWork.size();
		}

		template<typename WORKTYPE>
		void VectorContainer<WORKTYPE>::Add(WorkType&& work)
		{
			mWork.emplace_back(Move(work));
		}

		template<typename WORKTYPE>
		void VectorContainer<WORKTYPE>::Remove(const WorkType& work)
		{
			for (auto ibegin = mWork.begin(), iend = mWork.end(); ibegin!=iend; ++ibegin)
			{
				if (*ibegin == work)
				{
					mWork.erase(ibegin);
					return;
				}
			}
			// Trying to erase something that does not exist.
			CPF_ASSERT_ALWAYS;
		}

		template<typename WORKTYPE>
		const typename VectorContainer<WORKTYPE>::WorkType& VectorContainer<WORKTYPE>::operator [](const size_t index) const
		{
			return mWork[index];
		}

		//////////////////////////////////////////////////////////////////////////
		template<typename WORKTYPE, typename LESSTHAN = Less<WORKTYPE>>
		class SortedVectorContainer : public ContainerBase
		{
		public:
			using WorkType = WORKTYPE;

			void Acquire();
			void Release();

			size_t GetSize() const;
			void Add(WorkType&& work);
			void Remove(const WorkType& work);

			const WorkType& operator [](const size_t index) const;

			void Begin() override;
			void End() override;

		private:
			using WorkVector = Vector<WorkType>;

			int _Find(const WorkType& work) const;

			Threading::Mutex mLock;
			WorkVector mWork;

			// Per thread add/remove.
			WorkVector mAdditions[Concurrency::kMaxThreads];
			WorkVector mDeletions[Concurrency::kMaxThreads];
		};

		//////////////////////////////////////////////////////////////////////////
		template<typename WORKTYPE, typename LESSTHAN>
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::Acquire()
		{
			mLock.Acquire();
		}

		template<typename WORKTYPE, typename LESSTHAN>
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::Release()
		{
			mLock.Release();
		}

		template<typename WORKTYPE, typename LESSTHAN>
		size_t SortedVectorContainer<WORKTYPE, LESSTHAN>::GetSize() const
		{
			return mWork.size();
		}

		template<typename WORKTYPE, typename LESSTHAN>
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::Add(WorkType&& work)
		{
			mAdditions[0].emplace_back(Move(work));
		}

		template<typename WORKTYPE, typename LESSTHAN>
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::Remove(const WorkType& work)
		{
			auto it = _Find(work);
			CPF_ASSERT(it >= 0);
			CPF_ASSERT(mWork[it] == work);
			mWork.erase(mWork.begin() + it);
		}

		template<typename WORKTYPE, typename LESSTHAN>
		const typename SortedVectorContainer<WORKTYPE, LESSTHAN>::WorkType&
			SortedVectorContainer<WORKTYPE, LESSTHAN>::operator [](const size_t index) const
		{
			return mWork[index];
		}

		template<typename WORKTYPE, typename LESSTHAN> inline
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::Begin()
		{
			WorkVector accumulate;
			for (int i = 0; i < Concurrency::kMaxThreads; ++i)
			{
				accumulate.insert(accumulate.end(), mAdditions[i].begin(), mAdditions[i].end());
				mAdditions[i].clear();
			}
			std::sort(accumulate.begin(), accumulate.end());

			if (accumulate.size() > 0)
			{
				auto insertion = accumulate.begin();
				auto target = mWork.begin();

				while (insertion != accumulate.end() && target != mWork.end())
				{
					if (*insertion < *target)
					{
						target = mWork.emplace(target, Move(*insertion));
						++insertion;
						++target;
					}
				}

				mWork.insert(mWork.end(), insertion, accumulate.end());
			}
		}

		template<typename WORKTYPE, typename LESSTHAN> inline
		void SortedVectorContainer<WORKTYPE, LESSTHAN>::End()
		{
			WorkVector accumulate;
			for (int i = 0; i < Concurrency::kMaxThreads; ++i)
			{
				accumulate.insert(accumulate.end(), mDeletions[i].begin(), mDeletions[i].end());
				mDeletions[i].clear();
			}
			std::sort(accumulate.begin(), accumulate.end());

			if (accumulate.size() > 0)
			{
				auto icurrent = mWork.begin();
				for (auto ibegin = accumulate.begin(), iend = accumulate.end(); ibegin!=iend; ++ibegin)
				{
					while (*ibegin != *icurrent)
						++icurrent;
					CPF_ASSERT(*ibegin == *icurrent);
					icurrent = mWork.erase(icurrent);
				}
			}
		}

		template<typename WORKTYPE, typename LESSTHAN>
		int SortedVectorContainer<WORKTYPE, LESSTHAN>::_Find(const WorkType& work) const
		{
			LESSTHAN compare;
			int ilow = 0;
			int ihigh = int(mWork.size());
			int imid = 0;
			while (ilow < ihigh)
			{
				imid = ((ilow + ihigh) / 2);
				if (compare(mWork[imid], work))
				{
					ilow = imid + 1;
					continue;
				}
				if (compare(work, mWork[imid]))
				{
					ihigh = imid - 1;
					continue;
				}
				break;
			}
			return imid;
		}
	}
}


text:
=======
Compute
=======

The OpenStack Compute service allows you to control an
Infrastructure-as-a-Service (IaaS) cloud computing platform.  It gives you
control over instances and networks, and allows you to manage access to the
cloud through users and projects.

Compute does not include virtualization software. Instead, it defines drivers
that interact with underlying virtualization mechanisms that run on your host
operating system, and exposes functionality over a web-based API.

.. toctree::
   :maxdepth: 2

   admin-password-injection.rst
   adv-config.rst
   arch.rst
   availability-zones.rst
   configuring-migrations.rst
   cpu-topologies.rst
   default-ports.rst
   evacuate.rst
   flavors.rst
   huge-pages.rst
   live-migration-usage.rst
   manage-logs.rst
   manage-the-cloud.rst
   manage-users.rst
   manage-volumes.rst
   migration.rst
   networking-nova.rst
   node-down.rst
   pci-passthrough.rst
   quotas2.rst
   quotas.rst
   remote-console-access.rst
   root-wrap-reference.rst
   security-groups.rst
   security.rst
   service-groups.rst
   services.rst
   ssh-configuration.rst
   support-compute.rst
   system-admin.rst


text:
/**
 *
 */
package io.sipstack.netty.codec.sip.event.impl;

import io.netty.channel.ChannelPipeline;
import io.pkts.packet.sip.SipMessage;
import io.pkts.packet.sip.header.ViaHeader;
import io.sipstack.netty.codec.sip.Connection;
import io.sipstack.netty.codec.sip.event.SipMessageIOEvent;

/**
 * Whenever a {@link SipMessage} is received it will be framed and a
 * {@link SipMessageIOEventImpl} will be created and passed up through the
 * {@link ChannelPipeline}. The main reason for this object is the need to
 * encapsulate stream based and datagram based connections in Netty 4 (worked
 * differently in Netty 3) as well as to provide a time stamp for when the
 * message was received on the socket (or rather when it was framed)
 *
 * @author jonas@jonasborjesson.com
 */
public class SipMessageIOEventImpl extends IOEventImpl implements SipMessageIOEvent {

    private final SipMessage msg;

    /**
     *
     */
    public SipMessageIOEventImpl(final Connection connection, final SipMessage msg, final long arrivalTime) {
        super(connection, arrivalTime);
        this.msg = msg;
    }

    /**
     * Two SipMessageEvents are considered equal if they contain similar sip messages.
     * Similar because comparing the full sip message is expensive so we only care
     * about both being requests/responses, their method, cseq, io.sipstack.transaction.transaction, call-id.
     *
     * @param other
     * @return
     */
    public boolean equals(final Object other) {
        if (this == other) {
            return true;
        }

        try {
            final SipMessage otherMsg = ((SipMessageIOEventImpl)other).msg;
            if ((msg.isRequest() && otherMsg.isRequest() || msg.isResponse() && otherMsg.isResponse()) && msg.getMethod().equals(otherMsg.getMethod())) {
                if (!msg.getCallIDHeader().equals(otherMsg.getCallIDHeader())) {
                    return false;
                }

                final ViaHeader via1 = msg.getViaHeader();
                final ViaHeader via2 = otherMsg.getViaHeader();
                return via1.getBranch().equals(via2.getBranch());
            } else {
                return false;
            }

        } catch (final NullPointerException | ClassCastException e) {
            return false;
        }
    }

    /**
     * The framed {@link SipMessage}.
     *
     * @return
     */
    @Override
    public SipMessage message() {
        return this.msg;
    }

}


text:
![React-TimeAgo](http://naman.s3.amazonaws.com/react-timeago.png)

A simple time-ago component for [React].

## Usage:

`react-timeago` is a very simple component that takes a `date` prop and returns a span with live updating date in a time-ago format. The date will update only as often as needed. For timestamps below a minute away — every second, for timestamps up to 5 minutes away — every minute, and so on.

`react-timeago` does the minimum amount of updates necessary.

```jsx
<TimeAgo date="Aug 29, 2014" />

// OR in vanilla JS
React.createElement(TimeAgo, {date: 'Aug 29, 2014'})
```

## Language support

Since v3.1.0 `react-timeago` now comes with support for a large number of languages out of the box.
This support is based on the string objects taken from `jquery-timeago` and then updated with the help of the
community. Many thanks to all those who contribute language support.

### Usage
To use any of the languages provided, other than the default english, you will have to
import the language strings and build a custom formatter.

```jsx
import TimeAgo from 'react-timeago'
import frenchStrings from 'react-timeago/lib/language-strings/fr'
import buildFormatter from 'react-timeago/lib/formatters/buildFormatter'

const formatter = buildFormatter(frenchStrings)

// in your react component
<TimeAgo date='Feb 1, 1966' formatter={formatter} />
```

And that's it. You can also customize the language strings or provide your own.
(pull requests are welcome too!). Of course, for maximum control you can write your
own formatter function.

For best performance, I recommend that you build formatters that you're going to use once,
and pass them around.

## Flow Types

Since v3.0.0 `react-timeago` comes with flow type definitions out of the box.

In v3.1.0, the React.PropType validations have been removed in favour of just flow types.
Further, many type definitions are now exported for use in your own code.

Look through the source for more details.

## Props

#### `date` (required)
Date is a date in the past or the future. This can be a Date Object, A UTC date-string or number of milliseconds since epoch time.

#### `live` (optional)
React-Timeago is live by default and will auto update it's value. However, if you don't want this behaviour, you can set live:false.

#### `now` (optional)
A custom function that can be used instead of `Date.now()` to get the current value of `epochSeconds` in `formatter` below.
This can be specifically useful for server rendering when you want the datetime to be the same on the server and client.

#### `formatter` (optional)
A function that takes four arguments:
  - `value` : An integer value, already rounded off
  - `unit` : A string representing the unit in english. This could be one of:
    - 'second'
    - 'minute'
    - 'hour'
    - 'day'
    - 'week'
    - 'month'
    - 'year'
  - `suffix` : A string. This can be one of
    - 'ago'
    - 'from now'
  - `epochMilliseconds`: The result of `Date.now()` or the result of a custom `now` prop.
  - `nextFormatter`: A function that takes no arguments and gives you the result of the defaultFormatter using the same arguments above.

Here are some examples of what the formatter function will receive:

- '5 minutes ago' => formatter(5, 'minute', 'ago')
- '1 year from now' => formatter(1, 'year', 'from now')

The formatter function is a simple way to extend the functionality of React-Timeago to support any feature you may need from a fuzzy time display.
The formatter function is expected to return a string.
But it can also return any React component (or array of components) that would become the child of React-TimeAgo

The project comes with a set of languages and a formatter function builder based on those language strings.
You can customize the strings, or provide your own custom formatter function.

I recommend using the fantastic [L10ns](http://l10ns.org) for other internationalization needs.

#### `component` (optional) (default: 'time')
A string of ReactClass that is used to wrap the live updating string

#### `title` (optional)
If the component is left as the default 'time' component, a title attribute is passed to it.
You can customize this by passing a string, or a UTC date-string will be used based on
the given date.

#### `minPeriod` (optional) (default: 0)
The minimum number of seconds that the component should wait before updating. The component will still update if you pass new props.
Use this if, for example, you don't want to update every second for recent times.

#### `maxPeriod` (optional) (default: Infinity)
The opposite of minPeriod. Use this to force dates to update more often than the default behaviour.
For example, you can use this update a time every 5 minutes even after it is more than an hour old.

#### Anything Else? (optional)
As of v2.0 you can pass in any props. Any props not used by React-TimeAgo will be passed down to the resulting component.
This means that you can pass className, styles, id, title, aria-label, event handlers or anything else you want.

## Why React-TimeAgo

React-TimeAgo focuses on speed, and simplicity. At about 100 lines of code, the file size is extremely small. There are many similar libraries, but most of them come with large dependencies that aren't worth it for such a simple use case.

In the spirit of NPM and keeping libraries small, any additional features you may need from TimeAgo can be plugged-in using the formatter function.

In the future, I will be writing formatter functions for various languages, that can be required and passed-in as needed.
As you will only require the parts you actually use, there will be no need to bloat your JavaScript.

React-TimeAgo is also set apart from its competitors in that it is one of the only time-ago components that can update itself live.

## Contribution

While the code is complete and pretty stable, I welcome issues and pull requests.

React-TimeAgo is feature complete from my point of view (discussions welcome).

However, support for various languages can always be improved. So please, contribute strings for the language(s) you're fluent in. I'm specifically looking for strings for the unit 'week'. `jquery-timeago` did not support weeks in its strings, and so in all but the default English, weeks get down-converted to days instead. Help me fix that.

### Changelog and Versioning

After contributing your feature or fix, please update the [changelog](/CHANGELOG.md) describing your change. Don't forget to version `package.json` as well, as the package follows [SemVer] strictly.

See [CHANGELOG.md](/CHANGELOG.md).

[React]: https://reactjs.org/
[SemVer]: https://semver.org/


text:
/**
 * A simple concurrent work queue.
 *
 * @param {number} concurrency The amount of concurrency for the queue.
 *
 * @returns The work queue with a push function.
 */
module.exports = function queue(concurrency) {

	var count = 0;
	var queue = [];

	function drain() {
		if (queue.length && count < concurrency) {
			count++;
			var func = queue.shift();
			func(callback);
		}
	}

	function callback() {
		count--;
		drain();
	}

	function push(func) {
		queue.push(func);
		drain();
	}

	return { push: push };
};