text:
namespace NativeCode.Mobile.Core.XamarinForms.Platform
{
    public enum PlatformSystem
    {
        Unknown = 0,

        Android = 1,

        iOS = 2,

        WindowsPhone = 3
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android" android:keyHeight="@integer/key_normal_height" android:keyWidth="15%p">
  <!--Variants for 🤵-->
  <Row>
    <Key android:keyLabel="🤵🏻" android:keyOutputText="🤵🏻" xmlns:ask="http://schemas.android.com/apk/res-auto" ask:tags=""/>
    <Key android:keyLabel="🤵🏼" android:keyOutputText="🤵🏼" xmlns:ask="http://schemas.android.com/apk/res-auto" ask:tags=""/>
    <Key android:keyLabel="🤵🏽" android:keyOutputText="🤵🏽" xmlns:ask="http://schemas.android.com/apk/res-auto" ask:tags=""/>
    <Key android:keyLabel="🤵🏾" android:keyOutputText="🤵🏾" xmlns:ask="http://schemas.android.com/apk/res-auto" ask:tags=""/>
    <Key android:keyLabel="🤵🏿" android:keyOutputText="🤵🏿" xmlns:ask="http://schemas.android.com/apk/res-auto" ask:tags=""/>
  </Row>
</Keyboard>


text:
pub use super::{Parse, ParsedResponse};

use byteorder::{ByteOrder, BigEndian};

pub struct Response<'a> {
    pub response: &'a [u8],
}

impl<'a> Parse for Response<'a> {
    fn parse(&self) -> ParsedResponse {
        let bytes = self.response.len();
        if bytes > 4 {
            let length = BigEndian::read_u32(&self.response[0..4]);

            if bytes as u32 == (length + 4_u32) {
                return ParsedResponse::Ok;
            }
        }
        ParsedResponse::Incomplete
    }
}

#[cfg(test)]
mod tests {
    use super::{Parse, ParsedResponse, Response};

    #[test]
    fn test_parse_ok() {
        assert_eq!(Response { response: &[0, 0, 0, 1, 0] }.parse(),
                   ParsedResponse::Ok);
        assert_eq!(Response { response: &[0, 0, 0, 2, 0, 1] }.parse(),
                   ParsedResponse::Ok);
    }

    #[test]
    fn test_parse_incomplete() {
        assert_eq!(Response { response: &[0, 0] }.parse(),
                   ParsedResponse::Incomplete);
        assert_eq!(Response { response: &[0, 0, 0, 1] }.parse(),
                   ParsedResponse::Incomplete);
        assert_eq!(Response { response: &[0, 0, 0, 2, 0] }.parse(),
                   ParsedResponse::Incomplete);
    }
}


text:
import base64
import datetime
from functools import reduce
import hashlib
import json
import pymongo
import random
import re
from urllib.parse import urlencode
from urllib.request import Request, urlopen

"""
Contains username, password, and email validation routines
"""
class Validator:
  user_rgx = re.compile("^[ -~]{2}[ -~]*$")
  email_rgx = re.compile("^[ -~]+@[ -~]+\\.\\w+$")

  """
  Checks if username is valid--contains at least 2 printable characters
  """
  @staticmethod
  def user_valid(user):
    return re.match(Validator.user_rgx, user.strip())

  """
  Roughly checks if the email is of name@domain.tld format
  """
  @staticmethod
  def email_valid(email):
    return re.match(Validator.email_rgx, email.strip())

  """
  Determines if password is valid--contains at least 10 characters, has lower/upper/numeric chars
  """
  @staticmethod
  def password_valid(password):
    response = Validator()
    response.valid_len = len(password) >= 10
    response.has_lower = False
    response.has_upper = False
    response.has_numeric = False
    for c in password:
      response.has_lower = response.has_lower or c.islower()
      response.has_upper = response.has_upper or c.isupper()
      response.has_numeric = response.has_numeric or c.isdigit()
    response.__bool__ = lambda: response.has_lower and response.has_upper and response.has_numeric and response.valid_len
    return response

"""
More secure random.choice generator
"""
def sec_random_gen(length, alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789$!@#$%^&*()"):
  return ''.join(random.SystemRandom().choice(alphabet) for _ in range(length))

"""
Basic hash function for flowboard
"""
def sha256x2(password, salt):
  image1 = ''.join([hashlib.sha256(password.encode()).hexdigest(), salt])
  image2 = base64.b64encode(hashlib.sha256(image1.encode()).digest())
  return image2

def generate_session_id():
  return sec_random_gen(32)

"""
Checks if user is human via reCAPTCHA service
"""
def recaptcha_valid(recaptcha_secret, recaptcha_response, ip):
  fields = {'response': recaptcha_response, 'remoteip': ip, 'secret': recaptcha_secret}
  request = Request("https://www.google.com/recaptcha/api/siteverify", urlencode(fields).encode())
  response = urlopen(request).read().decode()
  return json.loads(response)["success"]

class AuthDatabase:
  status_ok = 1
  status_name_dup = 2
  status_email_dup = 4
  status_bad = 8
  def __init__(self, client):
    self.client = client
    self.users = client.db.users
    self.sessions = client.db.sessions
    try:
      self.users.create_index("name", unique=True)
      self.users.create_index("email", unique=True)
      self.sessions.create_index("session_id")
      self.sessions.create_index("last_accessed", expireAfterSeconds=600000)
    except:
      raise Exception("Couldn't create indices on database")

  def find_user_by_ssid(self, session_id):
    session = self.sessions.find_one({"session_id": session_id})
    if not session:
      return None
    user = self.users.find_one({"_id": session["user_id"]})
    return user

  def find_user_by_id(self, user_id):
    user = self.users.find_one({"_id": user_id})
    return user

  """
  Attempts to authenticate a user given name and password. Returns session ID string on success, None otherwise
  """
  def login_by_name(self, name, password):
    user = self.users.find_one({"name": re.compile(name, re.IGNORECASE)})
    if not user:
      return None
    salt = user["salt"]
    if not salt:
      return None
    sha256x2_hash = sha256x2(password, salt).decode("utf-8")
    if sha256x2_hash == user["password"]:
      sid = generate_session_id()
      self.sessions.insert_one({"user_id": user["_id"], "last_accessed": datetime.datetime.utcnow(), "session_id": sid})
      return sid
    return None

  """
  Attempts to authenticate user given session id. Returns user ID on success, None otherwise
  """
  def login_by_session_id(self, session_id):
    session = self.sessions.find_one_and_update({"session_id": session_id}, {"$set": {"last_accessed": datetime.datetime.utcnow()}}, upsert=False)
    if session is None:
      return None
    return str(session["user_id"])

  """
  Registers a user based on provided form data. Returns an integral value with status_ok, status_name_dup, or status_email_dup bits
  set depending on outcome
  """
  def create_user(self, form_data):
    ret = self.status_bad
    if self.users.find_one({"name": re.compile(form_data.user.strip(), re.IGNORECASE)}):
      ret |= self.status_name_dup
    if self.users.find_one({"email": re.compile(form_data.email, re.IGNORECASE)}):
      ret |= self.status_email_dup
    if ret != self.status_bad:
      return ret
    salt = sec_random_gen(8)
    try:
      hash64 = sha256x2(form_data.password, salt).decode("utf-8")
      self.users.insert_one({"name": form_data.user, "email": form_data.email, "password": hash64, "salt": salt})
      return self.status_ok
    except:
      return ret

"""
Wrapper/adapter between database and front end.
"""
class AuthService:
  def __init__(self, database):
    self.database = database

  """
  Attempts to register a user. Returns dictionary response suitable for conversion to JSON
  """
  def register(self, form_data):
    if not form_data.valid():
      return {"success": False, "password_valid": form_data.password_valid,
        "email_valid": form_data.email_valid, "user_valid": form_data.user_valid}
    response = self.database.create_user(form_data)
    register_response = {"success": response & AuthDatabase.status_ok == AuthDatabase.status_ok}
    if not response & AuthDatabase.status_ok:
      register_response["name_dup"] = response & AuthDatabase.status_name_dup == AuthDatabase.status_name_dup
      register_response["email_dup"] = response & AuthDatabase.status_email_dup == AuthDatabase.status_email_dup
    return register_response

  """
  Attempts to authenticate a user. Returns dictionary response suitable for conversion to JSON
  """
  def login(self, user=None, password=None, session_id=None):
    if session_id:
      response = self.database.login_by_session_id(session_id)
      if response:
        return {"success": True, "user_id": response}
    else:
      response = self.database.login_by_name(user, password)
      if response:
        return {"success": True, "session_id": response}
    return {"success": False}

  class FormData:
    def __init__(self, user, password, email):
      self.user = user
      self.password = password
      self.email = email
      self.user_valid = Validator.user_valid(self.user) is not None
      self.password_valid = Validator.password_valid(self.password).__bool__()
      self.email_valid = Validator.email_valid(self.email) is not None

    def valid(self):
      return self.user_valid and self.password_valid and self.email_valid


text:
package br.edu.uninassau.provaColegiada.usuario.dao;

import br.edu.uninassau.provaColegiada.DAO;
import br.edu.uninassau.provaColegiada.usuario.Usuario;
import java.util.List;

/**
 *
 * @author avld
 */
public interface UsuarioDAO extends DAO<Usuario>
{
    public List<Usuario> listar( int categoria ) throws Exception;
    public Usuario login( String email , String senha ) throws Exception;
}


text:
<?php
require __DIR__ . '/../lib/OAuth2.php';
require __DIR__ . '/../lib/IOAuth2Storage.php';
require __DIR__ . '/../lib/IOAuth2GrantCode.php';

/**
 * OAuth2 test case.
 */
class OAuth2Test extends PHPUnit_Framework_TestCase {

  /**
   * @var OAuth2
   */
  private $fixture;

  /**
   * The actual token ID is irrelevant, so choose one:
   * @var string
   */
  private $tokenId = 'my_token';

  /**
   * Tests OAuth2->verifyAccessToken() with a missing token
   */
  public function testVerifyAccessTokenWithNoParam() {
    $mockStorage = $this->getMock('IOAuth2Storage');
    $this->fixture = new OAuth2($mockStorage);

    $scope = null;
    $this->setExpectedException('OAuth2AuthenticateException');
    $this->fixture->verifyAccessToken('', $scope);
  }

  /**
   * Tests OAuth2->verifyAccessToken() with a invalid token
   */
  public function testVerifyAccessTokenInvalidToken() {

    // Set up the mock storage to say this token does not exist
    $mockStorage = $this->getMock('IOAuth2Storage');
    $mockStorage->expects($this->once())
      ->method('getAccessToken')
      ->will($this->returnValue(false));

    $this->fixture = new OAuth2($mockStorage);

    $scope = null;
    $this->setExpectedException('OAuth2AuthenticateException');
    $this->fixture->verifyAccessToken($this->tokenId, $scope);
  }

  /**
   * Tests OAuth2->verifyAccessToken() with a malformed token
   *
   * @dataProvider generateMalformedTokens
   */
  public function testVerifyAccessTokenMalformedToken($token) {

    // Set up the mock storage to say this token does not exist
    $mockStorage = $this->getMock('IOAuth2Storage');
    $mockStorage->expects($this->once())
      ->method('getAccessToken')
      ->will($this->returnValue($token));

    $this->fixture = new OAuth2($mockStorage);

    $scope = null;
    $this->setExpectedException('OAuth2AuthenticateException');
    $this->fixture->verifyAccessToken($this->tokenId, $scope);
  }

	/**
   * Tests OAuth2->verifyAccessToken() with different expiry dates
   *
   * @dataProvider generateExpiryTokens
   */
  public function testVerifyAccessTokenCheckExpiry($token, $expectedToPass) {

    // Set up the mock storage to say this token does not exist
    $mockStorage = $this->getMock('IOAuth2Storage');
    $mockStorage->expects($this->once())
      ->method('getAccessToken')
      ->will($this->returnValue($token));

    $this->fixture = new OAuth2($mockStorage);

    $scope = null;

    // When valid, we just want any sort of token
    if ($expectedToPass) {
      $actual = $this->fixture->verifyAccessToken($this->tokenId, $scope);
      $this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
      $this->assertInternalType('array', $actual);
    }
    else {
      $this->setExpectedException('OAuth2AuthenticateException');
      $this->fixture->verifyAccessToken($this->tokenId, $scope);
    }
  }

	/**
   * Tests OAuth2->verifyAccessToken() with different scopes
   *
   * @dataProvider generateScopes
   */
  public function testVerifyAccessTokenCheckScope($scopeRequired, $token, $expectedToPass) {

    // Set up the mock storage to say this token does not exist
    $mockStorage = $this->getMock('IOAuth2Storage');
    $mockStorage->expects($this->once())
      ->method('getAccessToken')
      ->will($this->returnValue($token));

    $this->fixture = new OAuth2($mockStorage);

    // When valid, we just want any sort of token
    if ($expectedToPass) {
      $actual = $this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
      $this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
      $this->assertInternalType('array', $actual);
    }
    else {
      $this->setExpectedException('OAuth2AuthenticateException');
      $this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
    }
  }

  /**
   * Tests OAuth2->grantAccessToken() for missing data
   *
   * @dataProvider generateEmptyDataForGrant
   */
  public function testGrantAccessTokenMissingData($inputData, $authHeaders) {
    $mockStorage = $this->getMock('IOAuth2Storage');
    $this->fixture = new OAuth2($mockStorage);

    $this->setExpectedException('OAuth2ServerException');
    $this->fixture->grantAccessToken($inputData, $authHeaders);
  }

  /**
   * Tests OAuth2->grantAccessToken()
   *
   * Tests the different ways client credentials can be provided.
   */
  public function testGrantAccessTokenCheckClientCredentials() {
    $mockStorage = $this->getMock('IOAuth2Storage');
    $mockStorage->expects($this->any())
      ->method('checkClientCredentials')
      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
    $this->fixture = new OAuth2($mockStorage);

    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE);
    $authHeaders = array();

    // First, confirm that an non-client related error is thrown:
    try {
      $this->fixture->grantAccessToken($inputData, $authHeaders);
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    } catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
    }

    // Confirm Auth header
    $authHeaders = array('PHP_AUTH_USER' => 'dev-abc', 'PHP_AUTH_PW' => 'pass');
    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'dev-abc'); // When using auth, client_id must match
    try {
      $this->fixture->grantAccessToken($inputData, $authHeaders);
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    } catch ( OAuth2ServerException $e ) {
      $this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
    }

