text:
<html>
<head>
  <title>JavaScript: Good Pratices - this in Object Scope</title>
  <script type="text/javascript" src="scripts/this-object-scope.js"></script>
</head>
<body>
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
var start = Date.now();

var server = require('./create-server')(3072, true);

setTimeout(function () {
	var runner = require('./test-runner');

	runner
		.then(function () {
			var end = Date.now();
			console.log('');
			console.log('Launched server, loaded babel, plus:');
			console.log(runner.count + ' children forked and loaded two transpiled dependencies each in ' + (end - start) + 'ms.');
			server.close();
		});
});


text:
#include <aws/privatenetworks/model/GetNetworkResourceRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::PrivateNetworks::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetNetworkResourceRequest::GetNetworkResourceRequest() :
    m_networkResourceArnHasBeenSet(false)
{
}

Aws::String GetNetworkResourceRequest::SerializePayload() const
{
  return {};
}


text:
using DragonSpark.Diagnostics;
using DragonSpark.Diagnostics.Configurations;
using PostSharp.Patterns.Contracts;
using Serilog;
using Serilog.Configuration;
using Serilog.Events;

namespace DragonSpark.Windows.Diagnostics
{
	public class AddConsoleSinkCommand : AddSinkCommand
	{
		public AddConsoleSinkCommand() : this( Defaults.Template, LogEventLevel.Verbose ) {}

		public AddConsoleSinkCommand( [NotEmpty]string outputTemplate, LogEventLevel restrictedToMinimumLevel ) : base( restrictedToMinimumLevel )
		{
			OutputTemplate = outputTemplate;
		}

		[NotEmpty]
		public string OutputTemplate { [return: NotEmpty]get; set; }

		protected override void Configure( LoggerSinkConfiguration configuration )
			=> configuration.ColoredConsole( RestrictedToMinimumLevel, OutputTemplate, FormatProvider );
	}
}


