text:
#import "OIDServiceDiscoveryTests.h"

#import "Source/OIDError.h"
#import "Source/OIDServiceDiscovery.h"

/*! Testing URL used when testing URL conversions. */
static NSString *const kTestURL = @"http://www.google.com/";

/*! A string for testing an invalid URL. */
static NSString *const kTestURLInvalid = @"abc";

/*! Field keys associated with an OpenID Connect Discovery Document. */
static NSString *const kIssuerKey = @"issuer";
static NSString *const kAuthorizationEndpointKey = @"authorization_endpoint";
static NSString *const kTokenEndpointKey = @"token_endpoint";
static NSString *const kUserinfoEndpointKey = @"userinfo_endpoint";
static NSString *const kJWKSURLKey = @"jwks_uri";
static NSString *const kRegistrationEndpointKey = @"registration_endpoint";
static NSString *const kScopesSupportedKey = @"scopes_supported";
static NSString *const kResponseTypesSupportedKey = @"response_types_supported";
static NSString *const kResponseModesSupportedKey = @"response_modes_supported";
static NSString *const kGrantTypesSupportedKey = @"grant_types_supported";
static NSString *const kACRValuesSupportedKey = @"acr_values_supported";
static NSString *const kSubjectTypesSupportedKey = @"subject_types_supported";
static NSString *const kIDTokenSigningAlgorithmValuesSupportedKey =
    @"id_token_signing_alg_values_supported";
static NSString *const kIDTokenEncryptionAlgorithmValuesSupportedKey =
    @"id_token_encryption_alg_values_supported";
static NSString *const kIDTokenEncryptionEncodingValuesSupportedKey =
    @"id_token_encryption_enc_values_supported";
static NSString *const kUserinfoSigningAlgorithmValuesSupportedKey =
    @"userinfo_signing_alg_values_supported";
static NSString *const kUserinfoEncryptionAlgorithmValuesSupportedKey =
    @"userinfo_encryption_alg_values_supported";
static NSString *const kUserinfoEncryptionEncodingValuesSupportedKey =
    @"userinfo_encryption_enc_values_supported";
static NSString *const kRequestObjectSigningAlgorithmValuesSupportedKey =
    @"request_object_signing_alg_values_supported";
static NSString *const kRequestObjectEncryptionAlgorithmValuesSupportedKey =
    @"request_object_encryption_alg_values_supported";
static NSString *const kRequestObjectEncryptionEncodingValuesSupported =
    @"request_object_encryption_enc_values_supported";
static NSString *const kTokenEndpointAuthMethodsSupportedKey =
    @"token_endpoint_auth_methods_supported";
static NSString *const kTokenEndpointAuthSigningAlgorithmValuesSupportedKey =
    @"token_endpoint_auth_signing_alg_values_supported";
static NSString *const kDisplayValuesSupportedKey = @"display_values_supported";
static NSString *const kClaimTypesSupportedKey = @"claim_types_supported";
static NSString *const kClaimsSupportedKey = @"claims_supported";
static NSString *const kServiceDocumentationKey = @"service_documentation";
static NSString *const kClaimsLocalesSupportedKey = @"claims_locales_supported";
static NSString *const kUILocalesSupportedKey = @"ui_locales_supported";
static NSString *const kClaimsParameterSupportedKey = @"claims_parameter_supported";
static NSString *const kRequestParameterSupportedKey = @"request_parameter_supported";
static NSString *const kRequestURIParameterSupportedKey = @"request_uri_parameter_supported";
static NSString *const kRequireRequestURIRegistrationKey = @"require_request_uri_registration";
static NSString *const kOPPolicyURIKey = @"op_policy_uri";
static NSString *const kOPTosURIKey = @"op_tos_uri";

@implementation OIDServiceDiscoveryTests

+ (NSDictionary *)minimumServiceDiscoveryDictionary {
  return @{
    kIssuerKey : @"http://www.example.com/issuer",
    kAuthorizationEndpointKey : @"http://www.example.com/authorization",
    kTokenEndpointKey : @"http://www.example.com/token",
    kJWKSURLKey : @"http://www.example.com/jwks",
    kResponseTypesSupportedKey : @"Response Types Supported",
    kSubjectTypesSupportedKey : @"Subject Types Supported",
    kIDTokenSigningAlgorithmValuesSupportedKey : @"ID Token Signing Algorithm Values Supported",
  };
}

+ (NSDictionary *)completeServiceDiscoveryDictionary {
  return @{
    kIssuerKey : @"http://www.example.com/issuer",
    kAuthorizationEndpointKey : @"http://www.example.com/authorization",
    kTokenEndpointKey : @"http://www.example.com/token",
    kUserinfoEndpointKey : @"User Info Endpoint",
    kJWKSURLKey : @"http://www.example.com/jwks",
    kRegistrationEndpointKey : @"Registration Endpoint",
    kScopesSupportedKey : @"Scopes Supported",
    kResponseTypesSupportedKey : @"Response Types Supported",
    kResponseModesSupportedKey : @"Response Modes Supported",
    kGrantTypesSupportedKey : @"Grant Types Supported",
    kACRValuesSupportedKey : @"ACR Values Supported",
    kSubjectTypesSupportedKey : @"Subject Types Supported",
    kIDTokenSigningAlgorithmValuesSupportedKey : @"Token Signing Algorithm Values Supported",
    kIDTokenEncryptionAlgorithmValuesSupportedKey : @"Token Encryption Algorithm Values Supported",
    kIDTokenEncryptionEncodingValuesSupportedKey : @"token Encryption Encoding Values Supported",
    kUserinfoSigningAlgorithmValuesSupportedKey : @"User Info Signing Algorithm Values Supported",
    kUserinfoEncryptionAlgorithmValuesSupportedKey :
        @"User Info Encryption Algorithm Values Supported",
    kUserinfoEncryptionEncodingValuesSupportedKey :
        @"User Info Encryption Encoding Values Supported",
    kRequestObjectSigningAlgorithmValuesSupportedKey :
        @"Request Object Signing Algorithm Values Supported",
    kRequestObjectEncryptionAlgorithmValuesSupportedKey :
        @"Reqest Object Encryption Algorithm Values Supported",
    kRequestObjectEncryptionEncodingValuesSupported :
        @"Request Object Encryption Encoding Values Supported",
    kTokenEndpointAuthMethodsSupportedKey : @"Token Endpoint Auth Methods Supported",
    kTokenEndpointAuthSigningAlgorithmValuesSupportedKey :
        @"Token Endpoint Auth Signing Algorithm Values Supported",
    kDisplayValuesSupportedKey : @"Display Values Supported",
    kClaimTypesSupportedKey : @"Claim Types Supported",
    kClaimsSupportedKey : @"Claims Supported",
    kServiceDocumentationKey : @"Service Documentation",
    kClaimsLocalesSupportedKey : @"Claims Locales Supported",
    kUILocalesSupportedKey : @"UI Locales Supported",
    kClaimsParameterSupportedKey : @YES,
    kRequestParameterSupportedKey : @YES,
    kRequestURIParameterSupportedKey : @NO,
    kRequireRequestURIRegistrationKey : @YES,
    kOPPolicyURIKey : @"OP Policy URI",
    kOPTosURIKey : @"OP TOS URI",
  };
}

+ (NSURL *)googleDiscoveryAuthorizationEndpoint {
  return [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/v2/auth"];
}

// from https://accounts.google.com/.well-known/openid-configuration
static NSString *const kDiscoveryDocument =
    @"{\"issuer\":\"https://accounts.google.com\",\"authorization_endpoint\":\"https://account"
      "s.google.com/o/oauth2/v2/auth\",\"token_endpoint\":\"https://www.googleapis.com/oauth2/v4/to"
      "ken\",\"userinfo_endpoint\":\"https://www.googleapis.com/oauth2/v3/userinfo\",\"revocation_e"
      "ndpoint\":\"https://accounts.google.com/o/oauth2/revoke\",\"jwks_uri\":\"https://www.googlea"
      "pis.com/oauth2/v3/certs\",\"response_types_supported\":[\"code\",\"token\",\"id_token\",\"co"
      "de token\",\"code id_token\",\"token id_token\",\"code token id_token\",\"none\"],\"subject_"
      "types_supported\":[\"public\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"scope"
      "s_supported\":[\"openid\",\"email\",\"profile\"],\"token_endpoint_auth_methods_supported\":["
      "\"client_secret_post\",\"client_secret_basic\"],\"claims_supported\":[\"aud\",\"email\",\"em"
      "ail_verified\",\"exp\",\"family_name\",\"given_name\",\"iat\",\"iss\",\"locale\",\"name\",\""
      "picture\",\"sub\"]}";

// from https://accounts.google.com/.well-known/openid-configuration with authorization_endpoint
// removed
static NSString *const kDiscoveryDocumentMissingField =
    @"{\"issuer\":\"https://accounts.google.com\",\"token_endpoint\":\"https://www.googleapis."
      "com/oauth2/v4/to"
      "ken\",\"userinfo_endpoint\":\"https://www.googleapis.com/oauth2/v3/userinfo\",\"revocation_e"
      "ndpoint\":\"https://accounts.google.com/o/oauth2/revoke\",\"jwks_uri\":\"https://www.googlea"
      "pis.com/oauth2/v3/certs\",\"response_types_supported\":[\"code\",\"token\",\"id_token\",\"co"
      "de token\",\"code id_token\",\"token id_token\",\"code token id_token\",\"none\"],\"subject_"
      "types_supported\":[\"public\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"scope"
      "s_supported\":[\"openid\",\"email\",\"profile\"],\"token_endpoint_auth_methods_supported\":["
      "\"client_secret_post\",\"client_secret_basic\"],\"claims_supported\":[\"aud\",\"email\",\"em"
      "ail_verified\",\"exp\",\"family_name\",\"given_name\",\"iat\",\"iss\",\"locale\",\"name\",\""
      "picture\",\"sub\"]}";

  // from https://accounts.google.com/.well-known/openid-configuration with authorization_endpoint
  // and token_endpoint set to JSON 'null'
static NSString *const kDiscoveryDocumentNullField =
    @"{\"issuer\":\"https://accounts.google.com\",\"authorization_endpoint\":null,"
      "\"token_endpoint\":null"
      ",\"userinfo_endpoint\":\"https://www.googleapis.com/oauth2/v3/userinfo\",\"revocation_e"
      "ndpoint\":\"https://accounts.google.com/o/oauth2/revoke\",\"jwks_uri\":\"https://www.googlea"
      "pis.com/oauth2/v3/certs\",\"response_types_supported\":[\"code\",\"token\",\"id_token\",\"co"
      "de token\",\"code id_token\",\"token id_token\",\"code token id_token\",\"none\"],\"subject_"
      "types_supported\":[\"public\"],\"id_token_signing_alg_values_supported\":[\"RS256\"],\"scope"
      "s_supported\":[\"openid\",\"email\",\"profile\"],\"token_endpoint_auth_methods_supported\":["
      "\"client_secret_post\",\"client_secret_basic\"],\"claims_supported\":[\"aud\",\"email\",\"em"
      "ail_verified\",\"exp\",\"family_name\",\"given_name\",\"iat\",\"iss\",\"locale\",\"name\",\""
      "picture\",\"sub\"]}";

/*! @fn testURLs
    @brief Tests that URLs are handled properly when converted from the dictionary's string
        representation.
 */
- (void)testURLs {
  NSError *error;
  NSMutableDictionary *serviceDiscoveryDictionary =
      [[[self class] minimumServiceDiscoveryDictionary] mutableCopy];
  serviceDiscoveryDictionary[kOPPolicyURIKey] = kTestURL;
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary
                                                error:&error];
  XCTAssertNotNil(discovery, @"We supplied the minimum required fields when initializing the "
                             "service discovery instance, so we should have gotten a new "
                             "instance.");
  XCTAssertNil(error, @"We supplied the minimum required fields when initializing the "
                      "service discovery instance, so we should not have gotten an error.");

  NSURL *testPolicyURL = [NSURL URLWithString:kTestURL];

  XCTAssertEqualObjects(discovery.OPPolicyURI, testPolicyURL);
}