    // Confirm GET/POST
    $authHeaders = array();
    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'dev-abc', 'client_secret' => 'foo'); // When using auth, client_id must match
    try {
      $this->fixture->grantAccessToken($inputData, $authHeaders);
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    } catch ( OAuth2ServerException $e ) {
      $this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
    }
  }

  /**
   * Tests OAuth2->grantAccessToken() with Auth code grant
   *
   */
  public function testGrantAccessTokenWithGrantAuthCodeMandatoryParams() {
    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'a', 'client_secret' => 'b');
    $fakeAuthCode = array('client_id' => $inputData['client_id'], 'redirect_uri' => '/foo', 'expires' => time() + 60);
    $fakeAccessToken = array('access_token' => 'abcde');

    // Ensure redirect URI and auth-code is mandatory
    try {
      $this->fixture = new OAuth2($mockStorage);
      $this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, true); // Only required when this is set
      $this->fixture->grantAccessToken($inputData + array('code' => 'foo'), array());
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    } catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
    }
    try {
      $this->fixture = new OAuth2($mockStorage);
      $this->fixture->grantAccessToken($inputData + array('redirect_uri' => 'foo'), array());
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    } catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
    }
  }

   /**
   * Tests OAuth2->grantAccessToken() with Auth code grant
   *
   */
  public function testGrantAccessTokenWithGrantAuthCodeNoToken() {
    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'a', 'client_secret' => 'b', 'redirect_uri' => 'foo', 'code'=> 'foo');

    // Ensure missing auth code raises an error
    try {
      $this->fixture = new OAuth2($mockStorage);
      $this->fixture->grantAccessToken($inputData + array(), array());
      $this->fail('The expected exception OAuth2ServerException was not thrown');
    }
    catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
    }
  }

  /**
   * Tests OAuth2->grantAccessToken() with checks the redirect URI
   *
   */
  public function testGrantAccessTokenWithGrantAuthCodeRedirectChecked() {
    $inputData = array('redirect_uri' => 'http://www.crossdomain.com/my/subdir', 'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code'=> 'foo');
    $storedToken = array('redirect_uri' => 'http://www.example.com', 'client_id' => 'my_little_app', 'expires' => time() + 60);

    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
    $mockStorage->expects($this->any())
      ->method('getAuthCode')
      ->will($this->returnValue($storedToken));

    // Ensure that the redirect_uri is checked
    try {
      $this->fixture = new OAuth2($mockStorage);
      $this->fixture->grantAccessToken($inputData, array());

      $this->fail('The expected exception OAuth2ServerException was not thrown');
    }
    catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_REDIRECT_URI_MISMATCH, $e->getMessage());
    }
  }

	/**
   * Tests OAuth2->grantAccessToken() with checks the client ID is matched
   *
   */
  public function testGrantAccessTokenWithGrantAuthCodeClientIdChecked() {
    $inputData = array('client_id' => 'another_app', 'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'redirect_uri' => 'http://www.example.com/my/subdir', 'client_secret' => 'b', 'code'=> 'foo');
    $storedToken = array('client_id' => 'my_little_app', 'redirect_uri' => 'http://www.example.com', 'expires' => time() + 60);

    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
    $mockStorage->expects($this->any())
      ->method('getAuthCode')
      ->will($this->returnValue($storedToken));

    // Ensure the client ID is checked
    try {
      $this->fixture = new OAuth2($mockStorage);
      $this->fixture->grantAccessToken($inputData, array());

      $this->fail('The expected exception OAuth2ServerException was not thrown');
    }
    catch ( OAuth2ServerException $e ) {
      $this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
    }
  }

  /**
   * Tests OAuth2->grantAccessToken() with implicit
   *
   */
  public function testGrantAccessTokenWithGrantImplicit() {
    $this->markTestIncomplete ( "grantAccessToken test not implemented" );

    $this->fixture->grantAccessToken(/* parameters */);
  }

	/**
   * Tests OAuth2->grantAccessToken() with user credentials
   *
   */
  public function testGrantAccessTokenWithGrantUser() {
    $this->markTestIncomplete ( "grantAccessToken test not implemented" );

    $this->fixture->grantAccessToken(/* parameters */);
  }

	/**
   * Tests OAuth2->grantAccessToken() with client credentials
   *
   */
  public function testGrantAccessTokenWithGrantClient() {
    $this->markTestIncomplete ( "grantAccessToken test not implemented" );

    $this->fixture->grantAccessToken(/* parameters */);
  }

	/**
   * Tests OAuth2->grantAccessToken() with refresh token
   *
   */
  public function testGrantAccessTokenWithGrantRefresh() {
    $this->markTestIncomplete ( "grantAccessToken test not implemented" );

    $this->fixture->grantAccessToken(/* parameters */);
  }

	/**
   * Tests OAuth2->grantAccessToken() with extension
   *
   */
  public function testGrantAccessTokenWithGrantExtension() {
    $this->markTestIncomplete ( "grantAccessToken test not implemented" );

    $this->fixture->grantAccessToken(/* parameters */);
  }

  /**
   * Tests OAuth2->getAuthorizeParams()
   */
  public function testGetAuthorizeParams() {
    // TODO Auto-generated OAuth2Test->testGetAuthorizeParams()
    $this->markTestIncomplete ( "getAuthorizeParams test not implemented" );

    $this->fixture->getAuthorizeParams(/* parameters */);

  }

  /**
   * Tests OAuth2->finishClientAuthorization()
   */
  public function testFinishClientAuthorization() {
    // TODO Auto-generated OAuth2Test->testFinishClientAuthorization()
    $this->markTestIncomplete ( "finishClientAuthorization test not implemented" );

    $this->fixture->finishClientAuthorization(/* parameters */);

  }

  // Utility methods

  /**
   *
   * @param string $interfaceName
   */
  protected function createBaseMock($interfaceName) {
    $mockStorage = $this->getMock($interfaceName);
    $mockStorage->expects($this->any())
      ->method('checkClientCredentials')
      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
    $mockStorage->expects($this->any())
      ->method('checkRestrictedGrantType')
      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass

     return $mockStorage;
  }

  // Data Providers below:

  /**
   * Dataprovider for testVerifyAccessTokenMalformedToken().
   *
   * Produces malformed access tokens
   */
  public function generateMalformedTokens() {
    return array(
      array(array()), // an empty array as a token
      array(array('expires' => 5)), // missing client_id
      array(array('client_id' => 6)), // missing expires
      array(array('something' => 6)), // missing both 'expires' and 'client_id'
    );
  }

  /**
   * Dataprovider for testVerifyAccessTokenCheckExpiry().
   *
   * Produces malformed access tokens
   */
  public function generateExpiryTokens() {
    return array(
      array(array('client_id' => 'blah', 'expires' => time() - 30),                 FALSE), // 30 seconds ago should fail
      array(array('client_id' => 'blah', 'expires' => time() - 1),                  FALSE), // now-ish should fail
      array(array('client_id' => 'blah', 'expires' => 0),                           FALSE), // 1970 should fail
      array(array('client_id' => 'blah', 'expires' => time() + 30),                 TRUE),  // 30 seconds in the future should be valid
      array(array('client_id' => 'blah', 'expires' => time() + 86400),              TRUE),  // 1 day in the future should be valid
      array(array('client_id' => 'blah', 'expires' => time() + (365 * 86400)),      TRUE),  // 1 year should be valid
      array(array('client_id' => 'blah', 'expires' => time() + (10 * 365 * 86400)), TRUE),  // 10 years should be valid
    );
  }

  /**
   * Dataprovider for testVerifyAccessTokenCheckExpiry().
   *
   * Produces malformed access tokens
   */
  public function generateScopes() {
    $baseToken = array('client_id' => 'blah', 'expires' => time() + 60);

    return array(
      array(null,   $baseToken + array(),                               TRUE), // missing scope is valif
      array(null,   $baseToken + array('scope' => null),                TRUE), // null scope is valid
      array('',     $baseToken + array('scope' => ''),                  TRUE), // empty scope is valid
      array('read', $baseToken + array('scope' => 'read'),              TRUE), // exact same scope is valid
      array('read', $baseToken + array('scope' => ' read '),            TRUE), // exact same scope is valid
      array(' read ', $baseToken + array('scope' => 'read'),            TRUE), // exact same scope is valid
      array('read', $baseToken + array('scope' => 'read write delete'), TRUE), // contains scope
      array('read', $baseToken + array('scope' => 'write read delete'), TRUE), // contains scope
      array('read', $baseToken + array('scope' => 'delete write read'), TRUE), // contains scope

      // Invalid combinations
      array('read', $baseToken + array('scope' => 'write'),            FALSE),
      array('read', $baseToken + array('scope' => 'apple banana'),     FALSE),
      array('read', $baseToken + array('scope' => 'apple read-write'), FALSE),
      array('read', $baseToken + array('scope' => 'apple read,write'), FALSE),
      array('read', $baseToken + array('scope' => null),               FALSE),
      array('read', $baseToken + array('scope' => ''),                 FALSE),
    );
  }

  /**
   * Provider for OAuth2->grantAccessToken()
   */
  public function generateEmptyDataForGrant() {
    return array(
      array(
        array(), array()
      ),
      array(
        array(), array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE) // grant_type in auth headers should be ignored
      ),
      array(
        array('not_grant_type' => 5), array()
      ),
    );
  }
}