text:
/*
Package validator implements value validations for structs and individual fields
based on tags.

It can also handle Cross-Field and Cross-Struct validation for nested structs
and has the ability to dive into arrays and maps of any type.

see more examples https://github.com/go-playground/validator/tree/master/_examples

Validation Functions Return Type error

Doing things this way is actually the way the standard library does, see the
file.Open method here:

	https://golang.org/pkg/os/#Open.

The authors return type "error" to avoid the issue discussed in the following,
where err is always != nil:

	http://stackoverflow.com/a/29138676/3158232
	https://github.com/go-playground/validator/issues/134

Validator only InvalidValidationError for bad validation input, nil or
ValidationErrors as type error; so, in your code all you need to do is check
if the error returned is not nil, and if it's not check if error is
InvalidValidationError ( if necessary, most of the time it isn't ) type cast
it to type ValidationErrors like so err.(validator.ValidationErrors).

Custom Validation Functions

Custom Validation functions can be added. Example:

	// Structure
	func customFunc(fl validator.FieldLevel) bool {

		if fl.Field().String() == "invalid" {
			return false
		}

		return true
	}

	validate.RegisterValidation("custom tag name", customFunc)
	// NOTES: using the same tag name as an existing function
	//        will overwrite the existing one

Cross-Field Validation

Cross-Field Validation can be done via the following tags:
	- eqfield
	- nefield
	- gtfield
	- gtefield
	- ltfield
	- ltefield
	- eqcsfield
	- necsfield
	- gtcsfield
	- gtecsfield
	- ltcsfield
	- ltecsfield

If, however, some custom cross-field validation is required, it can be done
using a custom validation.

Why not just have cross-fields validation tags (i.e. only eqcsfield and not
eqfield)?

The reason is efficiency. If you want to check a field within the same struct
"eqfield" only has to find the field on the same struct (1 level). But, if we
used "eqcsfield" it could be multiple levels down. Example:

	type Inner struct {
		StartDate time.Time
	}

	type Outer struct {
		InnerStructField *Inner
		CreatedAt time.Time      `validate:"ltecsfield=InnerStructField.StartDate"`
	}

	now := time.Now()

	inner := &Inner{
		StartDate: now,
	}

	outer := &Outer{
		InnerStructField: inner,
		CreatedAt: now,
	}

	errs := validate.Struct(outer)

	// NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
	//       into the function
	//       when calling validate.VarWithValue(val, field, tag) val will be
	//       whatever you pass, struct, field...
	//       when calling validate.Field(field, tag) val will be nil

Multiple Validators

Multiple validators on a field will process in the order defined. Example:

	type Test struct {
		Field `validate:"max=10,min=1"`
	}

	// max will be checked then min

Bad Validator definitions are not handled by the library. Example:

	type Test struct {
		Field `validate:"min=10,max=0"`
	}

	// this definition of min max will never succeed

Using Validator Tags

Baked In Cross-Field validation only compares fields on the same struct.
If Cross-Field + Cross-Struct validation is needed you should implement your
own custom validator.

Comma (",") is the default separator of validation tags. If you wish to
have a comma included within the parameter (i.e. excludesall=,) you will need to
use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
so the above will become excludesall=0x2C.

	type Test struct {
		Field `validate:"excludesall=,"`    // BAD! Do not include a comma.
		Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
	}

Pipe ("|") is the 'or' validation tags deparator. If you wish to
have a pipe included within the parameter i.e. excludesall=| you will need to
use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
so the above will become excludesall=0x7C

	type Test struct {
		Field `validate:"excludesall=|"`    // BAD! Do not include a a pipe!
		Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
	}

Baked In Validators and Tags

Here is a list of the current built in validators:

Skip Field

Tells the validation to skip this struct field; this is particularly
handy in ignoring embedded structs from being validated. (Usage: -)
	Usage: -

Or Operator

This is the 'or' operator allowing multiple validators to be used and
accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba
colors to be accepted. This can also be combined with 'and' for example
( Usage: omitempty,rgb|rgba)

	Usage: |

StructOnly

When a field that is a nested struct is encountered, and contains this flag
any validation on the nested struct will be run, but none of the nested
struct fields will be validated. This is useful if inside of your program
you know the struct will be valid, but need to verify it has been assigned.
NOTE: only "required" and "omitempty" can be used on a struct itself.

	Usage: structonly

NoStructLevel

Same as structonly tag except that any struct level validations will not run.

	Usage: nostructlevel

Omit Empty

Allows conditional validation, for example if a field is not set with
a value (Determined by the "required" validator) then other validation
such as min or max won't run, but if a value is set validation will run.

	Usage: omitempty

Dive

This tells the validator to dive into a slice, array or map and validate that
level of the slice, array or map with the validation tags that follow.
Multidimensional nesting is also supported, each level you wish to dive will
require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
the Keys & EndKeys section just below.

	Usage: dive

Example #1

	[][]string with validation tag "gt=0,dive,len=1,dive,required"
	// gt=0 will be applied to []
	// len=1 will be applied to []string
	// required will be applied to string

Example #2

	[][]string with validation tag "gt=0,dive,dive,required"
	// gt=0 will be applied to []
	// []string will be spared validation
	// required will be applied to string

Keys & EndKeys

These are to be used together directly after the dive tag and tells the validator
that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
values; think of it like the 'dive' tag, but for map keys instead of values.
Multidimensional nesting is also supported, each level you wish to validate will
require another 'keys' and 'endkeys' tag. These tags are only valid for maps.

	Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags

Example #1

	map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required"
	// gt=0 will be applied to the map itself
	// eg=1|eq=2 will be applied to the map keys
	// required will be applied to map values

Example #2

	map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
	// gt=0 will be applied to the map itself
	// eg=1|eq=2 will be applied to each array element in the the map keys
	// required will be applied to map values

Required

This validates that the value is not the data types default zero value.
For numbers ensures value is not zero. For strings ensures value is
not "". For slices, maps, pointers, interfaces, channels and functions
ensures the value is not nil.

	Usage: required

Required If

The field under validation must be present and not empty only if all
the other specified fields are equal to the value following the specified
field. For strings ensures value is not "". For slices, maps, pointers,
interfaces, channels and functions ensures the value is not nil.

	Usage: required_if

Examples:

	// require the field if the Field1 is equal to the parameter given:
	Usage: required_if=Field1 foobar

	// require the field if the Field1 and Field2 is equal to the value respectively:
	Usage: required_if=Field1 foo Field2 bar

Required Unless

The field under validation must be present and not empty unless all
the other specified fields are equal to the value following the specified
field. For strings ensures value is not "". For slices, maps, pointers,
interfaces, channels and functions ensures the value is not nil.

	Usage: required_unless

Examples:

	// require the field unless the Field1 is equal to the parameter given:
	Usage: required_unless=Field1 foobar

	// require the field unless the Field1 and Field2 is equal to the value respectively:
	Usage: required_unless=Field1 foo Field2 bar

Required With

The field under validation must be present and not empty only if any
of the other specified fields are present. For strings ensures value is
not "". For slices, maps, pointers, interfaces, channels and functions
ensures the value is not nil.

	Usage: required_with

Examples:

	// require the field if the Field1 is present:
	Usage: required_with=Field1

	// require the field if the Field1 or Field2 is present:
	Usage: required_with=Field1 Field2

Required With All

The field under validation must be present and not empty only if all
of the other specified fields are present. For strings ensures value is
not "". For slices, maps, pointers, interfaces, channels and functions
ensures the value is not nil.

	Usage: required_with_all

Example:

	// require the field if the Field1 and Field2 is present:
	Usage: required_with_all=Field1 Field2

Required Without

The field under validation must be present and not empty only when any
of the other specified fields are not present. For strings ensures value is
not "". For slices, maps, pointers, interfaces, channels and functions
ensures the value is not nil.

	Usage: required_without

Examples:

	// require the field if the Field1 is not present:
	Usage: required_without=Field1

	// require the field if the Field1 or Field2 is not present:
	Usage: required_without=Field1 Field2

Required Without All

The field under validation must be present and not empty only when all
of the other specified fields are not present. For strings ensures value is
not "". For slices, maps, pointers, interfaces, channels and functions
ensures the value is not nil.

	Usage: required_without_all

Example:

	// require the field if the Field1 and Field2 is not present:
	Usage: required_without_all=Field1 Field2

Is Default

This validates that the value is the default value and is almost the
opposite of required.

	Usage: isdefault

Length

For numbers, length will ensure that the value is
equal to the parameter given. For strings, it checks that
the string length is exactly that number of characters. For slices,
arrays, and maps, validates the number of items.

Example #1

	Usage: len=10

Example #2 (time.Duration)

For time.Duration, len will ensure that the value is equal to the duration given
in the parameter.

	Usage: len=1h30m

Maximum

For numbers, max will ensure that the value is
less than or equal to the parameter given. For strings, it checks
that the string length is at most that number of characters. For
slices, arrays, and maps, validates the number of items.

Example #1

	Usage: max=10

Example #2 (time.Duration)

For time.Duration, max will ensure that the value is less than or equal to the
duration given in the parameter.

	Usage: max=1h30m

Minimum

For numbers, min will ensure that the value is
greater or equal to the parameter given. For strings, it checks that
the string length is at least that number of characters. For slices,
arrays, and maps, validates the number of items.

Example #1

	Usage: min=10

Example #2 (time.Duration)

For time.Duration, min will ensure that the value is greater than or equal to
the duration given in the parameter.

	Usage: min=1h30m

Equals

For strings & numbers, eq will ensure that the value is
equal to the parameter given. For slices, arrays, and maps,
validates the number of items.

Example #1

	Usage: eq=10

Example #2 (time.Duration)

For time.Duration, eq will ensure that the value is equal to the duration given
in the parameter.

	Usage: eq=1h30m

Not Equal

For strings & numbers, ne will ensure that the value is not
equal to the parameter given. For slices, arrays, and maps,
validates the number of items.

Example #1

	Usage: ne=10

Example #2 (time.Duration)

For time.Duration, ne will ensure that the value is not equal to the duration
given in the parameter.

	Usage: ne=1h30m

One Of

For strings, ints, and uints, oneof will ensure that the value
is one of the values in the parameter.  The parameter should be
a list of values separated by whitespace. Values may be
strings or numbers. To match strings with spaces in them, include
the target string between single quotes.

    Usage: oneof=red green
           oneof='red green' 'blue yellow'
           oneof=5 7 9

Greater Than

For numbers, this will ensure that the value is greater than the
parameter given. For strings, it checks that the string length
is greater than that number of characters. For slices, arrays
and maps it validates the number of items.

Example #1

	Usage: gt=10

Example #2 (time.Time)

For time.Time ensures the time value is greater than time.Now.UTC().

	Usage: gt

Example #3 (time.Duration)

For time.Duration, gt will ensure that the value is greater than the duration
given in the parameter.

	Usage: gt=1h30m

Greater Than or Equal

Same as 'min' above. Kept both to make terminology with 'len' easier.

Example #1

	Usage: gte=10

Example #2 (time.Time)

For time.Time ensures the time value is greater than or equal to time.Now.UTC().

	Usage: gte

Example #3 (time.Duration)

For time.Duration, gte will ensure that the value is greater than or equal to
the duration given in the parameter.

	Usage: gte=1h30m

Less Than

For numbers, this will ensure that the value is less than the parameter given.
For strings, it checks that the string length is less than that number of
characters. For slices, arrays, and maps it validates the number of items.

Example #1

	Usage: lt=10

Example #2 (time.Time)

For time.Time ensures the time value is less than time.Now.UTC().

	Usage: lt

Example #3 (time.Duration)

For time.Duration, lt will ensure that the value is less than the duration given
in the parameter.

	Usage: lt=1h30m

Less Than or Equal

Same as 'max' above. Kept both to make terminology with 'len' easier.

Example #1

	Usage: lte=10

Example #2 (time.Time)

For time.Time ensures the time value is less than or equal to time.Now.UTC().

	Usage: lte

Example #3 (time.Duration)

For time.Duration, lte will ensure that the value is less than or equal to the
duration given in the parameter.

	Usage: lte=1h30m

Field Equals Another Field

This will validate the field value against another fields value either within
a struct or passed in field.

Example #1:

	// Validation on Password field using:
	Usage: eqfield=ConfirmPassword

Example #2:

	// Validating by field:
	validate.VarWithValue(password, confirmpassword, "eqfield")

Field Equals Another Field (relative)

This does the same as eqfield except that it validates the field provided relative
to the top level struct.

	Usage: eqcsfield=InnerStructField.Field)

Field Does Not Equal Another Field

This will validate the field value against another fields value either within
a struct or passed in field.

Examples:

	// Confirm two colors are not the same:
	//
	// Validation on Color field:
	Usage: nefield=Color2

	// Validating by field:
	validate.VarWithValue(color1, color2, "nefield")

Field Does Not Equal Another Field (relative)

This does the same as nefield except that it validates the field provided
relative to the top level struct.

	Usage: necsfield=InnerStructField.Field

Field Greater Than Another Field

Only valid for Numbers, time.Duration and time.Time types, this will validate
the field value against another fields value either within a struct or passed in
field. usage examples are for validation of a Start and End date:

Example #1:

	// Validation on End field using:
	validate.Struct Usage(gtfield=Start)

Example #2:

	// Validating by field:
	validate.VarWithValue(start, end, "gtfield")

Field Greater Than Another Relative Field

This does the same as gtfield except that it validates the field provided
relative to the top level struct.

	Usage: gtcsfield=InnerStructField.Field

Field Greater Than or Equal To Another Field

Only valid for Numbers, time.Duration and time.Time types, this will validate
the field value against another fields value either within a struct or passed in
field. usage examples are for validation of a Start and End date:

Example #1:

	// Validation on End field using:
	validate.Struct Usage(gtefield=Start)

Example #2:

	// Validating by field:
	validate.VarWithValue(start, end, "gtefield")

Field Greater Than or Equal To Another Relative Field

This does the same as gtefield except that it validates the field provided relative
to the top level struct.

	Usage: gtecsfield=InnerStructField.Field

Less Than Another Field

Only valid for Numbers, time.Duration and time.Time types, this will validate
the field value against another fields value either within a struct or passed in
field. usage examples are for validation of a Start and End date:

Example #1:

	// Validation on End field using:
	validate.Struct Usage(ltfield=Start)

Example #2:

	// Validating by field:
	validate.VarWithValue(start, end, "ltfield")

Less Than Another Relative Field

This does the same as ltfield except that it validates the field provided relative
to the top level struct.

	Usage: ltcsfield=InnerStructField.Field

Less Than or Equal To Another Field

Only valid for Numbers, time.Duration and time.Time types, this will validate
the field value against another fields value either within a struct or passed in
field. usage examples are for validation of a Start and End date:

Example #1:

	// Validation on End field using:
	validate.Struct Usage(ltefield=Start)

Example #2:

	// Validating by field:
	validate.VarWithValue(start, end, "ltefield")

Less Than or Equal To Another Relative Field

This does the same as ltefield except that it validates the field provided relative
to the top level struct.

	Usage: ltecsfield=InnerStructField.Field

Field Contains Another Field

This does the same as contains except for struct fields. It should only be used
with string types. See the behavior of reflect.Value.String() for behavior on
other types.

	Usage: containsfield=InnerStructField.Field

Field Excludes Another Field

This does the same as excludes except for struct fields. It should only be used
with string types. See the behavior of reflect.Value.String() for behavior on
other types.

	Usage: excludesfield=InnerStructField.Field

Unique

For arrays & slices, unique will ensure that there are no duplicates.
For maps, unique will ensure that there are no duplicate values.
For slices of struct, unique will ensure that there are no duplicate values
in a field of the struct specified via a parameter.

	// For arrays, slices, and maps:
	Usage: unique

	// For slices of struct:
	Usage: unique=field

Alpha Only

This validates that a string value contains ASCII alpha characters only

	Usage: alpha

Alphanumeric

This validates that a string value contains ASCII alphanumeric characters only

	Usage: alphanum

Alpha Unicode

This validates that a string value contains unicode alpha characters only

	Usage: alphaunicode

Alphanumeric Unicode

This validates that a string value contains unicode alphanumeric characters only

	Usage: alphanumunicode

Number

This validates that a string value contains number values only.
For integers or float it returns true.

	Usage: number

Numeric

This validates that a string value contains a basic numeric value.
basic excludes exponents etc...
for integers or float it returns true.

	Usage: numeric

Hexadecimal String

This validates that a string value contains a valid hexadecimal.

	Usage: hexadecimal

Hexcolor String

This validates that a string value contains a valid hex color including
hashtag (#)

		Usage: hexcolor

Lowercase String

This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.

	Usage: lowercase

Uppercase String

This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.

	Usage: uppercase

RGB String

This validates that a string value contains a valid rgb color

	Usage: rgb

RGBA String

This validates that a string value contains a valid rgba color

	Usage: rgba

HSL String

This validates that a string value contains a valid hsl color

	Usage: hsl

HSLA String

This validates that a string value contains a valid hsla color

	Usage: hsla

E.164 Phone Number String

This validates that a string value contains a valid E.164 Phone number
https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)

	Usage: e164

E-mail String

This validates that a string value contains a valid email
This may not conform to all possibilities of any rfc standard, but neither
does any email provider accept all possibilities.

	Usage: email

JSON String

This validates that a string value is valid JSON

	Usage: json

JWT String

This validates that a string value is a valid JWT

	Usage: jwt

File path

This validates that a string value contains a valid file path and that
the file exists on the machine.
This is done using os.Stat, which is a platform independent function.

	Usage: file

URL String

This validates that a string value contains a valid url
This will accept any url the golang request uri accepts but must contain
a schema for example http:// or rtmp://

	Usage: url

URI String

This validates that a string value contains a valid uri
This will accept any uri the golang request uri accepts

	Usage: uri

Urn RFC 2141 String

This validataes that a string value contains a valid URN
according to the RFC 2141 spec.

	Usage: urn_rfc2141

Base64 String

This validates that a string value contains a valid base64 value.
Although an empty string is valid base64 this will report an empty string
as an error, if you wish to accept an empty string as valid you can use
this with the omitempty tag.

	Usage: base64

Base64URL String

This validates that a string value contains a valid base64 URL safe value
according the the RFC4648 spec.
Although an empty string is a valid base64 URL safe value, this will report
an empty string as an error, if you wish to accept an empty string as valid
you can use this with the omitempty tag.

	Usage: base64url

Bitcoin Address

This validates that a string value contains a valid bitcoin address.
The format of the string is checked to ensure it matches one of the three formats
P2PKH, P2SH and performs checksum validation.

	Usage: btc_addr

Bitcoin Bech32 Address (segwit)

This validates that a string value contains a valid bitcoin Bech32 address as defined
by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
Special thanks to Pieter Wuille for providng reference implementations.

	Usage: btc_addr_bech32

Ethereum Address

This validates that a string value contains a valid ethereum address.
The format of the string is checked to ensure it matches the standard Ethereum address format.

	Usage: eth_addr

Contains

This validates that a string value contains the substring value.

	Usage: contains=@

Contains Any

This validates that a string value contains any Unicode code points
in the substring value.

	Usage: containsany=!@#?

Contains Rune

This validates that a string value contains the supplied rune value.

	Usage: containsrune=@

Excludes

This validates that a string value does not contain the substring value.

	Usage: excludes=@

Excludes All

This validates that a string value does not contain any Unicode code
points in the substring value.

	Usage: excludesall=!@#?

Excludes Rune

This validates that a string value does not contain the supplied rune value.

	Usage: excludesrune=@

Starts With

This validates that a string value starts with the supplied string value

	Usage: startswith=hello

Ends With

This validates that a string value ends with the supplied string value

	Usage: endswith=goodbye

Does Not Start With

This validates that a string value does not start with the supplied string value

	Usage: startsnotwith=hello

Does Not End With

This validates that a string value does not end with the supplied string value

	Usage: endsnotwith=goodbye

International Standard Book Number

This validates that a string value contains a valid isbn10 or isbn13 value.

	Usage: isbn

International Standard Book Number 10

This validates that a string value contains a valid isbn10 value.

	Usage: isbn10

International Standard Book Number 13

This validates that a string value contains a valid isbn13 value.

	Usage: isbn13

Universally Unique Identifier UUID

This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.

	Usage: uuid

Universally Unique Identifier UUID v3

This validates that a string value contains a valid version 3 UUID.  Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.

	Usage: uuid3

Universally Unique Identifier UUID v4

This validates that a string value contains a valid version 4 UUID.  Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.

	Usage: uuid4

Universally Unique Identifier UUID v5

This validates that a string value contains a valid version 5 UUID.  Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.

	Usage: uuid5

ASCII

This validates that a string value contains only ASCII characters.
NOTE: if the string is blank, this validates as true.

	Usage: ascii

Printable ASCII

This validates that a string value contains only printable ASCII characters.
NOTE: if the string is blank, this validates as true.

	Usage: printascii

Multi-Byte Characters

This validates that a string value contains one or more multibyte characters.
NOTE: if the string is blank, this validates as true.

	Usage: multibyte

Data URL

This validates that a string value contains a valid DataURI.
NOTE: this will also validate that the data portion is valid base64

	Usage: datauri

Latitude

This validates that a string value contains a valid latitude.

	Usage: latitude

Longitude

This validates that a string value contains a valid longitude.

	Usage: longitude

Social Security Number SSN

This validates that a string value contains a valid U.S. Social Security Number.

	Usage: ssn

Internet Protocol Address IP

This validates that a string value contains a valid IP Address.

	Usage: ip

Internet Protocol Address IPv4

This validates that a string value contains a valid v4 IP Address.

	Usage: ipv4

Internet Protocol Address IPv6

This validates that a string value contains a valid v6 IP Address.

	Usage: ipv6

Classless Inter-Domain Routing CIDR

This validates that a string value contains a valid CIDR Address.

	Usage: cidr

Classless Inter-Domain Routing CIDRv4

This validates that a string value contains a valid v4 CIDR Address.

	Usage: cidrv4

Classless Inter-Domain Routing CIDRv6

This validates that a string value contains a valid v6 CIDR Address.

	Usage: cidrv6

Transmission Control Protocol Address TCP

This validates that a string value contains a valid resolvable TCP Address.

	Usage: tcp_addr

Transmission Control Protocol Address TCPv4

This validates that a string value contains a valid resolvable v4 TCP Address.

	Usage: tcp4_addr

Transmission Control Protocol Address TCPv6

This validates that a string value contains a valid resolvable v6 TCP Address.

	Usage: tcp6_addr

User Datagram Protocol Address UDP

This validates that a string value contains a valid resolvable UDP Address.

	Usage: udp_addr

User Datagram Protocol Address UDPv4

This validates that a string value contains a valid resolvable v4 UDP Address.

	Usage: udp4_addr

User Datagram Protocol Address UDPv6

This validates that a string value contains a valid resolvable v6 UDP Address.

	Usage: udp6_addr

Internet Protocol Address IP

This validates that a string value contains a valid resolvable IP Address.

	Usage: ip_addr

Internet Protocol Address IPv4

This validates that a string value contains a valid resolvable v4 IP Address.

	Usage: ip4_addr

Internet Protocol Address IPv6

This validates that a string value contains a valid resolvable v6 IP Address.

	Usage: ip6_addr

Unix domain socket end point Address

This validates that a string value contains a valid Unix Address.

	Usage: unix_addr

Media Access Control Address MAC

This validates that a string value contains a valid MAC Address.

	Usage: mac

Note: See Go's ParseMAC for accepted formats and types:

	http://golang.org/src/net/mac.go?s=866:918#L29

Hostname RFC 952

This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952

	Usage: hostname

Hostname RFC 1123

This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123

	Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.

Full Qualified Domain Name (FQDN)

This validates that a string value contains a valid FQDN.

	Usage: fqdn

HTML Tags

This validates that a string value appears to be an HTML element tag
including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element

	Usage: html

HTML Encoded

This validates that a string value is a proper character reference in decimal
or hexadecimal format

	Usage: html_encoded

URL Encoded

This validates that a string value is percent-encoded (URL encoded) according
to https://tools.ietf.org/html/rfc3986#section-2.1

	Usage: url_encoded

Directory

This validates that a string value contains a valid directory and that
it exists on the machine.
This is done using os.Stat, which is a platform independent function.

	Usage: dir

HostPort

This validates that a string value contains a valid DNS hostname and port that
can be used to valiate fields typically passed to sockets and connections.

	Usage: hostname_port

Datetime

This validates that a string value is a valid datetime based on the supplied datetime format.
Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/

	Usage: datetime=2006-01-02

Iso3166-1 alpha-2

This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
see: https://www.iso.org/iso-3166-country-codes.html

	Usage: iso3166_1_alpha2

Iso3166-1 alpha-3

This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
see: https://www.iso.org/iso-3166-country-codes.html

	Usage: iso3166_1_alpha3

Iso3166-1 alpha-numeric

This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
see: https://www.iso.org/iso-3166-country-codes.html

	Usage: iso3166_1_alpha3

BCP 47 Language Tag

This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
More information on https://pkg.go.dev/golang.org/x/text/language

	Usage: bcp47_language_tag

BIC (SWIFT code)

This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
More information on https://www.iso.org/standard/60390.html

	Usage: bic

TimeZone

This validates that a string value is a valid time zone based on the time zone database present on the system.
Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
More information on https://golang.org/pkg/time/#LoadLocation

	Usage: timezone

Alias Validators and Tags

NOTE: When returning an error, the tag returned in "FieldError" will be
the alias tag unless the dive tag is part of the alias. Everything after the
dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
case will be the actual tag within the alias that failed.

Here is a list of the current built in alias tags:

	"iscolor"
		alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
	"country_code"
		alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)

Validator notes:

	regex
		a regex validator won't be added because commas and = signs can be part
		of a regex which conflict with the validation definitions. Although
		workarounds can be made, they take away from using pure regex's.
		Furthermore it's quick and dirty but the regex's become harder to
		maintain and are not reusable, so it's as much a programming philosophy
		as anything.

		In place of this new validator functions should be created; a regex can
		be used within the validator function and even be precompiled for better
		efficiency within regexes.go.

		And the best reason, you can submit a pull request and we can keep on
		adding to the validation library of this package!

Non standard validators

A collection of validation rules that are frequently needed but are more
complex than the ones found in the baked in validators.
A non standard validator must be registered manually like you would
with your own custom validation functions.

Example of registration and use:

	type Test struct {
		TestField string `validate:"yourtag"`
	}

	t := &Test{
		TestField: "Test"
	}

	validate := validator.New()
	validate.RegisterValidation("yourtag", validators.NotBlank)

Here is a list of the current non standard validators:

	NotBlank
		This validates that the value is not blank or with length zero.
		For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
		ensures they don't have zero length. For others, a non empty value is required.

		Usage: notblank

Panics

This package panics when bad input is provided, this is by design, bad code like
that should not make it to production.

	type Test struct {
		TestField string `validate:"nonexistantfunction=1"`
	}

	t := &Test{
		TestField: "Test"
	}

	validate.Struct(t) // this will panic
*/
package validator