/*! @fn testErrorWhenBadFormat
    @brief Tests that we get an error when the document is not valid JSON.
 */
- (void)testErrorWhenBadFormat {
  NSError *error;
  OIDServiceDiscovery *discovery = [[OIDServiceDiscovery alloc] initWithJSON:@"JUNK" error:&error];
  XCTAssertNil(discovery, @"When initializing a discovery document, it should not return an "
                          "instance if it is not valid JSON.");
  XCTAssertNotNil(error, @"There should be an error indicating we received bad JSON.");
  XCTAssertEqualObjects(error.domain, OIDGeneralErrorDomain);
  XCTAssertEqual(error.code, OIDErrorCodeJSONDeserializationError);
}

/*! @fn testErrorWhenMissingFields
    @brief Tests that we get an error when the required fields aren't in the source dictionary.
 */
- (void)testErrorWhenMissingFields {
  NSError *error;
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:@{ } error:&error];
  XCTAssertNil(discovery, @"When initializing a discovery document, it should not return an "
                          "instance if there are missing required fields.");
  XCTAssertNotNil(error, @"There should be an error indicating we are missing required fields.");
  XCTAssertEqualObjects(error.domain, OIDGeneralErrorDomain);
  XCTAssertEqual(error.code, OIDErrorCodeInvalidDiscoveryDocument);
}

/*! @fn testErrorWhenMissingFields
    @brief Tests that we get an error when the required fields aren't in the source dictionary.
 */
- (void)testErrorWhenMissingFieldsJSON {
  NSError *error;
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithJSON:kDiscoveryDocumentMissingField error:&error];
  XCTAssertNil(discovery, @"When initializing a discovery document with JSON, it should not return"
                          " an instance if there are missing required fields.");
  XCTAssertNotNil(error, @"There should be an error indicating we are missing required fields.");
  XCTAssertEqualObjects(error.domain, OIDGeneralErrorDomain);
  XCTAssertEqual(error.code, OIDErrorCodeInvalidDiscoveryDocument);
}

/*! @fn testNoErrorWhenNoMissingFields
    @brief Tests that we do not get an error, and we do get an instance of
        @c OIDServiceDiscovery when the required fields are in the source dictionary.
 */
- (void)testNoErrorWhenNoMissingFields {
  NSError *error;
  NSDictionary *serviceDiscoveryDictionary = [[self class] minimumServiceDiscoveryDictionary];
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary
                                                error:&error];
  XCTAssertNotNil(discovery, @"We supplied the minimum required fields when initializing the "
                             "service discovery instance, so we should have gotten a new "
                             "instance.");
  XCTAssertNil(error, @"We supplied the minimum required fields when initializing the "
                      "service discovery instance, so we should not have gotten an error.");
}

/*! @fn pendingTestErrorWhenMalformedFields
    @brief Tests that we get an error when the required fields are present but invalid.
 */
// TODO: this test is failing
- (void)pendingTestErrorWhenMalformedFields {
  NSError *error;
  // builds a discovery document with a munged field
  NSMutableDictionary *serviceDiscoveryDictionary =
      [[[self class] minimumServiceDiscoveryDictionary] mutableCopy];
  [serviceDiscoveryDictionary setObject:kTestURLInvalid forKey:kAuthorizationEndpointKey];
  [serviceDiscoveryDictionary setObject:kTestURLInvalid forKey:kTokenEndpointKey];

  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary error:&error];
  XCTAssertNil(discovery,
               @"When initializing a discovery document, it should not return an  instance if there"
                   " are missing required fields.");
  XCTAssertNotNil(error, @"There should be an error indicating we are missing required fields.");
  XCTAssertEqualObjects(error.domain, OIDGeneralErrorDomain);
  XCTAssertEqual(error.code, OIDErrorCodeInvalidDiscoveryDocument);
}

/*! @fn testErrorWhenJSONNullField
    @brief Tests that we get an error when null is passed in through JSON.
 */
// TODO: this test is failing
- (void)pendingTestErrorWhenJSONNullField {
  NSError *error;
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithJSON:kDiscoveryDocumentNullField error:&error];
  XCTAssertNil(discovery, @"When initializing a discovery document, it should not return an "
                          "instance if there are missing required fields.");
  XCTAssertNotNil(error, @"There should be an error indicating we are missing required fields.");
  XCTAssertEqualObjects(error.domain, OIDGeneralErrorDomain);
  XCTAssertEqual(error.code, OIDErrorCodeInvalidDiscoveryDocument);
}

/*! @fn testJSONStringDecoding
    @brief Tests that the JSON String version results in a valid object.
 */
- (void)testJSONStringDecoding {
  NSError *error;
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithJSON:kDiscoveryDocument error:&error];
  XCTAssertNotNil(discovery, @"When initializing a discovery document with JSON it should return a"
                              "valid object");
  XCTAssertNil(error, @"There should not be any errors.");
  XCTAssertEqualObjects(discovery.authorizationEndpoint,
                        [[self class] googleDiscoveryAuthorizationEndpoint]);
}

/*! @fn testJSONDataDecoding
    @brief Tests that the JSON NSData version results in a valid object.
 */
- (void)testJSONDataDecoding {
  NSError *error;
  NSData *jsonData = [kDiscoveryDocument dataUsingEncoding:NSUTF8StringEncoding];
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithJSONData:jsonData error:&error];
  XCTAssertNotNil(discovery, @"When initializing a discovery document with JSON it should return a"
                              "valid object");
  XCTAssertNil(error, @"There should not be any errors.");
  XCTAssertEqualObjects(discovery.authorizationEndpoint,
                        [[self class] googleDiscoveryAuthorizationEndpoint]);
}

/*! @fn testJSONEqualsDictionary
    @brief Tests that initialising with the dictionary initialiser and the JSON initialiser result
        in equal objects.
 */
// TODO: this test is failing
- (void)pendingTestJSONEqualsDictionary {
  NSError *error;
  OIDServiceDiscovery *discovery =
    [[OIDServiceDiscovery alloc] initWithDictionary:[[self class] minimumServiceDiscoveryDictionary]
                                              error:&error];
  XCTAssertNotNil(discovery, @"Discovery document should initialize.");
  XCTAssertNil(error, @"There should not be any errors.");

  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:discovery.discoveryDictionary
                                                     options:0
                                                       error:&error];
  XCTAssertNotNil(jsonData, @"Serialization error");
  XCTAssertNil(error, @"Serialization error");

  OIDServiceDiscovery *discovery2 =
      [[OIDServiceDiscovery alloc] initWithJSONData:jsonData error:&error];
  XCTAssertNotNil(discovery2, @"Discovery document should initialize.");
  XCTAssertNil(error, @"There should not be any errors.");

  XCTAssertEqualObjects(discovery.discoveryDictionary, discovery2.discoveryDictionary);
  XCTAssertEqualObjects(discovery, discovery2);
}

/*! @fn testRequestURIParameterSupportedDefaultToYes
    @brief Tests that requestURIParameterSupported returns YES (the default) when not specified in
        the source dictionary.
 */
- (void)testRequestURIParameterSupportedDefaultToYes {
  NSError *error;
  NSDictionary *serviceDiscoveryDictionary = [[self class] minimumServiceDiscoveryDictionary];
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary
                                                error:&error];
  XCTAssert(discovery.requestURIParameterSupported,
            @"When not specified, |requestURIParameterSupported| should return YES.");
}

/*! @fn testSecureCoding
    @brief Tests the NSSecureCoding by round-tripping an instance through the coding process and
        checking to make sure the source and destination instances have equivalent dictionaries.
 */
- (void)testSecureCoding {
  NSError *error;
  NSDictionary *serviceDiscoveryDictionary = [[self class] completeServiceDiscoveryDictionary];
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary
                                                             error:&error];
  NSData *data = [NSKeyedArchiver archivedDataWithRootObject:discovery];
  OIDServiceDiscovery *unarchived = [NSKeyedUnarchiver unarchiveObjectWithData:data];

  XCTAssertEqualObjects(discovery.discoveryDictionary, unarchived.discoveryDictionary);
}

/*! @fn testCopying
    @brief Tests the NSCopying implementation by round-tripping an instance through the copying
        process and checking to make sure the source and destination instances have equivalent
        dictionaries.
 */
- (void)testCopying {
  NSError *error;
  NSDictionary *serviceDiscoveryDictionary = [[self class] completeServiceDiscoveryDictionary];
  OIDServiceDiscovery *discovery =
      [[OIDServiceDiscovery alloc] initWithDictionary:serviceDiscoveryDictionary
                                                error:&error];

  OIDServiceDiscovery *unarchived = [discovery copy];

  XCTAssertEqualObjects(discovery.discoveryDictionary, unarchived.discoveryDictionary);
}

#pragma mark - Field Mappings

/*! @define TestFieldBackedBy
    @brief Auto-generates unit test methods for checking that a property in
        @c OIDServiceDiscovery is, in fact, using the key specified by the second
        parameter as it's source of data.
 */
#define TestFieldBackedBy(_field_, _backed_by_, _test_value_)                                      \
                                                                                \