text:
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

--]]

local miniz = require('miniz')
local modes = require('git').modes
local log = require('log').log

-- Create a zip from a hash optionally compiling lua files to bytecode.
return function (db, rootHash, compileLua)

  local writer = miniz.new_writer()

  local function importEntry(hash, path, mode)
    local kind, value = assert(db.loadAny(hash))
    mode = mode or modes[kind]
    if mode == modes.tree then
      if path then
        writer:add(path .. "/", "")
      end
      for i = 1, #value do
        local entry = value[i]
        local newPath = path and path .. '/' .. entry.name or entry.name
        importEntry(entry.hash, newPath, entry.mode)
      end
    elseif modes.isFile(mode) then
      if compileLua and path:find("%.lua$") then
        local fn = assert(loadstring(value, "bundle:" .. path))
        value = assert(string.dump(fn))
        log("compiling", path)
      else
        log("storing", path)
      end
      writer:add(path, value, 9)
    else
      error("Can't handle entry for " .. path)
    end
  end

  importEntry(rootHash)

  return writer:finalize()
end


text:
package DDG::Goodie::IPS;
# ABSTRACT: track a package through IPS.

use DDG::Goodie;

zci is_cached => 1;
zci answer_type => "ips";

primary_example_queries 'EM999999999IN';
description 'Track a package from IPS';
name 'IPS';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/IPS.pm';
category 'ids';
topics 'special_interest';
attribution github => [ 'https://github.com/duckduckgo', 'duckduckgo'];

triggers query_nowhitespace_nodash => qr/(E[MA]\d{9})(IN|HR|)/xi;

handle query_nowhitespace_nodash => sub {
    my $package_number = $1 . $2;
    my $country = lc $2 || '';

    my $tmp_link = '';

    if ( $country eq 'in' ) {
        $tmp_link = "http://ipsweb.ptcmysore.gov.in/ipswebtracking/IPSWeb_item_events.asp?itemid=$package_number&Submit=Submit";
    }
    elsif ( $country eq 'hr' ) {
        $tmp_link = "http://ips.posta.hr/IPSWeb_item_events.asp?itemid=$package_number&Submit=Submit";
    }
    else {
        $tmp_link = "http://mailtracking.gov.bm/IPSWeb_item_events.asp?itemid=$package_number&Submit=Submit+Query";
    }
    if ($tmp_link) {
        return $package_number, heading => "IPS Shipment Tracking", html => qq(Track this shipment at IPS.);
    }

    return;
};

1;


text:
Bitcoin ABC version 0.16.1 is now available from:

  <https://download.bitcoinabc.org/0.16.1/>

This release includes the following features and fixes:

- Update seeds


text:
package com.blogspot.toomuchcoding.book.chapter4._1_ArgumentMatchers;

import com.blogspot.toomuchcoding.person.Person;

public class PersonIrsDataVerifier {

    private final IrsDataFetcher irsDataFetcher;

    public PersonIrsDataVerifier(IrsDataFetcher irsDataFetcher) {
        this.irsDataFetcher = irsDataFetcher;
    }

    public boolean isIrsDepartmentApplicable(Person person, String city) {
        boolean irsDptApplicable = irsDataFetcher.isIrsApplicable(person, city);
        System.out.printf("IRS department is applicable [%s] for person [%s] and city [%s]%n", irsDptApplicable, person.getName(), city);
        return irsDptApplicable;
    }

}


text:
package messanger.virtualagent.bot.utils;

import java.util.HashMap;

import messanger.virtualagent.bot.jsonwrapers.FaceBookUser;

public class CacheUtils {

	private static HashMap<String, FaceBookUser> users = new HashMap<>();

	public static void cacheUser(String userID, FaceBookUser user) {

		users.put(userID, user);

	}

	public static FaceBookUser getCachedUser(String userID) {
		return users.get(userID);

	}

	public static void clearTheCache() {

		users.clear();
	}

}


text:
package AI::MXNet::Contrib::NDArray;
use strict;
use warnings;
use parent 'AI::MXNet::AutoLoad';
sub config { ('contrib', 'AI::MXNet::NDArray') }

1;


text:
package registry

import (
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/utils"
)

type tokenResponse struct {
	Token string `json:"token"`
}

func getToken(username, password string, params map[string]string, registryEndpoint *Endpoint, client *http.Client, factory *utils.HTTPRequestFactory) (token string, err error) {
	realm, ok := params["realm"]
	if !ok {
		return "", errors.New("no realm specified for token auth challenge")
	}

	realmURL, err := url.Parse(realm)
	if err != nil {
		return "", fmt.Errorf("invalid token auth challenge realm: %s", err)
	}

	if realmURL.Scheme == "" {
		if registryEndpoint.IsSecure {
			realmURL.Scheme = "https"
		} else {
			realmURL.Scheme = "http"
		}
	}

	req, err := factory.NewRequest("GET", realmURL.String(), nil)
	if err != nil {
		return "", err
	}

	reqParams := req.URL.Query()
	service := params["service"]
	scope := params["scope"]

	if service != "" {
		reqParams.Add("service", service)
	}

	for _, scopeField := range strings.Fields(scope) {
		reqParams.Add("scope", scopeField)
	}

	if username != "" {
		reqParams.Add("account", username)
		req.SetBasicAuth(username, password)
	}

	req.URL.RawQuery = reqParams.Encode()

	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("token auth attempt for registry %s: %s request failed with status: %d %s", registryEndpoint, req.URL, resp.StatusCode, http.StatusText(resp.StatusCode))
	}

	decoder := json.NewDecoder(resp.Body)

	tr := new(tokenResponse)
	if err = decoder.Decode(tr); err != nil {
		return "", fmt.Errorf("unable to decode token response: %s", err)
	}

	if tr.Token == "" {
		return "", errors.New("authorization server did not include a token in the response")
	}

	return tr.Token, nil
}


text:
namespace YAF.Core.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using YAF.Core.Extensions;
    using YAF.Types;
    using YAF.Types.Interfaces;
    using YAF.Types.Interfaces.Data;
    using YAF.Types.Models;

    /// <summary>
    /// The UserAlbum Repository Extensions
    /// </summary>
    public static class UserAlbumRepositoryExtensions
    {
        #region Public Methods and Operators

        /// <summary>
        /// Lists all the albums associated with the UserID or gets all the
        ///   specifications for the specified album id.
        /// </summary>
        /// <param name="userID">
        /// The user id.
        /// </param>
        /// <param name="albumID">
        /// the album id.
        /// </param>
        /// <returns>
        /// a Datatable containing the albums.
        /// </returns>
        public static List<UserAlbum> List(
            [NotNull] this IRepository<UserAlbum> repository, int albumId)
        {
            return repository.Get(userAlbum => userAlbum.ID == albumId);
        }

        /// <summary>
        /// Lists all the albums associated with the UserID or gets all the
        ///   specifications for the specified album id.
        /// </summary>
        /// <param name="userID">
        /// The user id.
        /// </param>
        /// <param name="albumID">
        /// the album id.
        /// </param>
        /// <returns>
        /// a Datatable containing the albums.
        /// </returns>
        public static List<UserAlbum> ListByUser(
            [NotNull] this IRepository<UserAlbum> repository, int userId)
        {
            return repository.Get(userAlbum => userAlbum.UserID == userId).OrderByDescending(u => u.Updated).ToList();
        }

        public static string GetTitle(this IRepository<UserAlbum> repository, [NotNull] int albumId)
        {
            return repository.GetById(albumId).Title;
        }

        public static void DeleteCover(this IRepository<UserAlbum> repository, [NotNull] int imageId)
        {
            repository.UpdateOnly(() => new UserAlbum { CoverImageID = null }, u => u.CoverImageID == imageId);
        }

        [NotNull]
        public static long CountUserAlbum([NotNull] this IRepository<UserAlbum> repository, [NotNull] int userId)
        {
            CodeContracts.VerifyNotNull(repository, "repository");

            return repository.Count(album => album.UserID == userId);
        }

        public static void UpdateTitle(
            this IRepository<UserAlbum> repository,
            [NotNull] int albumId,
            [NotNull] string title)
        {
            repository.UpdateOnly(
                () => new UserAlbum { Title = title },
                album => album.ID == albumId);
        }

        public static void UpdateCover(
            this IRepository<UserAlbum> repository,
            [NotNull] int albumId,
            [NotNull] int? coverImageId)
        {
            repository.UpdateOnly(
                () => new UserAlbum { CoverImageID = coverImageId },
                album => album.ID == albumId);
        }

        public static int Save(
            this IRepository<UserAlbum> repository,
            [NotNull] int userId,
            [NotNull] string title,
            [NotNull] int? coverImageId)
        {
            var entity = new UserAlbum
                             {
                                 UserID = userId, Title = title, CoverImageID = coverImageId, Updated = DateTime.UtcNow
                             };

            var newId = repository.Insert(entity);

            repository.FireNew(entity);

            return newId;
        }

        #endregion
    }
}