text:
package com.krishagni.catissueplus.core.administrative.services.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;

import com.krishagni.catissueplus.core.administrative.domain.Site;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.administrative.domain.factory.SiteErrorCode;
import com.krishagni.catissueplus.core.administrative.domain.factory.SiteFactory;
import com.krishagni.catissueplus.core.administrative.events.SiteDetail;
import com.krishagni.catissueplus.core.administrative.events.SiteQueryCriteria;
import com.krishagni.catissueplus.core.administrative.events.SiteSummary;
import com.krishagni.catissueplus.core.administrative.repository.SiteListCriteria;
import com.krishagni.catissueplus.core.administrative.services.SiteService;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.errors.ErrorType;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkEntityDetail;
import com.krishagni.catissueplus.core.common.events.DeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.Operation;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.Resource;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.ObjectAccessor;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.Status;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.exporter.domain.ExportJob;
import com.krishagni.catissueplus.core.exporter.services.ExportService;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import com.krishagni.rbac.events.SubjectRoleOpNotif;
import com.krishagni.rbac.service.RbacService;

public class SiteServiceImpl implements SiteService, ObjectAccessor, InitializingBean {
	private SiteFactory siteFactory;

	private DaoFactory daoFactory;

	private RbacService rbacSvc;

	private ExportService exportSvc;