- (void)testField_##_field_ {                                                                      \
  NSError *error;                                                                                \
  NSMutableDictionary *json = [[[self class] minimumServiceDiscoveryDictionary] mutableCopy];      \
  [json addEntriesFromDictionary:@{                                                                \
    _backed_by_ : _test_value_                                                                     \
  }];                                                                                \
  OIDServiceDiscovery *discovery =                                                                 \
      [[OIDServiceDiscovery alloc] initWithDictionary:json error:&error];                          \
  XCTAssertNotNil(discovery, @"We supplied the minimum required fields when initializing the "     \
                             "service discovery instance, so we should have gotten a new "         \
                             "instance.");                                                         \
  XCTAssertNil(error, @"We supplied the minimum required fields when initializing the "            \
                      "service discovery instance, so we should not have gotten an error.");       \
  XCTAssertEqualObjects(discovery._field_, _test_value_);                                          \
}

/*! @define TestBooleanFieldBackedBy
    @brief Same as @c TestFieldBackedBy, but tweaked to allow for BOOL values.
 */
#define TestBooleanFieldBackedBy(_field_, _backed_by_, _test_value_)                               \
                                                                                \
- (void)testField_##_field_ {                                                                      \
  NSError *error;                                                                                \
  NSMutableDictionary *json = [[[self class] minimumServiceDiscoveryDictionary] mutableCopy];      \
  [json addEntriesFromDictionary:@{                                                                \
    _backed_by_ : @(_test_value_)                                                                  \
  }];                                                                                \
  OIDServiceDiscovery *discovery =                                                                 \
      [[OIDServiceDiscovery alloc] initWithDictionary:json error:&error];                          \
  XCTAssertNotNil(discovery, @"We supplied the minimum required fields when initializing the "     \
                             "service discovery instance, so we should have gotten a new "         \
                             "instance.");                                                         \
  XCTAssertNil(error, @"We supplied the minimum required fields when initializing the "            \
                      "service discovery instance, so we should not have gotten an error.");       \
  XCTAssertEqual(discovery._field_, _test_value_);                                                 \
}

/*! @define TestURLFieldBackedBy
    @brief Same as @c TestFieldBackedBy, but tweaked to allow for URL values.
 */
#define TestURLFieldBackedBy(_field_, _backed_by_, _test_value_)                                   \
                                                                                \
- (void)testField_##_field_ {                                                                      \
  NSError *error;                                                                                \
  NSMutableDictionary *json = [[[self class] minimumServiceDiscoveryDictionary] mutableCopy];      \
  [json addEntriesFromDictionary:@{                                                                \
    _backed_by_ : _test_value_                                                                     \
  }];                                                                                \
  OIDServiceDiscovery *discovery =                                                                 \
      [[OIDServiceDiscovery alloc] initWithDictionary:json error:&error];                          \
  XCTAssertNotNil(discovery, @"We supplied the minimum required fields when initializing the "     \
                             "service discovery instance, so we should have gotten a new "         \
                             "instance.");                                                         \
  XCTAssertNil(error, @"We supplied the minimum required fields when initializing the "            \
                      "service discovery instance, so we should not have gotten an error.");       \
  XCTAssertEqualObjects(discovery._field_, [NSURL URLWithString:_test_value_]);                    \
}

TestURLFieldBackedBy(issuer, kIssuerKey, kTestURL);
TestURLFieldBackedBy(authorizationEndpoint, kAuthorizationEndpointKey, kTestURL);
TestURLFieldBackedBy(tokenEndpoint, kTokenEndpointKey, kTestURL);
TestURLFieldBackedBy(userinfoEndpoint, kUserinfoEndpointKey, kTestURL);
TestURLFieldBackedBy(jwksURL, kJWKSURLKey, kTestURL);
TestURLFieldBackedBy(registrationEndpoint, kRegistrationEndpointKey, kTestURL);
TestFieldBackedBy(scopesSupported, kScopesSupportedKey, @"Scopes Supported");
TestFieldBackedBy(responseTypesSupported, kResponseTypesSupportedKey, @"Response Types Supported");
TestFieldBackedBy(responseModesSupported, kResponseModesSupportedKey, @"Response Modes Supported");
TestFieldBackedBy(grantTypesSupported, kGrantTypesSupportedKey, @"Grant Types Supported");
TestFieldBackedBy(acrValuesSupported, kACRValuesSupportedKey, @"ACR Values Supported");
TestFieldBackedBy(subjectTypesSupported, kSubjectTypesSupportedKey, @"Subject Types Supported");
TestFieldBackedBy(IDTokenSigningAlgorithmValuesSupported,
                  kIDTokenSigningAlgorithmValuesSupportedKey,
                  @"Token Signing Algorithm Values Supported");
TestFieldBackedBy(IDTokenEncryptionAlgorithmValuesSupported,
                  kIDTokenEncryptionAlgorithmValuesSupportedKey,
                  @"Token Encryption Algorithm Values Supported");
TestFieldBackedBy(IDTokenEncryptionEncodingValuesSupported,
                  kIDTokenEncryptionEncodingValuesSupportedKey,
                  @"token Encryption Encoding Values Supported");
TestFieldBackedBy(userinfoSigningAlgorithmValuesSupported,
                  kUserinfoSigningAlgorithmValuesSupportedKey,
                  @"User Info Signing Algorithm Values Supported");
TestFieldBackedBy(userinfoEncryptionAlgorithmValuesSupported,
                  kUserinfoEncryptionAlgorithmValuesSupportedKey,
                  @"User Info Encryption Algorithm Values Supported");
TestFieldBackedBy(userinfoEncryptionEncodingValuesSupported,
                  kUserinfoEncryptionEncodingValuesSupportedKey,
                  @"User Info Encryption Encoding Values Supported");
TestFieldBackedBy(requestObjectSigningAlgorithmValuesSupported,
                  kRequestObjectSigningAlgorithmValuesSupportedKey,
                  @"Request Object Signing Algorithm Values Supported");
TestFieldBackedBy(requestObjectEncryptionAlgorithmValuesSupported,
                  kRequestObjectEncryptionAlgorithmValuesSupportedKey,
                  @"Reqest Object Encryption Algorithm Values Supported");
TestFieldBackedBy(requestObjectEncryptionEncodingValuesSupported,
                  kRequestObjectEncryptionEncodingValuesSupported,
                  @"Request Object Encryption Encoding Values Supported");
TestFieldBackedBy(tokenEndpointAuthMethodsSupported,
                  kTokenEndpointAuthMethodsSupportedKey,
                  @"Token Endpoint Auth Methods Supported");
TestFieldBackedBy(tokenEndpointAuthSigningAlgorithmValuesSupported,
                  kTokenEndpointAuthSigningAlgorithmValuesSupportedKey,
                  @"Token Endpoint Auth Signing Algorithm Values Supported");
TestFieldBackedBy(displayValuesSupported, kDisplayValuesSupportedKey, @"Display Values Supported");
TestFieldBackedBy(claimTypesSupported, kClaimTypesSupportedKey, @"Claim Types Supported");
TestFieldBackedBy(claimsSupported, kClaimsSupportedKey, @"Claims Supported");
TestURLFieldBackedBy(serviceDocumentation, kServiceDocumentationKey, kTestURL);
TestFieldBackedBy(claimsLocalesSupported, kClaimsLocalesSupportedKey, @"Claims Locales Supported");
TestFieldBackedBy(UILocalesSupported, kUILocalesSupportedKey, @"UI Locales Supported");
TestBooleanFieldBackedBy(claimsParameterSupported, kClaimsParameterSupportedKey, YES);
TestBooleanFieldBackedBy(requestParameterSupported, kRequestParameterSupportedKey, YES);
TestBooleanFieldBackedBy(requestURIParameterSupported, kRequestURIParameterSupportedKey, NO);
TestBooleanFieldBackedBy(requireRequestURIRegistration, kRequireRequestURIRegistrationKey, YES);
TestURLFieldBackedBy(OPPolicyURI, kOPPolicyURIKey, kTestURL);
TestURLFieldBackedBy(OPTosURI, kOPTosURIKey, kTestURL);

@end


text:
# Contributing

One of the great things about open source projects is that anyone can contribute in any number of meaningful ways. ESLint couldn't exist without the help of the many contributors its had since the project began, and we want you to feel like you can contribute and make a difference as well.

This guide is intended for anyone who wants to contribute to ESLint. Please read it carefully as it answers a lot of the questions many newcomers have when first working with ESLint.

## Ways to Contribute

There are many different ways you can contribute to ESLint:

* **Filing issues** - if you find a bug or want to request an enhancement, [file an issue](https://github.com/eslint/eslint/issues/new).
* **Working on issues** - if you have coding skills and want to contribute, you're welcome to pick up [any open issue](https://github.com/eslint/eslint/issues/).
* **Documentation** - if you enjoy writing and want to improve our documentation, it's all in [our repo](https://github.com/eslint/eslint/tree/master/docs) as well.
* **Graphic/web design** - if you want to help improve [eslint.org](http://eslint.org), our HTML, CSS, and JavaScript is all in a [separate repo](https://github.com/eslint/eslint.github.io)
* **Integrations** - if you'd like ESLint support in your favorite text editor, build system, or other software, we could use your help in creating plugins and addons.

For each way to contribute, there are some specific guidelines to keep in mind.

### Filing Issues

You can [file an issue](https://github.com/eslint/eslint/issues/new) directly inside of our GitHub repository. You should file an issue if you:

* Find a bug in ESLint. This means that you believe the behavior of ESLint is incorrect and needs to be fixed.
* Want to request a new feature for ESLint. This means a feature, rule, or capability is missing from ESLint that you think needs to be included.

When you file issues, please be sure to include the following information:

* Which version of ESLint you're currently using. If you installed ESLint via npm, then type `eslint -v` to get the version number. If you're using the latest code from GitHub, please say "I'm using master".
* If you have any interest in addressing the issue yourself.

For bug reports, also include:

1. The source code and configuration information (including `.eslintrc` and `.eslintignore` if applicable).
1. What you did.
1. What you expected to happen.
1. What actually happened.

For feature requests, also include:

1. The problem you want to solve.
1. Your take on the correct solution to problem.

Please include as much detail as possible to help us properly address your issue. If we need to triage issues and constantly ask people for more detail, that's time taken away from actually fixing issues. Help us be as efficient as possible by including a lot of detail in your issues.

**Note:** If you just have a question that won't necessarily result in a change to ESLint, such as asking how something works or how to contribute, please use the [mailing list](https://groups.google.com/group/eslint) instead of filing an issue.

### Working on Issues

You are welcome to work on any open issue in the [issues list](https://github.com/eslint/eslint/issues). If it's open, that means we are planning on doing it in the future, and your help is appreciated. Some thing to keep in mind:

* **Beginner issues** - if you've never contributed to ESLint before, you make want to try on of our [beginniner issues](https://github.com/eslint/eslint/issues?labels=beginner&milestone=&page=1&state=open). These are issues that tagged for beginners because they are small and self-contained.
* **Upcoming milestone issues** - if you're not sure what are the highest priority issues, then take a look at the issues assigned to the [next milestone](https://github.com/eslint/eslint/issues/milestones). The top milestone in the list is the one we're working towards, and these issues have highest priority.

If you're going to work on an issue, please add a comment to that issue saying so and indicating when you think you will complete it. It will help us to avoid duplication of effort. Some examples of good comments are:

* "I'll take a look at this over the weekend."
* "I'm going to do this, give me two weeks."
* "Working on this" (as in, I'm working on it right now)

If an issue has already been claimed by someone, please do not work on it.

If you find you can't finish the work, then simply add a comment letting people know, for example:

* "Sorry, it looks like I don't have time to do this."
* "I thought I knew enough to fix this, but it turns out I don't."

No one will blame you for backing out of an issue if you are unable to complete it. We just want to keep the process moving along as efficiently as possible.

### Documentation

We treat documentation the same as we do code, and that means you are welcome to improve upon it. The documentation is located in [our repo](https://github.com/eslint/eslint/tree/master/docs). All of this documentation gets converted into HTML and pushed to [eslint.org](http://eslint.org) with each release.

There are lots of ways to help:

* Fix typos
* Improve existing documentation
* Add new sections or pages

The ESLint project is committed to having great documentation as we believe that quality documentation is ultimately what causes projects to succeed or fail.

### Graphic/Web Design

Our site, [eslint.org](http://eslint.org) is our public face. It was started by designers and developers who donated their time and energy to getting it off the ground, and in the spirit of open source, we have shared the code in a [separate repo](https://github.com/eslint/eslint.github.io).

If you want to help, please check the [site issues]() to see where your help is most needed. In addition, we are always looking to improve our layout, design, and information architecture. Just as with the main ESLint project, you should feel free to file and work on issues.

**Important:** The documentation (everything under http://eslint.org/docs/) actually resides in the [main repo](https://github.com/eslint/eslint/tree/master/docs). Changes to that content must be made there. These pages are auto-generated on [eslint.org](http://eslint.org) with each release.

### Integrations

Part of what makes ESLint useful is the way it integrates into other systems. We have an [integrations](https://github.com/eslint/eslint/tree/master/docs/integrations) page that lists out all known integrations. If you have created an integration, please add your information to that page.

Additionally, we are always looking for official integrations to host under the ESLint organization on GitHub. Official integrations are tools that have a high-level quality and are managed by responsible maintainers who are committed to keeping the tool up-to-date and bettering the tool for the good of the ESLint community. If you think your integration qualifies, please contact the [mailing list](https://groups.google.com/group/eslint) with your information.

## Copyright and Licensing

When you submit code to the ESLint project, you agree:

1. The code you wrote is your original work (you own the copyright).
1. To allow the ESLint project to use your submitted code in any way.
1. You are capable of granting rights for the submitted code.

It is very important that you understand the implications of these conditions, as it gives ESLint the right to accept your contribution.

Since the code you wrote is your original work, you keep the copyright for it. This is why we ask you to include a copyright in the comments at the beginning of any file you submit, such as:

```js

```

The `@author` field gives you credit for having created the file. The `@copyright` field indicates that you are the copyright holder for the file.

Your submission may touch other parts of the ESLint code that you did not write. In that case, you are welcome to add a copyright notice to the top of the file if you have done any amount of significant work on the file (we leave it up to you to decide what "significant" means - if you aren't sure, just ask). You should never change the `@author` field, but you can add another `@copyright` field on top of the existing ones, such as:

```js
/**
 * @fileoverview Description of the file
 * @author Author's Name
 * @copyright 2015 Your Name. All rights reserved.
 * @copyright 2014 Author's Name. All rights reserved.
 */
```

## Pull Requests

If you want to contribute to an ESLint repo, please use a GitHub pull request. This is the fastest way for us to evaluate your code and to merge it into the code base. Please don't file an issue with snippets of code. Doing so means that we need to manually merge the changes in and update any appropriate tests. That decreases the likelihood that your code is going to get included in a timely manner. Please use pull requests.

We want to accept your contribution. Following these guidelines helps to create a patch that we want to accept:

* Make sure there is an issue for any pull request you send.
    * The only exception is for documentation changes. These don't require a pull request if they don't relate to an already-existing functionality issue.
* The pull request must have a description. The description should explain what you did and how its effects can be seen.
* The commit message should say "(fixes #1234)" at the end of the description if it closes out an existing issue (replace 1234 with the issue number).
* The change should introduce no functional regression. Be sure to run `npm test` to verify your changes before submitting a pull request.
* Make separate pull requests for unrelated changes. Large pull requests with multiple unrelated changes may be closed without merging.
* All changes must be accompanied by tests, even if the feature you're working on previously had no tests.
* All changes must work on the following Node.js versions:
    * 0.10.x
* Only *one commit* is allowed per pull request. If you have multiple commits, you'll be asked to squash them.
* Follow the [Code Conventions](code-conventions.md).

### Step 1: Create a new branch

The first step to sending a pull request is to create a new branch in your ESLint fork. Give the branch a descriptive name that describes what it is you're fixing, such as:

```
git checkout -b fix-broken-config
```

#### Step 2: Make your changes

Make the changes to the code and tests and then commit to your branch. Be sure to follow the commit message conventions.

Commit messages must follow this basic format:

```
Tag: Message (fixes #1234)
```

The `Tag` is one of the following:

* `Fix` - for a bug fix.
* `Update` - for a backwards-compatible enhancement.
* `Breaking` - for a backwards-incompatible enhancement.
* `Docs` - changes to documentation only.
* `Build` - changes to build process only.
* `New` - implemented a new feature.
* `Upgrade` - for a dependency upgrade.

The message should a one-sentence description of the change. The issue number should be mentioned at the end. If the commit doesn't completely fix the issue, then use `(refs #1234)` instead of `(fixes #1234)`.

Here are some good commit message examples:

```
Build: Update Travis to only test Node 0.10 (refs #734)
Fix: Semi rule incorrectly flagging extra semicolon (fixes #840)
Upgrade: Esprima to 1.2, switch to using Esprima comment attachment (fixes #730)
```

The commit message format is important because these messages are used to create a changelog for each release. The tag and issue number help to create more consistent and useful changelogs.

### Step 3: Rebase onto upstream

Before you send the pull request, be sure to rebase onto the upstream source. This ensures your code is running on the latest available code.

```
git fetch upstream
git rebase upstream/master
```

### Step 4: Run the tests

After rebasing, be sure to run all of the tests once again to make sure nothing broke:

```
npm test
```

### Step 5: Squash your commits

As mentioned previously, ESLint requires just one commit per pull request. If you have used multiple commits, be sure to [squash](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) your commits.

### Step 6: Send the pull request

Now you're ready to send the pull request. Go to your ESLint fork and then follow the [GitHub documentation](https://help.github.com/articles/creating-a-pull-request) on how to send a pull request.

### Following Up

All pull requests are sent through Travis CI to verify that no tests are broken. If the Travis build fails, it will show up on the pull request. We cannot accept any code that fails in Travis, so if this happens, make fixes and update the pull request to trigger another build.

## New Rules

If you want to create a new rule, the first step is to file an issue. Make sure the issue includes the following information:

1. The use case for the rule - what is it trying to prevent or flag? Include code examples.
1. Whether the rule is trying to prevent an error or is purely stylistic.
1. Why you believe this rule is generic enough to be included.
1. Whether the rule should be on or off by default.

To simplify creation of new rules, use [ESLint Yeoman generator](https://github.com/eslint/generator-eslint). It will automatically generate rule, documentation and test files to get you started faster.

Keep in mind that not all rules will be accepted for the main distribution. You may also request that your rule by on by default but we may accept it as off by default.

redpajama_set_name: RedPajamaGithub


text:
/**
 * Utility to show empty Table View
 *
 * @param {object} config - Config properties associated with a Table View
 * @param {object} config.data - Data set for DataTable
 * @param {string} config.deleteRowsSelector - Selector for delete rows control
 * @param {string} config.restoreRowsSelector - Selector for restore rows control
 * @param {string} config.tableSelector - Selector for the HTML table
 */
var emptyTableViewUtil = function (config) {
  var self = this;

  this.dt = $(config.tableSelector).DataTable(); // DataTable
  this.deleteRows = $(config.deleteRowsSelector); // Delete rows control
  this.restoreRows = $(config.restoreRowsSelector); // Restore rows control

  // Handle click on delete rows control
  this.deleteRows.on('click', function() {
    self.dt.clear().draw();
    $(self.restoreRows).prop("disabled", false);
  });

  // Handle click on restore rows control
  this.restoreRows.on('click', function() {
    self.dt.rows.add(config.data).draw();
    $(this).prop("disabled", true);
  });

  // Initialize restore rows
  if (this.dt.data().length === 0) {
    $(this.restoreRows).prop("disabled", false);
  }
};

// Initialize empty Table View util
new emptyTableViewUtil({
  data: dataSet,
  deleteRowsSelector: "#{{include.actionId1}}",
  restoreRowsSelector: "#{{include.actionId2}}",
  tableSelector: "#{{include.tableId}}"
});


text:
namespace impala {

template <class T>
Status SerializeThriftMsg(JNIEnv* env, T* msg, jbyteArray* serialized_msg) {
  int buffer_size = 100 * 1024;  // start out with 100KB
  ThriftSerializer serializer(false, buffer_size);

  uint8_t* buffer = NULL;
  uint32_t size = 0;
  RETURN_IF_ERROR(serializer.SerializeToBuffer(msg, &size, &buffer));

  /// create jbyteArray given buffer
  *serialized_msg = env->NewByteArray(size);
  RETURN_ERROR_IF_EXC(env);
  if (*serialized_msg == NULL) return Status("couldn't construct jbyteArray");
  env->SetByteArrayRegion(*serialized_msg, 0, size, reinterpret_cast<jbyte*>(buffer));
  RETURN_ERROR_IF_EXC(env);
  return Status::OK();
}

template <class T>
Status DeserializeThriftMsg(JNIEnv* env, jbyteArray serialized_msg, T* deserialized_msg) {
  jboolean is_copy = false;
  uint32_t buf_size = env->GetArrayLength(serialized_msg);
  jbyte* buf = env->GetByteArrayElements(serialized_msg, &is_copy);

  RETURN_IF_ERROR(DeserializeThriftMsg(
          reinterpret_cast<uint8_t*>(buf), &buf_size, false, deserialized_msg));

  /// Return buffer back. JNI_ABORT indicates to not copy contents back to java
  /// side.
  env->ReleaseByteArrayElements(serialized_msg, buf, JNI_ABORT);
  return Status::OK();
}

}

#endif


text:
// This file is automatically generated.

package adila.db;

/*
 * LG L90
 *
 * DEVICE: w7n
 * MODEL: LG-D400
 */
final class w7n_lg2dd400 {
    public static final String DATA = "LG|L90|";
}


text:
package com.msi.tough.model.elasticmapreduce;

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "JobFlowDetail")
public class JobFlowDetailBean
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "JobFlowId")
    private String jobFlowId;

    @Lob
    @Column(name = "LogUri", length = 10280)
    private String logUri;

    @Column(name = "Name")
    private String name;

    @Column(name = "CreationDateTime")
    private Date creationDateTime;

    @Column(name = "EndDateTime")
    private Date endDateTime;

    @Lob
    @Column(name = "LastStateChangeReason", length = 10280)
    private String lastStateChangeReason;

    @Column(name = "ReadyDateTime")
    private Date readyDateTime;

    @Column(name = "StartDateTime")
    private Date startDateTime;

    @Column(name = "State")
    private String state;

    @Column(name = "Ec2KeyName")
    private String ec2KeyName;

    @Column(name = "HadoopVersion")
    private String hadoopVersion;

    @Column(name = "InstanceCount")
    private Integer instanceCount;

    @Column(name = "KeepJobFlowAliveWhenNoSteps")
    private Boolean keepJobFlowAliveWhenNoSteps;

    @Column(name = "MasterInstanceId")
    private String masterInstanceId;

    @Column(name = "MasterInstanceType")
    private String masterInstanceType;

    @Lob
    @Column(name = "MasterPublicDnsName", length = 10280)
    private String masterPublicDnsName;

    @Column(name = "NormalizedInstanceHours")
    private Long normalizedInstanceHours;

    @Lob
    @Column(name = "Placement", length = 10280)
    private String placement;

    @Column(name = "SlaveInstanceType")
    private String slaveInstanceType;

    @OneToMany(mappedBy = "jobFlowDetail", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<BootstrapActionDetailBean> bootstrapActionDetails;

    @OneToMany(mappedBy = "jobFlowDetail", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<StepDetailBean> stepDetails;

    @OneToMany(mappedBy = "jobFlowDetail", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<InstanceGroupDetailBean> instanceGroupDetails;

    @Column(name = "Terminate")
    private Boolean terminate;

    public JobFlowDetailBean()
    {
    }

    public JobFlowDetailBean(Long id)
    {
        this.id = id;
    }

    public JobFlowDetailBean(Long id, String jobFlowId, String logUri,
        String name, Date creationDateTime, Date endDateTime,
        String lastStateChangeReason, Date readyDateTime, Date startDateTime,
        String state, String ec2KeyName, String hadoopVersion,
        Integer instanceCount, Boolean keepJobFlowAliveWhenNoSteps,
        String masterInstanceId, String masterInstanceType,
        String masterPublicDnsName, Long normalizedInstanceHours,
        String placement, String slaveInstanceType,
        Set<BootstrapActionDetailBean> bootstrapActionDetails,
        Set<StepDetailBean> stepDetails,
        Set<InstanceGroupDetailBean> instanceGroupDetails, Boolean terminate)
    {
        this.id = id;
        this.jobFlowId = jobFlowId;
        this.logUri = logUri;
        this.name = name;
        this.creationDateTime = creationDateTime;
        this.endDateTime = endDateTime;
        this.lastStateChangeReason = lastStateChangeReason;
        this.readyDateTime = readyDateTime;
        this.startDateTime = startDateTime;
        this.state = state;
        this.ec2KeyName = ec2KeyName;
        this.hadoopVersion = hadoopVersion;
        this.instanceCount = instanceCount;
        this.keepJobFlowAliveWhenNoSteps = keepJobFlowAliveWhenNoSteps;
        this.masterInstanceId = masterInstanceId;
        this.masterInstanceType = masterInstanceType;
        this.masterPublicDnsName = masterPublicDnsName;
        this.normalizedInstanceHours = normalizedInstanceHours;
        this.placement = placement;
        this.slaveInstanceType = slaveInstanceType;
        this.bootstrapActionDetails = bootstrapActionDetails;
        this.stepDetails = stepDetails;
        this.instanceGroupDetails = instanceGroupDetails;
        this.terminate = terminate;
    }

    public Set<BootstrapActionDetailBean> getBootstrapActionDetails()
    {
        return this.bootstrapActionDetails;
    }

    public Date getCreationDateTime()
    {
        return this.creationDateTime;
    }

    public String getEc2KeyName()
    {
        return this.ec2KeyName;
    }

    public Date getEndDateTime()
    {
        return this.endDateTime;
    }

    public String getHadoopVersion()
    {
        return this.hadoopVersion;
    }

    public Long getId()
    {
        return this.id;
    }

    public Integer getInstanceCount()
    {
        return this.instanceCount;
    }

    public Set<InstanceGroupDetailBean> getInstanceGroupDetails()
    {
        return this.instanceGroupDetails;
    }

    public String getJobFlowId()
    {
        return this.jobFlowId;
    }

    public Boolean getKeepJobFlowAliveWhenNoSteps()
    {
        return this.keepJobFlowAliveWhenNoSteps;
    }

    public String getLastStateChangeReason()
    {
        return this.lastStateChangeReason;
    }

    public String getLogUri()
    {
        return this.logUri;
    }

    public String getMasterInstanceId()
    {
        return this.masterInstanceId;
    }

    public String getMasterInstanceType()
    {
        return this.masterInstanceType;
    }

    public String getMasterPublicDnsName()
    {
        return this.masterPublicDnsName;
    }

    public String getName()
    {
        return this.name;
    }

    public Long getNormalizedInstanceHours()
    {
        return this.normalizedInstanceHours;
    }

    public String getPlacement()
    {
        return this.placement;
    }

    public Date getReadyDateTime()
    {
        return this.readyDateTime;
    }

    public String getSlaveInstanceType()
    {
        return this.slaveInstanceType;
    }

    public Date getStartDateTime()
    {
        return this.startDateTime;
    }

    public String getState()
    {
        return this.state;
    }

    public Set<StepDetailBean> getStepDetails()
    {
        return this.stepDetails;
    }

    public Boolean getTerminate()
    {
        return this.terminate;
    }

    public void setBootstrapActionDetails(
        Set<BootstrapActionDetailBean> bootstrapActionDetails)
    {
        this.bootstrapActionDetails = bootstrapActionDetails;
    }

    public void setCreationDateTime(Date creationDateTime)
    {
        this.creationDateTime = creationDateTime;
    }

    public void setEc2KeyName(String ec2KeyName)
    {
        this.ec2KeyName = ec2KeyName;
    }

    public void setEndDateTime(Date endDateTime)
    {
        this.endDateTime = endDateTime;
    }

    public void setHadoopVersion(String hadoopVersion)
    {
        this.hadoopVersion = hadoopVersion;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public void setInstanceCount(Integer instanceCount)
    {
        this.instanceCount = instanceCount;
    }

    public void setInstanceGroupDetails(
        Set<InstanceGroupDetailBean> instanceGroupDetails)
    {
        this.instanceGroupDetails = instanceGroupDetails;
    }

    public void setJobFlowId(String jobFlowId)
    {
        this.jobFlowId = jobFlowId;
    }

    public void setKeepJobFlowAliveWhenNoSteps(
        Boolean keepJobFlowAliveWhenNoSteps)
    {
        this.keepJobFlowAliveWhenNoSteps = keepJobFlowAliveWhenNoSteps;
    }

    public void setLastStateChangeReason(String lastStateChangeReason)
    {
        this.lastStateChangeReason = lastStateChangeReason;
    }

    public void setLogUri(String logUri)
    {
        this.logUri = logUri;
    }

    public void setMasterInstanceId(String masterInstanceId)
    {
        this.masterInstanceId = masterInstanceId;
    }

    public void setMasterInstanceType(String masterInstanceType)
    {
        this.masterInstanceType = masterInstanceType;
    }

    public void setMasterPublicDnsName(String masterPublicDnsName)
    {
        this.masterPublicDnsName = masterPublicDnsName;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setNormalizedInstanceHours(Long normalizedInstanceHours)
    {
        this.normalizedInstanceHours = normalizedInstanceHours;
    }

    public void setPlacement(String placement)
    {
        this.placement = placement;
    }

    public void setReadyDateTime(Date readyDateTime)
    {
        this.readyDateTime = readyDateTime;
    }

    public void setSlaveInstanceType(String slaveInstanceType)
    {
        this.slaveInstanceType = slaveInstanceType;
    }

    public void setStartDateTime(Date startDateTime)
    {
        this.startDateTime = startDateTime;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public void setStepDetails(Set<StepDetailBean> stepDetails)
    {
        this.stepDetails = stepDetails;
    }

    public void setTerminate(Boolean terminate)
    {
        this.terminate = terminate;
    }
}


text:
package org.keycloak;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Assert;
import org.junit.Test;
import org.keycloak.crypto.Algorithm;
import org.keycloak.jose.jws.crypto.HashUtils;

import java.security.Security;

/**
 * See "at_hash" in OIDC specification
 *
 * @author Marek Posolda
 */
public class AtHashTest {

    static {
        if (Security.getProvider("BC") == null) Security.addProvider(new BouncyCastleProvider());
    }

    @Test
    public void testAtHashRsa() {
        verifyHash(Algorithm.RS256,"jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KF0Y", "77QmUPtjPfzWtF2AnpK9RQ");
        verifyHash(Algorithm.RS256,"ya29.eQETFbFOkAs8nWHcmYXKwEi0Zz46NfsrUU_KuQLOLTwWS40y6Fb99aVzEXC0U14m61lcPMIr1hEIBA", "aUAkJG-u6x4RTWuILWy-CA");
    }

    @Test
    public void testAtHashEs() {
        verifyHash(Algorithm.ES256,"jHkWEdUXMU1BwAsC4vtUsZwnNvTIxEl0z9K3vx5KF0Y", "77QmUPtjPfzWtF2AnpK9RQ");
        verifyHash(Algorithm.ES256,"ya29.eQETFbFOkAs8nWHcmYXKwEi0Zz46NfsrUU_KuQLOLTwWS40y6Fb99aVzEXC0U14m61lcPMIr1hEIBA", "aUAkJG-u6x4RTWuILWy-CA");
    }

    private void verifyHash(String jwtAlgorithm, String accessToken, String expectedAtHash) {
        String atHash = HashUtils.oidcHash(jwtAlgorithm, accessToken);
        Assert.assertEquals(expectedAtHash, atHash);
    }
}


text:
[http://devgeeks.org/slides/melbourne-mobile-talk-2013.2.12](http://devgeeks.org/slides/melbourne-mobile-talk-2013.2.12)

## Slide Deck

## License

MIT licensed

Copyright (C) 2012 Tommy-Carlos Williams, http://devgeeks.org


text:
#ifndef WOFF2TAGS_H
#define WOFF2TAGS_H

#include <freetype/internal/ftobjs.h>
#include <freetype/internal/compiler-macros.h>

FT_BEGIN_HEADER

  FT_LOCAL( FT_ULong )
  woff2_known_tags( FT_Byte  index );

FT_END_HEADER

#endif /* WOFF2TAGS_H */

/* END */


text:
<?php

namespace app\helper;
use app\model\Ubermodel as Ubermodel;

class UsersHelper extends \core\helper\Helper
{

    // Api
    public function doesUserExist($args)
    {
        $user = Ubermodel::getOne('users', 'email', $args['email']);

        return $user;
    }

    public function apiIndex($args = array())
    {
        $user = Ubermodel::getAll('users', array(
            'SELECT' => array('email', 'name', 'gender', 'birth_date'),
        ));

        return $user;
    }

    public function apiView($args = array())
    {
        //$user = Ubermodel::getOne('users', $args['column'], $args['data']);
       $user = Ubermodel::getAll('users', array(
           'SELECT' => array('email', 'name', 'gender', 'birth_date'),
           'WHERE' => array($args['column'] => $args['data'])
        ));
        return $user;
    }

    static function testResponse()
    {
        return 'Success!';
    }
}


text:
"""
Contains Wagtail CMS integration hooks.
"""
from django.conf.urls import include
from django.conf.urls import url
from django.utils.html import format_html

from wagtail.wagtailcore import hooks

from . import admin_urls

@hooks.register('register_admin_urls')
def register_admin_urls():
    return [
        url(r'^rollback/', include(admin_urls, namespace='wagtailrollbacks')),
    ]

@hooks.register('insert_editor_js')
def editor_js():
    return """<script>
        $(function () {
            $('#revisions a.disabled').click(function(e) {
                e.preventDefault();
            });
            $('#revisions').on('click', '.pagination a', function(e) {
                e.preventDefault();
                $('#revisions').load($(this).attr('href'));
            });
        });
    </script>"""


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea wilmsii C.W. Dodge

### Remarks
null


text:
package com.bocaiweather.app.Activity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.bocaiweather.app.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * 数据库管理类
 */
public class DBManager
{
    private static String TAG = DBManager.class.getSimpleName();
    private final int BUFFER_SIZE = 400000;
    public final String DB_NAME = "cityname.db"; //数据库名字
    public static final String PACKAGE_NAME = "com.bocaiweather.app";
    public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" +
            PACKAGE_NAME;
    public String cityID;
    public String cityName;
    private SQLiteDatabase database;
    private Context context;

    public DBManager(Context context) {
        this.context = context;
    }

    public SQLiteDatabase getDatabase() {
        return database;
    }

    public void setDatabase(SQLiteDatabase database) {
        this.database = database;
    }

    public SQLiteDatabase openDatabase() {
        Log.e(TAG, DB_PATH + "/" + DB_NAME);
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
        return database;
    }

    //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库
    private SQLiteDatabase openDatabase(String dbfile) {

        try {
            if (!(new File(dbfile).exists())) {

                InputStream is = this.context.getResources().openRawResource(R.raw.citychina); //欲导入的数据库
                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }

            return SQLiteDatabase.openOrCreateDatabase(dbfile, null);
        } catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }

    public void closeDatabase() {
        this.database.close();
    }

    //获得对应城市的城市编号
    public String queryCityID(String cityName)
    {
        try
        {
            String sql = "select * from city_table where CITY =" + "'"
                    + cityName + "'" + ";";
            SQLiteDatabase db = this.openDatabase();
            Cursor cursor = db.rawQuery(sql,null);

            if (cursor != null) {
                cursor.moveToFirst();
                cityID = cursor.getString(cursor
                        .getColumnIndex("WEATHER_ID"));
                //  Toast.makeText(context,cityID , Toast.LENGTH_SHORT).show();
            }
            cursor.close();

        }catch (Exception e){e.printStackTrace();
            Toast.makeText(context,"请输入城市中文名",Toast.LENGTH_LONG).show();
        }
        return  cityID;
    }

    //获得对应编号的城市名
    public String queryCityName(String cityID)
    {
        String sql = "select * from city_table where WEATHER_ID =" + "'"
                + cityID + "'" + ";";
        SQLiteDatabase db = this.openDatabase();
        Cursor cursor = db.rawQuery(sql,null);

        if (cursor != null) {
            cursor.moveToFirst();
            cityName = cursor.getString(cursor
                    .getColumnIndex("CITY"));
           // Toast.makeText(context,cityName , Toast.LENGTH_SHORT).show();
        }
        cursor.close();
        return  cityName;
    }

}


text:
// BSONEncoder.java

package org.bson;

import static org.bson.BSON.ARRAY;
import static org.bson.BSON.BINARY;
import static org.bson.BSON.BOOLEAN;
import static org.bson.BSON.B_BINARY;
import static org.bson.BSON.B_GENERAL;
import static org.bson.BSON.B_UUID;
import static org.bson.BSON.CODE;
import static org.bson.BSON.CODE_W_SCOPE;
import static org.bson.BSON.DATE;
import static org.bson.BSON.EOO;
import static org.bson.BSON.MAXKEY;
import static org.bson.BSON.MINKEY;
import static org.bson.BSON.NULL;
import static org.bson.BSON.NUMBER;
import static org.bson.BSON.NUMBER_INT;
import static org.bson.BSON.NUMBER_LONG;
import static org.bson.BSON.OBJECT;
import static org.bson.BSON.OID;
import static org.bson.BSON.REGEX;
import static org.bson.BSON.STRING;
import static org.bson.BSON.SYMBOL;
import static org.bson.BSON.TIMESTAMP;
import static org.bson.BSON.UNDEFINED;
import static org.bson.BSON.regexFlags;

import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Pattern;

import org.bson.io.BasicOutputBuffer;
import org.bson.io.OutputBuffer;
import org.bson.types.BSONTimestamp;
import org.bson.types.Binary;
import org.bson.types.Code;
import org.bson.types.CodeWScope;
import org.bson.types.MaxKey;
import org.bson.types.MinKey;
import org.bson.types.ObjectId;
import org.bson.types.Symbol;

import com.mongodb.DBRefBase;

/**
 * this is meant to be pooled or cached
 * there is some per instance memory for string conversion, etc...
 */
@SuppressWarnings("unchecked")
public class BasicBSONEncoder implements BSONEncoder {

    static final boolean DEBUG = false;

    public BasicBSONEncoder(){

    }

    public byte[] encode( BSONObject o ){
        BasicOutputBuffer buf = new BasicOutputBuffer();
        set( buf );
        putObject( o );
        done();
        return buf.toByteArray();
    }

    public void set( OutputBuffer out ){
        if ( _buf != null )
            throw new IllegalStateException( "in the middle of something" );

        _buf = out;
    }

    public void done(){
        _buf = null;
    }

    /**
     * @return true if object was handled
     */
    protected boolean handleSpecialObjects( String name , BSONObject o ){
        return false;
    }

    protected boolean putSpecial( String name , Object o ){
        return false;
    }

    /** Encodes a BSONObject.
     * This is for the higher level api calls
     * @param o the object to encode
     * @return the number of characters in the encoding
     */
    public int putObject( BSONObject o ){
        return putObject( null , o );
    }

    /**
     * this is really for embedded objects
     */
    protected int putObject( String name , BSONObject o ){

        if ( o == null )
            throw new NullPointerException( "can't save a null object" );

        if ( DEBUG ) System.out.println( "putObject : " + name + " [" + o.getClass() + "]" + " # keys " + o.keySet().size() );

        final int start = _buf.getPosition();

        byte myType = OBJECT;
        if ( o instanceof List )
            myType = ARRAY;

        if ( handleSpecialObjects( name , o ) )
            return _buf.getPosition() - start;

        if ( name != null ){
            _put( myType , name );
        }

        final int sizePos = _buf.getPosition();
        _buf.writeInt( 0 ); // leaving space for this.  set it at the end

        List transientFields = null;
        boolean rewriteID = myType == OBJECT && name == null;

        if ( myType == OBJECT ) {
            if ( rewriteID && o.containsField( "_id" ) )
                _putObjectField( "_id" , o.get( "_id" ) );

            {
                Object temp = o.get( "_transientFields" );
                if ( temp instanceof List )
                    transientFields = (List)temp;
            }
        }

        //TODO: reduce repeated code below.
        if ( o instanceof Map ){
	        for ( Entry<String, Object> e : ((Map<String, Object>)o).entrySet() ){

	            if ( rewriteID && e.getKey().equals( "_id" ) )
	                continue;

	            if ( transientFields != null && transientFields.contains( e.getKey() ) )
	                continue;

	            _putObjectField( e.getKey() , e.getValue() );

	        }
        } else {
	        for ( String s : o.keySet() ){

	            if ( rewriteID && s.equals( "_id" ) )
	                continue;

	            if ( transientFields != null && transientFields.contains( s ) )
	                continue;

	            Object val = o.get( s );

	            _putObjectField( s , val );

	        }
        }
        _buf.write( EOO );

        _buf.writeInt( sizePos , _buf.getPosition() - sizePos );
        return _buf.getPosition() - start;
    }

	protected void _putObjectField( String name , Object val ){

        if ( name.equals( "_transientFields" ) )
            return;

        if ( DEBUG ) System.out.println( "\t put thing : " + name );

        if ( name.equals( "$where") && val instanceof String ){
            _put( CODE , name );
            _putValueString( val.toString() );
            return;
        }

        val = BSON.applyEncodingHooks( val );

        if ( val == null )
            putNull(name);
        else if ( val instanceof Date )
            putDate( name , (Date)val );
        else if ( val instanceof Number )
            putNumber(name, (Number)val );
        else if ( val instanceof Character )
            putString(name, val.toString() );
        else if ( val instanceof String )
            putString(name, val.toString() );
        else if ( val instanceof ObjectId )
            putObjectId(name, (ObjectId)val );
        else if ( val instanceof BSONObject )
            putObject(name, (BSONObject)val );
        else if ( val instanceof Boolean )
            putBoolean(name, (Boolean)val );
        else if ( val instanceof Pattern )
            putPattern(name, (Pattern)val );
        else if ( val instanceof Map )
            putMap( name , (Map)val );
        else if ( val instanceof Iterable)
            putIterable( name , (Iterable)val );
        else if ( val instanceof byte[] )
            putBinary( name , (byte[])val );
        else if ( val instanceof Binary )
            putBinary( name , (Binary)val );
        else if ( val instanceof UUID )
            putUUID( name , (UUID)val );
        else if ( val.getClass().isArray() )
        	putArray( name , val );

        else if (val instanceof Symbol) {
            putSymbol(name, (Symbol) val);
        }
        else if (val instanceof BSONTimestamp) {
            putTimestamp( name , (BSONTimestamp)val );
        }
        else if (val instanceof CodeWScope) {
            putCodeWScope( name , (CodeWScope)val );
        }
        else if (val instanceof Code) {
            putCode( name , (Code)val );
        }
        else if (val instanceof DBRefBase) {
            BSONObject temp = new BasicBSONObject();
            temp.put("$ref", ((DBRefBase)val).getRef());
            temp.put("$id", ((DBRefBase)val).getId());
            putObject( name, temp );
        }
        else if ( val instanceof MinKey )
            putMinKey( name );
        else if ( val instanceof MaxKey )
            putMaxKey( name );
        else if ( putSpecial( name , val ) ){
            // no-op
        }
        else {
            throw new IllegalArgumentException( "can't serialize " + val.getClass() );
        }

    }

    private void putArray( String name , Object array ) {
        _put( ARRAY , name );
        final int sizePos = _buf.getPosition();
        _buf.writeInt( 0 );

        int size = Array.getLength(array);
        for ( int i = 0; i < size; i++ )
            _putObjectField( String.valueOf( i ) , Array.get( array, i ) );

        _buf.write( EOO );
        _buf.writeInt( sizePos , _buf.getPosition() - sizePos );
    }

    private void putIterable( String name , Iterable l ){
        _put( ARRAY , name );
        final int sizePos = _buf.getPosition();
        _buf.writeInt( 0 );

        int i=0;
        for ( Object obj: l ) {
            _putObjectField( String.valueOf( i ) , obj );
            i++;
        }

        _buf.write( EOO );
        _buf.writeInt( sizePos , _buf.getPosition() - sizePos );
    }

    private void putMap( String name , Map m ){
        _put( OBJECT , name );
        final int sizePos = _buf.getPosition();
        _buf.writeInt( 0 );

        for ( Map.Entry entry : (Set<Map.Entry>)m.entrySet() )
            _putObjectField( entry.getKey().toString() , entry.getValue() );

        _buf.write( EOO );
        _buf.writeInt( sizePos , _buf.getPosition() - sizePos );
    }

    protected void putNull( String name ){
        _put( NULL , name );
    }

    protected void putUndefined(String name){
        _put(UNDEFINED, name);
    }

    protected void putTimestamp(String name, BSONTimestamp ts ){
        _put( TIMESTAMP , name );
        _buf.writeInt( ts.getInc() );
        _buf.writeInt( ts.getTime() );
    }

    protected void putCodeWScope( String name , CodeWScope code ){
        _put( CODE_W_SCOPE , name );
        int temp = _buf.getPosition();
        _buf.writeInt( 0 );
        _putValueString( code.getCode() );
        putObject( code.getScope() );
        _buf.writeInt( temp , _buf.getPosition() - temp );
    }

    protected void putCode( String name , Code code ){
        _put( CODE , name );
        int temp = _buf.getPosition();
        _putValueString( code.getCode() );
    }

    protected void putBoolean( String name , Boolean b ){
        _put( BOOLEAN , name );
        _buf.write( b ? (byte)0x1 : (byte)0x0 );
    }

    protected void putDate( String name , Date d ){
        _put( DATE , name );
        _buf.writeLong( d.getTime() );
    }

    protected void putNumber( String name , Number n ){
		if ( n instanceof Integer ||
	             n instanceof Short ||
	             n instanceof Byte ||
	             n instanceof AtomicInteger ){
		    _put( NUMBER_INT , name );
		    _buf.writeInt( n.intValue() );
		}
	    else if ( n instanceof Long || n instanceof AtomicLong ) {
	        _put( NUMBER_LONG , name );
	        _buf.writeLong( n.longValue() );
	    }
	    else if ( n instanceof Float || n instanceof Double ) {
	      _put( NUMBER , name );
	      _buf.writeDouble( n.doubleValue() );
	    }
		else {
	        throw new IllegalArgumentException( "can't serialize " + n.getClass() );
		}
    }

    protected void putBinary( String name , byte[] data ){
        putBinary( name, B_GENERAL, data );
    }

    protected void putBinary( String name , Binary val ){
        putBinary( name, val.getType(), val.getData() );
    }

    private void putBinary( String name , int type , byte[] data ){
        _put( BINARY , name );
        int totalLen = data.length;

        if (type == B_BINARY)
            totalLen += 4;

        _buf.writeInt( totalLen );
        _buf.write( type );
        if (type == B_BINARY)
            _buf.writeInt( totalLen -4 );
        int before = _buf.getPosition();
        _buf.write( data );
        int after = _buf.getPosition();
        com.mongodb.util.MyAsserts.assertEquals( after - before , data.length );
    }

    protected void putUUID( String name , UUID val ){
        _put( BINARY , name );
        _buf.writeInt( 16 );
        _buf.write( B_UUID );
        _buf.writeLong( val.getMostSignificantBits());
        _buf.writeLong( val.getLeastSignificantBits());
    }

    protected void putSymbol( String name , Symbol s ){
        _putString(name, s.getSymbol(), SYMBOL);
    }

    protected void putString(String name, String s) {
        _putString(name, s, STRING);
    }

    private void _putString( String name , String s, byte type ){
        _put( type , name );
        _putValueString( s );
    }

    protected void putObjectId( String name , ObjectId oid ){
        _put( OID , name );
        // according to spec, values should be stored big endian
        _buf.writeIntBE( oid._time() );
        _buf.writeIntBE( oid._machine() );
        _buf.writeIntBE( oid._inc() );
    }

    private void putPattern( String name, Pattern p ) {
        _put( REGEX , name );
        _put( p.pattern() );
        _put( regexFlags( p.flags() ) );
    }

    private void putMinKey( String name ) {
        _put( MINKEY , name );
    }

    private void putMaxKey( String name ) {
        _put( MAXKEY , name );
    }

    // ----------------------------------------------

    /**
     * Encodes the type and key.
     *
     */
    protected void _put( byte type , String name ){
        _buf.write( type );
        _put( name );
    }

    protected void _putValueString( String s ){
        int lenPos = _buf.getPosition();
        _buf.writeInt( 0 ); // making space for size
        int strLen = _put( s );
        _buf.writeInt( lenPos , strLen );
    }

    void _reset( Buffer b ){
        b.position(0);
        b.limit( b.capacity() );
    }

    /**
     * puts as utf-8 string
     */
    protected int _put( String str ){

        final int len = str.length();
        int total = 0;

        for ( int i=0; i<len; ){
            int c = Character.codePointAt( str , i );

            if ( c < 0x80 ){
                _buf.write( (byte)c );
                total += 1;
            }
            else if ( c < 0x800 ){
                _buf.write( (byte)(0xc0 + (c >> 6) ) );
                _buf.write( (byte)(0x80 + (c & 0x3f) ) );
                total += 2;
            }
            else if (c < 0x10000){
                _buf.write( (byte)(0xe0 + (c >> 12) ) );
                _buf.write( (byte)(0x80 + ((c >> 6) & 0x3f) ) );
                _buf.write( (byte)(0x80 + (c & 0x3f) ) );
                total += 3;
            }
            else {
                _buf.write( (byte)(0xf0 + (c >> 18)) );
                _buf.write( (byte)(0x80 + ((c >> 12) & 0x3f)) );
                _buf.write( (byte)(0x80 + ((c >> 6) & 0x3f)) );
                _buf.write( (byte)(0x80 + (c & 0x3f)) );
                total += 4;
            }

            i += Character.charCount(c);
        }

        _buf.write( (byte)0 );
        total++;
        return total;
    }

    public void writeInt( int x ){
        _buf.writeInt( x );
    }

    public void writeLong( long x ){
        _buf.writeLong( x );
    }

    public void writeCString( String s ){
        _put( s );
    }

    protected OutputBuffer _buf;

}


text:
import { buildGetDocumentParams } from "./test_utils.js";
import { EventBus } from "../../web/event_utils.js";
import { getDocument } from "../../src/display/api.js";
import { isNodeJS } from "../../src/shared/is_node.js";
import { PDFFindController } from "../../web/pdf_find_controller.js";
import { SimpleLinkService } from "../../web/pdf_link_service.js";

const tracemonkeyFileName = "tracemonkey.pdf";

class MockLinkService extends SimpleLinkService {
  constructor() {
    super();

    this._page = 1;
    this._pdfDocument = null;
  }

  setDocument(pdfDocument) {
    this._pdfDocument = pdfDocument;
  }

  get pagesCount() {
    return this._pdfDocument.numPages;
  }

  get page() {
    return this._page;
  }

  set page(value) {
    this._page = value;
  }
}

async function initPdfFindController(filename) {
  const loadingTask = getDocument(
    buildGetDocumentParams(filename || tracemonkeyFileName)
  );
  const pdfDocument = await loadingTask.promise;

  const eventBus = new EventBus();

  const linkService = new MockLinkService();
  linkService.setDocument(pdfDocument);

  const pdfFindController = new PDFFindController({
    linkService,
    eventBus,
  });
  pdfFindController.setDocument(pdfDocument); // Enable searching.

  return { eventBus, pdfFindController };
}

function testSearch({
  eventBus,
  pdfFindController,
  state,
  matchesPerPage,
  selectedMatch,
  pageMatches = null,
  pageMatchesLength = null,
}) {
  return new Promise(function (resolve) {
    const eventState = Object.assign(
      Object.create(null),
      {
        source: this,
        type: "",
        query: null,
        caseSensitive: false,
        entireWord: false,
        phraseSearch: true,
        findPrevious: false,
        matchDiacritics: false,
      },
      state
    );
    eventBus.dispatch("find", eventState);

    // The `updatefindmatchescount` event is only emitted if the page contains
    // at least one match for the query, so the last non-zero item in the
    // matches per page array corresponds to the page for which the final
    // `updatefindmatchescount` event is emitted. If this happens, we know
    // that any subsequent pages won't trigger the event anymore and we
    // can start comparing the matches per page. This logic is necessary
    // because we call the `pdfFindController.pageMatches` getter directly
    // after receiving the event and the underlying `_pageMatches` array
    // is only extended when a page is processed, so it will only contain
    // entries for the pages processed until the time when the final event
    // was emitted.
    let totalPages = matchesPerPage.length;
    for (let i = totalPages - 1; i >= 0; i--) {
      if (matchesPerPage[i] > 0) {
        totalPages = i + 1;
        break;
      }
    }

    const totalMatches = matchesPerPage.reduce((a, b) => {
      return a + b;
    });

    eventBus.on(
      "updatefindmatchescount",
      function onUpdateFindMatchesCount(evt) {
        if (pdfFindController.pageMatches.length !== totalPages) {
          return;
        }
        eventBus.off("updatefindmatchescount", onUpdateFindMatchesCount);

        expect(evt.matchesCount.total).toBe(totalMatches);
        for (let i = 0; i < totalPages; i++) {
          expect(pdfFindController.pageMatches[i].length).toEqual(
            matchesPerPage[i]
          );
        }
        expect(pdfFindController.selected.pageIdx).toEqual(
          selectedMatch.pageIndex
        );
        expect(pdfFindController.selected.matchIdx).toEqual(
          selectedMatch.matchIndex
        );

        if (pageMatches) {
          expect(pdfFindController.pageMatches).toEqual(pageMatches);
          expect(pdfFindController.pageMatchesLength).toEqual(
            pageMatchesLength
          );
        }

        resolve();
      }
    );
  });
}

describe("pdf_find_controller", function () {
  it("performs a normal search", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "Dynamic",
      },
      matchesPerPage: [11, 5, 0, 3, 0, 0, 0, 1, 1, 1, 0, 3, 4, 4],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
    });
  });

  it("performs a normal search and finds the previous result", async function () {
    // Page 14 (with page index 13) contains five results. By default, the
    // first result (match index 0) is selected, so the previous result
    // should be the fifth result (match index 4).
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "conference",
        findPrevious: true,
      },
      matchesPerPage: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
      selectedMatch: {
        pageIndex: 13,
        matchIndex: 4,
      },
    });
  });

  it("performs a case sensitive search", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "Dynamic",
        caseSensitive: true,
      },
      matchesPerPage: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
    });
  });

  it("performs an entire word search", async function () {
    // Page 13 contains both 'Government' and 'Governmental', so the latter
    // should not be found with entire word search.
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "Government",
        entireWord: true,
      },
      matchesPerPage: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
      selectedMatch: {
        pageIndex: 12,
        matchIndex: 0,
      },
    });
  });

  it("performs a multiple term (no phrase) search", async function () {
    // Page 9 contains 'alternate' and pages 6 and 9 contain 'solution'.
    // Both should be found for multiple term (no phrase) search.
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "alternate solution",
        phraseSearch: false,
      },
      matchesPerPage: [0, 0, 0, 0, 0, 1, 0, 0, 4, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 5,
        matchIndex: 0,
      },
    });
  });

  it("performs a normal search, where the text is normalized", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController(
      "fraction-highlight.pdf"
    );

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "fraction",
      },
      matchesPerPage: [3],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[19, 46, 62]],
      pageMatchesLength: [[8, 8, 8]],
    });

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "1/2",
      },
      matchesPerPage: [2],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[27, 54]],
      pageMatchesLength: [[1, 1]],
    });

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "½",
      },
      matchesPerPage: [2],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[27, 54]],
      pageMatchesLength: [[1, 1]],
    });
  });

  it("performs a normal search, where the text with diacritics is normalized", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController(
      "french_diacritics.pdf"
    );

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "a",
      },
      matchesPerPage: [6],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[0, 2, 4, 6, 8, 10]],
      pageMatchesLength: [[1, 1, 1, 1, 1, 1]],
    });

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "u",
      },
      matchesPerPage: [6],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[44, 46, 48, 50, 52, 54]],
      pageMatchesLength: [[1, 1, 1, 1, 1, 1]],
    });

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "ë",
        matchDiacritics: true,
      },
      matchesPerPage: [2],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[28, 30]],
      pageMatchesLength: [[1, 1]],
    });
  });

  it("performs a search where one of the results contains an hyphen", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "optimiz",
      },
      matchesPerPage: [1, 4, 2, 3, 3, 0, 2, 9, 1, 0, 0, 6, 3, 4],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
    });
  });

  it("performs a search where the result is on two lines", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "user experience",
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[2743]],
      pageMatchesLength: [[14]],
    });
  });

  it("performs a search where the result is on two lines with a punctuation at eol", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "version.the",
      },
      matchesPerPage: [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 1,
        matchIndex: 0,
      },
      pageMatches: [[], [1493]],
      pageMatchesLength: [[], [11]],
    });
  });

  it("performs a search with a minus sign in the query", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "trace-based  just-in-time",
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [
        [0],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [2087],
      ],
      pageMatchesLength: [
        [24],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [],
        [24],
      ],
    });
  });

  it("performs a search with square brackets in the query", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "[Programming Languages]",
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[1501]],
      pageMatchesLength: [[25]],
    });
  });

  it("performs a search with parenthesis in the query", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "\t   (checks)",
      },
      matchesPerPage: [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 1,
        matchIndex: 0,
      },
      pageMatches: [[], [201]],
      pageMatchesLength: [[], [9]],
    });
  });

  it("performs a search with a final dot in the query", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    // The whitespace after the dot mustn't be matched.
    const query = "complex applications.";

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query,
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[1946]],
      pageMatchesLength: [[21]],
    });
  });

  it("performs a search with a dot in the query and a missing whitespace", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();

    // The whitespace after the dot must be matched.
    const query = "complex applications.J";

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query,
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[1946]],
      pageMatchesLength: [[23]],
    });
  });

  it("performs a search with a dot followed by a whitespace in the query", async function () {
    const { eventBus, pdfFindController } = await initPdfFindController();
    const query = "complex applications. j";

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query,
      },
      matchesPerPage: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [[1946]],
      pageMatchesLength: [[23]],
    });
  });

  it("performs a search in a text containing diacritics before -\\n", async function () {
    if (isNodeJS) {
      pending("Linked test-cases are not supported in Node.js.");
    }

    const { eventBus, pdfFindController } = await initPdfFindController(
      "issue14562.pdf"
    );

    await testSearch({
      eventBus,
      pdfFindController,
      state: {
        query: "ä",
        matchDiacritics: true,
      },
      matchesPerPage: [80],
      selectedMatch: {
        pageIndex: 0,
        matchIndex: 0,
      },
      pageMatches: [
        [
          299, 337, 414, 476, 623, 797, 978, 984, 1010, 1058, 1079, 1144, 1152,
          1274, 1343, 1391, 1399, 1421, 1497, 1521, 1527, 1684, 1774, 1786,
          1857, 1879, 1909, 1946, 2064, 2074, 2161, 2178, 2213, 2227, 2272,
          2322, 2359, 2401, 2412, 2423, 2462, 2532, 2538, 2553, 2562, 2576,
          2602, 2613, 2638, 2668, 2792, 2805, 2836, 2848, 2859, 2896, 2902,
          2916, 2940, 2960, 3091, 3239, 3249, 3339, 3387, 3394, 3468, 3477,
          3485, 3502, 3690, 3696, 3711, 3758, 3789, 3865, 3977, 4052, 4058,
          4071,
        ],
      ],
      pageMatchesLength: [
        [
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        ],
      ],
    });
  });
});