text:
define([
    "jquery",
    "pat-logger"
], function($, logging) {
    var namespace = "input-change-events",
        log = logging.getLogger(namespace);

    var _ = {
        setup: function($form, pat) {

            if (!$form.is("form,.pat-subform")) {
                log.error("Input change event handler can only be set on forms.");
                return;
            }

            if (!pat) {
                log.error("The name of the calling pattern has to be set.");
                return;
            }

            // list of patterns that installed input-change-event handlers
            var patterns = $form.data(namespace) || [];
            log.debug("setup handlers for " + pat);

            if (!patterns.length) {
                log.debug("installing handlers");
                _.setupInputHandlers($form);

                $form.on("patterns-injected." + namespace, function(event) {
                    _.setupInputHandlers($(event.target));
                });
            }

            if (patterns.indexOf(pat) === -1) {
                patterns.push(pat);
                $form.data(namespace, patterns);
            }
        },

        setupInputHandlers: function($parent) {
            $parent.findInclusive(":input").each(function() {
                var $el = $(this),
                    isText = $el.is("input:text, input[type=search], textarea");

                if (isText) {
                    if ("oninput" in window) {
                        $el.on("input." + namespace, function() {
                            log.debug("translating input");
                            $el.trigger("input-change");
                        });
                    } else {
                        // this is the legacy code path for IE8
                        // Work around buggy placeholder polyfill.
                        if ($el.attr("placeholder")) {
                            $el.on("keyup." + namespace, function() {
                                log.debug("translating keyup");
                                $el.trigger("input-change");
                            });
                        } else {
                            $el.on("propertychange." + namespace, function(ev) {
                                if (ev.originalEvent.propertyName === "value") {
                                    log.debug("translating propertychange");
                                    $el.trigger("input-change");
                                }
                            });
                        }
                    }
                } else {
                    $el.on("change." + namespace, function() {
                        log.debug("translating change");
                        $el.trigger("input-change");
                    });
                }

                $el.on("blur", function() {
                    $el.trigger("input-defocus");
                });
            });
        },

        remove: function($form, pat) {
            var patterns = $form.data(namespace) || [];
            if (patterns.indexOf(pat) === -1) {
                log.warn("input-change-events were never installed for " + pat);
            } else {
                patterns = patterns.filter(function(e){return e!==pat;});
                if (patterns.length) {
                    $form.data(namespace, patterns);
                } else {
                    log.debug("remove handlers");
                    $form.removeData(namespace);
                    $form.find(":input").off("." + namespace);
                    $form.off("." + namespace);
                }
            }
        }
    };

    return _;

});

// jshint indent: 4, browser: true, jquery: true, quotmark: double
// vim: sw=4 expandtab


text:
module Gollum
  module Helpers

    # If url starts with a leading slash, trim down its number of leading slashes to 1. Else, return url unchanged.
    def trim_leading_slashes(url)
      return nil if url.nil?
      url.gsub!('%2F', '/')
      return '/' + url.gsub(/^\/+/, '') if url[0, 1] == '/'
      url
    end

    # Take a link path and turn it into a string for display as link text.
    # For example:
    # '/opt/local/bin/ruby.ext' -> 'ruby'
    def path_to_link_text(str)
      return nil unless str
      ::File.basename(str, Page.valid_extension?(str) ? ::File.extname(str) : '')
    end

  end
end


text:
set -o pipefail

REF_DIR=${REF:-/usr/share/jenkins/ref/plugins}
FAILED="$REF_DIR/failed-plugins.txt"

. /usr/local/bin/jenkins-support

getLockFile() {
    printf '%s' "$REF_DIR/${1}.lock"
}

getArchiveFilename() {
    printf '%s' "$REF_DIR/${1}.jpi"
}

download() {
    local plugin originalPlugin version lock ignoreLockFile
    plugin="$1"
    version="${2:-latest}"
    ignoreLockFile="${3:-}"
    lock="$(getLockFile "$plugin")"

    if [[ $ignoreLockFile ]] || mkdir "$lock" &>/dev/null; then
        if ! doDownload "$plugin" "$version"; then
            # some plugin don't follow the rules about artifact ID
            # typically: docker-plugin
            originalPlugin="$plugin"
            plugin="${plugin}-plugin"
            if ! doDownload "$plugin" "$version"; then
                echo "Failed to download plugin: $originalPlugin or $plugin" >&2
                echo "Not downloaded: ${originalPlugin}" >> "$FAILED"
                return 1
            fi
        fi

        if ! checkIntegrity "$plugin"; then
            echo "Downloaded file is not a valid ZIP: $(getArchiveFilename "$plugin")" >&2
            echo "Download integrity: ${plugin}" >> "$FAILED"
            return 1
        fi

        resolveDependencies "$plugin"
    fi
}

doDownload() {
    local plugin version url jpi
    plugin="$1"
    version="$2"
    jpi="$(getArchiveFilename "$plugin")"

    # If plugin already exists and is the same version do not download
    if test -f "$jpi" && unzip -p "$jpi" META-INF/MANIFEST.MF | tr -d '\r' | grep "^Plugin-Version: ${version}$" > /dev/null; then
        echo "Using provided plugin: $plugin"
        return 0
    fi

    JENKINS_UC_DOWNLOAD=${JENKINS_UC_DOWNLOAD:-"$JENKINS_UC/download"}

    url="$JENKINS_UC_DOWNLOAD/plugins/$plugin/$version/${plugin}.hpi"

    echo "Downloading plugin: $plugin from $url"
    curl --connect-timeout ${CURL_CONNECTION_TIMEOUT:-20} --retry ${CURL_RETRY:-5} --retry-delay ${CURL_RETRY_DELAY:-0} --retry-max-time ${CURL_RETRY_MAX_TIME:-60} -s -f -L "$url" -o "$jpi"
    return $?
}

checkIntegrity() {
    local plugin jpi
    plugin="$1"
    jpi="$(getArchiveFilename "$plugin")"

    unzip -t -qq "$jpi" >/dev/null
    return $?
}

resolveDependencies() {
    local plugin jpi dependencies
    plugin="$1"
    jpi="$(getArchiveFilename "$plugin")"

    dependencies="$(unzip -p "$jpi" META-INF/MANIFEST.MF | tr -d '\r' | tr '\n' '|' | sed -e 's#| ##g' | tr '|' '\n' | grep "^Plugin-Dependencies: " | sed -e 's#^Plugin-Dependencies: ##')"

    if [[ ! $dependencies ]]; then
        echo " > $plugin has no dependencies"
        return
    fi

    echo " > $plugin depends on $dependencies"

    IFS=',' read -r -a array <<< "$dependencies"

    for d in "${array[@]}"
    do
        plugin="$(cut -d':' -f1 - <<< "$d")"
        if [[ $d == *"resolution:=optional"* ]]; then
            echo "Skipping optional dependency $plugin"
        else
            local pluginInstalled
            if pluginInstalled="$(echo "${bundledPlugins}" | grep "^${plugin}:")"; then
                pluginInstalled="${pluginInstalled//[$'\r']}"
                local versionInstalled; versionInstalled=$(versionFromPlugin "${pluginInstalled}")
                local minVersion; minVersion=$(versionFromPlugin "${d}")
                if versionLT "${versionInstalled}" "${minVersion}"; then
                    echo "Upgrading bundled dependency $d ($minVersion > $versionInstalled)"
                    download "$plugin" &
                else
                    echo "Skipping already bundled dependency $d ($minVersion <= $versionInstalled)"
                fi
            else
                download "$plugin" &
            fi
        fi
    done
    wait
}

bundledPlugins() {
    local JENKINS_WAR=/usr/share/jenkins/jenkins.war
    if [ -f $JENKINS_WAR ]
    then
        TEMP_PLUGIN_DIR=/tmp/plugintemp.$$
        for i in $(jar tf $JENKINS_WAR | egrep '[^detached-]plugins.*\..pi' | sort)
        do
            rm -fr $TEMP_PLUGIN_DIR
            mkdir -p $TEMP_PLUGIN_DIR
            PLUGIN=$(basename "$i"|cut -f1 -d'.')
            (cd $TEMP_PLUGIN_DIR;jar xf "$JENKINS_WAR" "$i";jar xvf "$TEMP_PLUGIN_DIR/$i" META-INF/MANIFEST.MF >/dev/null 2>&1)
            VER=$(egrep -i Plugin-Version "$TEMP_PLUGIN_DIR/META-INF/MANIFEST.MF"|cut -d: -f2|sed 's/ //')
            echo "$PLUGIN:$VER"
        done
        rm -fr $TEMP_PLUGIN_DIR
    else
        rm -f "$TEMP_ALREADY_INSTALLED"
        echo "ERROR file not found: $JENKINS_WAR"
        exit 1
    fi
}

versionFromPlugin() {
    local plugin=$1
    if [[ $plugin =~ .*:.* ]]; then
        echo "${plugin##*:}"
    else
        echo "latest"
    fi

}

installedPlugins() {
    for f in "$REF_DIR"/*.jpi; do
        echo "$(basename "$f" | sed -e 's/\.jpi//'):$(get_plugin_version "$f")"
    done
}

main() {
    local plugin version

    mkdir -p "$REF_DIR" || exit 1

    # Create lockfile manually before first run to make sure any explicit version set is used.
    echo "Creating initial locks..."
    for plugin in "$@"; do
        mkdir "$(getLockFile "${plugin%%:*}")"
    done

    echo "Analyzing war..."
    bundledPlugins="$(bundledPlugins)"

    echo "Downloading plugins..."
    for plugin in "$@"; do
        version=""

        if [[ $plugin =~ .*:.* ]]; then
            version=$(versionFromPlugin "${plugin}")
            plugin="${plugin%%:*}"
        fi

        download "$plugin" "$version" "true" &
    done
    wait

    echo
    echo "WAR bundled plugins:"
    echo "${bundledPlugins}"
    echo
    echo "Installed plugins:"
    installedPlugins

    if [[ -f $FAILED ]]; then
        echo "Some plugins failed to download!" "$(<"$FAILED")" >&2
        exit 1
    fi

    echo "Cleaning up locks"
    rm -r "$REF_DIR"/*.lock
}

main "$@"


text:
from flask import render_template, request

def object_list(template_name, query, paginate_by=20, **context):
    page = request.args.get('page')
    if page and page.isdigit():
        page = int(page)
    else:
        page = 1
    object_list = query.paginate(page, paginate_by)
    return render_template(template_name, object_list=object_list,
    **context)


text:
import { URI } from './uri';
import * as platform from './platform';
export var Schemas;
(function (Schemas) {
    /**
     * A schema that is used for models that exist in memory
     * only and that have no correspondence on a server or such.
     */
    Schemas.inMemory = 'inmemory';
    /**
     * A schema that is used for setting files
     */
    Schemas.vscode = 'vscode';
    /**
     * A schema that is used for internal private files
     */
    Schemas.internal = 'private';
    /**
     * A walk-through document.
     */
    Schemas.walkThrough = 'walkThrough';
    /**
     * An embedded code snippet.
     */
    Schemas.walkThroughSnippet = 'walkThroughSnippet';
    Schemas.http = 'http';
    Schemas.https = 'https';
    Schemas.file = 'file';
    Schemas.mailto = 'mailto';
    Schemas.untitled = 'untitled';
    Schemas.data = 'data';
    Schemas.command = 'command';
    Schemas.vscodeRemote = 'vscode-remote';
    Schemas.vscodeRemoteResource = 'vscode-remote-resource';
    Schemas.userData = 'vscode-userdata';
})(Schemas || (Schemas = {}));
var RemoteAuthoritiesImpl = /** @class */ (function () {
    function RemoteAuthoritiesImpl() {
        this._hosts = Object.create(null);
        this._ports = Object.create(null);
        this._connectionTokens = Object.create(null);
        this._preferredWebSchema = 'http';
        this._delegate = null;
    }
    RemoteAuthoritiesImpl.prototype.setPreferredWebSchema = function (schema) {
        this._preferredWebSchema = schema;
    };
    RemoteAuthoritiesImpl.prototype.rewrite = function (uri) {
        if (this._delegate) {
            return this._delegate(uri);
        }
        var authority = uri.authority;
        var host = this._hosts[authority];
        if (host && host.indexOf(':') !== -1) {
            host = "[" + host + "]";
        }
        var port = this._ports[authority];
        var connectionToken = this._connectionTokens[authority];
        var query = "path=" + encodeURIComponent(uri.path);
        if (typeof connectionToken === 'string') {
            query += "&tkn=" + encodeURIComponent(connectionToken);
        }
        return URI.from({
            scheme: platform.isWeb ? this._preferredWebSchema : Schemas.vscodeRemoteResource,
            authority: host + ":" + port,
            path: "/vscode-remote-resource",
            query: query
        });
    };
    return RemoteAuthoritiesImpl;
}());
export var RemoteAuthorities = new RemoteAuthoritiesImpl();