	public void setDaoFactory(DaoFactory daoFactory) {
		this.daoFactory = daoFactory;
	}

	public void setSiteFactory(SiteFactory siteFactory) {
		this.siteFactory = siteFactory;
	}

	public void setRbacSvc(RbacService rbacSvc) {
		this.rbacSvc = rbacSvc;
	}

	public void setExportSvc(ExportService exportSvc) {
		this.exportSvc = exportSvc;
	}

	@Override
	@PlusTransactional
	public ResponseEvent<List<SiteSummary>> getSites(RequestEvent<SiteListCriteria> req) {
		try {
			SiteListCriteria listCrit = req.getPayload();
			List<Site> sites = null;

			if (AuthUtil.isAdmin()) {
				sites = daoFactory.getSiteDao().getSites(listCrit);
			} else if (listCrit.listAll() && isAllSitesAllowed()) {
				sites = daoFactory.getSiteDao().getSites(listCrit);
			} else {
				sites = getAccessibleSites(listCrit);
			}

			List<SiteSummary> result = SiteSummary.from(sites);
			if (listCrit.includeStat()) {
				addSiteStats(result);
			}

			return ResponseEvent.response(result);
		} catch(OpenSpecimenException ose) {
			return ResponseEvent.error(ose);
		} catch(Exception ex) {
			return ResponseEvent.serverError(ex);
		}
	}

	@Override
	@PlusTransactional
	public ResponseEvent<Long> getSitesCount(RequestEvent<SiteListCriteria> req) {
		return ResponseEvent.response(daoFactory.getSiteDao().getSitesCount(req.getPayload()));
	}

	@Override
	@PlusTransactional
	public ResponseEvent<SiteDetail> getSite(RequestEvent<SiteQueryCriteria> req) {
		SiteQueryCriteria crit = req.getPayload();
		Site site = getFromAccessibleSite(crit.getId(), crit.getName());
		return ResponseEvent.response(SiteDetail.from(site));
	}

	@Override
	@PlusTransactional
	public ResponseEvent<SiteDetail> createSite(RequestEvent<SiteDetail> req) {
		try {
			Site site = siteFactory.createSite(req.getPayload());
			AccessCtrlMgr.getInstance().ensureCreateUpdateDeleteSiteRights(site);

			OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
			ensureUniqueConstraint(site, null, ose);
			ose.checkAndThrow();
			daoFactory.getSiteDao().saveOrUpdate(site, true);
			site.addOrUpdateExtension();
			addDefaultCoordinatorRoles(site, site.getCoordinators(), "CREATE");
			return ResponseEvent.response(SiteDetail.from(site));
		} catch (OpenSpecimenException ose) {
			return ResponseEvent.error(ose);
		} catch (Exception e) {
			return ResponseEvent.serverError(e);
		}
	}

	@Override
	@PlusTransactional
	public ResponseEvent<SiteDetail> updateSite(RequestEvent<SiteDetail> req) {
		return updateSite(req, false);
	}

	@Override
	@PlusTransactional
	public ResponseEvent<SiteDetail> patchSite(RequestEvent<SiteDetail> req) {
		return updateSite(req, true);
	}

	@Override
	@PlusTransactional
	public ResponseEvent<List<SiteDetail>> bulkUpdateSites(RequestEvent<BulkEntityDetail<SiteDetail>> req) {
		try {
			BulkEntityDetail<SiteDetail> buDetail = req.getPayload();

			List<SiteDetail> updatedSites = new ArrayList<>();
			SiteDetail detail = curateBulkUpdateFields(buDetail.getDetail());
			for (Long siteId : Utility.nullSafe(buDetail.getIds())) {
				detail.setId(siteId);
				updatedSites.add(updateSite(detail, true));
			}

			detail.setId(null);
			for (String name : Utility.nullSafe(buDetail.getNames())) {
				detail.setName(name);
				updatedSites.add(updateSite(detail, true));
			}

			return ResponseEvent.response(updatedSites);
		} catch (OpenSpecimenException ose) {
			return ResponseEvent.error(ose);
		} catch (Exception e) {
			return ResponseEvent.serverError(e);
		}
	}

	@Override
	@PlusTransactional
	public ResponseEvent<List<DependentEntityDetail>> getDependentEntities(RequestEvent<Long> req) {
		try {
			Site existing = daoFactory.getSiteDao().getById(req.getPayload());
			if (existing == null) {
				return ResponseEvent.userError(SiteErrorCode.NOT_FOUND);
			}

			return ResponseEvent.response(existing.getDependentEntities());
		} catch (Exception e) {
			return ResponseEvent.serverError(e);
		}
	}

	@Override
	@PlusTransactional
	public ResponseEvent<SiteDetail> deleteSite(RequestEvent<DeleteEntityOp> req) {
		try {
			DeleteEntityOp deleteOp = req.getPayload();
			Site existing = daoFactory.getSiteDao().getById(deleteOp.getId());
			if (existing == null) {
				return ResponseEvent.userError(SiteErrorCode.NOT_FOUND);
			}

			AccessCtrlMgr.getInstance().ensureCreateUpdateDeleteSiteRights(existing);

			removeDefaultCoordinatorRoles(existing, existing.getCoordinators(), "DELETE");
			existing.delete(deleteOp.isClose());
			return ResponseEvent.response(SiteDetail.from(existing));
		} catch (OpenSpecimenException ose) {
			return ResponseEvent.error(ose);
		} catch (Exception e) {
			return ResponseEvent.serverError(e);
		}
	}

	@Override
	public String getObjectName() {
		return Site.getEntityName();
	}

	@Override
	@PlusTransactional
	public Map<String, Object> resolveUrl(String key, Object value) {
		if (key.equals("id")) {
			value = Long.valueOf(value.toString());
		}

		return daoFactory.getSiteDao().getSiteIds(key, value);
	}

	@Override
	public String getAuditTable() {
		return "CATISSUE_SITE_AUD";
	}

	@Override
	public void ensureReadAllowed(Long id) {
		getFromAccessibleSite(id, null);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		exportSvc.registerObjectsGenerator("site", this::getSitesGenerator);
	}

	private boolean isAllSitesAllowed() {
		return AccessCtrlMgr.getInstance().canCreateUpdateParticipant() ||
			AccessCtrlMgr.getInstance().canCreateUpdateDistributionOrder() ||
			AccessCtrlMgr.getInstance().canCreateUpdateShipment();
	}

	private void addSiteStats(List<SiteSummary> sites) {
		if (CollectionUtils.isEmpty(sites)) {
			return;
		}

		Map<Long, SiteSummary> sitesMap = new HashMap<Long, SiteSummary>();
		for (SiteSummary site : sites) {
			sitesMap.put(site.getId(), site);
		}

		Map<Long, Integer> cpCountMap = daoFactory.getSiteDao().getCpCountBySite(sitesMap.keySet());
		for (Map.Entry<Long, Integer> cpCount : cpCountMap.entrySet()) {
			sitesMap.get(cpCount.getKey()).setCpCount(cpCount.getValue());
		}
	}

	private ResponseEvent<SiteDetail> updateSite(RequestEvent<SiteDetail> req, boolean partial) {
		try {
			return ResponseEvent.response(updateSite(req.getPayload(), partial));
		} catch (OpenSpecimenException ose) {
			return ResponseEvent.error(ose);
		} catch (Exception e) {
			return ResponseEvent.serverError(e);
		}
	}

	private SiteDetail updateSite(SiteDetail detail, boolean partial) {
		Site existing = getSite(detail.getId(), detail.getName());
		AccessCtrlMgr.getInstance().ensureCreateUpdateDeleteSiteRights(existing);

		Site site = partial ? siteFactory.createSite(existing, detail) : siteFactory.createSite(detail);
		AccessCtrlMgr.getInstance().ensureCreateUpdateDeleteSiteRights(site);

		OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
		ensureUniqueConstraint(site, existing, ose);
		ose.checkAndThrow();

		Set<User> addedCoordinators   = Utility.subtract(site.getCoordinators(), existing.getCoordinators());
		Set<User> removedCoordinators = Utility.subtract(existing.getCoordinators(), site.getCoordinators());
		if (Status.isClosedOrDisabledStatus(site.getActivityStatus())) {
			removedCoordinators.addAll(existing.getCoordinators());
			addedCoordinators = Collections.emptySet();
		}

		//
		// OPSMN-4614: To prevent the mismatch between the site institute and that of the removed coordinators,
		// the roles of the removed coordinators are updated before doing site update
		//
		if (!removedCoordinators.isEmpty()) {
			removeDefaultCoordinatorRoles(existing, removedCoordinators, "UPDATE");
		}

		existing.update(site);
		daoFactory.getSiteDao().saveOrUpdate(existing);
		existing.addOrUpdateExtension();

		if (!addedCoordinators.isEmpty()) {
			addDefaultCoordinatorRoles(existing, addedCoordinators, "UPDATE");
		}

		return SiteDetail.from(existing);
	}