text:
@class HGTitleView;
@protocol HGTitleViewDelegate <NSObject>

@optional
-(void)titleView:(HGTitleView*)titleView scrollToIndex:(NSInteger)tagIndex;

@end

@interface HGTitleView : UIView

@property (nonatomic,weak) id<HGTitleViewDelegate>delegate;

-(void)wanerSelected:(NSInteger)tagIndex;

@end


text:
package v1

import (
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
)

// +genclient=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// NetworkPolicy describes what network traffic is allowed for a set of Pods
type NetworkPolicy struct {
	metav1.TypeMeta `json:",inline"`
	// Standard object's metadata.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Specification of the desired behavior for this NetworkPolicy.
	// +optional
	Spec NetworkPolicySpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
}

// NetworkPolicySpec provides the specification of a NetworkPolicy
type NetworkPolicySpec struct {
	// Selects the pods to which this NetworkPolicy object applies. The array of
	// ingress rules is applied to any pods selected by this field. Multiple network
	// policies can select the same set of pods. In this case, the ingress rules for
	// each are combined additively. This field is NOT optional and follows standard
	// label selector semantics. An empty podSelector matches all pods in this
	// namespace.
	PodSelector metav1.LabelSelector `json:"podSelector" protobuf:"bytes,1,opt,name=podSelector"`

	// List of ingress rules to be applied to the selected pods. Traffic is allowed to
	// a pod if there are no NetworkPolicies selecting the pod
	// (and cluster policy otherwise allows the traffic), OR if the traffic source is
	// the pod's local node, OR if the traffic matches at least one ingress rule
	// across all of the NetworkPolicy objects whose podSelector matches the pod. If
	// this field is empty then this NetworkPolicy does not allow any traffic (and serves
	// solely to ensure that the pods it selects are isolated by default)
	// +optional
	Ingress []NetworkPolicyIngressRule `json:"ingress,omitempty" protobuf:"bytes,2,rep,name=ingress"`
}