text:
<?php

/**
 * ZF
 *
 * @category   Zend
 * @package    Zend_Tool
 * @subpackage Framework
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
use Zend\Loader;
class ZF
{

    /**
     * @var bool
     */
    protected $_clientLoaded = false;

    /**
     * @var string
     */
    protected $_mode = 'runTool';

    /**
     * @var array of messages
     */
    protected $_messages = array();

    /**
     * @var string
     */
    protected $_homeDirectory = null;

    /**
     * @var string
     */
    protected $_storageDirectory = null;

    /**
     * @var string
     */
    protected $_configFile = null;

    /**
     * main()
     *
     * @return void
     */
    public static function main()
    {
        $zf = new self();
        $zf->bootstrap();
        $zf->run();
    }

    /**
     * bootstrap()
     *
     * @return ZF
     */
    public function bootstrap()
    {
        // detect settings
        $this->_mode             = $this->_detectMode();
        $this->_homeDirectory    = $this->_detectHomeDirectory();
        $this->_storageDirectory = $this->_detectStorageDirectory();
        $this->_configFile       = $this->_detectConfigFile();

        // setup
        $this->_setupPHPRuntime();
        $this->_setupToolRuntime();
    }

    /**
     * run()
     *
     * @return ZF
     */
    public function run()
    {
        switch ($this->_mode) {
            case 'runError':
                $this->_runError();
                $this->_runInfo();
                break;
            case 'runSetup':
                if ($this->_runSetup() === false) {
                    $this->_runInfo();
                }
                break;
            case 'runInfo':
                $this->_runInfo();
                break;
            case 'runTool':
            default:
                $this->_runTool();
                break;
        }

        return $this;
    }

    /**
     * _detectMode()
     *
     * @return ZF
     */
    protected function _detectMode()
    {
        $arguments = $_SERVER['argv'];

        $mode = 'runTool';

        if (!isset($arguments[0])) {
            return $mode;
        }

        if ($arguments[0] == $_SERVER['PHP_SELF']) {
            $this->_executable = array_shift($arguments);
        }

        if (!isset($arguments[0])) {
            return $mode;
        }

        if ($arguments[0] == '--setup') {
            $mode = 'runSetup';
        } elseif ($arguments[0] == '--info') {
            $mode = 'runInfo';
      }

      return $mode;
    }

    /**
     * _detectHomeDirectory() - detect the home directory in a variety of different places
     *
     * @param boolean $mustExist      Should the returned value already exist in the file system
     * @param boolean $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectHomeDirectory($mustExist = true, $returnMessages = true)
    {
        $homeDirectory = null;

        $homeDirectory = getenv('ZF_HOME'); // check env var ZF_HOME
        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable ZF_HOME with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        $homeDirectory = getenv('HOME'); // HOME environment variable

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable HOME with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }

        }

        $homeDirectory = getenv('HOMEPATH');

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable HOMEPATH with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        $homeDirectory = getenv('USERPROFILE');

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable USERPROFILE with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _detectStorageDirectory() - Detect where the storage directory is from a variaty of possiblities
     *
     * @param boolean $mustExist      Should the returned value already exist in the file system
     * @param boolean $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectStorageDirectory($mustExist = true, $returnMessages = true)
    {
        $storageDirectory = false;

        $storageDirectory = getenv('ZF_STORAGE_DIR');
        if ($storageDirectory) {
            $this->_logMessage('Storage directory path found in environment variable ZF_STORAGE_DIR with value ' . $storageDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($storageDirectory))) {
                return $storageDirectory;
            } else {
                $this->_logMessage('Storage directory does not exist at ' . $storageDirectory, $returnMessages);
            }
        }

        $homeDirectory = ($this->_homeDirectory) ? $this->_homeDirectory : $this->_detectHomeDirectory(true, false);

        if ($homeDirectory) {
            $storageDirectory = $homeDirectory . '/.zf/';
            $this->_logMessage('Storage directory assumed in home directory at location ' . $storageDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($storageDirectory))) {
                return $storageDirectory;
            } else {
                $this->_logMessage('Storage directory does not exist at ' . $storageDirectory, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _detectConfigFile() - Detect config file location from a variety of possibilities
     *
     * @param boolean $mustExist      Should the returned value already exist in the file system
     * @param boolean $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectConfigFile($mustExist = true, $returnMessages = true)
    {
        $configFile = null;

        $configFile = getenv('ZF_CONFIG_FILE');
        if ($configFile) {
            $this->_logMessage('Config file found environment variable ZF_CONFIG_FILE at ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        $homeDirectory = ($this->_homeDirectory) ? $this->_homeDirectory : $this->_detectHomeDirectory(true, false);
        if ($homeDirectory) {
            $configFile = $homeDirectory . '/.zf.ini';
            $this->_logMessage('Config file assumed in home directory at location ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        $storageDirectory = ($this->_storageDirectory) ? $this->_storageDirectory : $this->_detectStorageDirectory(true, false);
        if ($storageDirectory) {
            $configFile = $storageDirectory . '/zf.ini';
            $this->_logMessage('Config file assumed in storage directory at location ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _setupPHPRuntime() - parse the config file if it exists for php ini values to set
     *
     * @return void
     */
    protected function _setupPHPRuntime()
    {
      // set php runtime settings
      ini_set('display_errors', true);

        // support the changing of the current working directory, necessary for some providers
        if (isset($_ENV['ZEND_TOOL_CURRENT_WORKING_DIRECTORY'])) {
            chdir($_ENV['ZEND_TOOL_CURRENT_WORKING_DIRECTORY']);
        }

        if (!$this->_configFile) {
            return;
        }
        $zfINISettings = parse_ini_file($this->_configFile);
        $phpINISettings = ini_get_all();
        foreach ($zfINISettings as $zfINIKey => $zfINIValue) {
            if (substr($zfINIKey, 0, 4) === 'php.') {
                $phpINIKey = substr($zfINIKey, 4);
                if (array_key_exists($phpINIKey, $phpINISettings)) {
                    ini_set($phpINIKey, $zfINIValue);
                }
            }
        }

        return null;
    }

    /**
     * _setupToolRuntime() - setup the tools include_path and load the proper framwork parts that
     * enable Zend_Tool to work.
     *
     * @return void
     */
    protected function _setupToolRuntime()
    {

        $includePathPrepend = getenv('ZEND_TOOL_INCLUDE_PATH_PREPEND');
        $includePathFull = getenv('ZEND_TOOL_INCLUDE_PATH');

        // check if the user has not provided anything
        if (!($includePathPrepend || $includePathFull)) {
            if ($this->_tryClientLoad()) {
                return;
            }
        }

        // if ZF is not in the include_path, but relative to this file, put it in the include_path
        if ($includePathPrepend || $includePathFull) {
            if (isset($includePathPrepend) && ($includePathPrepend !== false)) {
                set_include_path($includePathPrepend . PATH_SEPARATOR . get_include_path());
            } elseif (isset($includePathFull) && ($includePathFull !== false)) {
                set_include_path($includePathFull);
            }
        }

        if ($this->_tryClientLoad()) {
            return;
        }

        $zfIncludePath['relativePath'] = __DIR__ . '/../library/';
        if (file_exists($zfIncludePath['relativePath'] . 'Zend/Tool/Framework/Client/Console/Console.php')) {
            set_include_path(realpath($zfIncludePath['relativePath']) . PATH_SEPARATOR . get_include_path());
        }

        if (!$this->_tryClientLoad()) {
            $this->_mode = 'runError';
            return;
        }

        return null;
    }

    /**
     * _tryClientLoad() - Attempt to load the Zend_Tool_Framework_Client_Console to enable the tool to run.
     *
     * This method will return false if its not loaded to allow the consumer to alter the environment in such
     * a way that it can be called again to try loading the proper file/class.
     *
     * @return bool if the client is actuall loaded or not
     */
    protected function _tryClientLoad()
    {
        $this->_clientLoaded = false;
        $fh = @fopen('Zend/Loader/StandardAutoloader.php', 'r', true);
        if (!$fh) {
            return $this->_clientLoaded; // false
        } else {
            fclose($fh);
            unset($fh);
            include 'Zend/Loader/StandardAutoloader.php';
            $this->_clientLoaded = class_exists('Zend\Loader\StandardAutoloader', false);
        }

        return $this->_clientLoaded;
    }

    /**
     * _runError() - Output the error screen that tells the user that the tool was not setup
     * in a sane way
     *
     * @return void
     */
    protected function _runError()
    {

        echo <<<EOS

***************************** ZF ERROR ********************************
In order to run the zf command, you need to ensure that Zend Framework
is inside your include_path.  There are a variety of ways that you can
ensure that this zf command line tool knows where the Zend Framework
library is on your system, but not all of them can be described here.

The easiest way to get the zf command running is to give it the include
path via an environment variable ZEND_TOOL_INCLUDE_PATH or
ZEND_TOOL_INCLUDE_PATH_PREPEND with the proper include path to use,
then run the command "zf --setup".  This command is designed to create
a storage location for your user, as well as create the zf.ini file
that the zf command will consult in order to run properly on your
system.

Example you would run:

$ ZEND_TOOL_INCLUDE_PATH=/path/to/library zf --setup

Your are encourged to read more in the link that follows.

EOS;

        return null;
    }

    /**
     * _runInfo() - this command will produce information about the setup of this script and
     * Zend_Tool
     *
     * @return void
     */
    protected function _runInfo()
    {
        echo 'Zend_Tool & CLI Setup Information' . PHP_EOL
           . '(available via the command line "zf --info")'
           . PHP_EOL;

        echo '   * ' . implode(PHP_EOL . '   * ', $this->_messages) . PHP_EOL;

        echo PHP_EOL;

        echo 'To change the setup of this tool, run: "zf --setup"';

        echo PHP_EOL;

    }

    /**
     * _runSetup() - parse the request to see which setup command to run
     *
     * @return void
     */
    protected function _runSetup()
    {
        $setupCommand = (isset($_SERVER['argv'][2])) ? $_SERVER['argv'][2] : null;

        switch ($setupCommand) {
            case 'storage-directory':
                $this->_runSetupStorageDirectory();
                break;
            case 'config-file':
                $this->_runSetupConfigFile();
                break;
            default:
                $this->_runSetupMoreInfo();
                break;
        }

        return null;
    }

    /**
     * _runSetupStorageDirectory() - if the storage directory does not exist, create it
     *
     * @return void
     */
    protected function _runSetupStorageDirectory()
    {
        $storageDirectory = $this->_detectStorageDirectory(false, false);

        if (file_exists($storageDirectory)) {
            echo 'Directory already exists at ' . $storageDirectory . PHP_EOL
               . 'Cannot create storage directory.';
            return;
        }

        mkdir($storageDirectory);

        echo 'Storage directory created at ' . $storageDirectory . PHP_EOL;
    }

    /**
     * _runSetupConfigFile()
     *
     * @return void
     */
    protected function _runSetupConfigFile()
    {
        $configFile = $this->_detectConfigFile(false, false);

        if (file_exists($configFile)) {
            echo 'File already exists at ' . $configFile . PHP_EOL
               . 'Cannot write new config file.';
            return;
        }

        $includePath = get_include_path();

        $contents = 'php.include_path = "' . $includePath . '"';

        file_put_contents($configFile, $contents);

        $iniValues = ini_get_all();
        if ($iniValues['include_path']['global_value'] != $iniValues['include_path']['local_value']) {
            echo 'NOTE: the php include_path to be used with the tool has been written' . PHP_EOL
               . 'to the config file, using ZF_INCLUDE_PATH (or other include_path setters)' . PHP_EOL
               . 'is no longer necessary.' . PHP_EOL . PHP_EOL;
        }

        echo 'Config file written to ' . $configFile . PHP_EOL;

        return null;
    }

    /**
     * _runSetupMoreInfo() - return more information about what can be setup, and what is setup
     *
     * @return void
     */
    protected function _runSetupMoreInfo()
    {
        $homeDirectory    = $this->_detectHomeDirectory(false, false);
        $storageDirectory = $this->_detectStorageDirectory(false, false);
        $configFile       = $this->_detectConfigFile(false, false);

        echo <<<EOS

ZF Command Line Tool - Setup
----------------------------

Current Paths (Existing or not):
    Home Directory: {$homeDirectory}
    Storage Directory: {$storageDirectory}
    Config File: {$configFile}

Important Environment Variables:
    ZF_HOME
        - the directory this tool will look for a home directory
        - directory must exist
    ZF_STORAGE_DIRECTORY
        - where this tool will look for a storage directory
        - directory must exist
    ZF_CONFIG_FILE
        - where this tool will look for a configuration file
    ZF_INCLUDE_PATH
        - set the include_path for this tool to use this value
    ZF_INCLUDE_PATH_PREPEND
        - prepend the current php.ini include_path with this value

Search Order:
    Home Directory:
        - ZF_HOME, then HOME (*nix), then HOMEPATH (windows)
    Storage Directory:
        - ZF_STORAGE_DIR, then {home}/.zf/
    Config File:
        - ZF_CONFIG_FILE, then {home}/.zf.ini, then {home}/zf.ini,
          then {storage}/zf.ini

Commands:
    zf --setup storage-directory
        - setup the storage directory, directory will be created
    zf --setup config-file
        - create the config file with some default values

EOS;
    }

    /**
     * _runTool() - This is where the magic happens, dispatch Zend_Tool
     *
     * @return void
     */
    protected function _runTool()
    {

      $configOptions = array();
      if (isset($this->_configFile) && $this->_configFile) {
          $configOptions['configOptions']['configFilepath'] = $this->_configFile;
      }
      if (isset($this->_storageDirectory) && $this->_storageDirectory) {
          $configOptions['storageOptions']['directory'] = $this->_storageDirectory;
      }

      // ensure that zf.php loads the Zend_Tool_Project features
      $configOptions['classesToLoad'] = 'Zend\Tool\Project\Provider\Manifest';

        $autoloader = new Zend\Loader\StandardAutoloader();
        $autoloader->setFallbackAutoloader(true);
        $autoloader->register();

      $console = new Zend\Tool\Framework\Client\Console\Console($configOptions);
      $console->dispatch();
    return null;
    }

    /**
     * _logMessage() - Internal method used to log setup and information messages.
     *
     * @param string  $message
     * @param boolean $storeMessage
     * @return void
     */
    protected function _logMessage($message, $storeMessage = true)
    {
        if (!$storeMessage) {
            return;
        }

        $this->_messages[] = $message;
    }

}