	private Site getSite(Long siteId, String name) {
		Site site = null;
		Object key = null;

		if (siteId != null) {
			site = daoFactory.getSiteDao().getById(siteId);
			key = siteId;
		} else if (StringUtils.isNotBlank(name)) {
			site = daoFactory.getSiteDao().getSiteByName(name);
			key = name;
		}

		if (key == null) {
			throw  OpenSpecimenException.userError(SiteErrorCode.NAME_REQUIRED);
		} else if (site == null) {
			throw  OpenSpecimenException.userError(SiteErrorCode.NOT_FOUND, key);
		}

		return site;
	}

	private void addDefaultCoordinatorRoles(Site site, Collection<User> users, String siteOp) {
		SubjectRoleOpNotif notifReq = getNotifReq(site, siteOp, "ADD");
		for (User user : users) {
			notifReq.setUser(user);
			notifReq.setAdminNotifParams(new Object[] { user.getFirstName(), user.getLastName(), site.getName() });
			rbacSvc.addSubjectRole(site, null, user, getDefaultCoordinatorRoles(), notifReq);
		}
	}

	private void removeDefaultCoordinatorRoles(Site site, Collection<User> users, String siteOp) {
		SubjectRoleOpNotif notifReq = getNotifReq(site, siteOp, "REMOVE");
		for (User user: users) {
			notifReq.setUser(user);
			notifReq.setAdminNotifParams(new Object[]{user.getFirstName(), user.getLastName(), site.getName()});
			rbacSvc.removeSubjectRole(site, null, user, getDefaultCoordinatorRoles(), notifReq);
		}
	}

	private SubjectRoleOpNotif getNotifReq(Site site, String siteOp, String roleOp) {
		SubjectRoleOpNotif notifReq = new SubjectRoleOpNotif();
		notifReq.setEndUserOp(siteOp);
		notifReq.setAdmins(AccessCtrlMgr.getInstance().getSuperAdmins());
		notifReq.setAdminNotifMsg("site_admin_notif_role_" + roleOp.toLowerCase());
		notifReq.setSubjectNotifMsg(siteOp.equals("DELETE") ? "site_delete_user_notif": "site_user_notif_role_" + roleOp.toLowerCase());
		notifReq.setSubjectNotifParams(new Object[] { site.getName() });
		return notifReq;
	}

	private String[] getDefaultCoordinatorRoles() {
		return new String[] {"Administrator"};
	}

	private void ensureUniqueConstraint(Site newSite, Site existingSite, OpenSpecimenException ose) {
		if (!isUniqueName(newSite, existingSite)) {
			ose.addError(SiteErrorCode.DUP_NAME);
		}

		if(!isUniqueCode(newSite, existingSite)) {
			ose.addError(SiteErrorCode.DUP_CODE);
		}
	}

	private boolean isUniqueName(Site newSite, Site existingSite) {
		if (existingSite != null && newSite.getName().equals(existingSite.getName())) {
			return true;
		}

		Site site = daoFactory.getSiteDao().getSiteByName(newSite.getName());
		if (site != null) {
			return false;
		}

		return true;
	}

	private boolean isUniqueCode(Site newSite, Site existingSite) {
		if (StringUtils.isBlank(newSite.getCode()) ||
			existingSite != null && newSite.getCode().equals(existingSite.getCode())) {
			return true;
		}

		Site site = daoFactory.getSiteDao().getSiteByCode(newSite.getCode());
		if (site != null) {
			return false;
		}

		return true;
	}

	private List<Site> getAccessibleSites(SiteListCriteria criteria) {
		return AccessCtrlMgr.getInstance().getAccessibleSites(criteria);
	}

	private Site getFromAccessibleSite(Long siteId, String siteName) {
		Site site = getSite(siteId, siteName);

		if (AuthUtil.isAdmin()) {
			return site;
		}

		if (AccessCtrlMgr.getInstance().isAccessible(site)) {
			return site;
		}

		AccessCtrlMgr.getInstance().ensureCreateShipmentRights();
		return site;
	}

	private SiteDetail curateBulkUpdateFields(SiteDetail input) {
		SiteDetail detail = new SiteDetail();

		if (input.isAttrModified("instituteName")) {
			detail.setInstituteName(input.getInstituteName());
		}

		if (input.isAttrModified("coordinators")) {
			detail.setCoordinators(input.getCoordinators());
		}

		if (input.isAttrModified("type")) {
			detail.setType(input.getType());
		}

		if (input.isAttrModified("activityStatus")) {
			detail.setActivityStatus(input.getActivityStatus());
		}

		//
		// TODO: need to handle custom site fields
		//

		return detail;
	}

	private Function<ExportJob, List<? extends Object>> getSitesGenerator() {
		return new Function<ExportJob, List<? extends Object>>() {
			private boolean endOfSites;

			private int startAt;

			@Override
			public List<? extends Object> apply(ExportJob job) {
				if (endOfSites) {
					return Collections.emptyList();
				}

				int maxRecs = CollectionUtils.isNotEmpty(job.getRecordIds()) ? job.getRecordIds().size() : 100;
				SiteListCriteria crit = new SiteListCriteria().ids(job.getRecordIds()).startAt(startAt).maxResults(maxRecs);
				if (!AuthUtil.isAdmin()) {
					crit.institute(AuthUtil.getCurrentUserInstitute().getName());
				}

				Collection<Site> sites = daoFactory.getSiteDao().getSites(crit);
				startAt += sites.size();
				if (sites.isEmpty() || CollectionUtils.isNotEmpty(job.getRecordIds())) {
					endOfSites = true;
				}

				return SiteDetail.from(sites);
			}
		};
	}
}


text:
<?php
$currentUser = erLhcoreClassUser::instance();
if (!$currentUser->isLogged() && !$currentUser->authenticate($_POST['username'],$_POST['password']))
{
    exit;
}

$chat = erLhcoreClassChat::getSession()->load( 'erLhcoreClassModelChat', $Params['user_parameters']['chat_id']);

if ( erLhcoreClassChat::hasAccessToRead($chat) )
{
		// If status is pending change status to active
        $operatorAccepted = false;
        $chatDataChanged = false;

        if ($chat->user_id == 0) {
        	$currentUser = erLhcoreClassUser::instance();
        	$chat->user_id = $currentUser->getUserID();
        	$chatDataChanged = true;
        }

        // If status is pending change status to active
        if ($chat->status == erLhcoreClassModelChat::STATUS_PENDING_CHAT) {
        	$chat->status = erLhcoreClassModelChat::STATUS_ACTIVE_CHAT;

        	if ($chat->wait_time == 0) {
        		$chat->wait_time = time() - $chat->time;
        	}

        	$chat->user_id = $currentUser->getUserID();
        	$operatorAccepted = true;
        	$chatDataChanged = true;
        }

        if ($chat->support_informed == 0 || $chat->has_unread_messages == 1 ||  $chat->unread_messages_informed == 1) {
        	$chatDataChanged = true;
        }

        $chat->support_informed = 1;
        $chat->has_unread_messages = 0;
        $chat->unread_messages_informed = 0;
        erLhcoreClassChat::getSession()->update($chat);

        $ownerString = 'No data';
        $user = $chat->getChatOwner();
        if ($user !== false)
        {
            $ownerString = $user->name.' '.$user->surname;
        }

        $cannedmsg = erLhcoreClassModelCannedMsg::getCannedMessages($chat->dep_id,$currentUser->getUserID());

    	echo json_encode(array('operator' => (string)$currentUser->getUserData(true)->name_support,'error' => false, 'canned_messages' => $cannedmsg, 'chat' => $chat, 'ownerstring' => $ownerString));

	    flush();
	    session_write_close();

	    if ( function_exists('fastcgi_finish_request') ) {
	        fastcgi_finish_request();
	    };

	    if ($chatDataChanged == true) {
	    	erLhcoreClassChatEventDispatcher::getInstance()->dispatch('chat.data_changed',array('chat' => & $chat,'user' => $currentUser));
	    }

	    if ($operatorAccepted == true) {
	    	erLhcoreClassChatEventDispatcher::getInstance()->dispatch('chat.accept',array('chat' => & $chat,'user' => $currentUser));
	    	erLhcoreClassChat::updateActiveChats($chat->user_id);
	    	erLhcoreClassChatWorkflow::presendCannedMsg($chat);
	    	$options = $chat->department->inform_options_array;
	    	erLhcoreClassChatWorkflow::chatAcceptedWorkflow(array('department' => $chat->department,'options' => $options),$chat);
	    };

} else {
    echo json_encode(array('error' => true,'error_string' => 'You do not have permission to read this chat!'));
}

exit;
?>


text:
package org.nschmidt.ldparteditor.win32appdata;

import java.io.File;

import org.eclipse.swt.SWT;
import org.nschmidt.ldparteditor.helper.FileHelper;

public enum AppData {
    INSTANCE;

    private static String path = null;

    /**
     * Windows only: Gets the path to LDPE's AppData folder
     *
     * @return {drive}\Documents and Settings\{user}\Application Data\LDPartEditor\
     */
    public static String getPath() {
        if (path != null) {
            return path;
        }

        if ("win32".equals(SWT.getPlatform())) { //$NON-NLS-1$
            try {
                path = System.getenv("APPDATA"); //$NON-NLS-1$
                if (path == null) {
                    path = ""; //$NON-NLS-1$
                } else {
                    if (!path.endsWith(File.separator)) {
                        path = path + File.separator;
                    }

                    if (FileHelper.canReadFromPath(path) && FileHelper.canWriteToPath(path)) {
                        path = path + "LDPartEditor" + File.separator; //$NON-NLS-1$
                        final File settingsFolder = new File(path);
                        if (!settingsFolder.exists()) {
                            // Try to create the directory
                            if (!settingsFolder.mkdir()) {
                                path = ""; //$NON-NLS-1$
                            }
                        } else if (!FileHelper.canReadFromPath(path) || !FileHelper.canWriteToPath(path)) {
                            path = ""; //$NON-NLS-1$
                        }
                    } else {
                        path = ""; //$NON-NLS-1$
                    }
                }
            } catch (SecurityException se) {
                // Do not log this, since the logger needs the AppData path.
                path = ""; //$NON-NLS-1$
            }
        } else {
            path = ""; //$NON-NLS-1$
        }

        return path;
    }
}


