text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

 <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
 <title>TRIO</title>
 <link href="trio.css" rel="stylesheet" type="text/css">

Main Page   Modules

Formatted Printing Functions.
Variations of formatted printing functions.
More...

Functions

int 	trio_printf (const char *format,...)

 	Print to standard output stream.

int 	trio_vprintf (const char *format, va_list args)

 	Print to standard output stream.

int 	trio_printfv (const char *format, trio_pointer_t *args)

 	Print to standard output stream.

int 	trio_fprintf (FILE *file, const char *format,...)

 	Print to file.

int 	trio_vfprintf (FILE *file, const char *format, va_list args)

 	Print to file.

int 	trio_fprintfv (FILE *file, const char *format, trio_pointer_t *args)

 	Print to file.

int 	trio_dprintf (int fd, const char *format,...)

 	Print to file descriptor.

int 	trio_vdprintf (int fd, const char *format, va_list args)

 	Print to file descriptor.

int 	trio_dprintfv (int fd, const char *format, trio_pointer_t *args)

 	Print to file descriptor.

int 	trio_sprintf (char *buffer, const char *format,...)

 	Print to string.

int 	trio_vsprintf (char *buffer, const char *format, va_list args)

 	Print to string.

int 	trio_sprintfv (char *buffer, const char *format, trio_pointer_t *args)

 	Print to string.

int 	trio_snprintf (char *buffer, size_t max, const char *format,...)

 	Print at most max characters to string.

int 	trio_vsnprintf (char *buffer, size_t max, const char *format, va_list args)

 	Print at most max characters to string.

int 	trio_snprintfv (char *buffer, size_t max, const char *format, trio_pointer_t *args)

 	Print at most max characters to string.

int 	trio_asprintf (char **result, const char *format,...)

 	Allocate and print to string.

int 	trio_vasprintf (char **result, const char *format, va_list args)

 	Allocate and print to string.

int 	trio_asprintfv (char **result, const char *format, trio_pointer_t *args)

 	Allocate and print to string.

Detailed Description

Variations of formatted printing functions.

SYNOPSIS

cc ... -ltrio -lm

#include <trio.h>

DESCRIPTION

This documentation is incomplete. The documentation of the printf family in [C99] and [UNIX98] also applies to the trio counterparts.

All these functions outputs a string which is formatted according to the format string and the consecutive arguments. The format string is described in the Formatting section below.

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. writes the output to the standard output stream (stdout).

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. writes the output to a given output stream.

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. writes the output to a file descriptor (this includes, for example, sockets).

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. writes the output into buffer.

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. writes max - 1 characters into buffer followed by a terminating zero character. If max is 1, then buffer will be an empty string. If max is 0, then buffer is left untouched, and can consequently be NULL. The number of characters that would have been written to buffer, had there been sufficient space, is returned.

trio_snprintfcat appends the formatted text at the end of buffer.

Formatted Printing Functions., Formatted Printing Functions., and Formatted Printing Functions. allocates and returns an allocated string in buffer containing the formatted text.

FORMATTING

The format string can contain normal text and conversion indicators. The normal text can be any character except the nil character (\000 = '\0') and the percent character (\045 = '%'). Conversion indicators consists of an indication character (%), followed by zero or more conversion modifiers, and exactly one conversion specifier.

Modifiers

Some modifiers exhibit the same behaviour for all specifiers, other modifiers indicate different behaviours for different specifiers, and other modifiers are only applicable to certain specifiers. The relationship is described for each modifier. The number 9 is used to denotes an arbitrary integer.

Positional ( 9$ ) [UNIX98]

Normally the arguments supplied to these functions are interpreted incrementially from left to right. Arguments can be referenced specifically in the format string. The modifier n$ selects the nth argument. The first argument is referred as 1$. If this modifier is used, it must be the first modifier after the indication character. n$ can also be used for argument width, precision, and base.

The performance penalty of using positionals is almost neglible (contrary to most other printf implementations).

 Reference Mix. Mixing normal and positional specifiers is allowed [TRIO]. For example,

  trio_printf("%d %3$d %2$d\n", 1, 2, 3);

 results in

  1 3 2

 Arguments for the printf family are passed on the stack. On most platforms it is not possible to determine the size of individual stack elements, so it is essential that the format string corresponds exactly to the passed arguments. If this is not the case, incorrect values may be put into the result.

 Reference Gap. For the same reason it is also essential that the format string does not contain any "gaps" in the positional arguments. For example,

  trio_printf("%1$d %3$d\n", 1, 2, 3);

 is NOT allowed. The format string parser has no knowledge about whether the second argument is, say, an integer or a long double (which have different sizes).

 [UNIX98] describes this as unspecified behaviour. [TRIO] will detect reference gaps and return an error.

 Double Reference. It is also not allowed to reference an argument twice or more. For example,

  trio_printf("%1$d %1$lf\n", 1);

 is NOT allowed, because it references the first argument as two differently sized objects.

 [UNIX98] describes this as unspecified behaviour. [TRIO] will detect double references and return an error.

The following two statements are equivalent

  trio_printf("|%d %s\n|", 42, "meanings");
  |42 meanings|

  trio_printf("|%1$d %2$s|\n", 42, "meanings");
  |42 meanings|

Width ( 9 )

Specifies the minimum width of a field. If the fields has less characters than specified by the width, the field will be left adjusted and padded by spaces. The adjustment and padding can be changed by the Alignment ( - ) and Padding ( 0 ) modifiers.

The width is specified as a number. If an asterix ( * ) is used instead, the width will be read from the argument list.

Prefixes, such as 0x for hexadecimal integers, are part of width.

  trio_printf("|%10i|\n", 42);
  |        42|

Precision ( .9 )

The precision has different semantics for the various data types. The precision specifies the maximum number of printed characters for strings, the number of digits after the decimal-point for floating-point numbers, the number of significant digits for the g (and G) representation of floating-point numbers, the minimum number of printed digits for integers.

  trio_printf("|%10.8i|%.8i|\n", 42, 42);
  |  00000042|00000042|

Base ( ..9 ) [TRIO]

Sets the base that the associated integer must be converted to. The base can be between 2 and 36 (both included).

  trio_printf("|%10.8.2i|%10..2i|%..2i|\n", 42, 42, 42);
  |  00101010|    101010|101010|

  trio_printf("|%*.8.*i|\n", 10, 2, 42);
  |  00101010|

Padding ( 0 )

Integer and floating point numbers are prepended by zeros. The number of leading zeros are determined by the precision. If precision is not present, width is used instead.

Short ( h )

Integer arguments are read as an ( unsigned ) short int. String and character arguments are read as char * and char respectively.

Short short ( hh ) [C99, GNU]

The argument is read as an ( unsigned ) char.

Fixed Size ( I ) [MSVC]

The argument is read as a fixed sized integer. The modifier is followed by a number, which specifies the number of bits in the integer, and can be one of the following

 I8
 I16
 I32
 I64 (if 64-bits integers are supported)

Works only for integers (i, u, d, o, x, X)

Largest ( j ) [C99]

The argument is read as an intmax_t / uintmax_t, which is defined to be the largest signed/unsigned integer.

Long ( l )

An integral argument is read as an ( unsigned ) long int. A string argument is read as a wchar_t *, and output as a multi-byte character sequence.

Long long ( ll ) [C99, UNIX98, GNU]

The argument is read as an ( unsigned ) long long int.

Long double ( L ) [C99, UNIX98, GNU]

The argument is read as a long double.

ptrdiff_t ( t ) [C99]

The argument is read as a ptrdiff_t, which is defined to be the signed integer type of the result of subtracting two pointers.

Quad ( q ) [BSD, GNU]

Corresponds to the long long modifier ( ll ).

Wide ( w ) [MISC]

For a string argument this is equivalent to using the long modifier ( l ).

size_t ( z ) [C99]

The argument is read as a size_t, which is defined to be the type returned by the sizeof operator.

size_t ( Z ) [GNU]

Corresponds to the size_t modifier ( z ).