if (!getenv('ZF_NO_MAIN')) {
    ZF::main();
}


text:
package com.iweb.entity;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.util.stream.IntStream;

public class Question {
	private int id;
	private String question;
	private String[] check = new String[6];
	private String answer;

	public Question(){
		super();
	}

	public Question(int id, String question, String[] check, String answer) {
		super();
		this.id = id;
		this.question = question;
		this.check = check;
		this.answer = answer;
	}

	public Question(int id, String question, String answer) {
		super();
		this.id = id;
		this.question = question;
		this.answer = answer;
	}

	public String getQuestion() {
		return question;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public int getQid() {
		return id;
	}
	public void setQid(int qid) {
		this.id = qid;
	}
	public String[] getCheck() {
		return check;
	}
	public void setCheck(String[] check) {
		this.check = check;
	}
	public String getAnswer() {
		return answer;
	}
	public void setAnswer(String answer) {
		this.answer = answer;
	}

}


text:
import 'core-js/modules/es6.array.find-index';
import 'core-js/modules/es6.set';
import { install } from '@material-ui/styles';

// Disable auto highlighting
// https://github.com/PrismJS/prism/issues/765
if (process.browser) {
  window.Prism = window.Prism || {};
  window.Prism.manual = true;
}

install();


text:
namespace ManagedCircuitBreaker.Tests.Settings.FakeService
{
    public class AlsoDoThisSettings : BaseSettings
    {
        public override string CircuitName
        {
            get { return "FakeService_AlsoDoThis"; }
        }
    }
}


text:
<RelativeLayout
	android:id="@+id/RelativeLayout01"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	android:minHeight="480dp"
	android:minWidth="340dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
	xmlns:android="http://schemas.android.com/apk/res/android">
	<Button
		android:layout_width="wrap_content"
		android:layout_alignParentBottom="true"
		android:id="@+id/savePositionsButton"
		android:text="@string/saveTitle"
		android:layout_height="wrap_content"
		android:layout_alignParentLeft="true">
	</Button>
	<Button
		android:layout_width="wrap_content"
		android:id="@+id/cancelPositionsButtons"
		android:text="@string/cancelTitle"
		android:layout_height="wrap_content"
		android:layout_alignParentBottom="true"
		android:layout_alignParentRight="true">
	</Button>
</RelativeLayout>


text:
<!doctype html>

	<title>Kaboobly Doo Generator</title>
	<link rel="stylesheet" type="text/css" href="/static/stylesheet.css">

	<form action="/kabooblydoo" method="POST">

Prefix Length (Words):

			<input type="number" name="n" value="2">

 Output Limit (Words):

			<input type="number" name="words" value="200">

Source:

<input type="radio" name="source" value="url">URL: <input type="url" name="url" />

<input type="radio" name="source" value="book" checked>Book: <select name="books">
					<option value="bobbym">The Blue book of bobbym quotes</option>
					<option value="aesop">Aesop's Fables</option>
					<option value="word">Buddah, The Word</option>
					<option value="alice">Alice in Wonderland</option>
					<option value="benjamin">The Autobiography of Benjamin Franklin</option>
				</select>

<input type="radio" name="source" value="custom">Custom Text: <textarea name="message" rows="10" cols="30"></textarea>

		<input class="myButton" type="submit" value="Kabooble!">
	</form>
	What's this?


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('realtime', '0033_auto_20180202_0723'),
    ]

    operations = [
        migrations.AddField(
            model_name='ash',
            name='hazard_path',
            field=models.CharField(default=None, max_length=255, blank=True, help_text='Location of hazard layer', null=True, verbose_name='Hazard Layer path'),
        ),
        migrations.AddField(
            model_name='ash',
            name='inasafe_version',
            field=models.CharField(default=None, max_length=10, blank=True, help_text='InaSAFE version being used', null=True, verbose_name='InaSAFE version'),
        ),
        migrations.AddField(
            model_name='earthquake',
            name='generated_time',
            field=models.DateTimeField(default=None, help_text='The time the shake report generated.', null=True, verbose_name='Report Generated Date and Time'),
        ),
        migrations.AddField(
            model_name='earthquake',
            name='hazard_path',
            field=models.CharField(default=None, max_length=255, blank=True, help_text='Location of hazard layer', null=True, verbose_name='Hazard Layer path'),
        ),
        migrations.AddField(
            model_name='earthquake',
            name='inasafe_version',
            field=models.CharField(default=None, max_length=10, blank=True, help_text='InaSAFE version being used', null=True, verbose_name='InaSAFE version'),
        ),
        migrations.AddField(
            model_name='earthquake',
            name='source_type',
            field=models.CharField(default=b'initial', help_text='Source type of shake grid', max_length=30, verbose_name='Source Type'),
        ),
        migrations.AddField(
            model_name='flood',
            name='hazard_path',
            field=models.CharField(default=None, max_length=255, blank=True, help_text='Location of hazard layer', null=True, verbose_name='Hazard Layer path'),
        ),
        migrations.AddField(
            model_name='flood',
            name='inasafe_version',
            field=models.CharField(default=None, max_length=10, blank=True, help_text='InaSAFE version being used', null=True, verbose_name='InaSAFE version'),
        ),
        migrations.AddField(
            model_name='flood',
            name='source_type',
            field=models.CharField(default=b'petabencana', help_text='Source type of shake grid', max_length=30, verbose_name='Source Type'),
        ),
        migrations.AlterField(
            model_name='earthquake',
            name='shake_id',
            field=models.CharField(help_text='The Shake ID, which represents the time of the event.', max_length=b'14', verbose_name='The Shake ID'),
        ),
    ]