text:
import modService from './service.js';

let mod = angular.module('dekutcuapp.accessibility', []);

mod.factory('$WPHCAccessibility', modService);

export default mod = mod.name;


text:
package org.artifactory.addon.plugin.download;

import org.artifactory.addon.plugin.PluginAction;
import org.artifactory.repo.RepoPath;
import org.artifactory.request.Request;

/**
 * @author Yoav Landman
 */
public interface AfterRemoteDownloadAction extends PluginAction {
    void afterRemoteDownload(Request request, RepoPath repoPath);
}


text:
/**
* Repositorio de objetos do Parse.org
* https://parse.com/docs/js_guide
**/
var ParseRepository = Repository.extend({

    prototype: {

       _class: undefined,

       /**
       * Repository initializer
       * @param args.class_name Parse class name or
       * @param args.class Parse class. If setted then class_name not needed
       **/
       initialize: function (args){

           if (args){
               this._class_name = args.class_name;
               this._class = args.class;

               if (typeof this._class_name !== "undefined"){
                   this._class = Parse.Object.extend(this._class_name);
               }
           }

       },

       /**
       * Parse query object for the class
       **/
       _query: function(){
           return new Parse.Query(this._class);
       },

       /**
       * Create a parse object
       **/
       _create: function(){
           return new this._class();
       },

       /**
       * Retrieve all objects
       **/
       getAll: function(args){
           return this.find(null, args.success, args.error);
       },

       /**
       * Retrieve only a object
       * @param args.id The object ID
       **/
       get: function(args){
           var objectId = args.data.objectId;
           var success = args.success;
           var error = args.error;
           this.first({data: {objectId : objectId}, success: success, error: error});
           return;
       },

       /**
       * Update a parse object
       * @param args.id The object ID
       * @param args.data The new data of object
       **/
       put: function(args){
           var data = args.data;
           var objectId = args.data.objectId;
           var success = args.success;
           var error = args.error;

           function get_callback(response){
               response.save(data, {success: success, error: error});
           };

           this.get({data: {objectId : objectId}, success: get_callback, error: error});
           return;
       },

       /**
       * Create a parse object
       * @param data The data of the new object
       **/
       post: function(args) {
           var data = args.data;
           var success = args.success;
           var error = args.error;

           this._create().save(data, {success: success, error: error});
           return;
       },

       /**
       * Delete a parse object
       * @param args.id The ID of the object that will be deleted
       **/
       delete: function(args){
           var objectId = args.data.objectId;
           var success = args.success;
           var error = args.error;

           function get_callback(response){
               response.destroy({success: success, error: error});
           };

           this.get({data: {objectId: objectId}, success: get_callback, error: error});
           return;
       },

        /**
        * Find objects
        * @param args The key : value sings
        **/
       find: function(args){
           var data = args.data;
           var success = args.success;
           var error = args.error;

           var query = this._query();
           for(var key in data){
               query.equalTo(key, data[key]);
           }
           query.find({success: success, error: error});
           return;
       },

        /**
        * Find first object
        * @param args The key : value sings
        **/
       first: function(args){
           var data = args.data;
           var success = args.success;
           var error = args.error;

           var query = this._query();
           for(var key in data){
               query.equalTo(key, data[key]);
           }
           query.first({success: success, error: error});
           return;
       },

    },

    /**
    * Upload a file to parse
    * @param args.name filename
    * @param args.ext file extension
    * @param args.content_type The file content type
    * @param args.file_upload_control $("#id")[0] or document.getElementById("id")
    **/
    uploadFile: function(args, callback, error_callback){
        var name = args.name;
        var ext = args.ext;
        var content_type = args.content_type;
        var file_upload_control = args.file_upload_control;

        if (file_upload_control.files.length > 0) {

            var file = file_upload_control.files[0];
            var parseFile = new Parse.File(name + ext, file, content_type);

            parseFile.save().then(
                function(response){
                    console.log("Sucess: The file was uploaded");
                    console.log(response.url());
                    if (callback !== null && typeof callback !== "undefined"){
                        callback();
                    }
                },
                function(error){
                    console.log("Error: The file was not uploaded");
                    if (error_callback !== null && typeof error_callback !== "undefined"){
                        error_callback(error);
                    }
                }
            );
        }

        return;
   }

});

/**
* Repositorio de usuarios parse. Baseado nas classes especiais Parse.User e Parse.FacebookUtils
**/
ParseRepository.User = ParseRepository.extend({

    prototype: {

        _class : Parse.User,

        /**
        * Create a new user. Before, it also checks if both the username and email are unique
        * @param args.username Username
        * @param args.password Encrypeted password
        * @param args.email User email
        * @param args... Any data do you want to save
        **/
        signup : function(args) {
            var data = args.data;
            var success = args.success;
            var error = args.error;

            var user = this._create();
            user.signUp(data, {success: success, error: error});
            return;
        },

        /**
        * Redirect to signup method
        **/
        post : function(args){
            return this.signUp(args);
        },

        /**
        * Log the user in the app. Traditional mode.
        * @param args.username Username
        * @param args.password html input value Encrypted password
        **/
        login : function(args){
            var username = args.data.username;
            var password = args.data.password;
            var success = args.success;
            var error = args.error;

            this._class.logIn(username, password, {success: success, error: error});
            return;
        },

        /**
        * Log out the current user
        **/
        logout: function (){
            this._class.logOut();
        },

        /**
        * Get the current user that is logged in the session (localStorage).
        **/
        current: function(args){
            var success = args.success;
            var error = args.error;

            var current_user = this._class.current();

            if (current_user) {

                if (success !== null && typeof success !== "undefined"){
                    success(current_user);
                }

            } else {

                if (error !== null && typeof error !== "undefined"){
                    error();
                }
            }

            return;
        },

        /**
        * Request a password reset to parse.org
        * @param args.email The user email needed to reset the password
        **/
        reset_password : function(args){
            var email = args.data.email;
            var success = args.success;
            var error = args.error;

            this._class.requestPasswordReset(
                email,
                {success: success, error: error}
            );
            return;
        }
    }

});

/**
* Repositorio de usuarios Facebook. Baseado na classe Parse.FacebookUtils
**/
ParseRepository.FacebookUser = ParseRepository.User.extend({

    prototype: {

        _util: Parse.FacebookUtils,

        /**
        * @see ParseRepository.FacebookUser.login
        **/
        signup : function(args) {
            return this.login(args);
        },

        /**
        * Redirect to signup method
        **/
        post : function(args){
            return this.login(args);
        },

        /**
        * Login or sign up a user through Facebook
        * @param args.permisions Facebook permissions
        **/
        login: function(args){
            var permissions = args.data.permissions;
            var success = args.success;
            var error = args.error;

            if (typeof permissions === "undefined"){
                permissions = "email";
            }

            function login_callback(response){

                if (!response.existed()) {
                    console.log("User signed up and logged in through Facebook.");
                } else {
                    console.log("User just logged in through Facebook!");
                }

                if (success !== null && typeof success !== "undefined"){
                    success(response);
                }

            };

            this._util.logIn(
                permissions,
                {success: login_callback, error: error}
            );
            return;
        },

        /**
        * Associate an existing Parse.User to a Facebook account
        * @param args.id User ID
        **/
        link: function(args){
            var objectId = args.data.objectId;
            var permissions = args.data.permissions;
            var success = args.success;
            var error = args.error;

            function get_callback(response){
                if (!this._util.isLinked(response)) {
                    this._util.link(
                        response,
                        permissions,
                        {success: success, error: error}
                    );
                }
            }

            this.get({data: {objectId: objectId}, success: get_callback, error: error});
            return;
        },

        /**
        * Unassociate an existing Parse.User to a Facebook account
        * @param args.id User object ID
        **/
        unlink: function(args){
            var objectId = args.data.objectId;
            var success = args.success;
            var error = args.error;

            function get_callback(response){
                this._util.unlink(
                    response, {success: success, error: error}
                );
            }

            this.get({data: {objectId: objectId}, success: get_callback, error: error});
            return;
        },

        /**
        * Login or sign up a user through Facebook (openFB)
        * @see https://github.com/fernandojunior/OpenFB
        * @param args.permisions Facebook permissions
        **/
        loginWithOpenFB: function(args){
            var permissions = args.data.permissions;
            var success = args.success;
            var error = args.error;

            if (typeof permissions === "undefined"){
                permissions = "email";
            }

            if (typeof openFB === "undefined"){
                console.log("openFB was not loaded. See https://github.com/fernandojunior/OpenFB");
                return;
            }

            var self = this;

            openFB.login(
                permissions,
                function(response){

                    console.log("Logged in with openFB.");

                    // setting the auth data for parse login
                    var authData = {
                        id: response.auth_response.user_id,
                        access_token: response.auth_response.access_token,
                        expiration_date: new Date(response.auth_response.expires_in * 1000 +
                                                  (new Date()).getTime()).toJSON()
                    };

                    self.login({data: {permissions: authData}, success: success, error: error});

                },
                function(){
                    if (typeof error !== "undefined"){
                        error(arguments);
                    }
                }
            )

            return;
        }

    }

});


text:
package eu.riscoss.agent.services;

import eu.riscoss.agent.RiscossRESTClient;

public class DomainService extends RESTService {