Alternative ( # )

Prepend radix indicator for hexadecimal, octal, and binary integer numbers and for pointers. Always add a decimal-point for floating-point numbers. Escape non-printable characters for strings.

Spacing ( )

Prepend leading spaces when necessary.

Sign ( + )

Always prepend a sign to numbers. Normally only the negative sign is prepended to a number. With this modifier the positive sign may also be prepended.

Alignment ( - )

The output will be left-justified in the field specified by the width.

Argument ( * )

Width, precision, or base is read from the argument list, rather than from the formatting string.

Quote / Grouping ( ' ) [MISC]

Groups integers and the integer-part of floating-point numbers according to the locale. Quote strings and characters.

Sticky ( ! ) [TRIO]

The modifiers listed for the current specifier will be reused by subsequent specifiers of the same group. The following specifier groups exists

 Integer ( i, u, d, o, x, X )
 Floating-point ( f, F, e, E, g, G, a, A )
 Character ( c )
 String ( s )
 Pointer ( p )
 Count ( n )
 Errno ( m )
 Group ( [] )

The sticky modifiers are active until superseeded by other sticky modifiers, or the end of the format string is reached. Local modifiers overrides sticky modifiers for the given specifier only.

  trio_printf("|%!08#x|%04x|%x|\n", 42, 42, 42);
  |0x00002a|0x2a|0x00002a|

Specifiers

Percent ( % )

Produce a percent ( % ) character. This is used to quote the indication character. No modifiers are allowed. The full syntax is %%.

  trio_printf("Percent is %%\n");
  Percent is %

Hex floats ( a, A ) [C99]

Output a hexadecimal (base 16) representation of a floating point number. The number is automatically preceeded by 0x ( or 0X ). The exponent is p ( or P ).

  trio_printf("|%a|%A|\n", 3.1415, 3.1415e20);
  |0x3.228bc|0X3.228BCP+14|

Binary numbers ( b, B ) [MISC - SCO UnixWare 7]

DEPRECATED: Use Base modifier %..2i instead.

Character ( c )

Output a single character.

 Quote ( ' ) [TRIO]. Quote the character.

Decimal ( d )

Output a decimal (base 10) representation of a number.

 Grouping ( ' ) [TRIO]. The number is separated by the locale thousand separator.

  trio_printf("|%'ld|\n", 1234567);
  |1,234,567|

Floating-point ( e, E)

Output a decimal floating-point number. The style is [-]9.99e[-]9, where

 [-]9.99 is the mantissa (as described for the f, F specifier), and
 e[-]9 is the exponent indicator (either e or E, depending on the floating-point specifier), followed by an optional sign and the exponent

If the precision is wider than the maximum number of digits that can be represented by the floating-point unit, then the number will be adequately rounded. For example, assuming DBL_DIG is 15

  trio_printf("|%.18e|\n", (1.0 / 3.0));
  |3.333333333333333000e-01|

Floating-point ( f, F )

Output a decimal floating-point number. The style is [-]9.99, where

 [-] is an optional sign (either + or -),
 9 is the integer-part (possibly interspersed with thousand-separators),
 . is the decimal-point (depending on the locale), and
 99 is the fractional-part.

If more digits are needed to output the number, than can be represented with the accuracy of the floating-point unit, then the number will be adequately rounded. For example, assuming that DBL_DIG is 15

  trio_printf("|%f|\n", (2.0 / 3.0) * 1E18);
  |666666666666666700.000000|

The following modifiers holds a special meaning for this specifier

 Alternative ( # ) [C99]. Add decimal point.
 Grouping ( ' ) [TRIO]. Group integer part of number into thousands (according to locale).

Floating-point ( g, G)

Output a decimal floating-point representation of a number. The format of either the f, F specifier or the e, E specifier is used, whatever produces the shortest result.

Integer ( i )

Output a signed integer. Default base is 10.

Errno ( m ) [GNU]

Count ( n )

Insert into the location pointed to by the argument, the number of octets written to the output so far.

Octal ( o )

Output an octal (base 8) representation of a number.

Pointer ( p )

Ouput the address of the argument. The address is printed as a hexadecimal number. If the argument is the NULL pointer the text (nil) will be used instead.

 Alternative ( # ) [TRIO]. Prepend 0x

String ( s, S )

Output a string. The argument must point to a zero terminated string. If the argument is the NULL pointer the text (nil) will be used instead. S is equivalent to ls.

 Alternative ( # ) [TRIO]. Escape non-printable characters.

Non-printable characters are converted into C escapes, or hexadecimal numbers where no C escapes exists for the character. The C escapes, the hexadecimal number, and all backslashes are prepended by a backslash ( \ ). The supported C escapes are

 \a (\007) = alert
 \b (\010) = backspace
 \f (\014) = formfeed
 \n (\012) = newline
 \r (\015) = carriage return
 \t (\011) = horizontal tab
 \v (\013) = vertical tab

  trio_printf("|One %s Three|One %'s Three|\n", "Two", "Two");
  |One Two Three|One "Two" Three|

  trio_printf("|Argument missing %s|\n", NULL);
  |Argument missing (nil)|

  trio_printf("|%#s|\n", "\007 \a.");
  |\a \a.|

Unsigned ( u )

Output an unsigned integer. Default base is 10.

Hex ( x, X )

Output a hexadecimal (base 16) representation of a number.

 Alternative ( # ). Preceed the number by 0x ( or 0X ). The two characters are counted as part of the width.

User-defined ( <> )

Invoke user-defined formatting. See User-defined Formatted Printing Functions. for further information.

RETURN VALUES

All functions returns the number of outputted characters. If an error occured then a negative error code is returned [TRIO]. Note that this is a deviation from the standard, which simply returns -1 (or EOF) and errno set appropriately. The error condition can be detected by checking whether the function returns a negative number or not, and the number can be parsed with the following macros. The error codes are primarily intended as debugging aide for the developer.

 TRIO_EINVAL: Invalid argument.
 TRIO_ETOOMANY: Too many arguments.
 TRIO_EDBLREF: Double argument reference.
 TRIO_EGAP: Argument reference gap.
 TRIO_ENOMEM: Out of memory.
 TRIO_ERANGE: Invalid range.
 TRIO_ERRNO: The error is specified by the errno variable.

Example:

  int rc;

  rc = trio_printf("%r\n", 42);
  if (rc < 0) {
    if (TRIO_ERROR_CODE(rc) != TRIO_EOF) {
      trio_printf("Error: %s at position %d\n",
                  TRIO_ERROR_NAME(rc),
                  TRIO_ERROR_POSITION(rc));
    }
  }

SEE ALSO

trio_scanf, trio_register.

NOTES

The printfv family uses an array rather than the stack to pass arguments. This means that short int and float values will not be handled by the default argument promotion in C. Instead, these values must be explicitly converted with the Short (h) modifier in both cases.

Example:

  void *array[2];
  float float_number = 42.0;
  short short_number = 42;

  array[0] = &float_number;
  array[1] = &short_number;

  trio_printfv("%hf %hd\n", array); /* CORRECT
  trio_printfv("%f %d\n", array); /* WRONG

CONFORMING TO

Throughout this document the following abbreviations have been used to indicate what standard a feature conforms to. If nothing else is indicated ANSI C (C89) is assumed.

 [C89] ANSI X3.159-1989
 [C99] ISO/IEC 9899:1999
 [UNIX98] The Single UNIX Specification, Version 2
 [BSD] 4.4BSD
 [GNU] GNU libc
 [MSVC] Microsoft Visual C
 [MISC] Other non-standard sources
 [TRIO] Extensions specific for this package

Function Documentation

           int trio_asprintf
          (
          char **
            result,

          const char *
            format,

          ...

          )

Allocate and print to string.

The memory allocated and returned by result must be freed by the calling application.

Parameters:

result
Output string.

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_asprintfv
          (
          char **
            result,

          const char *
            format,

          trio_pointer_t *
            args

          )

Allocate and print to string.

The memory allocated and returned by result must be freed by the calling application.

Parameters:

result
Output string.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_dprintf
          (
          int
            fd,

          const char *
            format,

          ...

          )

Print to file descriptor.

Parameters:

fd
File descriptor.

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_dprintfv
          (
          int
            fd,

          const char *
            format,

          trio_pointer_t *
            args

          )

Print to file descriptor.

Parameters:

fd
File descriptor.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_fprintf
          (
          FILE *
            file,

          const char *
            format,

          ...

          )

Print to file.

Parameters:

file
File pointer.

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_fprintfv
          (
          FILE *
            file,

          const char *
            format,

          trio_pointer_t *
            args

          )

Print to file.

Parameters:

file
File pointer.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_printf
          (
          const char *
            format,

          ...

          )

Print to standard output stream.

Parameters:

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_printfv
          (
          const char *
            format,

          trio_pointer_t *
            args

          )

Print to standard output stream.

Parameters:

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_snprintf
          (
          char *
            buffer,

          size_t
            max,

          const char *
            format,

          ...

          )

Print at most max characters to string.

Parameters:

buffer
Output string.

max
Maximum number of characters to print.

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_snprintfv
          (
          char *
            buffer,

          size_t
            max,

          const char *
            format,

          trio_pointer_t *
            args

          )

Print at most max characters to string.

Parameters:

buffer
Output string.

max
Maximum number of characters to print.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_sprintf
          (
          char *
            buffer,

          const char *
            format,

          ...

          )

Print to string.

Parameters:

buffer
Output string.

format
Formatting string.

...
Arguments.

Returns:

Number of printed characters.

           int trio_sprintfv
          (
          char *
            buffer,

          const char *
            format,

          trio_pointer_t *
            args

          )

Print to string.

Parameters:

buffer
Output string.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vasprintf
          (
          char **
            result,

          const char *
            format,

          va_list
            args

          )

Allocate and print to string.

The memory allocated and returned by result must be freed by the calling application.

Parameters:

result
Output string.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vdprintf
          (
          int
            fd,

          const char *
            format,

          va_list
            args

          )

Print to file descriptor.

Parameters:

fd
File descriptor.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vfprintf
          (
          FILE *
            file,

          const char *
            format,

          va_list
            args

          )

Print to file.

Parameters:

file
File pointer.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vprintf
          (
          const char *
            format,

          va_list
            args

          )

Print to standard output stream.

Parameters:

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vsnprintf
          (
          char *
            buffer,

          size_t
            max,

          const char *
            format,

          va_list
            args

          )

Print at most max characters to string.

Parameters:

buffer
Output string.

max
Maximum number of characters to print.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

           int trio_vsprintf
          (
          char *
            buffer,

          const char *
            format,

          va_list
            args

          )

Print to string.

Parameters:

buffer
Output string.

format
Formatting string.

args
Arguments.

Returns:

Number of printed characters.

Copyright (C) 2001 - 2006 Bjørn Reese and Daniel Stenberg.


text:
/**
* This validation program specifically checks that the generated HTML is identical in content
* to the original USX file.  To do this it reads the HTML data from the generated database,
* parses it, and generates USX files
*/
var fs = require("fs");
//var os = require("os");
var HTML_BIBLE_PATH = "../../DBL/3prepared/";
var USX_BIBLE_PATH = "../../DBL/2current/";
var EOL = '\r\n';
var END_EMPTY = ' />';

function HTMLValidator(version) {
	this.version = version;
	this.versionPath = HTML_BIBLE_PATH + version + '.db';
	this.parser = new HTMLParser();
	this.db = null;
}
HTMLValidator.prototype.open = function(callback) {
	var that = this;
	var sqlite3 = require('sqlite3');
	this.db = new sqlite3.Database(this.versionPath, sqlite3.OPEN_READWRITE, function(err) {
		if (err) that.fatalError(err, 'openDatabase');
		//that.db.on('trace', function(sql) { console.log('DO ', sql); });
		//that.db.on('profile', function(sql, ms) { console.log(ms, 'DONE', sql); });
		callback();
	});
};
HTMLValidator.prototype.validateBook = function(outPath, index, books, callback) {
	var that = this;
	if (index >= books.length) {
		callback();
	} else {
		var chapters = [];
		var chapterNum = null;
		console.log('doing ', books[index]);
		var book = books[index].code;
		this.db.all("SELECT html FROM chapters WHERE reference LIKE ?", book + '%', function(err, results) {
			if (err) that.fatalError(err, 'select html');
			for (var i=0; i<results.length; i++) {
				var node = that.parser.readBook(results[i].html);
				chapters.push(node);
			}
			var usx = convertHTML2USX(chapters);
			compareUSXFile(book, outPath, usx, function() {
				that.validateBook(outPath, index + 1, books, callback);
			});
		});
	}

	function convertHTML2USX(chapters) {
		var usx = [];
		usx.push(String.fromCharCode('0xFEFF'));
		usx.push('<?xml version="1.0" encoding="utf-8"?>', EOL);
		usx.push('<usx version="2.0">');
		for (var i=0; i<chapters.length; i++) {
			recurseOverHTML(usx, chapters[i]);
		}
		usx.push('</usx>');
		return(usx.join(''));
	}

	function recurseOverHTML(usx, node) {
		convertOpenElement(usx, node);
		if (node.children) {
			for (var i=0; i<node.children.length; i++) {
				recurseOverHTML(usx, node.children[i]);
			}
		}
		convertCloseElement(usx, node);
	}

	function convertOpenElement(usx, node) {
		//console.log(node.tagName);
		switch(node.tagName) {
			case 'ROOT':
				// do nothing
				break;
			case 'article':
				usx.push('<book code="', node.id, '" style="', node['class'], '"');
				if (node.emptyElement) {
					usx.push(END_EMPTY);
				} else {
					usx.push('>');
					if (node.hidden) {
						usx.push(node.hidden);
					}
				}
				break;
			case 'section':
				chapterNum = node.id.split(':')[1];
				break;
			case 'p':
				if (node['class'] === 'c') {
					usx.push('<chapter number="', chapterNum, '" style="c"', END_EMPTY);
					node.children = [];
				} else if (node.emptyElement) {
					usx.push('<para style="', node['class'], '"', END_EMPTY);
				} else {
					usx.push('<para style="', node['class'], '">');
				}
				if (node.hidden) {
					usx.push(node.hidden);
				}
				break;
			case 'span':
				if (node['class'] === 'v') {
					var parts = node.id.split(':');
					usx.push('<verse number="', parts[2], '" style="', node['class'], '"', END_EMPTY);
					node.children = [];
				} else if (node['class'] === 'topf') {
					usx.push('<note caller="', node.caller, '" style="f">');
					clearTextChildren(node); // clear note button
				} else if (node['class'] === 'topx') {
					usx.push('<note caller="', node.caller, '" style="x">');
					clearTextChildren(node); // clear note button
				} else if (node.hidden) {
					if (node.closed) {
						usx.push('<char style="', node['class'], '" closed="', node.closed, '">');
					} else {
						usx.push('<char style="', node['class'], '">');
					}
					usx.push(node.hidden);
				} else if (node.loc) {
					usx.push('<ref loc="', node.loc, '">');
				} else if (node['class'] !== 'f' && node['class'] !== 'x') {
					if (node.closed) {
						usx.push('<char style="', node['class'], '" closed="', node.closed, '"');
					} else {
						usx.push('<char style="', node['class'], '"');
					}
					if (node.emptyElement) {
						usx.push(END_EMPTY)
					} else {
						usx.push('>');
					}
				}
				break;
			case 'table':
				usx.push('<table>');
				break;
			case 'tr':
				usx.push('<row style="tr">');
				break;
			case 'td':
				var nodeClass = node['class'];
				if (nodeClass.length === 3) {
					usx.push('<cell style="', node['class'], '" align="start">');
				} else {
					usx.push('<cell style="', node['class'], '" align="end">');
				}
				break;
			case 'wbr':
				usx.push('<optbreak', END_EMPTY);
				break;
			case 'TEXT':
				usx.push(node.text);
				break;
			default:
				throw new Error('unexpected HTML element ' + node.tagName + '.');
		}
	}

	function clearTextChildren(node) {
		for (var i=0; i<node.children.length; i++) {
			var child = node.children[i];
			if (child.tagName === 'TEXT') {
				child.text = '';
			}
		}
	}

	function convertCloseElement(usx, node) {
		if (! node.emptyElement) {
			switch(node.tagName) {
				case 'ROOT':
				case 'section':
					break;
				case 'article':
					usx.push('</book>');
					break;
				case 'TEXT':
					// do nothing
					break;
				case 'p':
					if (node['class'] !== 'c' && ! node.emptyElement) {
						usx.push('</para>');
					}
					break;
				case 'span':
					if (node['class'] === 'v') {
						// do nothing
					} else if (node['class'] === 'topf' || node['class'] === 'topx') {
						usx.push('</note>');
					} else if (node.hidden) {
						usx.push('</char>');
					} else if (node.loc) {
						usx.push('</ref>');
					} else if (node['class'] !== 'f' && node['class'] !== 'x') {
						usx.push('</char>');
					}
					break;
				case 'table':
					usx.push('</table>');
					break;
				case 'tr':
					usx.push('</row>');
					break;
				case 'td':
					usx.push('</cell>');
					break;
				case 'wbr':
					break;
				default:
					throw new Error('unexpected HTML element ' + node.tagName + '.');

			}
		}
	}

	function compareUSXFile(book, outPath, data, callback) {
		var inFile = USX_BIBLE_PATH + that.version + '/USX_1/' + book + '.usx';
		//var outFile = OUT_BIBLE_PATH + book + '.usx';
		var outFile = outPath + '/' + book + '.usx';
		fs.writeFile(outFile, data, { encoding: 'utf8'}, function(err) {
			if (err) {
				//console.log('WRITE ERROR', JSON.stringify(err));
				//process.exit(1);
				that.fatalError(err, 'Write USX File');
			}
			var proc = require('child_process');
			proc.exec('diff ' + inFile + ' ' + outFile, { encoding: 'utf8' }, function(err, stdout, stderr) {
				if (err) {
					console.log('Diff Error', JSON.stringify(err));
				}
				console.log('STDOUT', stdout);
				console.log('STDERR', stderr);
				callback();
			});
		});
	}
};
HTMLValidator.prototype.fatalError = function(err, source) {
	console.log('FATAL ERROR ', err, ' AT ', source);
	process.exit(1);
};
HTMLValidator.prototype.completed = function() {
	console.log('HTMLValidator COMPLETED');
	this.db.close();
	process.exit(0);
};

function HTMLParser() {
}
HTMLParser.prototype.readBook = function(data) {
	var reader = new XMLTokenizer(data);
	var rootNode = new HTMLRoot();
	var nodeStack = [rootNode];
	var node = null;
	var count = 0;
	while (tokenType !== XMLNodeType.END && count < 300000) {

		var tokenType = reader.nextToken();

		var tokenValue = reader.tokenValue();
		//console.log('type=|' + tokenType + '|  value=|' + tokenValue + '|');
		count++;

		switch(tokenType) {
			case XMLNodeType.ELE:
				node = new HTMLElement(tokenValue);
				//node.emptyNode = false;
				nodeStack[nodeStack.length -1].addChild(node);
				nodeStack.push(node);
				break;
			case XMLNodeType.ELE_OPEN:
				node = new HTMLElement(tokenValue);
				break;
			case XMLNodeType.ATTR_NAME:
				// do nothing
				break;
			case XMLNodeType.ATTR_VALUE:
				if (priorValue !== 'onclick' && priorValue !== 'style') {
					node[priorValue] = tokenValue;
				}
				break;
			case XMLNodeType.ELE_END:
				node.emptyElement = false;
				nodeStack[nodeStack.length -1].addChild(node);
				nodeStack.push(node);
				break;
			case XMLNodeType.WHITESP:
			case XMLNodeType.TEXT:
				node = new HTMLTextNode(tokenValue);
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_EMPTY:
				node.emptyElement = true;
				nodeStack[nodeStack.length -1].addChild(node);
				break;
			case XMLNodeType.ELE_CLOSE:
				node = nodeStack.pop();
				if (node.tagName !== tokenValue) {
					throw new Error('closing element mismatch ' + node.openElement() + ' and ' + tokenValue);
				}
				break;
			case XMLNodeType.PROG_INST:
				// do nothing
				break;
			case XMLNodeType.END:
				// do nothing
				break;
			default:
				throw new Error('The XMLNodeType ' + tokenType + ' is unknown in HTMLParser.');
		}
		var priorValue = tokenValue;
	}
	return(rootNode);
};

function HTMLElement(tagName) {
	this.tagName = tagName;
	this.id = null;
	this['class'] = null;
	this.caller = null;
	this.loc = null;
	this.note = null;
	this.hidden = null;
	this.closed = null;
	this.emptyElement = false;
	this.children = [];
	Object.seal(this);
}
HTMLElement.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLElement.prototype.toString = function() {
	var array = [];
	this.buildHTML(array, false);
	return(array.join(''));
};
HTMLElement.prototype.toHTML = function() {
	var array = [];
	this.buildHTML(array, true);
	return(array.join(''));
};
HTMLElement.prototype.buildHTML = function(array, includeChildren) {
	array.push(EOL, '<', this.tagName);
	if (this.id) array.push(' id="', this.id, '"');
	if (this['class']) array.push(' class="', this['class'], '"');
	if (this.caller) array.push(' caller="', this.caller, '"');
	if (this.loc) array.push(' loc="', this.loc, '"');
	if (this.note) array.push(' note="', this.note, '"');
	if (this.hidden) array.push(' hidden="', this.hidden, '"');
	if (this.closed) array.push(' closed"', this.closed, '"');
	if (this.emptyElement) {
		array.push(' />');
	} else {
		array.push('>');
		if (includeChildren) {
			for (var i=0; i<this.children.length; i++) {
				this.children[i].buildHTML(array, includeChildren);
			}
		}
		array.push('</', this.tagName, '>');
	}
};

function HTMLTextNode(text) {
	this.tagName = 'TEXT';
	this.text = text;
	Object.seal(this);
}
HTMLTextNode.prototype.toString = function() {
	return(this.text);
};
HTMLTextNode.prototype.buildHTML = function(array) {
	array.push(this.text);
};

function HTMLRoot() {
	this.tagName = 'ROOT';
	this.children = [];
	Object.seal(this);
}
HTMLRoot.prototype.addChild = function(node) {
	this.children.push(node);
};
HTMLRoot.prototype.toHTML = function() {
	var array = [];
	for (var i=0; i<this.children.length; i++) {
		this.children[i].buildHTML(array, true);
	}
	return(array.join(''));
};

if (process.argv.length < 3) {
	console.log('Usage: HTMLValidator.sh  version');
	process.exit(1);
}

const outPath = 'output/' + process.argv[2] + '/html';
ensureDirectory(outPath, function() {
	var version = process.argv[2];
	var htmlValidator = new HTMLValidator(version);
	htmlValidator.open(function() {
		var canon = new Canon();
		htmlValidator.validateBook(outPath, 0, canon.books, function() {
			htmlValidator.completed();
			console.log('HTMLValidator DONE');
		});
	});
});

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

# We use eval to load code snippets that we also parse to avoid needing to
# create fixture files for short bits of code.
# rubocop:disable Eval

describe TypeTracer::InstanceMethodChecker, '#undefined_method_messages' do
  it 'returns an empty list if no undefined instance methods' do
    code = <<-EOS
    class Test
      def hi
        puts "hi"
      end
    end
    EOS
    eval(code)
    ast = TypeTracer.parse(code)

    messages = TypeTracer::InstanceMethodChecker.new(ast).undefined_method_messages

    expect(messages).to be_empty
  end

  it 'properly considers dynamically defined methods' do
    code = <<-EOS
    class Test
      def hi
        greet
      end

      define_method(:greet) do
        puts "hi"
      end
    end
    EOS
    eval(code)
    ast = TypeTracer.parse(code)

    messages = TypeTracer::InstanceMethodChecker.new(ast).undefined_method_messages

    expect(messages).to be_empty
  end

  it 'returns messages for undefined instance methods' do
    code = <<-EOS
    class Test
      def hi
        undefined_method!
      end
    end
    EOS
    eval(code)
    ast = TypeTracer.parse(code)

    messages = TypeTracer::InstanceMethodChecker.new(ast).undefined_method_messages

    expect(messages.size).to eq 1
  end
end


text:
/**
 * @license Long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
 * Released under the Apache License, Version 2.0
 * see: https://github.com/dcodeIO/Long.js for details
 */
(function(global, factory) {

    /* AMD */ if (typeof define === 'function' && define["amd"])
        define([], factory);
    /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
        module["exports"] = factory();
    /* Global */ else
        (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();

})(this, function() {
    "use strict";

    //? include("long.js");

    return Long;
});


text:
class Subject < ActiveRecord::Base
  belongs_to :taggable, polymorphic: true
end


text:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';

import { SkySearchTestingModule } from '../search-testing.module';

import { SearchHarnessTestComponent } from './search-harness-test.component';

@NgModule({
  imports: [CommonModule, SkySearchTestingModule],
  declarations: [SearchHarnessTestComponent],
})
export class SearchHarnessTestModule {}


text:
<tt>Whois</tt> is an intelligent — pure Ruby — WHOIS client and parser.

This library was extracted from [RoboWhois](https://robowhois.com/) and [RoboDomain](https://robodomain.com/), and it's now in use at [DNSimple](https://dnsimple.com/). It has been performing queries in production since July 2009.

[![Build Status](https://github.com/weppos/whois/actions/workflows/tests.yml/badge.svg)](https://github.com/weppos/whois/actions/workflows/tests.yml)

## Donate a coffee

<tt>Whois</tt> is free software, but it requires a lot of coffee to write, test, and distribute it. You can support the development by [donating a coffee](https://whoisrb.org/contribute/#donate).

Any amount is greatly appreciated.

## Features

- Ability to lookup WHOIS record for [IPv4, IPv6, TLDs, and ICANN new gTLDs](http://whoisrb.org/manual/usage/#usage-objects)
- Ability to [parse WHOIS responses](http://whoisrb.org/manual/parser/) (via the `whois-parser` library)
- Flexible and extensible interface (e.g. You can define [custom servers](http://whoisrb.org/manual/server/) on the fly)
- Object oriented design, featuring 10 different design patterns
- Pure Ruby library, without any external dependency other than Ruby itself
- Successfully tested against different Ruby implementations, including Ruby and JRuby

## Whois and Whois parser

Starting from version 4, WHOIS parser component is available in a separate repository called [whois-parser](https://github.com/weppos/whois-parser), and released as a separate gem called `whois-parser`.

This repository contains the core whois library, that includes the WHOIS client, the server definitions and all the features required to perform WHOIS queries and obtain the WHOIS record.

## Requirements

- Ruby >= 2.4

For older versions of Ruby, see the [CHANGELOG](CHANGELOG.md).

## Installation

You can install the gem manually:

```shell
gem install whois
```

Or use [Bundler](http://bundler.io/) and define it as a dependency in your `Gemfile`:

```ruby
gem 'whois'
```

To use the WHOIS parser component you need to install the `whois-parser` gem:

```shell
gem install whois-parser
```

```ruby
gem 'whois-parser'
```

The `whois-parser` gem already depends on the `whois` gem. If you install `whois-parser`, `whois` will be installed as well and it will also be automatically required when you `require 'whois-parser'`.

If you are upgrading to 4.0, see [4.0-Upgrade.md](4.0-Upgrade.md).

## Getting Started

This section covers only the essentials for getting started with the Whois library. The [documentation](https://whoisrb.org/docs/) provides a more accurate explanation including tutorials, more examples and technical details about the client/server/record/parser architecture.

### Querying a WHOIS

<tt>Whois</tt> provides the ability to get WHOIS information for TLD, domain names, IPv4 and IPv6 addresses. The client is smart enough to guess the best WHOIS server according to given query, send the request and return the response.

Check out the following examples:

```ruby
# Domain WHOIS
whois = Whois::Client.new
whois.lookup("google.com")
# => #<Whois::Record>

# TLD WHOIS
whois = Whois::Client.new
whois.lookup(".com")
# => #<Whois::Record>

# IPv4 WHOIS
whois = Whois::Client.new
whois.lookup("74.125.67.100")
# => #<Whois::Record>

# IPv6 WHOIS
whois = Whois::Client.new
whois.lookup("2001:db8::1428:57ab")
# => #<Whois::Record>
```

The query method is stateless. For this reason, you can safely re-use the same client instance for multiple queries.

```ruby
whois = Whois::Client.new
whois.lookup("google.com")
whois.lookup(".com")
whois.lookup("74.125.67.100")
whois.lookup("2001:db8::1428:57ab")
whois.lookup("google.it")
```

If you just need a WHOIS response and you don't care about a full control of the WHOIS client, the `Whois` module provides an all-in-one method called `Whois.whois`. This is the simplest way to send a WHOIS request.

```ruby
Whois.whois("google.com")
# => #<Whois::Record>
```

Did I mention you can even use blocks?

```ruby
Whois::Client.new do |w|
  w.lookup("google.com")
  w.lookup(".com")
  w.lookup("74.125.67.100")
  w.lookup("2001:db8::1428:57ab")
  w.lookup("google.it")
end
```

### Consuming the Record

Any WHOIS query returns a `Whois::Record`. This object looks like a String, but it's way more powerful.

`Whois::Record` encapsulates a WHOIS record and provides the ability to parse the WHOIS response programmatically, when the `whois-parser` gem is installed and loaded.

```ruby
require 'whois-parser'

record = Whois.whois("google.it")
# => #<Whois::Record>

parser = record.parser
# => #<Whois::Parser>

parser.available?
# => false
parser.registered?
# => true

parser.created_on
# => Fri Dec 10 00:00:00 +0100 1999

tech = parser.technical_contacts.first
# => #<Whois::Record::Contact>
tech.id
# => "TS7016-ITNIC"
tech.name
# => "Technical Services"

parser.nameservers.each do |nameserver|
  puts nameserver
end
```

This feature is made possible by the <tt>Whois</tt> record parsers. Unfortunately, due to the lack of a global standard, each WHOIS server requires a specific parser. For this reason, the library doesn't support all existing WHOIS servers.

If you create a new parser, please consider releasing it to the public so that it can be included in a next version.

### Timeout

By default, each query run though the client has a timeout value of 5 seconds. If the execution exceeds the timeout limit, the client raises a `Timeout::Error` exception.

Of course, you can customize the timeout value setting a different value. If timeout is `nil`, the client will wait until the response is sent back from the server or the process is killed. Don't disable the timeout unless you really know what you are doing!

```ruby
whois = Whois::Client.new(:timeout => 10)
whois.timeout # => 10
whois.timeout = 5
whois.timeout # => 5

whois.lookup("google.com")
```

## Credits

<tt>Whois</tt> was created and is maintained by [Simone Carletti](https://simonecarletti.com/). Many improvements and bugfixes were contributed by the [open source community](https://github.com/weppos/whois/graphs/contributors).

## Contributing

Direct questions and discussions to [Stack Overflow](https://stackoverflow.com/questions/tagged/whois-ruby).

[Pull requests](https://github.com/weppos/whois/pulls) are very welcome! Please include spec and/or feature coverage for every patch, and create a topic branch for every separate change you make.

Report issues or feature requests to [GitHub Issues](https://github.com/weppos/whois/issues).

## More Information

- [Homepage](http://whoisrb.org/)
- RubyGems: [`whois`](https://rubygems.org/gems/whois) and [`whois-parser`](https://rubygems.org/gems/whois-parser)
- Issues: [`whois`](https://github.com/weppos/whois) and [`whois-parser`](https://github.com/weppos/whois-parser)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/whois-ruby)

## Versioning

<tt>Whois</tt> uses [Semantic Versioning 2.0.0](http://semver.org)

## License

Copyright (c) 2009-2022 [Simone Carletti](https://simonecarletti.com/). This is Free Software distributed under the MIT license.


text:
(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['exports', 'lodash', 'randomstring'], factory);
  } else if (typeof exports !== "undefined") {
    factory(exports, require('lodash'), require('randomstring'));
  } else {
    var mod = {
      exports: {}
    };
    factory(mod.exports, global.lodash, global.randomstring);
    global.copier = mod.exports;
  }
})(this, function (exports, _lodash, _randomstring) {
  'use strict';

  Object.defineProperty(exports, "__esModule", {
    value: true
  });
  exports.copifyReducer = exports.copifyActions = undefined;

  var _randomstring2 = _interopRequireDefault(_randomstring);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
      });
    } else {
      obj[key] = value;
    }

    return obj;
  }

  var _extends = Object.assign || function (target) {
    for (var i = 1; i < arguments.length; i++) {
      var source = arguments[i];

      for (var key in source) {
        if (Object.prototype.hasOwnProperty.call(source, key)) {
          target[key] = source[key];
        }
      }
    }

    return target;
  };

  var DEFAULT_STATE_STORE_KEY = '@@DEFAULT_STATE';

  function generateKey() {
    return _randomstring2.default.generate();
  }
  function copifyActions(actionCreators, customKey) {
    var key = generateKey();
    if (customKey) key = customKey;

    function copifyActionCreator(actionCreator) {
      return function () {
        return _extends({}, actionCreator.apply(undefined, arguments), {
          key: key
        });
      };
    }

    return {
      actionCreators: (0, _lodash.mapValues)(actionCreators, copifyActionCreator),
      // state[key] is undefined at beginning, we need to read the default value
      // once we modify own state, use own state
      // like copy on write in linux
      selector: function selector(state) {
        return state[key] || state[DEFAULT_STATE_STORE_KEY];
      }
    };
  }

  /*
   * separate different state scope using action's key
   */
  function copifyReducer(reducer) {
    return function (state, action) {
      var key = action.key;

      // MAYBE it's redux INIT action when in combineReducers, state is undefined
      // and reducer(state, action) will generate defaultState
      if (key === undefined) {
        /*
         * everytime when combineReducer is called, we receive a INIT action
         * we need the next line, or state will change to shape like
         * {
         *   DEFAULT_STATE_STORE_KEY: {
         *     DEFAULT_STATE_STORE_KEY: {
         *       DEFAULT_STATE_STORE_KEY: {
         *         ...state
         *     }
         *    }
         *   }
         */
        if (!(DEFAULT_STATE_STORE_KEY in (state || {} /* INIT action, state is undefined */))) {
          return _defineProperty({}, DEFAULT_STATE_STORE_KEY, reducer(state, action));
        }
        return state;
      }

      // when encount a key doesn't exist, init scope state for it
      if (!(key in state)) {
        state = _extends({}, state, _defineProperty({}, key, (0, _lodash.cloneDeep)(state[DEFAULT_STATE_STORE_KEY])));
      }
      return _extends({}, state, _defineProperty({}, key, reducer(state[key], action)));
    };
  }

  exports.copifyActions = copifyActions;
  exports.copifyReducer = copifyReducer;
});


text:
<?php

namespace demo;

use PHPUnit\Framework\TestCase;
use wulaphp\app\App;
use wulaphp\app\ModuleLoader;

/**
 * Class InstallTest
 * @package demo
 * @group   demo
 */
class InstallTest extends TestCase {

    public function testConstant() {
        self::assertEquals(APP_MODE,'test');
        self::assertTrue(defined('APPROOT'));
        self::assertEquals(APPROOT, realpath(__DIR__ . '/../../') . DS);
    }

    public function testModuleLoaded() {
        $loader = App::moduleLoader();
        self::assertTrue($loader instanceof ModuleLoader);
        $module = App::getModule('app');
        self::assertNotNull($module);
    }

    /**
     * @depends testConstant
     * @depends testModuleLoaded
     */
    public function testViewHomePage() {
        $module = App::getModule('app');
        self::assertNotNull($module, 'app module is not loaded');
        @ob_start();
        try {
            App::run('/');
        } catch (\Exception $e) {
        }
        $page = @ob_get_clean();
        self::assertNotEmpty($page);
        self::assertStringContainsString('Hello wula !!', $page);
    }
}


text:
using namespace swift;

/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
/// FIXME: Why don't we strip projections after stripping indexes?
SILValue swift::getUnderlyingObject(SILValue V) {
  while (true) {
    SILValue V2 = stripIndexingInsts(stripAddressProjections(stripCasts(V)));
    if (V2 == V)
      return V2;
    V = V2;
  }
}

static bool isRCIdentityPreservingCast(ValueKind Kind) {
  switch (Kind) {
    case ValueKind::UpcastInst:
    case ValueKind::UncheckedRefCastInst:
    case ValueKind::UncheckedRefCastAddrInst:
    case ValueKind::UnconditionalCheckedCastInst:
    case ValueKind::RefToBridgeObjectInst:
    case ValueKind::BridgeObjectToRefInst:
      return true;
    default:
      return false;
  }
}

/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
SILValue swift::stripSinglePredecessorArgs(SILValue V) {
  while (true) {
    auto *A = dyn_cast<SILArgument>(V);
    if (!A)
      return V;

    SILBasicBlock *BB = A->getParent();

    // First try and grab the single predecessor of our parent BB. If we don't
    // have one, bail.
    SILBasicBlock *Pred = BB->getSinglePredecessor();
    if (!Pred)
      return V;

    // Then grab the terminator of Pred...
    TermInst *PredTI = Pred->getTerminator();

    // And attempt to find our matching argument.
    //
    // *NOTE* We can only strip things here if we know that there is no semantic
    // change in terms of upcasts/downcasts/enum extraction since this is used
    // by other routines here. This means that we can only look through
    // cond_br/br.
    //
    // For instance, routines that use stripUpcasts() do not want to strip off a
    // downcast that results from checked_cast_br.
    if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
      V = BI->getArg(A->getIndex());
      continue;
    }

    if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
      if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
        V = Arg;
        continue;
      }
    }

    return V;
  }
}

SILValue swift::stripCasts(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);

    auto K = V->getKind();
    if (isRCIdentityPreservingCast(K)
        || K == ValueKind::UncheckedTrivialBitCastInst
        || K == ValueKind::MarkDependenceInst) {
      V = cast<SILInstruction>(V)->getOperand(0);
      continue;
    }

    return V;
  }
}

SILValue swift::stripUpCasts(SILValue V) {
  assert(V->getType().isClassOrClassMetatype() &&
         "Expected class or class metatype!");

  V = stripSinglePredecessorArgs(V);

  while (isa<UpcastInst>(V))
    V = stripSinglePredecessorArgs(cast<UpcastInst>(V)->getOperand());

  return V;
}

SILValue swift::stripClassCasts(SILValue V) {
  while (true) {
    if (auto *UI = dyn_cast<UpcastInst>(V)) {
      V = UI->getOperand();
      continue;
    }

    if (auto *UCCI = dyn_cast<UnconditionalCheckedCastInst>(V)) {
      V = UCCI->getOperand();
      continue;
    }

    return V;
  }
}

SILValue swift::stripAddressProjections(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);
    if (!Projection::isAddressProjection(V))
      return V;
    V = cast<SILInstruction>(V)->getOperand(0);
  }
}

SILValue swift::stripUnaryAddressProjections(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);
    if (!Projection::isAddressProjection(V))
      return V;
    auto *Inst = cast<SILInstruction>(V);
    if (Inst->getNumOperands() > 1)
      return V;
    V = Inst->getOperand(0);
  }
}

SILValue swift::stripValueProjections(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);
    if (!Projection::isObjectProjection(V))
      return V;
    V = cast<SILInstruction>(V)->getOperand(0);
  }
}

SILValue swift::stripIndexingInsts(SILValue V) {
  while (true) {
    if (!isa<IndexingInst>(V))
      return V;
    V = cast<IndexingInst>(V)->getBase();
  }
}

SILValue swift::stripExpectIntrinsic(SILValue V) {
  auto *BI = dyn_cast<BuiltinInst>(V);
  if (!BI)
    return V;
  if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::expect)
    return V;
  return BI->getArguments()[0];
}


text:
require 'progressbar'
require 'ostruct'

module Jekyll
  module Algolia
    # Module to push records to Algolia and configure the index
    module ProgressBar
      include Jekyll::Algolia

      def self.should_be_silenced?
        Configurator.verbose?
      end

      def self.create(options)
        if should_be_silenced?
          fake_bar = OpenStruct.new
          fake_bar.increment = nil
          return fake_bar
        end

        ::ProgressBar.create(options)
      end
    end
  end
end


text:
namespace AVDump3Lib.Processing.BlockConsumers.Ogg.BitStreams;

public abstract class SubtitleOGGBitStream : OGGBitStream {
	public SubtitleOGGBitStream(bool isOfficiallySupported) : base(isOfficiallySupported) { }
}


text:
module PactBroker
  module Pacts
    module PactPublicationWipDatasetModule
      def successfully_verified_by_provider_branch_when_not_wip(provider_id, provider_version_branch)
        from_self(alias: :pp)
          .select(Sequel[:pp].*)
          .where(Sequel[:pp][:provider_id] => provider_id)
          .join_successful_non_wip_verifications_for_provider_id(provider_id)
          .join_provider_versions_for_provider_id_and_branch(provider_id, provider_version_branch)
          .distinct
      end

      def successfully_verified_by_provider_another_branch_before_this_branch_first_created(provider_id, provider_version_branch)
        first_version_for_branch = PactBroker::Domain::Version.first_for_pacticipant_id_and_branch(provider_id, provider_version_branch)

        from_self(alias: :pp)
          .select(Sequel[:pp].*)
          .join_successful_non_wip_verifications_for_provider_id(provider_id)
          .join_provider_versions_for_provider_id(provider_id)
          .join_branch_versions_excluding_branch(provider_version_branch)
          .where(Sequel[:pp][:provider_id] => provider_id)
          .verified_before_creation_date_of(first_version_for_branch)
          .distinct
      end

      def join_branch_versions_excluding_branch(branch_name)
        branch_versions_join = {
          Sequel[:provider_versions][:id] => Sequel[:branch_versions][:version_id]
        }
        join(:branch_versions, branch_versions_join) do
          Sequel.lit("branch_versions.branch_name != ?", branch_name)
        end
      end

      def successfully_verified_by_provider_tag_when_not_wip(provider_tag)
        pact_version_provider_tag_verifications_join = {
          Sequel[:sv][:pact_version_id] => Sequel[:pp][:pact_version_id],
          Sequel[:sv][:provider_version_tag_name] => provider_tag,
          Sequel[:sv][:wip] => false
        }

        from_self(alias: :pp)
          .select(Sequel[:pp].*)
          .join(:pact_version_provider_tag_successful_verifications, pact_version_provider_tag_verifications_join, { table_alias: :sv })
          .distinct

      end

      def successfully_verified_by_provider_another_tag_before_this_tag_first_created(provider_id, provider_tag)
        first_tag_with_name = PactBroker::Domain::Tag.where(pacticipant_id: provider_id, name: provider_tag).order(:created_at).first

        pact_version_provider_tag_verifications_join = {
          Sequel[:sv][:pact_version_id] => Sequel[:pp][:pact_version_id],
          Sequel[:sv][:wip] => false
        }

        created_at_criteria = if first_tag_with_name
                                Sequel.lit("sv.execution_date < ?", first_tag_with_name.created_at)
                              else
                                Sequel.lit("1 = 1")
                              end

        from_self(alias: :pp)
          .select(Sequel[:pp].*)
          .where(Sequel[:pp][:provider_id] => provider_id)
          .join(:pact_version_provider_tag_successful_verifications, pact_version_provider_tag_verifications_join, { table_alias: :sv }) do
            Sequel.&(
              Sequel.lit("sv.provider_version_tag_name NOT IN (?)", provider_tag),
              created_at_criteria
            )
          end
          .distinct
      end

      protected

      def verified_before_date(date)
        where { Sequel[:verifications][:execution_date] < date }
      end

      def join_successful_non_wip_verifications_for_provider_id(provider_id, &block)
        verifications_join = {
          pact_version_id: :pact_version_id,
          Sequel[:verifications][:success] => true,
          Sequel[:verifications][:wip] => false,
          Sequel[:verifications][:provider_id] => provider_id
        }
        join(:verifications, verifications_join, {}, &block)
      end

      def join_provider_version_tags &block
        tags_join = {
          Sequel[:verifications][:provider_version_id] => Sequel[:provider_tags][:version_id],
        }
        join(:tags, tags_join, { table_alias: :provider_tags }, &block)
      end

      def join_provider_version_tags_for_tag(tag)
        tags_join = {
          Sequel[:verifications][:provider_version_id] => Sequel[:provider_tags][:version_id],
          Sequel[:provider_tags][:name] => tag
        }
        join(:tags, tags_join, { table_alias: :provider_tags } )
      end

      def join_provider_versions_for_provider_id_and_branch(provider_id, provider_version_branch)
        versions_join = {
          Sequel[:verifications][:provider_version_id] => Sequel[:provider_versions][:id],
          Sequel[:provider_versions][:pacticipant_id] => provider_id
        }
        branch_versions_join = {
          Sequel[:provider_versions][:id] => Sequel[:branch_versions][:version_id],
          Sequel[:branch_versions][:branch_name] => provider_version_branch
        }
        join(:versions, versions_join, { table_alias: :provider_versions } )
          .join(:branch_versions, branch_versions_join)
      end

      def join_provider_versions_for_provider_id(provider_id, &block)
        versions_join = {
          Sequel[:verifications][:provider_version_id] => Sequel[:provider_versions][:id],
          Sequel[:provider_versions][:pacticipant_id] => provider_id
        }
        join(:versions, versions_join, { table_alias: :provider_versions }, &block)
      end

      def verified_before_creation_date_of(record)
        if record
          verified_before_date(record.created_at)
        else
          self
        end
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Mmoreram\SimpleDoctrineMapping\CompilerPass\Abstracts;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

use Mmoreram\SimpleDoctrineMapping\DataObject\EntityMapping;
use Mmoreram\SimpleDoctrineMapping\Exception\ConfigurationInvalidException;
use Mmoreram\SimpleDoctrineMapping\Exception\EntityManagerNotFoundException;
use Mmoreram\SimpleDoctrineMapping\Exception\MappingExtensionWithoutDriverException;

/**
 * Class MappingCompilerPass.
 */
abstract class AbstractMappingCompilerPass implements CompilerPassInterface
{
    /**
     * Add mapping entity.
     *
     * This method adds a new Driver into global MappingDriverChain with single
     * entity mapping information.
     *
     * $entityManagerName must be an existing entityManager. By default doctrine
     * creates just one common EntityManager called default, but many can be
     * defined with different connection information
     *
     * p.e. default
     * p.e. anotherEntityManager
     *
     * $entityNamespace must be an existing namespace of Entity. This value also
     * can be a valid and existing container parameter, with an existing
     * namespace of Entity as value.
     *
     * p.e. MyBundle\Entity\User
     * p.e. mybundle.entity.user.class
     *
     * $entityMappingFilePath must be a path of an existing yml or xml file with
     * mapping information about $entityNamespace. This bundle uses Short Bundle
     * notation, with "@" symbol. This value also can be a valid and existing
     * container parameter, with a path of an existing yml or xml file as value.
     *
     * p.e. @MyBundle/Resources/config/doctrine/User.orm.yml
     * p.e. @MyBundle/Resources/config/doctrine/User.orm.xml
     * p.e. mybundle.entity.user.mapping_file_path
     *
     * Finally, $enable flag just allow you to add current mapping definition
     * into all Doctrine Map table, or just dismiss it. This is useful when you
     * want to give possibility to final user to enable or disable a mapping
     * class.
     *
     * @param ContainerBuilder $container             Container
     * @param string           $entityManagerName     EntityManager name
     * @param string           $entityNamespace       Entity namespace
     * @param string           $entityMappingFilePath Entity Mapping file path
     * @param bool|string      $enable                Entity mapping must be included
     *
     * @return AbstractMappingCompilerPass
     *
     * @throws EntityManagerNotFoundException Entity Manager nod found
     */
    protected function addEntityMapping(
        ContainerBuilder $container,
        $entityManagerName,
        $entityNamespace,
        $entityMappingFilePath,
        $enable = true
    ) : self {
        $entityMapping = $this->resolveEntityMapping(
            $container,
            $entityManagerName,
            $entityNamespace,
            $entityMappingFilePath,
            $enable
        );

        if ($entityMapping instanceof EntityMapping) {
            $this->registerLocatorConfigurator($container);
            $this->registerLocator($container, $entityMapping);
            $this->registerDriver($container, $entityMapping);
            $this->addDriverInDriverChain($container, $entityMapping);
            $this->addAliases($container, $entityMapping);
        }

        return $this;
    }

    /**
     * Resolve EntityMapping inputs and build a consistent EntityMapping object.
     *
     * This method returns null if the current entity has not been added
     *
     * @param ContainerBuilder $container
     * @param string           $entityManagerName
     * @param string           $entityNamespace
     * @param string           $entityMappingFilePath
     * @param string|bool      $enable
     *
     * @return EntityMapping|null
     *
     * @throws ConfigurationInvalidException  Configuration invalid
     * @throws EntityManagerNotFoundException Entity Manager not found
     */
    private function resolveEntityMapping(
        ContainerBuilder $container,
        string $entityManagerName,
        string $entityNamespace,
        string $entityMappingFilePath,
        $enable = true
    ) : ? EntityMapping {
        $enableEntityMapping = $this->resolveParameterName(
            $container,
            $enable
        );

        if (false === $enableEntityMapping) {
            return null;
        }

        $entityNamespace = $this->resolveParameterName($container, $entityNamespace);

        if (!class_exists($entityNamespace)) {
            throw new ConfigurationInvalidException('Entity ' . $entityNamespace . ' not found');
        }

        $entityMappingFilePath = $this->resolveParameterName($container, $entityMappingFilePath);
        $entityManagerName = $this->resolveParameterName($container, $entityManagerName);
        $this->resolveEntityManagerName($container, $entityManagerName);

        return new EntityMapping(
            $entityNamespace,
            $entityMappingFilePath,
            $entityManagerName
        );
    }

    /**
     * Register locator configurator.
     *
     * @param ContainerBuilder $container
     */
    private function registerLocatorConfigurator(ContainerBuilder $container)
    {
        $locatorConfiguratorId = 'simple_doctrine_mapping.locator_configurator';
        if ($container->hasDefinition($locatorConfiguratorId)) {
            return;
        }

        $locatorConfigurator = new Definition('Mmoreram\SimpleDoctrineMapping\Configurator\LocatorConfigurator');
        $locatorConfigurator->setPublic(true);
        $locatorConfigurator->setArguments([
            new Reference('kernel'),
        ]);

        $container->setDefinition($locatorConfiguratorId, $locatorConfigurator);
    }

    /**
     * Register the locator.
     *
     * @param ContainerBuilder $container
     * @param EntityMapping    $entityMapping
     */
    private function registerLocator(
        ContainerBuilder $container,
        EntityMapping $entityMapping
    ) {
        /**
         * Locator.
         */
        $locatorId = 'simple_doctrine_mapping.locator.' . $entityMapping->getUniqueIdentifier();
        $locator = new Definition('Mmoreram\SimpleDoctrineMapping\Locator\SimpleDoctrineMappingLocator');
        $locator->setPublic(false);
        $locator->setArguments([
            $entityMapping->getEntityNamespace(),
            [$entityMapping->getEntityMappingFilePath()],
        ]);
        $locator->setConfigurator([
            new Reference('simple_doctrine_mapping.locator_configurator'),
            'configure',
        ]);
        $container->setDefinition($locatorId, $locator);
    }

    /**
     * Register the driver.
     *
     * @param ContainerBuilder $container
     * @param EntityMapping    $entityMapping
     */
    private function registerDriver(
        ContainerBuilder $container,
        EntityMapping $entityMapping
    ) {
        /**
         * Specific extension Driver definition.
         */
        $mappingDriverId = 'doctrine.orm.' . $entityMapping->getUniqueIdentifier() . '_metadata_driver';
        $mappingDriverDefinition = new Definition($this->getDriverNamespaceGivenEntityMapping($entityMapping));
        $mappingDriverDefinition->setPublic(false);
        $mappingDriverDefinition->setArguments([
            new Reference('simple_doctrine_mapping.locator.' . $entityMapping->getUniqueIdentifier()),
        ]);
        $mappingDriverDefinition->addMethodCall('setGlobalBasename', [
            $entityMapping->getEntityNamespace(),
        ]);
        $container->setDefinition($mappingDriverId, $mappingDriverDefinition);
    }

    /**
     * Register and override the DriverChain definition.
     *
     * @param ContainerBuilder $container
     * @param EntityMapping    $entityMapping
     *
     * @throws EntityManagerNotFoundException Entity Manager nod found
     */
    private function addDriverInDriverChain(
        ContainerBuilder $container,
        EntityMapping $entityMapping
    ) {
        $chainDriverDefinition = $container
            ->getDefinition(
                'doctrine.orm.' . $entityMapping->getEntityManagerName() . '_metadata_driver'
            );

        $container->setParameter(
            'doctrine.orm.metadata.driver_chain.class',
            'Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain'
        );

        $chainDriverDefinition->addMethodCall('addDriver', [
            new Reference(
                'doctrine.orm.' . $entityMapping->getUniqueIdentifier() . '_metadata_driver'
            ),
            $entityMapping->getEntityNamespace(),
        ]);
    }

    /**
     * Add aliases for short Doctrine accessing mode.
     *
     * This method will make a vitual association between the bundle proposing
     * the entity and the entity namespace, even if both elements are in
     * different packages (Bundle + Component).
     *
     * Only useful and working when the relation between a bundle and the entity
     * folder path [[ Bundle (*) => (1) Entity path ]]
     *
     * @param ContainerBuilder $container
     * @param EntityMapping    $entityMapping
     */
    private function addAliases(
        ContainerBuilder $container,
        EntityMapping $entityMapping
    ) {
        $entityMappingFilePath = $entityMapping->getEntityMappingFilePath();
        if (strpos($entityMappingFilePath, '@') === 0) {
            $bundleName = trim(explode('/', $entityMappingFilePath, 2)[0]);
            $className = explode('\\', $entityMapping->getEntityNamespace());
            unset($className[count($className) - 1]);
            $configurationServiceDefinition = $container
                ->getDefinition(
                    'doctrine.orm.' . $entityMapping->getEntityManagerName() . '_configuration'
                );

            $configurationServiceDefinition->addMethodCall('addEntityNamespace', [
                $bundleName,
                implode('\\', $className),
            ]);
        }
    }

    /**
     * Resolvers.
     */

    /**
     * Return value of parameter name if exists
     * Return itself otherwise.
     *
     * @param ContainerBuilder $container
     * @param mixed            $parameterName
     *
     * @return mixed
     */
    private function resolveParameterName(
        ContainerBuilder $container,
        $parameterName
    ) {
        if (!is_string($parameterName)) {
            return $parameterName;
        }

        return $container->hasParameter($parameterName)
            ? $container->getParameter($parameterName)
            : $parameterName;
    }

    /**
     * Throws an exception if given entityName is not available or does
     * not exist.
     *
     * @param ContainerBuilder $container
     * @param string           $entityManagerName
     *
     * @throws EntityManagerNotFoundException Entity manager not found
     */
    private function resolveEntityManagerName(
        ContainerBuilder $container,
        string $entityManagerName
    ) {
        if (!$container->has('doctrine.orm.' . $entityManagerName . '_metadata_driver')) {
            throw new EntityManagerNotFoundException($entityManagerName);
        }
    }

    /**
     * Return the namespace of the driver to use given an EntityMapping.
     *
     * @param EntityMapping $entityMapping
     *
     * @return string
     *
     * @throws MappingExtensionWithoutDriverException Driver not found
     */
    private function getDriverNamespaceGivenEntityMapping(EntityMapping $entityMapping) : string
    {
        $namespace = 'Doctrine\ORM\Mapping\Driver\\';

        switch ($entityMapping->getExtension()) {
            case 'yml':
                $namespace .= 'YamlDriver';
                break;
            case 'yaml':
                $namespace .= 'YamlDriver';
                break;
            case 'xml':
                $namespace .= 'XmlDriver';
                break;
            default:
                throw new MappingExtensionWithoutDriverException($entityMapping->getExtension());
        }

        return $namespace;
    }
}


text:
using System.Runtime.Serialization;

namespace Eciton
{
    /// Ecitonの標準的な関数を表します。
    /// <typeparam name="T">戻り値</typeparam>
    [DataContract]
    public abstract class EcitonFunc<T> : EcitonObject, IEcitonOut<T>
    {
        protected abstract T Implement();

        public T Send() => Implement();
        public override object Eval() => Send();
    }

    /// Ecitonの標準的な関数を表します。
    /// <typeparam name="TArg1">引数</typeparam>
    /// <typeparam name="T">戻り値</typeparam>
    [DataContract]
    public abstract class EcitonFunc<TArg1, T> : EcitonObject, IEcitonOut<T>
    {
        protected abstract T Implement(TArg1 arg1);

        [DataMember]
        protected readonly IEcitonInImpl<TArg1> _arg1 = new EcitonIn<TArg1>();
        public IEcitonIn<TArg1> Arg1 => _arg1;

        public T Send() => Implement(_arg1.Pull());
        public override object Eval() => Send();
    }

    /// Ecitonの標準的な関数を表します。
    /// <typeparam name="TArg1">引数</typeparam>
    /// <typeparam name="TArg2">引数</typeparam>
    /// <typeparam name="T">戻り値</typeparam>
    [DataContract]
    public abstract class EcitonFunc<TArg1, TArg2, T> : EcitonObject, IEcitonOut<T>
    {
        protected abstract T Implement(TArg1 arg1, TArg2 arg2);

        [DataMember]
        protected readonly IEcitonInImpl<TArg1> _arg1 = new EcitonIn<TArg1>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg2> _arg2 = new EcitonIn<TArg2>();
        public IEcitonIn<TArg1> Arg1 => _arg1;
        public IEcitonIn<TArg2> Arg2 => _arg2;

        public T Send() => Implement(_arg1.Pull(), _arg2.Pull());
        public override object Eval() => Send();
    }

    /// Ecitonの標準的な関数を表します。
    /// <typeparam name="TArg1">引数</typeparam>
    /// <typeparam name="TArg2">引数</typeparam>
    /// <typeparam name="TArg3">引数</typeparam>
    /// <typeparam name="T">戻り値</typeparam>
    [DataContract]
    public abstract class EcitonFunc<TArg1, TArg2, TArg3, T> : EcitonObject, IEcitonOut<T>
    {
        protected abstract T Implement(TArg1 arg1, TArg2 arg2, TArg3 arg3);

        [DataMember]
        protected readonly IEcitonInImpl<TArg1> _arg1 = new EcitonIn<TArg1>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg2> _arg2 = new EcitonIn<TArg2>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg3> _arg3 = new EcitonIn<TArg3>();

        public IEcitonIn<TArg1> Arg1 => _arg1;
        public IEcitonIn<TArg2> Arg2 => _arg2;
        public IEcitonIn<TArg3> Arg3 => _arg3;

        public T Send() => Implement(_arg1.Pull(), _arg2.Pull(), _arg3.Pull());
        public override object Eval() => Send();
    }

    /// Ecitonの標準的な関数を表します。
    /// <typeparam name="TArg1">引数</typeparam>
    /// <typeparam name="TArg2">引数</typeparam>
    /// <typeparam name="TArg3">引数</typeparam>
    /// <typeparam name="TArg4">引数</typeparam>
    /// <typeparam name="T">戻り値</typeparam>
    [DataContract]
    public abstract class EcitonFunc<TArg1, TArg2, TArg3, TArg4, T> : EcitonObject, IEcitonOut<T>
    {
        protected abstract T Implement(TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4);

        [DataMember]
        protected readonly IEcitonInImpl<TArg1> _arg1 = new EcitonIn<TArg1>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg2> _arg2 = new EcitonIn<TArg2>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg3> _arg3 = new EcitonIn<TArg3>();
        [DataMember]
        protected readonly IEcitonInImpl<TArg4> _arg4 = new EcitonIn<TArg4>();

        public IEcitonIn<TArg1> Arg1 => _arg1;
        public IEcitonIn<TArg2> Arg2 => _arg2;
        public IEcitonIn<TArg3> Arg3 => _arg3;
        public IEcitonIn<TArg4> Arg4 => _arg4;

        public T Send() => Implement(_arg1.Pull(), _arg2.Pull(), _arg3.Pull(), _arg4.Pull());
        public override object Eval() => Send();
    }

}


text:
Signatures down for maintenance!

Not sure when we want to restore them, as they consume a lot of resources and no-one seems to use them.

Подписи для технического обслуживания!

Не уверен, что, когда мы хотим, чтобы восстановить их, так как они потребляют много ресурсов, и никто, кажется, не использовать их.


text:
"""Inplace operations.
"""
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.util import deprecation

def _inplace_helper(x, i, v, op):
  """Applies an inplace op on (x, i, v).

  op is one of gen_array_ops.alias_inplace_update,
  gen_array_ops.alias_inplace_add, or gen_array_ops.alias_inplace_sub.

  If i is None, x and v must be the same shape. Computes
    x op v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    x[i, :] op v;
  Otherwise, x and v must have the same rank. Computes
    x[i, :] op v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.
    op: alias_inplace_update, alias_inplace_add, or alias_inplace_sub.

  Returns:
    Returns x.

  """
  x = ops.convert_to_tensor(x)
  v = ops.convert_to_tensor(v, x.dtype)
  if i is None:
    # Full tensor.
    return array_ops.reshape(
        op(array_ops.reshape(x, [1, -1]), [0], array_ops.reshape(v, [1, -1])),
        array_ops.shape(x))
  i = math_ops.cast(i, dtypes.int32)
  if i.get_shape().ndims == 0:
    # Single 0-dim update.
    return op(x, array_ops.reshape(i, [1]), array_ops.expand_dims(v, 0))
  return op(x, i, v)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_update, which offers the same functionality '
     'with well-defined read-write semantics.'))
def alias_inplace_update(x, i, v):
  """Applies an inplace update on input x at index i with value v. Aliases x.

  If i is None, x and v must be the same shape. Computes
    x = v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    x[i, :] = v;
  Otherwise, x and v must have the same rank. Computes
    x[i, :] = v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns x.

  """
  return _inplace_helper(x, i, v, gen_array_ops.inplace_update)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_add, which offers the same functionality '
     'with well-defined read-write semantics.'))
def alias_inplace_add(x, i, v):
  """Applies an inplace add on input x at index i with value v. Aliases x.

  If i is None, x and v must be the same shape. Computes
    x += v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    x[i, :] += v;
  Otherwise, x and v must have the same rank. Computes
    x[i, :] += v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns x.

  """
  return _inplace_helper(x, i, v, gen_array_ops.inplace_add)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_sub, which offers the same functionality '
     'with well-defined read-write semantics.'))
def alias_inplace_sub(x, i, v):
  """Applies an inplace sub on input x at index i with value v. Aliases x.

  If i is None, x and v must be the same shape. Computes
    x -= v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    x[i, :] -= v;
  Otherwise, x and v must have the same rank. Computes
    x[i, :] -= v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns x.

  """
  return _inplace_helper(x, i, v, gen_array_ops.inplace_sub)

def empty_like(x, init=None):
  """Returns a non-initialized tensor with the same shape and dtype as x.

  Args:
    x: A Tensor.
    init: Initialize the returned tensor with the default value of
      x.dtype(), if True. Otherwise, do not initialize. Defaults to
      None.

  Returns:
    A tensor y, whose dtype and shape are the same as those of x.
    y is guaranteed not to be an alias of x. Upon return, y may contain
    arbitrary data.

  """
  x = ops.convert_to_tensor(x)
  return gen_array_ops.empty(array_ops.shape(x), x.dtype, init=init)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_update, which offers the same functionality '
     'with well-defined read-write semantics.'))
def inplace_update(x, i, v):
  """Applies an inplace update on input x at index i with value v.

  Note that this function is not actually inplace - it allocates
  a copy of x.  The utility is not avoiding memory copies but rather
  specifying a sparse update.

  If i is None, x and v must be the same shape. Computes
    y = x; y = v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    y = x; y[i, :] = v;
  Otherwise, x and v must have the same rank. Computes
    y = x; y[i, :] = v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns y, which is guaranteed not to be an alias of x.

  """
  return alias_inplace_update(gen_array_ops.deep_copy(x), i, v)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_add, which offers the same functionality '
     'with well-defined read-write semantics.'))
def inplace_add(x, i, v):
  """Applies an inplace add on input x at index i with value v.

  Note that this function is not actually inplace - it allocates
  a copy of x.  The utility is not avoiding memory copies but rather
  specifying a sparse update.

  If i is None, x and v must be the same shape. Computes
    y = x; y += v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    y = x; y[i, :] += v;
  Otherwise, x and v must have the same rank. Computes
    y = x; y[i, :] += v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns y, which is guaranteed not to be an alias of x.

  """
  return alias_inplace_add(gen_array_ops.deep_copy(x), i, v)

@deprecation.deprecated(
    None,
    ('Prefer tf.tensor_scatter_nd_sub, which offers the same functionality '
     'with well-defined read-write semantics.'))
def inplace_sub(x, i, v):
  """Applies an inplace sub on input x at index i with value v.

  Note that this function is not actually inplace - it allocates
  a copy of x.  The utility is not avoiding memory copies but rather
  specifying a sparse update.

  If i is None, x and v must be the same shape. Computes
    y = x; y -= v;
  If i is a scalar, x has a rank 1 higher than v's. Computes
    y = x; y[i, :] -= v;
  Otherwise, x and v must have the same rank. Computes
    y = x; y[i, :] -= v;

  Args:
    x: A Tensor.
    i: None, a scalar or a vector.
    v: A Tensor.

  Returns:
    Returns y, which is guaranteed not to be an alias of x.

  """
  return alias_inplace_sub(gen_array_ops.deep_copy(x), i, v)

empty = gen_array_ops.empty


text:
require 'java'
require 'observer'

java.lang.System.setProperty('org.jpedal.jai', 'true')
require_relative './jars/jpedal_lgpl.jar'

java_import javax.imageio.ImageIO
java_import java.awt.image.BufferedImage
java_import java.awt.Image

java_import org.jpedal.PdfDecoder
java_import org.jpedal.fonts.FontMappings

class AbstractThumbnailGenerator
  include Observable

  def initialize(pdf_filename, output_directory, sizes=[2048, 560], pages=[])
    raise Errno::ENOENT unless File.directory?(output_directory)
    raise ArgumentError if sizes.empty?
    @sizes = sizes.sort.reverse
    @output_directory = output_directory
  end

  def generate_thumbnails!
    raise 'NotImplemented'
  end

end

class JPedalThumbnailGenerator < AbstractThumbnailGenerator
  def initialize(pdf_filename, output_directory, sizes=[2048, 560], pages=[])
    super(pdf_filename, output_directory, sizes, pages)
    @decoder = PdfDecoder.new(true)
    FontMappings.setFontReplacements
    @decoder.openPdfFile(pdf_filename)
    @decoder.setExtractionMode(0, 1.0)
    @decoder.useHiResScreenDisplay(true)
  end

  def generate_thumbnails!
    total_pages = @decoder.getPageCount

    total_pages.times do |i|
      # w = pageData.getCropBoxWidth(pageNo);
      # h = pageData.getCropBoxHeight(pageNo);
      image = @decoder.getPageAsImage(i+1);
      image_w, image_h = image.getWidth, image.getHeight

      @sizes.each do |s|
        scale = s.to_f / image_w.to_f
        bi = BufferedImage.new(s, image_h * scale, image.getType)
        bi.getGraphics.drawImage(image.getScaledInstance(s, image_h * scale, Image::SCALE_SMOOTH), 0, 0, nil)
        ImageIO.write(bi,
                      'png',
                      java.io.File.new(File.join(@output_directory,
                                                 "document_#{s}_#{i+1}.png")))
        changed
        notify_observers(i+1, total_pages * 2, "generating page thumbnails...")
      end
    end
    @decoder.closePdfFile
  end
end

if __FILE__ == $0

  class STDERRProgressReporter
    def update(page, total_pages)
      STDERR.puts "#{page}///#{total_pages}"
    end
  end

  pdftg = JPedalThumbnailGenerator.new(ARGV[0], '/tmp', [560])
  pdftg.add_observer(STDERRProgressReporter.new)
  pdftg.generate_thumbnails!
end


text:
import logging
import optparse
import os.path
import pacoRun
import pacoUtils as pu
import yaml

stepsToRun = [pacoRun.runStage1, pacoRun.runStage2, pacoRun.runStage3]

def main():
    p = optparse.OptionParser(
            usage  ="usage: %prog [options] CONFIG [DIRECTORY]",
            description =   "Execute run with config file."
                            "Optionally, can specify a directory"
                            "(if none given, uses same as config file.)",
            version="%prog 2.0"
            )
    p.add_option('--prefix', '-p',
            help="override prefix with which all intermediate and output files with this prefix.")
    p.add_option('--verbose', '-v', action="store_true", default=False)
    CLIoptions, arguments = p.parse_args()
    if len(arguments) > 2 or len(arguments) < 1:
        p.error("incorrect number of arguments, must specify the config file (and optionally a directory).")

    # set up logging
    logLevel = logging.WARNING
    if CLIoptions.verbose:
        logLevel = logging.DEBUG

    logging.basicConfig(
            level=logLevel,
            format='%(asctime)s. %(levelname)s in %(funcName)s: %(message)s')

    # get first arg: configPath
    configPath = arguments[0]

    # set up paths
    configDir, configBasename = os.path.split(configPath)
    configDir = os.path.abspath(configDir)

    # get second arg: dataDir
    if len(arguments) > 1:
        dataDir = arguments[1]
    else:
        dataDir = configDir
    dataDir = os.path.abspath(dataDir)

    # if not os.path.isdir(dataDir):
    #     msg = "directory not found: %s" % dataDir
    #     logging.error(msg)
    #     return -1

    pu.ensurePath(dataDir)

    # now, read config
    # if the file does not end with yaml, warn
    fileExtension = os.path.splitext(configBasename)[1]
    if fileExtension != ".yaml":
        logging.warn("config file does not end with .yaml: %s", configPath)

    msg = "Executing config file %s" % configPath
    print(msg)
    logging.info(msg)

    with open(configPath, 'r') as f:
        params = yaml.load(f)

    # print(params)

    # add/override options in params (prefix, dataDir, etc.)
    params['Config']['verbose'] = CLIoptions.verbose
    if CLIoptions.prefix is None:
        if 'Prefix_Default' in params['Config']:
            params['Config']['Prefix'] = params['Config']['Prefix_Default']
        else:
            logging.error("No prefix provided, and no Prefix_Default in config file.")
            return -1
    else:
        if 'Prefix_Default' in params['Config']:
            msg = "Prefix provided (%s) used instead of Prefix_Default (%s)" % (
                CLIoptions.prefix, params['Config']['Prefix_Default']
            )
            print(msg)
            logging.warn(msg)
        params['Config']['Prefix'] = CLIoptions.prefix

    # record directories
    pacoRootDir = os.path.abspath(os.path.dirname(pacoRun.__file__))
    params['Config']['DirData'] = dataDir
    params['Config']['DirCurrent'] = os.getcwd()
    params['Config']['DirConfig'] = configDir
    params['Config']['DirPacoRoot'] = pacoRootDir
    params['Config']['DirPacoBin'] = os.path.abspath(os.path.join(pacoRootDir, '..', 'src'))

    # what about stokes.edp?    # deal with in runStage1

    # dump actually used params to new location
    pu.ensurePath(dataDir)
    if not configBasename.startswith(params['Config']['Prefix']):
        configBasename_new = params['Config']['Prefix'] + "s0_" + configBasename
    else:
        configBasename_new = configBasename
    with open(os.path.join(dataDir, configBasename_new), "w") as f:
        yaml.dump(params, f)

    runStages(params)
    logging.shutdown()

def runStages(params):
    # Now run the stuff:
    for func in stepsToRun:
        fname = func.func_name
        if fname in params:
            msg = "Executing %s." % fname
            print(msg)
            logging.info(msg)
            func(params)

if __name__ == '__main__':
    main()


text:
from setuptools import setup, find_packages

requires = [
    'pyramid',
    'SQLAlchemy',
    'transaction',
    'pyramid_tm',
    'pyramid_debugtoolbar',
    'pyramid_celery',
    'zope.sqlalchemy',
    'redis',
    'psycopg2'
]

setup(name='long_running_with_tm',
      version='0.0',
      description='long_running_with_tm',
      long_description="",
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pylons",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='web wsgi bfg pylons pyramid',
      packages=find_packages(),
      include_package_data=True,
      zip_safe=False,
      test_suite='long_running_with_tm',
      install_requires = requires,
      entry_points = """\
      [paste.app_factory]
      main = long_running_with_tm:main
      [console_scripts]
      populate_long_running_with_tm = long_running_with_tm.scripts.populate:main
      """,
      )


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

<title>StreamingRepairTask (apache-cassandra API)</title>
<meta name="date" content="2016-06-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.repair

Class StreamingRepairTask

java.lang.Object

org.apache.cassandra.repair.StreamingRepairTask

All Implemented Interfaces:

com.google.common.util.concurrent.FutureCallback<StreamState>, java.lang.Runnable, StreamEventHandler

public class StreamingRepairTask
extends java.lang.Object
implements java.lang.Runnable, StreamEventHandler

StreamingRepairTask performs data streaming between two remote replica which neither is not repair coordinator.
 Task will send SyncComplete message back to coordinator upon streaming completion.

Constructor Summary

Constructors

Constructor and Description

StreamingRepairTask(RepairJobDesc desc,
                   SyncRequest request,
                   long repairedAt)

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
handleStreamEvent(StreamEvent event)

Callback for various streaming events.

void
onFailure(java.lang.Throwable t)

If we failed on either stream in or out, reply fail to coordinator

void
onSuccess(StreamState state)

If we succeeded on both stream in and out, reply back to coordinator

void
run()

Methods inherited from class java.lang.Object

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

Constructor Detail

StreamingRepairTask

public StreamingRepairTask(RepairJobDesc desc,
                           SyncRequest request,
                           long repairedAt)

Method Detail

run

public void run()

Specified by:

run in interface java.lang.Runnable

handleStreamEvent

public void handleStreamEvent(StreamEvent event)

Description copied from interface: StreamEventHandler

Callback for various streaming events.

Specified by:

handleStreamEvent in interface StreamEventHandler

Parameters:

event - Stream event.

See Also:

StreamEvent.Type

onSuccess

public void onSuccess(StreamState state)

If we succeeded on both stream in and out, reply back to coordinator

Specified by:

onSuccess in interface com.google.common.util.concurrent.FutureCallback<StreamState>

onFailure

public void onFailure(java.lang.Throwable t)

If we failed on either stream in or out, reply fail to coordinator

Specified by:

onFailure in interface com.google.common.util.concurrent.FutureCallback<StreamState>

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
/*
Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections.
The path does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.
*/

'use strict'

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
const maxPathSum = function(root) {
  const maxPathSumRec = function(node) {
    if (node === null) {
      return [-Infinity, -Infinity]
    }

    if ((node.left === null) && (node.right === null)) {
      return [node.val, node.val]
    }

    const l = maxPathSumRec(node.left)
    const r = maxPathSumRec(node.right)

    const open = Math.max(node.val, Math.max(node.val + l[0], node.val + r[0]))
    const closed = Math.max(Math.max(l[1], r[1]), Math.max(node.val + l[0] + r[0], open))

    return [open, closed]
  }

  return maxPathSumRec(root)[1]
}


text:
package leap.db.change;

import leap.db.model.DbIndex;
import leap.db.model.DbTable;

public interface IndexChange extends SchemaChange {

	DbTable getTable();

	DbIndex getOldIndex();

	DbIndex getNewIndex();

}


text:
		<title>SP - Peak detection - Mass detection</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<link rel="stylesheet" type="text/css" href="/net/sf/mzmine/desktop/impl/helpsystem/HelpStyles.css">

Mass detection

Description

The Mass detection module generates a list of masses (ions) for a scan.
Several algorithms are provided for this step.
The choice of the optimal algorithm depends on the raw data characteristics (mass resolution, mass precision, peak shape, noise).
In case the raw data is already centroided, only one algorithm (Centroid mass detector) can be used.
Other algorithms work only with continuous type data.
A mass detection is needed for other processing steps.

Method parameters

Mass detector

Algorithm to use for mass detection and its parameters

Display results

If enabled, the result will be displayed in the spectrum plot. If this is the last module in the processing list, the results will be displayed in any way.

Dataset color

Select the color, the results of this module shall be displayed in.


text:
@interface FunkyNSDictionaryPrefixUtilitiesTests : XCTestCase

@end

@implementation FunkyNSDictionaryPrefixUtilitiesTests
{
    NSDictionary* dictionary;
}

- (void)setUp {
    [super setUp];
    dictionary = @{@0: @"0", @1: @"1", @2: @"2", @3: @"3"};
    mockedDictionaryUtils = OCMPartialMock([FunkyDictionaryUtilities utilitiesWithObject:dictionary]);
}

- (void)tearDown {
    mockedDictionaryUtils = nil;
    [super tearDown];
}

- (void)test_all_callsUtilitiesClass
{
    [dictionary funky_all:^BOOL(id key, id item) {
        return item != nil;
    }];
    OCMVerify([mockedDictionaryUtils all:[OCMArg any]]);
}

- (void)test_none_callsUtilitiesClass
{
    [dictionary funky_none:^BOOL(id key, id item) {
        return item != nil;
    }];
    OCMVerify([mockedDictionaryUtils none:[OCMArg any]]);
}

- (void)test_contains_callsUtilitiesClass
{
    [dictionary funky_contains:^BOOL(id key, id item) {
        return item != nil;
    }];
    OCMVerify([mockedDictionaryUtils contains:[OCMArg any]]);
}

- (void)test_count_callsUtilitiesClass
{
    [dictionary funky_count:^BOOL(id key, id item) {
        return item != nil;
    }];
    OCMVerify([mockedDictionaryUtils count:[OCMArg any]]);
}

- (void)test_map_callsUtilitiesClass
{
    [dictionary funky_map:^FunkyPair*(id key, id item) {
        return [FunkyPair pairWithKey:key value:item];
    }];
    OCMVerify([mockedDictionaryUtils map:[OCMArg any]]);
}

- (void)test_nilTolerantMap_callsUtilitiesClass
{
    [dictionary funky_nilTolerantMap:^FunkyPair*(id key, id item) {
        return [FunkyPair pairWithKey:key value:item];
    }];
    OCMVerify([mockedDictionaryUtils nilTolerantMap:[OCMArg any]]);
}

- (void)test_filtered_callsUtilitiesClass
{
    [dictionary funky_filtered:^BOOL(id key, id item) {
        return item != nil;
    }];
    OCMVerify([mockedDictionaryUtils filtered:[OCMArg any]]);
}

- (void)test_reduce_callsUtilitiesClass
{
    [dictionary funky_reduce:^id(id previousValue, id key, id item) {
        return 0;
    } withInitialValue:@0];
    OCMVerify([mockedDictionaryUtils reduce:[OCMArg any] withInitialValue:[OCMArg any]]);
}

- (void)test_merged_callsUtilitiesClass
{
    [dictionary funky_merged:@{@5: @"5", @6: @"6"}];
    OCMVerify([mockedDictionaryUtils merged:[OCMArg any]]);
}

- (void)test_forEach_callsUtilitiesClass
{
    [dictionary funky_forEach:^(id key, id item) {
    }];
    OCMVerify([mockedDictionaryUtils forEach:[OCMArg any]]);
}

- (void)test_invertedObjectsAndKeys_callsUtilitiesClass
{
    [dictionary funky_invertedObjectsAndKeys];
    OCMVerify([mockedDictionaryUtils invertedObjectsAndKeys]);
}

- (void)test_keys_callsUtilitiesClass
{
    [dictionary funky_keys:^BOOL(id key, id value) {
        return YES;
    }];
    OCMVerify([mockedDictionaryUtils keys:[OCMArg any]]);
}

- (void)test_values_callsUtilitiesClass
{
    [dictionary funky_values:^BOOL(id key, id value) {
        return YES;
    }];
    OCMVerify([mockedDictionaryUtils values:[OCMArg any]]);
}

@end


text:
 * Check the year as well, because at the end of the year we may have a mismatch
 * Add this `HISTORY.md` file

##v0.1.4
 * The schedule is based on Japan time, later we can give you an option to pass in your own timezone


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

<title>¸ÅÀÀÁбí</title>
<meta name="date" content="2014-04-06">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

ËùÓÐÀà

³ÌÐò°ü

westion.www.action

westion.www.admin.action

westion.www.dao

westion.www.dao.impl

westion.www.entity

westion.www.exception

westion.www.filter

westion.www.listener

westion.www.service

westion.www.service.impl

westion.www.servlet

westion.www.test

westion.www.utls