// NetworkPolicyIngressRule describes a particular set of traffic that is allowed to the pods
// matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and from.
type NetworkPolicyIngressRule struct {
	// List of ports which should be made accessible on the pods selected for this
	// rule. Each item in this list is combined using a logical OR. If this field is
	// empty or missing, this rule matches all ports (traffic not restricted by port).
	// If this field is present and contains at least one item, then this rule allows
	// traffic only if the traffic matches at least one port in the list.
	// +optional
	Ports []NetworkPolicyPort `json:"ports,omitempty" protobuf:"bytes,1,rep,name=ports"`

	// List of sources which should be able to access the pods selected for this rule.
	// Items in this list are combined using a logical OR operation. If this field is
	// empty or missing, this rule matches all sources (traffic not restricted by
	// source). If this field is present and contains at least on item, this rule
	// allows traffic only if the traffic matches at least one item in the from list.
	// +optional
	From []NetworkPolicyPeer `json:"from,omitempty" protobuf:"bytes,2,rep,name=from"`
}

// NetworkPolicyPort describes a port to allow traffic on
type NetworkPolicyPort struct {
	// The protocol (TCP or UDP) which traffic must match. If not specified, this
	// field defaults to TCP.
	// +optional
	Protocol *v1.Protocol `json:"protocol,omitempty" protobuf:"bytes,1,opt,name=protocol,casttype=k8s.io/api/core/v1.Protocol"`

	// The port on the given protocol. This can either be a numerical or named port on
	// a pod. If this field is not provided, this matches all port names and numbers.
	// +optional
	Port *intstr.IntOrString `json:"port,omitempty" protobuf:"bytes,2,opt,name=port"`
}

// NetworkPolicyPeer describes a peer to allow traffic from. Exactly one of its fields
// must be specified.
type NetworkPolicyPeer struct {
	// This is a label selector which selects Pods in this namespace. This field
	// follows standard label selector semantics. If present but empty, this selector
	// selects all pods in this namespace.
	// +optional
	PodSelector *metav1.LabelSelector `json:"podSelector,omitempty" protobuf:"bytes,1,opt,name=podSelector"`

	// Selects Namespaces using cluster scoped-labels. This matches all pods in all
	// namespaces selected by this label selector. This field follows standard label
	// selector semantics. If present but empty, this selector selects all namespaces.
	// +optional
	NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,2,opt,name=namespaceSelector"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// NetworkPolicyList is a list of NetworkPolicy objects.
type NetworkPolicyList struct {
	metav1.TypeMeta `json:",inline"`
	// Standard list metadata.
	// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
	// +optional
	metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

	// Items is a list of schema objects.
	Items []NetworkPolicy `json:"items" protobuf:"bytes,2,rep,name=items"`
}