text:
layout: default
---

## Voter API Feedback

#### Being the RIGHT user, not just ANY user

Some submissions had a line like this:

    user = Voter.where(security_key: api_key).first if api_key

This looks up a user based on an key.  However, this would let me in if I had ANY valid key.  In other words, I could use my personal key to vote as ANYONE.  As we discussed in class, you should look the Voter up by `params[:id]`, then check to see if the key matches that specific user.

#### The magic number to rule them all

So...

    test "shows only one race" do
      senate = Race.create!(name: "Senate")
      get :show, {id: 980190963}
      assert_response :success
    end

That's a serious magic number.  Instead of putting that in (which might be different every time), do this:

    test "shows only one race" do
      senate = Race.create!(name: "Senate")
      get :show, {id: senate.id}
      assert_response :success
    end

#### More magic numbers

This test... probably won't work:

    test "should be able to destroy" do
      assert_difference("Vote.count") do
        delete :destroy, {voter_id: 1, candidate_id: 1, race_id: 2}
      end
    end

First off, if you're deleting something, it's best to assert that the difference will be negative one, like this: `assert_difference("Vote.count", -1)`.

Second, when you destroy, all you need to pass it is an `id`.

Beyond that, the numbers are really arbitrary.  The right way to do this is to write fixtures, then change your test to look more like this.

    test "should be able to destroy" do
      assert_difference("Vote.count", -1) do
        delete :destroy, id: vote(:one).id
      end
    end

#### Positive and negative in most tests

Here's a test that works well:

    test "candidate_id" do
      two = Vote.new(voter_id: 1)
      refute two.save
    end

It will be better, though, if it also had an `assert`.  Right now this test would be perfectly happy if it was always impossible to save a vote.  Probably want to make sure that it WILL save if you give it everything that it needs.

#### Where to put `before_action`

This code (which did not run) is worth discussing:

    def show
      before_action :require_security_key
      render json: Voter.find_by_id(params[:id])
    end

If you're going to use `before_action`, it goes outside the method.  If you want it to apply to EVERY action in the controller, you write it like this:

    class VotersController...
      before_action :require_security_key
      ...
    end

If you want to apply to ONLY the show action, you write it like this:

    class VotersController...
      before_action :require_security_key, only: [:show]
      ...
    end

You can put more things in that array if you want it to only apply to a few actions.


text:
git submodule update --init --recursive

echo "
" > change-notes.html
git log `git describe --tags --abbrev=0`..HEAD --no-merges --oneline --pretty=format:"
%h %s (%an)
" >> change-notes.html
echo "
" >> change-notes.html

cp change-notes.html src/main/resources/META-INF/

rm change-notes.html


text:
package com.ge.predix.acs.service.policy.admin.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;

import com.ge.predix.acs.config.InMemoryDataSourceConfig;
import com.ge.predix.acs.testutils.TestActiveProfilesResolver;
import com.ge.predix.acs.zone.management.dao.ZoneEntity;
import com.ge.predix.acs.zone.management.dao.ZoneRepository;

@ContextConfiguration(classes = InMemoryDataSourceConfig.class)
@EnableAutoConfiguration
@ActiveProfiles(resolver = TestActiveProfilesResolver.class)
public class PolicySetRepositoryTest extends AbstractTransactionalTestNGSpringContextTests {
    private static final String SUBDOMAIN = "PolicySetRepositoryTest-acs";

    @Autowired
    private PolicySetRepository policySetRepository;

    @Autowired
    private ZoneRepository zoneRepository;

    @Test
    public void testPersistPolicy() {

        ZoneEntity zone = createZone();
        this.zoneRepository.save(zone);

        PolicySetEntity policySetEntity = new PolicySetEntity(zone, "policy-set-2", "{}");
        PolicySetEntity savedPolicySet = this.policySetRepository.save(policySetEntity);
        Assert.assertEquals(this.policySetRepository.count(), 1);
        Assert.assertTrue(savedPolicySet.getId() > 0);
    }

    private ZoneEntity createZone() {
        ZoneEntity zone = new ZoneEntity();
        zone.setName("PolicySetRepositoryTest-ACS");
        zone.setSubdomain(SUBDOMAIN);
        zone.setDescription("PolicySetRepositoryTest zone description");
        return zone;
    }
}


text:
<?php

namespace Joli\Jane;

use Joli\Jane\Generator\Context\Context;
use Joli\Jane\Generator\ModelGenerator;
use Joli\Jane\Generator\Naming;
use Joli\Jane\Generator\NormalizerGenerator;
use Joli\Jane\Guesser\ChainGuesser;
use Joli\Jane\Guesser\JsonSchema\JsonSchemaGuesserFactory;
use Joli\Jane\Normalizer\NormalizerFactory;
use Joli\Jane\Runtime\Encoder\RawEncoder;
use PhpCsFixer\Differ\NullDiffer;
use PhpCsFixer\Error\ErrorsManager;
use PhpCsFixer\Linter\NullLinter;
use PhpCsFixer\Runner\Runner;
use PhpParser\PrettyPrinter\Standard;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Serializer;
use PhpCsFixer\Config;
use PhpCsFixer\ConfigInterface;
use PhpCsFixer\Console\ConfigurationResolver;
use PhpCsFixer\Finder;

class Jane
{
    const VERSION = '1.0-dev';

    private $serializer;

    private $modelGenerator;

    private $normalizerGenerator;

    private $fixerConfig;

    private $chainGuesser;

    public function __construct(Serializer $serializer, ChainGuesser $chainGuesser, ModelGenerator $modelGenerator, NormalizerGenerator $normalizerGenerator, ConfigInterface $fixerConfig = null)
    {
        $this->serializer = $serializer;
        $this->chainGuesser = $chainGuesser;
        $this->modelGenerator = $modelGenerator;
        $this->normalizerGenerator = $normalizerGenerator;
        $this->fixerConfig = $fixerConfig;
    }

    /**
     * Return a list of class guessed.
     *
     * @param $schemaFilePath
     * @param $name
     * @param $namespace
     * @param $directory
     *
     * @return Context
     */
    public function createContext($schemaFilePath, $name, $namespace, $directory)
    {
        $schema = $this->serializer->deserialize(file_get_contents($schemaFilePath), 'Joli\Jane\Model\JsonSchema', 'json');
        $classes = $this->chainGuesser->guessClass($schema, $name);

        foreach ($classes as $class) {
            $properties = $this->chainGuesser->guessProperties($class->getObject(), $name, $classes);

            foreach ($properties as $property) {
                $property->setType($this->chainGuesser->guessType($property->getObject(), $property->getName(), $classes));
            }

            $class->setProperties($properties);
        }

        return new Context($schema, $namespace, $directory, $classes);
    }

    /**
     * Generate code.
     *
     * @param $schemaFilePath
     * @param $name
     * @param $namespace
     * @param $directory
     *
     * @return array
     */
    public function generate($schemaFilePath, $name, $namespace, $directory)
    {
        $context = $this->createContext($schemaFilePath, $name, $namespace, $directory);

        if (!file_exists(($directory.DIRECTORY_SEPARATOR.'Model'))) {
            mkdir($directory.DIRECTORY_SEPARATOR.'Model', 0755, true);
        }

        if (!file_exists(($directory.DIRECTORY_SEPARATOR.'Normalizer'))) {
            mkdir($directory.DIRECTORY_SEPARATOR.'Normalizer', 0755, true);
        }

        $prettyPrinter = new Standard();
        $modelFiles = $this->modelGenerator->generate($context->getRootReference(), $name, $context);
        $normalizerFiles = $this->normalizerGenerator->generate($context->getRootReference(), $name, $context);
        $generated = [];

        foreach ($modelFiles as $file) {
            $generated[] = $file->getFilename();
            file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()]));
        }

        foreach ($normalizerFiles as $file) {
            $generated[] = $file->getFilename();
            file_put_contents($file->getFilename(), $prettyPrinter->prettyPrintFile([$file->getNode()]));
        }

        $this->fix($directory);

        return $generated;
    }

    /**
     * Fix files generated in a directory.
     *
     * @param $directory
     *
     * @return array|void
     */
    protected function fix($directory)
    {
        if (!class_exists('PhpCsFixer\Runner\Runner')) {
            return;
        }

        /** @var Config $fixerConfig */
        $fixerConfig = $this->fixerConfig;

        if (null === $fixerConfig) {
            $fixerConfig = Config::create()
                ->setRiskyAllowed(true)
                ->setRules(array(
                    '@Symfony' => true,
                    'simplified_null_return' => false,
                    'concat_without_spaces' => false,
                    'double_arrow_multiline_whitespaces' => false,
                    'unalign_equals' => false,
                    'unalign_double_arrow' => false,
                    'align_double_arrow' => true,
                    'align_equals' => true,
                    'concat_with_spaces' => true,
                    'ordered_imports' => true,
                    'phpdoc_order' => true,
                    'short_array_syntax' => true,
                ))
            ;

            $resolver = new ConfigurationResolver();

            if (method_exists($resolver, 'setFormats')) {
                $resolver->setFormats(['txt']);
            }

            $resolver->setDefaultConfig($fixerConfig);
            $resolver->resolve();
        }

        $finder = new Finder();
        $finder->in($directory);
        $fixerConfig->finder($finder);

        $fixer = new Runner(
            $fixerConfig,
            new NullDiffer(),
            null,
            new ErrorsManager(),
            new NullLinter(),
            false
        );

        return $fixer->fix();
    }

    public static function build($options = [])
    {
        $serializer = self::buildSerializer();
        $chainGuesser = JsonSchemaGuesserFactory::create($serializer, $options);
        $naming = new Naming();
        $modelGenerator = new ModelGenerator($naming, $chainGuesser, $chainGuesser);
        $normGenerator = new NormalizerGenerator($naming, isset($options['reference']) ? $options['reference'] : true);

        return new self($serializer, $chainGuesser, $modelGenerator, $normGenerator);
    }

    public static function buildSerializer()
    {
        $encoders = [new JsonEncoder(new JsonEncode(JSON_UNESCAPED_SLASHES), new JsonDecode(false)), new RawEncoder()];
        $normalizers = NormalizerFactory::create();

        return new Serializer($normalizers, $encoders);
    }
}


text:
<?php

    include '../../../../common/include/common.php';
    include_once '../../../config.php';
    $module = modules::GATK;
    $name = docSN::toolDocs;

    printHeader($module, $name, topSN::guide);

    $selected_major_version = 4;
    $dirs = lookupVersionDirs($selected_major_version);
?>

<link type='text/css' rel='stylesheet' href='gatkDoc.css'>

        <?php echo produceGuideNav($module, $name) . makeTwitterFeed(); ?>

<i class='<?php print ico::toolDocsIcon; ?>'> GATK WDL Index

                        Version 1.2.3.4

                        <?php foreach($dirs as $dir) { ?>

<a tabindex='-1' href='../<?=$dir?>' ><?=$dir?>

                        <?php } ?>

            Showing docs for version 1.2.3.4 | The latest version is <?php print $latest_version; ?>