	public DomainService( RiscossRESTClient rest, String name) {
		super( rest );
		this.rest.set( "domain", name );
	}

	public LayersService layers() {
		return new LayersService( this.rest );
	}

	public LayerService layer( String layer ) {
		return new LayerService( this.rest, layer );
	}

	public EntityService entity( String entity ) {
		return new EntityService( this.rest, entity );
	}

	public EntitiesService entities() {
		return new EntitiesService( rest );
	}

	public ModelsService models() {
		return new ModelsService( rest );
	}

	public RCSService rcs() {
		return new RCSService( rest );
	}

	public AnalysisService analysis() {
		return new AnalysisService( rest );
	}

	public RDRService rdr() {
		return new RDRService( rest );
	}

}


text:
class TeamOwnerList < ApplicationRecord
  belongs_to :team
  belongs_to :team_owner

  validates :team_owner_id, presence: true
  validates :team_id, presence: true
end


text:
'use strict';

var MenuItem = function (config) {
    this.weight = 0;
    this.isIconVisible = true;
    this.isDivider = false;
    this.isReadOnly = false;
    this.ngBindHtml = '';
    angular.extend(this, config);
};

MenuItem.prototype.children = function () {
    var children = [];
    angular.forEach(this, function (property) {
        if (angular.isObject(property) && property instanceof MenuItem) {
            children.push(property);
        }
    });
    return children;
};

MenuItem.prototype.hasChildren = function () {
    return this.children().length > 0;
};

MenuItem.prototype._isVisible = function () {
    var hasVisibleChildren = this.children().filter(function (child) {
        return child._isVisible() !== false;
    }).length > 0;

    if (!hasVisibleChildren &&
        !this.isDivider &&
        angular.isUndefined(this.state) &&
        angular.isUndefined(this.href) &&
        angular.isUndefined(this.click) &&
        angular.isUndefined(this.ngInclude) &&
        !this.isReadOnly) {
        return false;
    }

    if (angular.isFunction(this.isVisible)) {
        return this.isVisible();
    }
    if (angular.isDefined(this.isVisible)) {
        return this.isVisible;
    }
    return true;
};

MenuItem.prototype.isVisible = function () {
    return true;
};

MenuItem.prototype.isHeavy = function () {
    if (this.hasOwnProperty('weight')) {
        return this.weight >= 0;
    }
};

MenuItem.prototype._ngBindHtml = function () {
    return angular.isFunction(this.ngBindHtml) ? this.ngBindHtml() : this.ngBindHtml;
};


text:
<?xml version="1.0" encoding="UTF-8" ?>
<Page>
  <ScrollView>
    <StackLayout>
      <Button text="alert" tap="alertTapped"/>
      <Button text="alert with options" tap="alertWithOptionsTapped"/>
      <Button text="confirm" tap="confirmTapped"/>
      <Button text="confirm with options" tap="confirmWithOptionsTapped"/>
      <Button text="prompt" tap="promptTapped"/>
      <Button text="prompt with options" tap="promptWithOptionsTapped"/>
      <Button text="prompt with options password" tap="promptWithOptionsPasswordTapped"/>
      <Button text="login" tap="loginTapped"/>
      <Button text="login with options" tap="loginWithOptionsTapped"/>
      <Button text="action" tap="actionTapped"/>
      <Button text="action with options" tap="actionWithOptionsTapped"/>
    </StackLayout>
  </ScrollView>
</Page>


text:
package com.ecwid.consul.v1.kv.model;

import com.ecwid.consul.json.Base64TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;

import java.util.Arrays;

/**
 * @author Vasily Vasilkov (vgv@ecwid.com)
 */
public class GetBinaryValue {

	@SerializedName("CreateIndex")
	private long createIndex;

	@SerializedName("ModifyIndex")
	private long modifyIndex;

	@SerializedName("LockIndex")
	private Long lockIndex;

	@SerializedName("Flags")
	private long flags;

	@SerializedName("Session")
	private String session;

	@SerializedName("Key")
	private String key;

	@SerializedName("Value")
	@JsonAdapter(Base64TypeAdapter.class)
	private byte[] value;

	public long getCreateIndex() {
		return createIndex;
	}

	public void setCreateIndex(long createIndex) {
		this.createIndex = createIndex;
	}

	public long getModifyIndex() {
		return modifyIndex;
	}

	public void setModifyIndex(long modifyIndex) {
		this.modifyIndex = modifyIndex;
	}

	public Long getLockIndex() {
		return lockIndex;
	}

	public void setLockIndex(Long lockIndex) {
		this.lockIndex = lockIndex;
	}

	public long getFlags() {
		return flags;
	}

	public void setFlags(long flags) {
		this.flags = flags;
	}

	public String getSession() {
		return session;
	}