WDL feature group name

Tools for internal test purposes

                            Name
                            Summary

                                    TestWDLTool
                                        WDL Test Tool to test WDL Generation

 Return to top

See also
        	General Documentation |
        	Tool WDL Index Tool WDL Index |
        	Support Forum

GATK version 1.2.3.4 built at 2016/11/11 11:11:11.

<?php

    printFooter($module);

?>


text:
import React from 'react';
import {MemoryRouter} from 'react-router-dom';
import {storiesOf} from '@storybook/react';
import {withDefaultNowContext} from '../testing/NowContainer';
import ClassListCreatorPage from './ClassListCreatorPage';
import mockWithFixtures from './fixtures/mockWithFixtures';
import storybookFrame from './storybookFrame';
import {testProps} from './ClassListCreatorPage.test';

storiesOf('classlists/ClassListCreatorPage', module) // eslint-disable-line no-undef
  .add('normal', () => {
    mockWithFixtures();
    const props = testProps();
    return storybookFrame(
      <MemoryRouter initialEntries={['/classlists']}>
        {withDefaultNowContext(<ClassListCreatorPage {...props} />)}
      </MemoryRouter>
    );
  });


text:
<?php

namespace om;

class EventsList extends \ArrayObject {

	/**
	 * Return array of Events
	 *
	 * @return array
	 */
	public function getArrayCopy(): array {
		return array_values(parent::getArrayCopy());
	}

	/**
	 * Return sorted EventList (the newest dates are first)
	 *
	 * @return $this
	 */
	public function sorted(): EventsList {
		$this->uasort(static function ($a, $b): int {
			if ($a['DTSTART'] === $b['DTSTART']) {
				return 0;
			}
			return ($a['DTSTART'] < $b['DTSTART']) ? -1 : 1;
		});

		return $this;
	}

	/**
	 * Return reversed sorted EventList (the oldest dates are first)
	 *
	 * @return $this
	 */
	public function reversed(): EventsList {
		$this->uasort(static function ($a, $b): int {
			if ($a['DTSTART'] === $b['DTSTART']) {
				return 0;
			}
			return ($a['DTSTART'] > $b['DTSTART']) ? -1 : 1;
		});

		return $this;
	}

}


text:
using UnityEngine;
using System.Collections;

namespace Ferr {
	public abstract class Singleton<T> : MonoBehaviour where T:Component{
		private static T _instance;
		public  static T  Instance {
			get {
				if (_instance == null)
					EnsureInstantiated();

				return _instance;
			}
		}
		public static bool Instantiated {
			get { return _instance != null; }
		}
		public static void EnsureInstantiated() {
			if (_instance == null) {
				// singletons can get disconnected when unity compile events occur, this will serve as a re-connection if that occurs
				_instance = GameObject.FindObjectOfType<T>() as T;
				// if it's still null, see if we can instantiate it from the resources folder!
				if (_instance == null) {
					GameObject obj = Resources.Load("Singletons/" + typeof(T).Name) as GameObject;
					if (obj != null) {
						GameObject go = GameObject.Instantiate(obj);
						_instance = go.GetComponent<T>();
					}
				}
				// and if there was no prefab, lets just try a plain create and go!
				if (_instance == null) {
					GameObject go = new GameObject("_" + typeof(T).Name);
					_instance = go.AddComponent(typeof(T)) as T;
				}
				// and if all else fails, start spouting smoke
				if (_instance == null) {
					Debug.LogErrorFormat("Couldn't connect or create singleton {0}!", typeof(T).Name);
				}
			}
		}

		protected virtual void Awake() {
			if (_instance != null && _instance != this) {
				Debug.LogErrorFormat(gameObject, "Creating a new instance of a singleton [{0}] when one already exists!", typeof(T).Name);
				gameObject.SetActive(false);
				return;
			}
			_instance = GetComponent<T>();
		}
		protected virtual void OnDestroy() {
			_instance = null;
		}
	}
}


text:
post_title: Install a DC/OS cluster
nav_title: Install
menu_order: 1
---

DC/OS can be installed on any cluster of physical or virtual machines.

# [Local Installation][1]

For first-time users or developers looking to build services or modify DC/OS, the [Vagrant installer][1] provides a quick, free way to deploy a virtual cluster on a single machine.

# [Cloud Provisioning][6]

For users deploying to the public cloud, DC/OS offers configurable cloud provisioning templates for [AWS][2] and [Azure][3] that will manage virtual machines and DC/OS installation.

DC/OS can be installed on other public and private clouds using the Datacenter Installation process, provided virtual machines and networks are created first.

# [Custom Installation][7]

For new users installing to existing virtual or physical machines, on-premises or in the cloud, the [GUI Installer][4] provides a guided experience for bootstrapping a DC/OS cluster.

For advanced users installing to existing virtual or physical machines, on-premises or in the cloud, the [Advanced Installer][5] provides a scriptable, automatable interface to integrate with your preferred configuration management system.

[1]: local/
[2]: cloud/aws/
[3]: cloud/azure/
[4]: custom/gui/
[5]: custom/advanced/
[6]: cloud/
[7]: custom/


text: ${nls.numberFound}:


text:
<?php

namespace Oro\Bundle\PlatformBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

use Oro\Component\Config\Loader\CumulativeConfigLoader;
use Oro\Component\Config\Loader\YamlCumulativeFileLoader;
use Oro\Component\DependencyInjection\ExtendedContainerBuilder;
use Oro\Component\PhpUtils\ArrayUtil;

use Oro\Bundle\EntityBundle\ORM\DatabaseDriverInterface;

class OroPlatformExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function prepend(ContainerBuilder $container)
    {
        $configLoader = new CumulativeConfigLoader(
            'oro_app_config',
            new YamlCumulativeFileLoader('Resources/config/oro/app.yml')
        );

        // original security config
        $securityConfig = null;
        $securityModified = false;
        if ($container->hasExtension('security')) {
            $securityConfig = $container->getExtensionConfig('security');
        }

        $resources    = $configLoader->load();
        $extensions   = $container->getExtensions();
        foreach ($resources as $resource) {
            foreach ($resource->data as $name => $config) {
                if (!empty($extensions[$name])) {
                    if ($name === 'security') {
                        $this->mergeConfigIntoOne($container, $name, $config);
                        $securityModified = true;
                    } else {
                        $container->prependExtensionConfig($name, $config);
                    }
                }
            }
        }

        // original security config has highest priority
        if ($securityConfig && $securityModified) {
            $this->mergeConfigIntoOne($container, 'security', reset($securityConfig));
        }

        $this->preparePostgreSql($container);
    }

    /**
     * Enable ATTR_EMULATE_PREPARES for PostgreSQL connections to avoid https://bugs.php.net/bug.php?id=36652
     *
     * @param ContainerBuilder $container
     */
    public function preparePostgreSql(ContainerBuilder $container)
    {
        $dbDriver = $container->getParameter('database_driver');
        if ($dbDriver === DatabaseDriverInterface::DRIVER_POSTGRESQL) {
            $doctrineConfig = $container->getExtensionConfig('doctrine');
            $doctrineConnectionOptions = [];
            foreach ($doctrineConfig as $config) {
                if (isset($config['dbal']['connections'])) {
                    foreach (array_keys($config['dbal']['connections']) as $connectionName) {
                        // Enable ATTR_EMULATE_PREPARES for PostgreSQL
                        $doctrineConnectionOptions['dbal']['connections'][$connectionName]['options'] = [
                            \PDO::ATTR_EMULATE_PREPARES => true
                        ];
                        // Add support of "oid" and "name" Db types for EnterpriseDB
                        $doctrineConnectionOptions['dbal']['connections'][$connectionName]['mapping_types'] = [
                            'oid' => 'integer',
                            'name' => 'string'
                        ];
                    }
                }
            }
            $container->prependExtensionConfig('doctrine', $doctrineConnectionOptions);
        }
    }

    /**
     * Merge configuration into one config
     *
     * @param ContainerBuilder $container
     * @param string $name
     * @param array $config
     *
     * @throws \RuntimeException
     */
    private function mergeConfigIntoOne(ContainerBuilder $container, $name, array $config = [])
    {
        if (!$container instanceof ExtendedContainerBuilder) {
            throw new \RuntimeException(
                sprintf(
                    '%s is expected to be passed into OroPlatformExtension',
                    'Oro\Component\DependencyInjection\ExtendedContainerBuilder'
                )
            );
        }

        $originalConfig = $container->getExtensionConfig($name);
        if (!count($originalConfig)) {
            $originalConfig[] = array();
        }

        $mergedConfig = ArrayUtil::arrayMergeRecursiveDistinct($originalConfig[0], $config);
        $originalConfig[0] = $mergedConfig;

        $container->setExtensionConfig($name, $originalConfig);
    }

    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

        $loader->load('services.yml');
        $loader->load('doctrine.yml');
        $loader->load('session.yml');
    }
}


text:
$(document).ready(function(){
  $("#login").on('click', function(event){
    event.preventDefault();
    var $target = $(event.target)
    $.ajax({
      url: "/login",
      data: $target.serialize()
    })
    .done(function(loginForm){
      $("#login").toggle(false)
      $("body").prepend(loginForm)
    })
    .fail(function(error){
      console.log(error, "fail panda")
    });
  })
});


text:
package com.sequenceiq.consumption.configuration;

import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;

import javax.inject.Inject;
import javax.ws.rs.client.Client;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.sequenceiq.cloudbreak.client.ConfigKey;
import com.sequenceiq.cloudbreak.client.RestClientUtil;
import com.sequenceiq.cloudbreak.concurrent.TracingAndMdcCopyingTaskDecorator;

import io.opentracing.Tracer;

@Configuration
@EnableRetry
public class AppConfig {

    private static final Logger LOGGER = getLogger(AppConfig.class);

    @Inject
    private Tracer tracer;

    @Value("${rest.debug:false}")
    private boolean restDebug;

    @Value("${cert.validation:true}")
    private boolean certificateValidation;

    @Value("${cert.ignorePreValidation:false}")
    private boolean ignorePreValidation;

    @Value("${consumption.intermediate.threadpool.core.size:}")
    private int intermediateCorePoolSize;

    @Value("${consumption.intermediate.threadpool.capacity.size:}")
    private int intermediateQueueCapacity;

    @Bean
    @Primary
    public AsyncTaskExecutor intermediateBuilderExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(intermediateCorePoolSize);
        executor.setQueueCapacity(intermediateQueueCapacity);
        executor.setThreadNamePrefix("intermediateBuilderExecutor-");
        executor.setTaskDecorator(new TracingAndMdcCopyingTaskDecorator(tracer));
        executor.initialize();
        return executor;
    }

    @Bean
    @Scope(SCOPE_PROTOTYPE)
    public Client restClient() {
        return RestClientUtil.get(new ConfigKey(certificateValidation, restDebug, ignorePreValidation));
    }

}