	public void setSession(String session) {
		this.session = session;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public byte[] getValue() {
		return value;
	}

	public void setValue(byte[] value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "GetBinaryValue{" +
				"createIndex=" + createIndex +
				", modifyIndex=" + modifyIndex +
				", lockIndex=" + lockIndex +
				", flags=" + flags +
				", session='" + session + '\'' +
				", key='" + key + '\'' +
				", value=" + Arrays.toString(value) +
				'}';
	}
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using Cosmos.Logging.Events;
using Cosmos.Logging.Formattings;

namespace Cosmos.Logging.Sinks.File.Renderers {
    /// <summary>
    /// Basic output preferences renderer
    /// </summary>
    public abstract class BasicOutputPreferencesRenderer : IOutputPreferencesRenderer {
        /// <inheritdoc />
        public abstract string Name { get; }

        /// <inheritdoc />
        public virtual bool IsNull => false;

        /// <inheritdoc />
        public abstract string ToString(string format, string paramsText,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null);

        /// <inheritdoc />
        public abstract string ToString(IList<FormatEvent> formattingEvents, string paramsText,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null);

        /// <inheritdoc />
        public abstract string ToString(IList<Func<object, IFormatProvider, object>> formattingFuncs, string paramsText,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null);

        /// <inheritdoc />
        public virtual void Render(string format, string paramsText, StringBuilder stringBuilder,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null) {
            stringBuilder.Append(ToString(format, paramsText, logEvent, targetMessageBuilder, formatProvider));
        }

        /// <inheritdoc />
        public virtual void Render(IList<FormatEvent> formattingEvents, string paramsText, StringBuilder stringBuilder,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null) {
            stringBuilder.Append(ToString(formattingEvents, paramsText, logEvent, targetMessageBuilder, formatProvider));
        }

        /// <inheritdoc />
        public virtual void Render(IList<Func<object, IFormatProvider, object>> formattingFuncs, string paramsText, StringBuilder stringBuilder,
            LogEvent logEvent, StringBuilder targetMessageBuilder, IFormatProvider formatProvider = null) {
            stringBuilder.Append(ToString(formattingFuncs, paramsText, logEvent, targetMessageBuilder, formatProvider));
        }
    }
}


text:
package com.jtbdevelopment.games.factory;

import com.jtbdevelopment.games.state.Game;

/**
 * Date: 1/13/15 Time: 7:12 AM
 */
public interface GameValidator<IMPL extends Game> {

  boolean validateGame(final IMPL game);

  String errorMessage();
}


text:
title: Perfect Full Page Background Image
localeTitle: Imagem de fundo perfeita página inteira
---
## Imagem de fundo perfeita página inteira

Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/css/tutorials/perfect-full-page-background-image/index.md) .

[Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Mais Informações:


text:
using System;

namespace pilha_csharp
{
    class Stack : IStack
    {
        private int control;
        private Object[] stack;
        private int constant;

        private void updateStack(Object[] oldStack, int newLength) {
          this.stack = new Object[newLength];
          for (int i = 0; i < oldStack.Length; i++) {
            this.stack[i] = oldStack[i];
          }
        }

        private void handleFull() {
          if (this.control < this.stack.Length) {
            return;
          }
          int newLength;
          if (this.constant > 0) {
            newLength = this.stack.Length + this.constant;
          } else {
            newLength = this.stack.Length * 2;
          }
          this.updateStack(this.stack, newLength);
        }

        public Stack(int constant = 0) {
          this.control = 0;
          this.constant = constant;
          this.stack = new Object[20];
        }

        public void Push(Object o) {
          this.handleFull();
          int i = this.control;
          this.stack[i] = o;
          this.control++;
        }

        public Object Pop() {
          if (this.IsEmpty()) {
            throw new Exception("Stack is empty! Pop() not allowed.");
          }
          Object o = this.stack[this.control - 1];
          this.stack[this.control - 1] = null;
          this.control--;
          return o;
        }

        public Object Top() {
          if (this.IsEmpty()) {
            throw new Exception("Stack is empty! Top() not allowed.");
          }
          return this.stack[this.control - 1];
        }

        public int GetSize() {
          return this.control;
        }

        public bool IsEmpty() {
          return this.control == 0;
        }
    }
}


text:
using GraphQL.Validation.Rules;
using Xunit;

namespace GraphQL.Tests.Validation
{
    public class KnownArgumentNamesTests : ValidationTestBase<KnownArgumentNames, ValidationSchema>
    {
        [Fact]
        public void single_arg_is_known()
        {
            ShouldPassRule(@"
              fragment argOnRequiredArg on Dog {
                doesKnowCommand(dogCommand: SIT)
              }
            ");
        }

        [Fact]
        public void no_args_are_known()
        {
            ShouldPassRule(@"
              fragment multipleArgs on ComplicatedArgs {
                noArgsField
              }
            ");
        }

        [Fact]
        public void multiple_args_are_known()
        {
            ShouldPassRule(@"
              fragment multipleArgs on ComplicatedArgs {
                multipleReqs(req1: 1, req2: 2)
              }
            ");
        }

        [Fact]
        public void ignores_args_of_unknown_fields()
        {
            ShouldPassRule(@"
              fragment argOnUnknownField on Dog {
                unknownField(unknownArg: SIT)
              }
            ");
        }

        [Fact]
        public void multiple_args_in_reverse_order_are_known()
        {
            ShouldPassRule(@"
              fragment multipleArgsReverseOrder on ComplicatedArgs {
                multipleReqs(req2: 2, req1: 1)
              }
            ");
        }

        [Fact]
        public void no_args_on_optional_arg()
        {
            ShouldPassRule(@"
              fragment noArgOnOptionalArg on Dog {
                isHousetrained
              }
            ");
        }

        [Fact]
        public void args_are_known_deeply()
        {
            ShouldPassRule(@"
              {
                dog {
                  doesKnowCommand(dogCommand: SIT)
                }
                human {
                  pet {
                    ... on Dog {
                      doesKnowCommand(dogCommand: SIT)
                    }
                  }
                }
              }
            ");
        }

        [Fact]
        public void directive_args_are_known()
        {
            ShouldPassRule(@"
              {
                dog @skip(if: true)
              }
            ");
        }

        [Fact]
        public void field_with_no_args_given_arg_is_invalid()
        {
            ShouldFailRule(_ =>
            {
                _.Query = @"
                  fragment multipleArgs on ComplicatedArgs {
                    noArgsField(first: 1)
                  }
                ";
                _.Error(Rule.UnknownArgMessage("first", "noArgsField", "ComplicatedArgs", null), 3, 33);
            });
        }

        [Fact]
        public void undirective_args_are_invalid()
        {
            ShouldFailRule(_ =>
            {
                _.Query = @"
                  {
                    dog @skip(unless: true)
                  }
                ";
                _.Error(Rule.UnknownDirectiveArgMessage("unless", "skip", null), 3, 31);
            });
        }

        [Fact]
        public void invalid_arg_name()
        {
            ShouldFailRule(_ =>
            {
                _.Query = @"
                  fragment oneGoodArgOneInvalidArg on Dog {
                    doesKnowCommand(whoknows: 1, dogCommand: SIT, unknown: true)
                  }
                ";
                _.Error(Rule.UnknownArgMessage("whoknows", "doesKnowCommand", "Dog", null), 3, 37);
                _.Error(Rule.UnknownArgMessage("unknown", "doesKnowCommand", "Dog", null), 3, 67);
            });
        }

        [Fact]
        public void unknown_args_deeply()
        {
            ShouldFailRule(_ =>
            {
                _.Query = @"
                  {
                    dog {
                      doesKnowCommand(unknown: true)
                    }
                    human {
                      pet {
                        ... on Dog {
                          doesKnowCommand(unknown: true)
                        }
                      }
                    }
                  }
                ";
                _.Error(Rule.UnknownArgMessage("unknown", "doesKnowCommand", "Dog", null), 4, 39);
                _.Error(Rule.UnknownArgMessage("unknown", "doesKnowCommand", "Dog", null), 9, 43);
            });
        }
    }
}


text:
if (!%IsConcurrentRecompilationSupported()) {
  print("Concurrent recompilation is disabled. Skipping this test.");
  quit();
}

function new_object() {
  var o = {};
  o.a = 1;
  o.b = 2;
  return o;
}

function add_field(obj) {
  obj.c = 3;
}

add_field(new_object());
add_field(new_object());
%OptimizeFunctionOnNextCall(add_field, "concurrent");

var o = new_object();
// Kick off recompilation.
add_field(o);
// Invalidate transition map after compile graph has been created.
o.c = 2.2;
// In the mean time, concurrent recompiling is still blocked.
assertUnoptimized(add_field, "no sync");
// Let concurrent recompilation proceed.
%UnblockConcurrentRecompilation();
// Sync with background thread to conclude optimization that bailed out.
assertUnoptimized(add_field, "sync");


text:
from django.core.management import call_command

from celery import shared_task

@shared_task()
def tweet_next_task():
    call_command('tweet_next', verbose=True, interactive=False)


text:
#pragma once

#include <cstdint>
#include <vector>

#include <QString>

#include "dbif/types.h"

namespace veles {
namespace dbif {

struct Error {
  virtual ~Error() {}

 protected:
  Error() {}
};

struct ObjectGoneError : Error {};
struct ObjectInvalidRequestError : Error {};
struct BlobDataInvalidRangeError : Error {};
struct BlobDataInvalidWidthError : Error {};
struct InvalidTypeError : Error {};

}  // namespace dbif
}  // namespace veles


text:
jQuery( function ( $ ) {
	$( '.contact-form input[type="date"]' ).datepicker( { dateFormat : 'yy-mm-dd' } );
} );


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Calc
{
    public class Multiplication : TwoOperands
    {
        public Multiplication(AbstractOperation l, AbstractOperation r) : base(l, r) { }
        public override float Eval() { return left.Eval() * right.Eval(); }
    }
}


text:
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;

namespace EventFlow.Subscribers
{
    public interface ISubscribeSynchronousToAll
    {
        Task HandleAsync(
            IReadOnlyCollection<IDomainEvent> domainEvents,
            CancellationToken cancellationToken);
    }
}


text:
import os
import ast
from MovieData import MovieData
from whoosh.fields import Schema, TEXT, KEYWORD, ID, STORED, DATETIME, NUMERIC, BOOLEAN
from whoosh.analysis import StemmingAnalyzer
from whoosh.qparser import QueryParser
from whoosh import index, query
from whoosh import scoring
import sys, time
reload(sys)
sys.setdefaultencoding("utf-8")

BASE_PATH="/Users/bhavyachandra/Desktop/trial/"
FILEPATH="/Users/bhavyachandra/Desktop/Index_notstemmed"
# Schema for Movie data
# Stored= True corresponds to all items that require to be returned with the search result
# schema = Schema(overview=TEXT(analyzer=StemmingAnalyzer(), spelling=True, stored=True),
#                 tagline=TEXT(analyzer=StemmingAnalyzer(), spelling=True, stored=True),
#                 title=TEXT(analyzer=StemmingAnalyzer(), spelling=True, stored=True),
#                 production_companies=TEXT(analyzer=StemmingAnalyzer(), spelling=True, stored=True),
#                 genres=TEXT(analyzer=StemmingAnalyzer(), spelling=True, stored=True),
#                 runtime=STORED,
#                 poster_path=STORED,
#                 imdb_id=ID(stored=True),
#                 popularity=NUMERIC(float,bits=64, stored=True),
#                 revenue=NUMERIC(float,bits=64, stored=True),
#                 vote_average=NUMERIC(float,bits=64, stored=True),
#                 adult=BOOLEAN(stored=True),
#                 release_date=DATETIME(stored=True)
#                 )

# # instantiate index
# if not os.path.exists(FILEPATH):
#     os.mkdir(FILEPATH)
# ix = index.create_in(FILEPATH, schema)
#
# #open index writer
ix = index.open_dir(FILEPATH)
# writer = ix.writer()
#
# count1=10
# for i in range(1, count1):
#     f21=MovieData(BASE_PATH+str(i)+'.txt')
#     print (i)
#     prod=[]
#     # print (f2.get("production_companies"))
#     for x in f21.get("production_companies"):
#         prod.append(x['name'])
#     genres=[]
#     for x in f21.get("genres"):
#         genres.append(x['name'])
#
#     prodstring=''
#     for x in prod:
#         prodstring=prodstring+x+' '
#     print (prodstring)
#     genrestring=''
#     for x in genres:
#         genrestring=genrestring+x+' '
#     print (genrestring)
#     rdate=f21.get("release_date")
#     print (rdate)
#     if rdate=='':
#         rdate=u'2100-10-10'
#     f2=dict()
#     f2['overview']=f21.get('overview')
#     f2['tagline']=f21.get('tagline')
#     f2['title']=f21.get('title')
#     f2['runtime']=f21.get('runtime')
#     f2['poster_path']=f21.get('poster_path')
#     f2['imdb_id']=f21.get('imdb_id')
#     f2['popularity']=f21.get('popularity')
#     f2['revenue']=f21.get('revenue')
#     f2['vote_average']=f21.get('vote_average')
#     f2['adult']=f21.get('adult')
#
#
#
#     print ("##################################################################################")
#     writer.add_document(overview=unicode(f2['overview']), tagline=unicode(f2['tagline']),title=unicode(f2['title']), production_company=unicode(prodstring), \
#                     genre=unicode(genrestring),runtime=unicode(f2['runtime']), poster=unicode(f2['poster_path']),IMDB_id=unicode(f2['imdb_id']),Popularity=unicode(f2['popularity']),\
#                     Revenue=unicode(f2['revenue']), Vote_Avg=unicode(f2['vote_average']), Adult=unicode(f2['adult']), Release_Date=unicode(rdate))
#
# #commit writer
# writer.commit()
# print("done ##################################################################################")

qstring="crime"
qp = QueryParser("genres", schema=ix.schema, termclass=query.Variations)
q = qp.parse(qstring)
mistyped_words = []

start = time.time()
with ix.searcher(weighting=scoring.TF_IDF()) as s:
    corrected = s.correct_query(q, qstring)
    if corrected.query != q:
        print("Did you mean:", corrected.string)
    for word in qstring.split(" "):
        if word not in corrected.string:
            mistyped_words.append(word)
    print (mistyped_words)
    corrector = s.corrector("genres")
    for mistyped_word in mistyped_words:
        lis=corrector.suggest(mistyped_word, limit=3)
        print lis
        q = qp.parse(corrected.string)
    results = s.search(q)
    print (len(results))
    print (list(results))
    counter = 0
    for hit in results:
        print hit['title']
        counter += 1
        if counter == 10:
            break
    # print ((list(s.lexicon("overview"))))
    # print (len(list(s.lexicon("title"))))
    # print (len(list(s.lexicon("tagline"))))
    # print (len(list(s.lexicon("production_companies"))))
    # print (len(list(s.lexicon("genres"))))
end = time.time()
print ("Total time:"+str((end-start)*1000))