text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="StepView">
        <attr name="circleRadius" format="dimension" />
        <attr name="circleColorDone" format="color" />
        <attr name="circleColorDefault" format="color" />
        <attr name="lineHeight" format="dimension" />
        <attr name="lineColorDone" format="color" />
        <attr name="lineColorDefault" format="color" />
        <attr name="statusTextColorDone" format="color" />
        <attr name="statusTextColorDefault" format="color" />
        <attr name="textDateColor" format="color" />
        <attr name="statusTextSize" format="dimension" />
        <attr name="dateTextSize" format="dimension" />
        <attr name="textSpace" format="dimension" />
        <attr name="stepCount" format="integer" />
    </declare-styleable>

    <declare-styleable name="TXEditText">
        <attr name="limitLength" format="integer" />
        <attr name="limitText" format="string" />
    </declare-styleable>

    <declare-styleable name="TXRatingView">
        <!-- 最大分 -->
        <attr name="maxRating" format="integer" />
        <!-- 当前分 -->
        <attr name="rating" format="integer" />
        <!-- 没分的icon -->
        <attr name="emptyDrawable" format="reference" />
        <!-- 有分的icon -->
        <attr name="filledDrawable" format="reference" />
        <!-- icon大小 -->
        <attr name="ratingSize" format="dimension" />
        <!-- icon间距 -->
        <attr name="itemSpace" format="dimension" />
        <!-- 是否能修改分数 -->
        <attr name="enabled" format="boolean" />
    </declare-styleable>

    <!-- tab 控件 -->
    <declare-styleable name="PagerSlidingTabStrip">
        <attr name="pstsIndicatorColor" format="color" />
        <attr name="pstsTabTextColor" format="color" />
        <attr name="pstsTabSelectedTextColor" format="color" />
        <attr name="pstsUnderlineColor" format="color" />
        <attr name="pstsDividerColor" format="color" />
        <attr name="pstsTabTextSize" format="dimension" />
        <attr name="pstsIndicatorHeight" format="dimension" />
        <attr name="pstsUnderlineHeight" format="dimension" />
        <attr name="pstIndicatorPadding" format="dimension" />
        <attr name="pstsDividerPadding" format="dimension" />
        <attr name="pstsTabPaddingLeftRight" format="dimension" />
        <attr name="pstsScrollOffset" format="dimension" />
        <attr name="pstsTabBackground" format="reference" />
        <attr name="pstsTabSelectedBackgrground" format="reference" />
        <attr name="pstsShouldExpand" format="boolean" />
        <attr name="pstsTextAllCaps" format="boolean" />
    </declare-styleable>

    <declare-styleable name="RangeSeekbar">
        <attr name="seekbarHeight" format="dimension" />
        <attr name="textSize" format="dimension" />
        <attr name="spaceBetween" format="dimension" />

        <attr name="leftCursorBackground" format="reference" />
        <attr name="rightCursorBackground" format="reference" />
        <attr name="markTextArray" format="reference" />

        <attr name="textColorNormal" format="color" />
        <attr name="textColorSelected" format="color" />
        <attr name="seekbarColorNormal" format="color" />
        <attr name="seekbarColorSelected" format="color" />

        <attr name="autoMoveDuration" format="integer" />
    </declare-styleable>

    <declare-styleable name="NumberProgressBar">
        <attr name="progress_current" format="integer" />
        <attr name="progress_max" format="integer" />

        <attr name="progress_unreached_color" format="color" />
        <attr name="progress_reached_color" format="color" />

        <attr name="progress_reached_bar_height" format="dimension" />
        <attr name="progress_unreached_bar_height" format="dimension" />

        <attr name="progress_text_size" format="dimension" />
        <attr name="progress_text_color" format="color" />

        <attr name="progress_text_offset" format="dimension" />

        <attr name="progress_text_visibility" format="enum">
            <enum name="visible" value="0" />
            <enum name="invisible" value="1" />
        </attr>
    </declare-styleable>

    <declare-styleable name="TXThreeTextView">
        <attr name="firstTextColor" format="color" />
        <attr name="secondTextColor" format="color" />
        <attr name="thirdTextColor" format="color" />
        <attr name="firstTextSize" format="dimension" />
        <attr name="secondTextSize" format="dimension" />
        <attr name="thirdTextSize" format="dimension" />
        <attr name="firstText" format="string" />
        <attr name="secondText" format="string" />
        <attr name="thirdText" format="string" />
        <attr name="ellipsisType">
            <flag name="first" value="0x01" />
            <flag name="second" value="0x02" />
            <flag name="firstAndThird" value="0x03" />
            <flag name="firstAndSecond" value="0x04" />
            <flag name="secondAndThird" value="0x05" />
        </attr>
        <attr name="firstSpace" format="dimension" />
        <attr name="secondSpace" format="dimension" />
    </declare-styleable>
</resources>


text:
#include "mongoc-config.h"
#include "mongoc-crypto-private.h"

#ifdef MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO
#include "mongoc-crypto-common-crypto-private.h"
#include <CommonCrypto/CommonHMAC.h>
#include <CommonCrypto/CommonDigest.h>

void
mongoc_crypto_common_crypto_hmac_sha1 (mongoc_crypto_t *crypto,
                                       const void *key,
                                       int key_len,
                                       const unsigned char *data,
                                       int data_len,
                                       unsigned char *hmac_out)
{
   /* U1 = HMAC(input, salt + 0001) */
   CCHmac (
      kCCHmacAlgSHA1, key, (size_t) key_len, data, (size_t) data_len, hmac_out);
}

bool
mongoc_crypto_common_crypto_sha1 (mongoc_crypto_t *crypto,
                                  const unsigned char *input,
                                  const size_t input_len,
                                  unsigned char *hash_out)
{
   if (CC_SHA1 (input, (CC_LONG) input_len, hash_out)) {
      return true;
   }
   return false;
}

void
mongoc_crypto_common_crypto_hmac_sha256 (mongoc_crypto_t *crypto,
                                         const void *key,
                                         int key_len,
                                         const unsigned char *data,
                                         int data_len,
                                         unsigned char *hmac_out)
{
   CCHmac (kCCHmacAlgSHA256,
           key,
           (size_t) key_len,
           data,
           (size_t) data_len,
           hmac_out);
}

bool
mongoc_crypto_common_crypto_sha256 (mongoc_crypto_t *crypto,
                                    const unsigned char *input,
                                    const size_t input_len,
                                    unsigned char *hash_out)
{
   if (CC_SHA256 (input, (CC_LONG) input_len, hash_out)) {
      return true;
   }
   return false;
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
 <!--
Copyright 2007 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
 <head>
  <!--
This test has not yet been updated to run on IE8. See http://b/hotlist?id=36311
-->
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>
   Closure Unit Tests - goog.ui.PlainTextSpellChecker
  </title>
  <script src="../base.js">
  </script>
  <script>
   goog.require('goog.ui.PlainTextSpellCheckerTest');
  </script>
 </head>
 <body>
  <textarea id="test1" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test2" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test3" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test4" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test5" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test6" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test7" style="width: 50ex; height: 15em;">
  </textarea>
  <textarea id="test8" style="width: 50ex; height: 15em;">
  </textarea>
 </body>
</html>


text:
<?php
namespace eMacros\Runtime\Builder;

use eMacros\Runtime\GenericFunction;
use eMacros\Applicable;
use eMacros\GenericList;
use eMacros\Scope;

class ArrayBuilder implements Applicable {
	/**
	 * Builds an array with the specified elements
	 * Usage: (array 1 null "Hello" (-7 56.25) ("key" "val"))
	 * Returns: array
	 * (non-PHPdoc)
	 * @see \eMacros\Applicable::apply()
	 */
	public function apply(Scope $scope, GenericList $arguments) {
		$values = [];

		foreach ($arguments as $arg) {
			if ($arg instanceof GenericList) {
				if (count($arg) < 1) throw new \InvalidArgumentException("ArrayBuilder: No key defined.");
				if (count($arg) < 2) throw new \InvalidArgumentException("ArrayBuilder: No value defined.");
				//obtain symbol pair
				list($key, $value) = $arg;
				$key = $key->evaluate($scope);
				$values[$key] = $value->evaluate($scope);
			}
			else $values[] = $arg->evaluate($scope);
		}

		return $values;
	}
}
?>


text:
/**
 * This package contains a simple data binding framework for use in nui (or elsewhere).
 */
@API package org.terasology.rendering.nui.databinding;

import org.terasology.module.sandbox.API;


text:
class GithubRepoHelper
  class CreateCommitError < StandardError
  end
  class RepoCredentialsMissingError < StandardError
  end

  def initialize(all_repo_credentials)
    @all_repo_credentials = all_repo_credentials
  end

  def create_commit(repo_uri, application_name)
    repo_credentials = credentials_for_repo_uri(repo_uri)
    if repo_credentials.nil? || !credentials_are_present?(repo_credentials)
      raise RepoCredentialsMissingError
    end

    create_and_push_result = shell_create_and_push_commit(repo_credentials, application_name)

    raise CreateCommitError.new(create_and_push_result[:command_output]) unless 0 == create_and_push_result[:command_status]
  end

  private

  def credentials_for_repo_uri(uri)
    # NOTE - per Cloud Controller behavior, there should only be 1 binding,
    # hence 1 set of credentials for a service instance
    @all_repo_credentials.detect do |credentials|
      credentials["uri"] == uri
    end
  end

  # This function shells out to issue commands that do the following:
  #
  # - write ssh private key to file
  # - configure git ssh (known hosts, and private key file)
  # - clone the repo
  # - set git author
  # - check out master
  # - create empty commit
  # - print the commit log
  # - push commit to master
  # - delete private key
  # - delete ssh script
  # - delete cloned directory
  #
  # returns a hash: {
  #   command_status: <status code>,
  #   command_output: <stdio and stderr output of all commands>
  # }
  # command_status is 0 if all commands succeed
  # command_status is status code of the failing command if any command fails
  def shell_create_and_push_commit(repo_credentials, application_name)
    private_key = repo_credentials["private_key"]
    repo_name = repo_credentials["name"]
    repo_ssh_url = repo_credentials["ssh_url"]
    temp_dir = Dir.mktmpdir
    keys_dir = "#{temp_dir}/github_keys"
    key_file_name = "#{keys_dir}/#{repo_name}.key"
    git_ssh_script = "#{temp_dir}/#{repo_name}_ssh_script.sh"
    known_hosts_file = "#{temp_dir}/github_known_hosts"

    # Create directory for storing key file, and set permissions
    `if [ ! -d #{keys_dir} ]; then mkdir #{keys_dir}; fi`
    `chmod 0700 #{keys_dir}`

    # Store the private key in a file
    File.open(key_file_name, "w", 0600) do |f|
      f.puts private_key
    end

    # Create a unique known hosts file with github's public key, for these purposes:
    # 1) since SSH StrictHostKeyChecking is "on" by default, this file prevents SSH from asking the user to
    # confirm the github.com host upon the first connection.
    # 2) not relying on the default ~/.ssh/known_hosts file
    File.open(known_hosts_file, "w", 0700) do |f|
      f.puts <<TEXT
github.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==
TEXT
    end

    # Configure git to use this custom ssh script instead of the default "ssh" command
    File.open(git_ssh_script, "w", 0700) do |f|
      f.puts <<BASH
#!/bin/sh
exec `which ssh` -o UserKnownHostsFile=#{known_hosts_file} -o HashKnownHosts=no -i #{key_file_name} "$@"
BASH
    end

    commands = [
        "cd #{temp_dir}; GIT_SSH=#{git_ssh_script} git clone #{repo_ssh_url} 2>&1",
        "cd #{temp_dir}/#{repo_name} && git config user.name '#{application_name}' 2>&1",
        "cd #{temp_dir}/#{repo_name} && git config user.email '#{application_name}@example.com' 2>&1",
        "cd #{temp_dir}/#{repo_name} && git commit --allow-empty -m 'auto generated empty commit' 2>&1",
        "cd #{temp_dir}/#{repo_name} && git log --pretty=format:\"%h%x09%ad%x09%s\" 2>&1",
        "cd #{temp_dir}/#{repo_name}; GIT_SSH=#{git_ssh_script} git push origin master 2>&1"
    ]

    return_code = 0
    output = ""

    commands.each do |command|
      output << "\n\n> #{command}\n"
      output << `#{command}`
      return_code = $?
      break if return_code != 0
    end

    # Remove the temp files regardless of success or failure
    cleanup_commands = [
        "rm #{key_file_name}",
        "rm #{git_ssh_script}",
        "rm -rf #{temp_dir}/#{repo_name}"
    ]

    cleanup_commands.each do |command|
      output << "\n> #{command}\n"
      output << `#{command}`
    end

    puts output
    {command_status: return_code, command_output: output}
  end

  def blank?(value)
    value.nil? || value.empty?
  end

  def credentials_are_present?(credentials)
    !(blank?(credentials["name"]) ||
        blank?(credentials["uri"]) ||
        blank?(credentials["ssh_url"]) ||
        blank?(credentials["private_key"]))
  end
end


text:
using SFA.DAS.CommitmentsV2.Types;

namespace SFA.DAS.CommitmentsV2.Api.Types.Responses
{
    public class AccountLegalEntityResponse
    {
        public long AccountId { get; set; }
        public long MaLegalEntityId { get; set; }
        public string AccountName { get; set; }
        public string LegalEntityName { get; set; }
        public ApprenticeshipEmployerType LevyStatus { get; set; }
    }
}


text:
// flow-typed signature: d0c30e9bce3665277ba8239261d43cbe
// flow-typed version: <<STUB>>/react-native-vector-icons_v^4.0.0/flow_v0.40.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'react-native-vector-icons'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module 'react-native-vector-icons' {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module 'react-native-vector-icons/Entypo' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/EvilIcons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/FontAwesome' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/Foundation' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/generate-icon' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/generate-material-icons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/Ionicons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/create-icon-set-from-fontello' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/create-icon-set-from-icomoon' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/create-icon-set' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/generate-icon-set-from-css' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/icon-button' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/react-native' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/react-native.osx' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/tab-bar-item-ios' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/lib/toolbar-android' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/MaterialCommunityIcons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/MaterialIcons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/Octicons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/RNIMigration' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/SimpleLineIcons' {
  declare module.exports: any;
}

declare module 'react-native-vector-icons/Zocial' {
  declare module.exports: any;
}

// Filename aliases
declare module 'react-native-vector-icons/Entypo.js' {
  declare module.exports: $Exports<'react-native-vector-icons/Entypo'>;
}
declare module 'react-native-vector-icons/EvilIcons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/EvilIcons'>;
}
declare module 'react-native-vector-icons/FontAwesome.js' {
  declare module.exports: $Exports<'react-native-vector-icons/FontAwesome'>;
}
declare module 'react-native-vector-icons/Foundation.js' {
  declare module.exports: $Exports<'react-native-vector-icons/Foundation'>;
}
declare module 'react-native-vector-icons/generate-icon.js' {
  declare module.exports: $Exports<'react-native-vector-icons/generate-icon'>;
}
declare module 'react-native-vector-icons/generate-material-icons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/generate-material-icons'>;
}
declare module 'react-native-vector-icons/index' {
  declare module.exports: $Exports<'react-native-vector-icons'>;
}
declare module 'react-native-vector-icons/index.js' {
  declare module.exports: $Exports<'react-native-vector-icons'>;
}
declare module 'react-native-vector-icons/Ionicons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/Ionicons'>;
}
declare module 'react-native-vector-icons/lib/create-icon-set-from-fontello.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/create-icon-set-from-fontello'>;
}
declare module 'react-native-vector-icons/lib/create-icon-set-from-icomoon.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/create-icon-set-from-icomoon'>;
}
declare module 'react-native-vector-icons/lib/create-icon-set.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/create-icon-set'>;
}
declare module 'react-native-vector-icons/lib/generate-icon-set-from-css.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/generate-icon-set-from-css'>;
}
declare module 'react-native-vector-icons/lib/icon-button.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/icon-button'>;
}
declare module 'react-native-vector-icons/lib/react-native.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/react-native'>;
}
declare module 'react-native-vector-icons/lib/react-native.osx.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/react-native.osx'>;
}
declare module 'react-native-vector-icons/lib/tab-bar-item-ios.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/tab-bar-item-ios'>;
}
declare module 'react-native-vector-icons/lib/toolbar-android.js' {
  declare module.exports: $Exports<'react-native-vector-icons/lib/toolbar-android'>;
}
declare module 'react-native-vector-icons/MaterialCommunityIcons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/MaterialCommunityIcons'>;
}
declare module 'react-native-vector-icons/MaterialIcons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/MaterialIcons'>;
}
declare module 'react-native-vector-icons/Octicons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/Octicons'>;
}
declare module 'react-native-vector-icons/RNIMigration.js' {
  declare module.exports: $Exports<'react-native-vector-icons/RNIMigration'>;
}
declare module 'react-native-vector-icons/SimpleLineIcons.js' {
  declare module.exports: $Exports<'react-native-vector-icons/SimpleLineIcons'>;
}
declare module 'react-native-vector-icons/Zocial.js' {
  declare module.exports: $Exports<'react-native-vector-icons/Zocial'>;
}


text:
import { TinyMCE } from 'tinymce/core/api/PublicApi';

declare let tinymce: TinyMCE;

tinymce.init({
  selector: 'textarea.tinymce',
  plugins: 'lists advlist code',
  toolbar: 'bullist numlist | outdent indent | code',
  height: 600
});

export {};


text:
@interface GPUImageMultiplyBlendFilter : GPUImageFilter
{
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Protocols/IFlySpeechplusDelegate.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/intf/IFlySpeechplusDelegate</TokenIdentifier>
			<Abstract type="html">语记返回回调</Abstract>
			<DeclaredIn>IFlySpeechUtility.h</DeclaredIn>

			<NodeRef refid="24"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/IFlySpeechplusDelegate/onError:</TokenIdentifier>
			<Abstract type="html">发生错误</Abstract>
			<DeclaredIn>IFlySpeechUtility.h</DeclaredIn>

			<Declaration>- (void)onError:(int)errorCode</Declaration>
			<Parameters>
				<Parameter>
					<Name>errorCode</Name>
					<Abstract type="html">错误码</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/onError:</Anchor>
            <NodeRef refid="24"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/intfm/IFlySpeechplusDelegate/onCompleted</TokenIdentifier>
			<Abstract type="html">服务正常结束</Abstract>
			<DeclaredIn>IFlySpeechUtility.h</DeclaredIn>

			<Declaration>- (void)onCompleted</Declaration>

			<Anchor>//api/name/onCompleted</Anchor>
            <NodeRef refid="24"/>
		</Token>

	</File>
</Tokens>


text:
require 'spec_helper'

describe 'PostgreSQL' do
  describe service('postgresql') do
    it { is_expected.to be_enabled }
  end

  describe process('postgres') do
    it { is_expected.to be_running }
    its(:user) { is_expected.to eq('postgres') }
  end

  describe port(5432) do
    subject(:default_port) { port(5432) }

    it { is_expected.to be_listening }
  end

  describe 'client version' do
    subject(:client_version) { command('psql --version') }

    its(:stdout) { is_expected.to match(/psql \(PostgreSQL\) 9\.3/) }
  end

  describe 'server version' do
    subject(:server_version) { command('sudo -u postgres psql -c "select version();"') }

    its(:stdout) { is_expected.to match(/PostgreSQL 9\.3/)}
  end

  describe 'vagrant db role' do
    subject(:vagrant_role) { command("sudo -u postgres psql -c \"SELECT rolname FROM pg_roles WHERE rolname='vagrant'\"") }

    its(:stdout) { is_expected.to match(/vagrant/) }
  end

  describe package('postgresql-contrib-9.3') do
    it { is_expected.to be_installed }
  end
end


text:
/*[2-3]*/

var say = function myName(){
	console.log("Fah");
}
say();

/*-----------*/

function firstName(){
	console.log("Nattaya");
}

function sayFirstName(name){
	name();
}

sayFirstName(firstName);

/*-----------*/

function lastName(){
	return function sayLastName(){
		console.log("Mairittha");
	}
}

var lastNameFn = lastName();
lastNameFn();

/////// closure //////

function parent (){
	var x = 1;

	function child(){
		console.log(x);
	}
	return child;
}
var childFn = parent();
childFn();

/////// closure-2 //////
function prefix(pre){
	return function fileHandler(err , data){
		console.log(pre + " "+ data);
	}
}

var say = prefix("Say: ");
var shout = prefix("Shout: ");

var fs = require('fs');
fs.readFile('hello.txt', say);
fs.readFile('hello.txt', shout);


text:
include_recipe "apt" if platform_family?("debian")
include_recipe "ntp"

if node["platform"] == "oracle"
  platform_version = node["platform_version"].to_i
  tag = node["platform_version"].to_i == 6 ? "ol" : "el"

  remote_file "/etc/yum.repos.d/public-yum-#{tag}#{platform_version}.repo" do
    source "http://public-yum.oracle.com/public-yum-#{tag}#{platform_version}.repo"
    mode "0644"
  end
end


text:
// ==========================================================================
//                            DG.MapModel
//
//  Author:   William Finzer
//
//  Copyright ©2014 Concord Consortium
//
//  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.
// ==========================================================================

sc_require('components/graph_map_common/data_layer_model');

/** @class  DG.MapLayerModel - The model for a layer in a map.

 @extends DG.DataLayerModel
 */
DG.MapLayerModel = DG.DataLayerModel.extend(
    /** @scope DG.MapLayerModel.prototype */
    {
      isVisible: true,

      init: function() {
        sc_super();
      },

      somethingIsSelectable: function() {
        return false;
      }.property(),

      gridIsVisible: function() {
        return false;
      }.property(),

      /**
       * Base class returns false
       * @return {boolean}
       */
      hasValidMapAttributes: function() {
        return false;
      },

      handleLegendAttrChange: function() {
        var tLegendAttrDesc = this.getPath('dataConfiguration.legendAttributeDescription');
        if( tLegendAttrDesc) {
          tLegendAttrDesc.set('offsetMinProportion', DG.PlotUtilities.kMapColorRangeOffset);
          tLegendAttrDesc.invalidateCaches();
        }
      }.observes('dataConfiguration.legendAttributeDescription.attribute'),

      handleLegendCategoryMapChange: function() {
        this.notifyPropertyChange('colorMap');
      }.observes('dataConfiguration.legendAttributeDescription.attribute.categoryMap'),

      handleOneDataContextChange: function( iNotifier, iChange) {
        sc_super();

        var tDataConfiguration = this.get('dataConfiguration'),
            tOperation = iChange && iChange.operation;

        if( !tDataConfiguration)
          return; // Occurs when a notification was queued up before a destroy took place

        if (tOperation === 'deleteCases')
          this.get('dataConfiguration').synchHiddenCases();
        if (tOperation === 'selectCases')
          this.notifyPropertyChange('selection');

        // We must invalidate before we build indices because the change may
        // have affected the set of included cases, which affects indices.
        // It would be better not to be dealing with indices at all, but
        // that refactoring is left for another day.
        this.get('dataConfiguration').invalidateCaches( null, iChange);
        iChange.indices = this.buildIndices( iChange);
        this.dataRangeDidChange( this, 'revision', this, iChange.indices);
        this.set('lastChange', iChange);
      },

      /**
       * One or more of the attributes belonging to the collection used by this layer has been changed;
       * e.g. by having its name changed.
       * @param iChange {Object}
       */
      handleUpdateAttributes: function( iChange) {
        if( this.isAffectedByChange( iChange)) {
          this.notifyPropertyChange('attributeUpdated');
          var tAssignedAttr = this.getPath( 'dataConfiguration.legendAttributeDescription.attribute'),
              tAssignedAttrID = tAssignedAttr && tAssignedAttr.get('id');
          if( !SC.none(tAssignedAttrID)) {
            var tSubModel = this.get('legend');
            if (tSubModel)
              tSubModel.handleUpdateAttribute(tAssignedAttrID);
          }
        }
      },

      /**
       * This method is called when an area, latitude, or longitude attribute is deleted from the data context currently
       * being used by this map. Our job is to reconfigure our data configuration so there will no longer be any attempt
       * to plot data
       *
       * @param iDescKey {String}
       */
      removeAttribute: function( iDescKey) {
        var tDescription = this.getPath('dataConfiguration.' + iDescKey);
        if( tDescription) {
          tDescription.removeAllAttributes();
          this.notifyPropertyChange('attributeRemoved');
        }
      },

      /**
       @param {CaseModel} iCase The case to be selected.
       @param {Boolean} iExtend Should the current selection be extended?
       */
      selectCase: function( iCase, iExtend) {
        var tSelection = this.get('selection'),
            tChange = {
              operation: 'selectCases',
              collection: this.get('collectionClient'),
              cases: [ iCase ],
              select: true,
              extend: iExtend
            };

        if( tSelection.get('length') !== 0) {
          if( tSelection.contains( iCase)) {  // Case is already selected
            if( iExtend) {
              tChange.select = false;
            }
            // clicking on a selected case leaves it selected
            else return;
          }
          else {
            tChange.select = true;
          }
        }

        this.get('dataContext').applyChange( tChange);
      },

      /**
       * Not yet. Compare with dot chart <==> bar chart
       * @property {Boolean}
       */
      canSupportConfigurations: function() {
        return false;
      }.property(),

      /**
       * Returns true if the specified change could affect the current map
       * @param     {object}  - iChange
       * @returns   {boolean} - true if the change could affect the plot; false otherwise
       */
      isAffectedByChange: function( iChange) {
        var attrs, i, collChange, collChanges, collChangeCount;

        // returns true if the specified list of attribute IDs contains any
        // that are being displayed in the map in any graph place
        var containsMappedAttrs = function(iAttrIDs) {
          var mappedAttrs = this.getPath('dataConfiguration.placedAttributeIDs'),
              attrCount = iAttrIDs && iAttrIDs.length,
              i, attrID;
          for (i = 0; i < attrCount; ++i) {
            attrID = iAttrIDs[i];
            if (mappedAttrs.indexOf(attrID) >= 0)
              return true;
          }
          return false;
        }.bind(this);

        switch (iChange.operation) {
          case 'createCases':
          case 'deleteCases':
            return true;
          case 'updateCases':
            attrs = iChange.attributeIDs;
            if (!attrs) return true;  // all attributes affected
            return containsMappedAttrs(attrs);
          case 'dependentCases':
            collChanges = iChange.changes;
            collChangeCount = collChanges ? collChanges.length : 0;
            for (i = 0; i < collChangeCount; ++i) {
              collChange = collChanges[i];
              if (collChange) {
                attrs = collChange.attributeIDs;
                if (attrs && containsMappedAttrs(attrs))
                  return true;
              }
            }
            return false;
          case 'updateAttributes':
            attrs = iChange.attrPropsArray.map( function( iProp) {
              return iProp.id;
            });
            return containsMappedAttrs(attrs);
        }

        // For now, we'll assume all other changes affect us
        return true;
      },

      checkboxDescriptions: function() {
        return [];
      }.property(),

      lastValueControls: function() {
        return [];
      }.property(),

      _observedDataConfiguration: null,

      /**
       * Store the information needed to put my data configuration back together.
       * @return {Object}
       */
      createStorage: function () {
        var tStorage = {_links_: {}},
            tDataContext = this.get('dataContext'),
            tDataConfiguration = this.get('dataConfiguration'),
            tHiddenCases = tDataConfiguration && tDataConfiguration.get('hiddenCases');

        if (tHiddenCases) {
          tStorage._links_.hiddenCases = tHiddenCases
              .filter(function (iCase) {
                return !!iCase;
              })
              .map(function (iCase) {
                return iCase.toLink();
              });
        }

        if (tDataContext)
          tStorage._links_.context = tDataContext.toLink();

        tDataConfiguration.addToStorageForDimension( tStorage, 'legend');
        tStorage.isVisible = this.get('isVisible');

        return tStorage;
      },

      restoreStorage: function( iStorage) {
        // This is our chance to restore the proper data context. We can't do it at a higher level because
        // each of our layers can have a different one
        var tContextID = DG.ArchiveUtils.getLinkID( iStorage, 'context');
        if( !SC.none( tContextID)) {
          this.beginPropertyChanges();  // So that polygon layer will only clear once
          var tDataContext = DG.currDocumentController().getContextByID(tContextID);
          this.set('dataContext', tDataContext);
          this.endPropertyChanges();
        }

        sc_super();
        var tLegendAttrRef = this.instantiateAttributeRefFromStorage(iStorage, 'legendColl', 'legendAttr'),
            tDataConfig = this.get('dataConfiguration');
        tDataConfig.setAttributeAndCollectionClient('legendAttributeDescription', tLegendAttrRef,
            iStorage.legendRole, iStorage.legendAttributeType);
        if( !SC.none( iStorage.isVisible))
          this.set('isVisible', iStorage.isVisible);
      }
    });


text:
import C from '../constants';

export default function(state = [], action) {
  switch (action.type) {
    case C.ADD_RESULTS:
        return action.payload;
    case C.CLEAR_RESULTS:
        return [];
  }
  return state;
}


text:
.class Lcom/android/internal/policy/impl/GlobalActions$9$1;
.super Landroid/os/Handler;
.source "GlobalActions.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/policy/impl/GlobalActions$9;->onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

.field final synthetic val$myConn:Landroid/content/ServiceConnection;

# direct methods
.method constructor <init>(Lcom/android/internal/policy/impl/GlobalActions$9;Landroid/os/Looper;Landroid/content/ServiceConnection;)V
    .locals 0
    .parameter
    .parameter "x0"
    .parameter

    .prologue
    .line 481
    iput-object p1, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iput-object p3, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->val$myConn:Landroid/content/ServiceConnection;

    invoke-direct {p0, p2}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 3
    .parameter "msg"

    .prologue
    .line 484
    iget-object v0, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v0, v0, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    #getter for: Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotLock:Ljava/lang/Object;
    invoke-static {v0}, Lcom/android/internal/policy/impl/GlobalActions;->access$1100(Lcom/android/internal/policy/impl/GlobalActions;)Ljava/lang/Object;

    move-result-object v1

    monitor-enter v1

    .line 485
    :try_start_0
    iget-object v0, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v0, v0, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    #getter for: Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotConnection:Landroid/content/ServiceConnection;
    invoke-static {v0}, Lcom/android/internal/policy/impl/GlobalActions;->access$1300(Lcom/android/internal/policy/impl/GlobalActions;)Landroid/content/ServiceConnection;

    move-result-object v0

    iget-object v2, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->val$myConn:Landroid/content/ServiceConnection;

    if-ne v0, v2, :cond_0

    .line 486
    iget-object v0, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v0, v0, Lcom/android/internal/policy/impl/GlobalActions$9;->val$context:Landroid/content/Context;

    iget-object v2, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v2, v2, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    #getter for: Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotConnection:Landroid/content/ServiceConnection;
    invoke-static {v2}, Lcom/android/internal/policy/impl/GlobalActions;->access$1300(Lcom/android/internal/policy/impl/GlobalActions;)Landroid/content/ServiceConnection;

    move-result-object v2

    invoke-virtual {v0, v2}, Landroid/content/Context;->unbindService(Landroid/content/ServiceConnection;)V

    .line 487
    iget-object v0, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v0, v0, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    const/4 v2, 0x0

    #setter for: Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotConnection:Landroid/content/ServiceConnection;
    invoke-static {v0, v2}, Lcom/android/internal/policy/impl/GlobalActions;->access$1302(Lcom/android/internal/policy/impl/GlobalActions;Landroid/content/ServiceConnection;)Landroid/content/ServiceConnection;

    .line 488
    iget-object v0, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v0, v0, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    #getter for: Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotHandler:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/internal/policy/impl/GlobalActions;->access$700(Lcom/android/internal/policy/impl/GlobalActions;)Landroid/os/Handler;

    move-result-object v0

    iget-object v2, p0, Lcom/android/internal/policy/impl/GlobalActions$9$1;->this$1:Lcom/android/internal/policy/impl/GlobalActions$9;

    iget-object v2, v2, Lcom/android/internal/policy/impl/GlobalActions$9;->this$0:Lcom/android/internal/policy/impl/GlobalActions;

    iget-object v2, v2, Lcom/android/internal/policy/impl/GlobalActions;->mScreenshotTimeout:Ljava/lang/Runnable;

    invoke-virtual {v0, v2}, Landroid/os/Handler;->removeCallbacks(Ljava/lang/Runnable;)V

    .line 490
    :cond_0
    monitor-exit v1

    .line 491
    return-void

    .line 490
    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method


text:
<?php

namespace Codeklan\AfricaistalkingApi;

use \GuzzleHttp\Client;
use Config;

class AfricaistalkingApiClass
{
    /**
     * Create a new Skeleton Instance
     */
    public function __construct()
    {
        // constructor body
    }

    /**
     * Friendly welcome
     *
     * @param string $phrase Phrase to return
     *
     * @return string Returns the phrase passed in
     */
    public function echoPhrase($phrase)
    {
        return $phrase;
    }
}


text:
<!DOCTYPE html >

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

    <title>A Line chart demonstrating the crosshairs snap option</title>

    <meta name="keywords" content="demo line crosshairs snap" />
    <meta name="description" content="The crosshairs has a snap option to 'lock' it to points - this demonstrates it" />
    <meta name="robots" content="noindex,nofollow" />

A Line chart demonstrating  the crosshairs snap option

        This line chart demonstrates how you can extract the Line charts dataset and index from the variables set on the canvas tag
        by RGraph.

    <canvas id="cvs" width="600" height="400">[No canvas support]</canvas>

    Dataset:

    <input id="dataset" type="text" />

    Point:

    <input id="point" type="text" />

        « Back


text:
    <meta charset="UTF-8">
    <title>MTFractionDisplay.updateDenominatorPosition - </title>
    <link rel="stylesheet" href="../../style.css">

com.agog.mathdisplay.render / MTFractionDisplay / updateDenominatorPosition

updateDenominatorPosition

fun updateDenominatorPosition(): Unit


text:
class Animal
  attr_accessor :life, :attendants, :friends
  def initialize
    self.life = true
    self.attendants = []
    self.friends = []
  end

  def talk(speech)
    puts speech
  end

  def meets(other_animal)
    self.attendants << other_animal
  end

  def has_attendant?(attendant)
    self.attendants.include? attendant
  end

  def alive?
    self.life
  end

  def is(state)
    @state = state
  end

  def is?(state)
    @state == state
  end

  def thank(animal)
    animal # thank you!
  end

  def miserable
    has_pain?
  end
end

class Donkey < Animal
  attr_accessor :splinter
  def has_pain?
    alive? && splinter
  end
end

class Wolf < Animal
  def tear_apart(animal)
    animal.life = nil
  end

  def has_pain?
    false
  end
end

class Lion < Animal
  def catch(animal)
    animal.is(:catched)
  end

  def release(animal)
    animal.is(:released)
  end

  def roar(opts={})
    talk "ROAAAR"
    if opts[:how] == :desparately
      talk "AYEE!"
    end
  end
end

class Mouse < Animal
  def plead(speech)
    talk speech
  end

  def help(animal)
    animal.attendants << self
  end

  def try_to_free(animal)
    if animal.is? :trapped
      r = Random.new
      if r.rand(0..10) == 10
        animal.is(:free)
      end
    end
  end
end


text:
#ifdef CPUT_GPA_INSTRUMENTATION
// constructor
// automatically creates an ITT begin marker at the start of this task
//-----------------------------------------------------------------------------
CPUTPerfTaskMarker::CPUTPerfTaskMarker(DWORD color, wchar_t *pString)
{
    D3DPERF_BeginEvent(color, pString);
}

// destructor
// when class goes out of scope, this marker will automatically be called
//-----------------------------------------------------------------------------
CPUTPerfTaskMarker::~CPUTPerfTaskMarker()
{
    D3DPERF_EndEvent();
}
#else
    // This is a bit of a hack to get the compiler not to complain about this being an empty file
    // during the compilation in any mode that doesn't have CPUT_GPA_INSTRUMENTATION defined
    #define CPUTPerfTaskMarkerNotEmpty()   namespace { char CPUTPerfTaskMarkerDummy##__LINE__; }
    CPUTPerfTaskMarkerNotEmpty();
#endif


text:
package main

import (
	"fmt"
	"os"

	"github.com/millere/todo"
)

var cmdArchive = &Command{
	UsageLine: "archive",
	Short:     "archives completed todos",
}

func init() {
	cmdArchive.Run = runArchive
}

func runArchive(cmd *Command, conf config, args []string) {
	inFile, err := readTodoFile(conf.Todos)
	if err != nil {
		fmt.Println(err)
		return
	}
	var active todo.TaskList
	var archive todo.TaskList
	for _, task := range inFile {
		if task.Done {
			archive = append(archive, task)
		} else {
			active = append(active, task)
		}
	}

	if len(archive) == 0 {
		fmt.Println("No tasks archived.")
		return
	}

	arcFile, err := os.OpenFile(conf.Archive, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		fmt.Println("Couldn't archive:", err)
		return
	}
	defer arcFile.Close()
	for _, t := range archive {
		_, err := fmt.Fprintln(arcFile, t.Raw)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	file, err := os.Create(conf.Todos)
	if err != nil {
		fmt.Println("Couldn't modify todo file:", err)
		return
	}
	defer file.Close()
	for _, t := range active {
		_, err := fmt.Fprintln(file, t.Raw)
		if err != nil {
			fmt.Println(err)
			return
		}
	}

	fmt.Printf("Archived %d task", len(archive))
	if len(archive) != 1 {
		fmt.Print("s")
	}
	fmt.Println(".")

}

func readTodoFile(f string) (todo.TaskList, error) {
	file, err := os.Open(f)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	todos, err := todo.FromReader(file)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	return todos, nil
}


text:
package config

import (
	"reflect"
	"testing"
)

func TestConfig(t *testing.T) {
	var (
		skey    = "string.value"
		ikey    = "int.value"
		uikey   = "uint.value"
		i64key  = "int64.value"
		ui64key = "uint64.value"
		bkey    = "bool.value"
		btkey   = "byte.value"
		fkey    = "float.value"
		f64key  = "float64.value"
		btskey  = "byte.slice.value"
		slkey   = "slice.value"
		nonkey  = "~!@#$%"
		branch  = "branchname.nest"

		sval            = "12345678"
		ival            = 12345678
		uival   uint32  = 4294967295
		i64val  int64   = -9223372036854775808
		ui64val uint64  = 18446744073709551615
		bval            = true
		btval           = byte(82)
		fval    float32 = 123.456
		f64val          = 123.23787283123123
		btsval          = []byte{1, 2, 3, 4, 5, 6, 7, 8}
		slval           = []interface{}{"12345678", 12345678}
	)

	c := NewConfiguration()
	c.Set(skey, sval)
	c.Set(ikey, ival)
	c.Set(uikey, uival)
	c.Set(i64key, i64val)
	c.Set(ui64key, ui64val)
	c.Set(bkey, bval)
	c.Set(btkey, btval)
	c.Set(fkey, fval)
	c.Set(f64key, f64val)
	c.Set(btskey, btsval)
	c.Set(slkey, slval)
	b, err := c.MakeBranch(branch)

	if !c.Exists(skey, ikey, uikey, i64key, ui64key, bkey, btkey, fkey, f64key, btskey, slkey) {
		t.Error("Keys do not exists")
	} else if c.Exists(nonkey) {
		t.Error("Key exists")
	}

	if c.String(skey) != sval {
		t.Log("Key:", skey)
		t.Log("Expected:", sval)
		t.Log("Result:", c.String(skey))
		t.Error("Expected value and result does not match")
	} else if c.String(nonkey, "not exists") != "not exists" {
		t.Log("Key:", nonkey)
		t.Log("Expected:", "not exists")
		t.Log("Result:", c.String(nonkey, "not exists"))
		t.Error("Expected value and result does not match")
	}
	if !reflect.DeepEqual(c.Bytes(skey), []byte(sval)) {
		t.Log("Key:", skey)
		t.Log("Expected:", []byte(sval))
		t.Log("Result:", c.Bytes(skey))
		t.Error("Expected value and result does not match")
	} else if !reflect.DeepEqual(c.Bytes(nonkey, []byte("not exists b")), []byte("not exists b")) {
		t.Log("Key:", nonkey)
		t.Log("Expected:", []byte("not exists b"))
		t.Log("Result:", c.Bytes(nonkey, []byte("not exists b")))
		t.Error("Expected value and result does not match")
	}

	if c.Int(ikey) != ival {
		t.Log("Key:", ikey)
		t.Log("Expected:", ival)
		t.Log("Result:", c.Int(ikey))
		t.Error("Expected value and result does not match")
	} else if c.Int(nonkey, 8282) != 8282 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8282)
		t.Log("Result:", c.Int(nonkey, 8282))
		t.Error("Expected value and result does not match")
	}
	if c.Int32(ikey) != int32(ival) {
		t.Log("Key:", ikey)
		t.Log("Expected:", int32(ival))
		t.Log("Result:", c.Int32(ikey))
		t.Error("Expected value and result does not match")
	} else if c.Int32(nonkey, 828232) != 828232 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 828232)
		t.Log("Result:", c.Int32(nonkey, 828232))
		t.Error("Expected value and result does not match")
	}

	if c.Uint32(uikey) != uival {
		t.Log("Key:", uikey)
		t.Log("Expected:", uival)
		t.Log("Result:", c.Uint32(uikey))
		t.Error("Expected value and result does not match")
	} else if c.Uint32(nonkey, 8282132) != 8282132 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8282132)
		t.Log("Result:", c.Uint32(nonkey, 8282132))
		t.Error("Expected value and result does not match")
	}
	if c.Uint(uikey) != uint(uival) {
		t.Log("Key:", uikey)
		t.Log("Expected:", uint(uival))
		t.Log("Result:", c.Uint(uikey))
		t.Error("Expected value and result does not match")
	} else if c.Uint(nonkey, 82821) != 82821 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 82821)
		t.Log("Result:", c.Uint(nonkey, 82821))
		t.Error("Expected value and result does not match")
	}

	if c.Int64(i64key) != i64val {
		t.Log("Key:", i64key)
		t.Log("Expected:", i64val)
		t.Log("Result:", c.Int64(i64key))
		t.Error("Expected value and result does not match")
	} else if c.Int64(nonkey, 828264) != 828264 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 828264)
		t.Log("Result:", c.Int64(nonkey, 828264))
		t.Error("Expected value and result does not match")
	}

	if c.Uint64(ui64key) != ui64val {
		t.Log("Key:", ui64key)
		t.Log("Expected:", ui64val)
		t.Log("Result:", c.Uint64(ui64key))
		t.Error("Expected value and result does not match")
	} else if c.Uint64(nonkey, 8282164) != 8282164 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8282164)
		t.Log("Result:", c.Uint64(nonkey, 8282164))
		t.Error("Expected value and result does not match")
	}

	if c.Bool(bkey) != bval {
		t.Log("Key:", bkey)
		t.Log("Expected:", bval)
		t.Log("Result:", c.Bool(bkey))
		t.Error("Expected value and result does not match")
	} else if c.Bool(nonkey, true) != true {
		t.Log("Key:", nonkey)
		t.Log("Expected:", true)
		t.Log("Result:", c.Bool(nonkey, true))
		t.Error("Expected value and result does not match")
	}

	if c.Byte(btkey) != btval {
		t.Log("Key:", btkey)
		t.Log("Expected:", btval)
		t.Log("Result:", c.Byte(btkey))
		t.Error("Expected value and result does not match")
	} else if c.Byte(nonkey, 8) != 8 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8)
		t.Log("Result:", c.Byte(nonkey, 8))
		t.Error("Expected value and result does not match")
	}
	if c.Int8(btkey) != int8(btval) {
		t.Log("Key:", btkey)
		t.Log("Expected:", int8(btval))
		t.Log("Result:", c.Int8(btkey))
		t.Error("Expected value and result does not match")
	} else if c.Int8(nonkey, 9) != 9 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 9)
		t.Log("Result:", c.Int8(nonkey, 9))
		t.Error("Expected value and result does not match")
	}
	if c.Int16(btkey) != int16(btval) {
		t.Log("Key:", btkey)
		t.Log("Expected:", int16(btval))
		t.Log("Result:", c.Int16(btkey))
		t.Error("Expected value and result does not match")
	} else if c.Int16(nonkey, 8216) != 8216 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8216)
		t.Log("Result:", c.Int16(nonkey, 8216))
		t.Error("Expected value and result does not match")
	}
	if c.Uint8(btkey) != btval {
		t.Log("Key:", btkey)
		t.Log("Expected:", btval)
		t.Log("Result:", c.Uint8(btkey))
		t.Error("Expected value and result does not match")
	} else if c.Uint8(nonkey, 81) != 81 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 81)
		t.Log("Result:", c.Uint8(nonkey, 81))
		t.Error("Expected value and result does not match")
	}
	if c.Uint16(btkey) != uint16(btval) {
		t.Log("Key:", btkey)
		t.Log("Expected:", uint16(btval))
		t.Log("Result:", c.Uint16(btkey))
		t.Error("Expected value and result does not match")
	} else if c.Uint16(nonkey, 8216) != 8216 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 8216)
		t.Log("Result:", c.Uint16(nonkey, 8216))
		t.Error("Expected value and result does not match")
	}

	if c.Float32(fkey) != fval {
		t.Log("Key:", fkey)
		t.Log("Expected:", fval)
		t.Log("Result:", c.Float32(fkey))
		t.Error("Expected value and result does not match")
	} else if c.Float32(nonkey, 82.32) != 82.32 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 82.32)
		t.Log("Result:", c.Float32(nonkey, 82.32))
		t.Error("Expected value and result does not match")
	}
	if c.Float64(f64key) != f64val {
		t.Log("Key:", f64key)
		t.Log("Expected:", f64val)
		t.Log("Result:", c.Float64(f64key))
		t.Error("Expected value and result does not match")
	} else if c.Float64(nonkey, 82.64) != 82.64 {
		t.Log("Key:", nonkey)
		t.Log("Expected:", 82.64)
		t.Log("Result:", c.Float64(nonkey, 82.64))
		t.Error("Expected value and result does not match")
	}

	if !reflect.DeepEqual(c.ByteSlice(btskey), btsval) {
		t.Log("Key:", btskey)
		t.Log("Expected:", btsval)
		t.Log("Result:", c.Byte(btskey))
		t.Error("Expected value and result does not match")
	} else if !reflect.DeepEqual(c.ByteSlice(nonkey, []byte("not exists bs")), []byte("not exists bs")) {
		t.Log("Key:", nonkey)
		t.Log("Expected:", []byte("not exists bs"))
		t.Log("Result:", c.ByteSlice(nonkey, []byte("not exists bs")))
		t.Error("Expected value and result does not match")
	}

	if err != nil {
		t.Error("MakeBranch error:", err)
	} else {
		b.Set(skey, sval)

		if b.String(skey) != sval {
			t.Log("Key:", branch, skey)
			t.Log("Expected:", sval)
			t.Log("Result:", b.String(skey))
			t.Error("Expected value and result does not match")
		} else if c.String(branch+"."+skey) != sval {
			t.Log("Key:", branch, skey)
			t.Log("Expected:", sval)
			t.Log("Result:", b.String(skey))
			t.Error("Expected value and result does not match")
		} else if c.Branch(branch).String(skey) != sval {
			t.Log("Key:", branch, skey)
			t.Log("Expected:", sval)
			t.Log("Result:", b.String(skey))
			t.Error("Expected value and result does not match")
		}
	}
}

func TestConfigMap(t *testing.T) {
	m := map[string]interface{}{
		"name":    "sunnified",
		"version": "b",
		"branch": map[string]interface{}{
			"key":   "value",
			"int":   42,
			"float": 32.12,
			"bool":  true,
		},
		"switches": map[string]interface{}{
			"__switch__": map[string]interface{}{
				"__key__":     "version",
				"__default__": "c",
				"a": map[string]interface{}{
					"1": "1",
					"2": "2",
				},
				"b": map[string]interface{}{
					"1": "one",
					"2": "two",
				},
				"c": map[string]interface{}{
					"1": "ichi",
					"2": "ni",
				},
			},
			"1": "will be overwritten",
			"2": 2,
		},
	}

	c := NewConfigurationFromMap(m)
	if !c.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2") {
		t.Error("Keys do not exists")
	} else if c.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	}

	if c.String("version") != "b" {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c.String("branch.key") != "value" {
		t.Log("Key: branch.key")
		t.Log("Expected: value")
		t.Log("Result:", c.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c.Int("branch.int") != 42 {
		t.Log("Key: branch.int")
		t.Log("Expected: 42")
		t.Log("Result:", c.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c.Float64("branch.float") != 32.12 {
		t.Log("Key: branch.float")
		t.Log("Expected: 32.12")
		t.Log("Result:", c.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c.Bool("branch.bool") != true {
		t.Log("Key: branch.bool")
		t.Log("Expected: true")
		t.Log("Result:", c.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.1") != "one" {
		t.Log("Key: switches.1")
		t.Log("Expected: one")
		t.Log("Result:", c.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.2") != "two" {
		t.Log("Key: switches.2")
		t.Log("Expected: two")
		t.Log("Result:", c.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	m["version"] = "a"
	c2 := NewConfigurationFromMap(m)

	if c2.String("version") != "a" {
		t.Log("Key: version")
		t.Log("Expected: a")
		t.Log("Result:", c2.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.1") != "1" {
		t.Log("Key: switches.1")
		t.Log("Expected: 1")
		t.Log("Result:", c2.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.2") != "2" {
		t.Log("Key: switches.2")
		t.Log("Expected: 2")
		t.Log("Result:", c2.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	delete(m, "version")
	c3 := NewConfigurationFromMap(m)

	if c3.Exists("version") {
		t.Error("Version still exists")
	} else if !c.Exists("version") {
		t.Error("Version gone")
	}

	if c3.String("switches.1") != "ichi" {
		t.Log("Key: switches.1")
		t.Log("Expected: ichi")
		t.Log("Result:", c3.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c3.String("switches.2") != "ni" {
		t.Log("Key: switches.2")
		t.Log("Expected: ni")
		t.Log("Result:", c3.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	c4, err := NewConfigurationFromFile("test_a.json")
	if err != nil {
		t.Error("File failed", err)
	}
	if !c4.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2") {
		t.Error("Keys do not exists")
	} else if c4.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	}

	if c4.String("version") != c.String("version") {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c4.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c4.String("branch.key") != c.String("branch.key") {
		t.Log("Key: branch.key")
		t.Log("Expected:", c.String("branch.key"))
		t.Log("Result:", c4.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c4.Int("branch.int") != c.Int("branch.int") {
		t.Log("Key: branch.int")
		t.Log("Expected:", c.Int("branch.int"))
		t.Log("Result:", c4.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c4.Float64("branch.float") != c.Float64("branch.float") {
		t.Log("Key: branch.float")
		t.Log("Expected:", c.Float64("branch.float"))
		t.Log("Result:", c4.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c4.Bool("branch.bool") != c.Bool("branch.bool") {
		t.Log("Key: branch.bool")
		t.Log("Expected:", c.Bool("branch.bool"))
		t.Log("Result:", c4.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c4.String("switches.1") != c.String("switches.1") {
		t.Log("Key: switches.1")
		t.Log("Expected:", c.String("switches.1"))
		t.Log("Result:", c4.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c4.String("switches.2") != c.String("switches.2") {
		t.Log("Key: switches.2")
		t.Log("Expected:", c.String("switches.2"))
		t.Log("Result:", c4.String("switches.2"))
		t.Error("Expected value and result does not match")
	}
}

func TestConfigInclude(t *testing.T) {
	c, err := NewConfigurationFromFile("test_b.json")
	if err != nil {
		t.Error("File failed", err)
	}
	if !c.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2") {
		t.Error("Keys do not exists")
	} else if c.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	}

	if c.String("version") != "b" {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c.String("branch.key") != "value" {
		t.Log("Key: branch.key")
		t.Log("Expected: value")
		t.Log("Result:", c.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c.Int("branch.int") != 42 {
		t.Log("Key: branch.int")
		t.Log("Expected: 42")
		t.Log("Result:", c.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c.Float64("branch.float") != 32.12 {
		t.Log("Key: branch.float")
		t.Log("Expected: 32.12")
		t.Log("Result:", c.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c.Bool("branch.bool") != true {
		t.Log("Key: branch.bool")
		t.Log("Expected: true")
		t.Log("Result:", c.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.1") != "one" {
		t.Log("Key: switches.1")
		t.Log("Expected: one")
		t.Log("Result:", c.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.2") != "two" {
		t.Log("Key: switches.2")
		t.Log("Expected: two")
		t.Log("Result:", c.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	c2, err := NewConfigurationFromFile("test_d.json")
	if err != nil {
		t.Error("File failed", err)
	}
	if !c2.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2",
		"app.db_username", "app.db_password", "app.db_database") {
		t.Error("Keys do not exists")
	} else if c2.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	} else if c2.Exists("app.__switch__") {
		t.Error("Switch still exists")
	}

	if c2.String("version") != "b" {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c2.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("branch.key") != "value" {
		t.Log("Key: branch.key")
		t.Log("Expected: value")
		t.Log("Result:", c2.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c2.Int("branch.int") != 42 {
		t.Log("Key: branch.int")
		t.Log("Expected: 42")
		t.Log("Result:", c2.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c2.Float64("branch.float") != 32.12 {
		t.Log("Key: branch.float")
		t.Log("Expected: 32.12")
		t.Log("Result:", c2.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c2.Bool("branch.bool") != true {
		t.Log("Key: branch.bool")
		t.Log("Expected: true")
		t.Log("Result:", c2.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.1") != "one" {
		t.Log("Key: switches.1")
		t.Log("Expected: one")
		t.Log("Result:", c2.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.2") != "two" {
		t.Log("Key: switches.2")
		t.Log("Expected: two")
		t.Log("Result:", c2.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	if c2.String("app.db_database") != "myapp" {
		t.Log("Key: app.db_database")
		t.Log("Expected: myapp")
		t.Log("Result:", c2.String("app.db_database"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.db_username") != "appuser" {
		t.Log("Key: app.db_username")
		t.Log("Expected: appuser")
		t.Log("Result:", c2.String("app.db_username"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.db_password") != "apppass" {
		t.Log("Key: app.db_password")
		t.Log("Expected: apppass")
		t.Log("Result:", c2.String("app.db_password"))
		t.Error("Expected value and result does not match")
	}

	if c2.Bool("app.ssl") != true {
		t.Log("Key: app.ssl")
		t.Log("Expected: true")
		t.Log("Result:", c2.Bool("app.ssl"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.domain") != "www.myapp.com" {
		t.Log("Key: app.domain")
		t.Log("Expected: www.myapp.com")
		t.Log("Result:", c2.String("app.domain"))
		t.Error("Expected value and result does not match")
	}
	if c2.Int("app.port") != 80 {
		t.Log("Key: app.port")
		t.Log("Expected: 80")
		t.Log("Result:", c2.Int("app.port"))
		t.Error("Expected value and result does not match")
	}
}

func TestRelativePathInclude(t *testing.T) {
	c, err := NewConfigurationFromFile("test/test_dir.json")
	if err != nil {
		t.Error("File failed", err)
	}
	if !c.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2",
		"app.db_username", "app.db_password", "app.db_database") {
		t.Error("Keys do not exists")
	} else if c.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	} else if c.Exists("app.__switch__") {
		t.Error("Switch still exists")
	}

	if c.String("version") != "b" {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c.String("branch.key") != "value" {
		t.Log("Key: branch.key")
		t.Log("Expected: value")
		t.Log("Result:", c.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c.Int("branch.int") != 42 {
		t.Log("Key: branch.int")
		t.Log("Expected: 42")
		t.Log("Result:", c.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c.Float64("branch.float") != 32.12 {
		t.Log("Key: branch.float")
		t.Log("Expected: 32.12")
		t.Log("Result:", c.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c.Bool("branch.bool") != true {
		t.Log("Key: branch.bool")
		t.Log("Expected: true")
		t.Log("Result:", c.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.1") != "one" {
		t.Log("Key: switches.1")
		t.Log("Expected: one")
		t.Log("Result:", c.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c.String("switches.2") != "two" {
		t.Log("Key: switches.2")
		t.Log("Expected: two")
		t.Log("Result:", c.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	if c.String("app.db_database") != "myapp" {
		t.Log("Key: app.db_database")
		t.Log("Expected: myapp")
		t.Log("Result:", c.String("app.db_database"))
		t.Error("Expected value and result does not match")
	}
	if c.String("app.db_username") != "appuser" {
		t.Log("Key: app.db_username")
		t.Log("Expected: appuser")
		t.Log("Result:", c.String("app.db_username"))
		t.Error("Expected value and result does not match")
	}
	if c.String("app.db_password") != "apppass" {
		t.Log("Key: app.db_password")
		t.Log("Expected: apppass")
		t.Log("Result:", c.String("app.db_password"))
		t.Error("Expected value and result does not match")
	}

	if c.Bool("app.ssl") != true {
		t.Log("Key: app.ssl")
		t.Log("Expected: true")
		t.Log("Result:", c.Bool("app.ssl"))
		t.Error("Expected value and result does not match")
	}
	if c.String("app.domain") != "www.myapp.com" {
		t.Log("Key: app.domain")
		t.Log("Expected: www.myapp.com")
		t.Log("Result:", c.String("app.domain"))
		t.Error("Expected value and result does not match")
	}
	if c.Int("app.port") != 80 {
		t.Log("Key: app.port")
		t.Log("Expected: 80")
		t.Log("Result:", c.Int("app.port"))
		t.Error("Expected value and result does not match")
	}

	c2, err := NewConfigurationFromFile("test_e.json")
	if err != nil {
		t.Error("File failed", err)
	}
	if !c2.Exists("name", "version", "branch", "branch.key", "switches", "switches.1", "switches.2",
		"app.db_username", "app.db_password", "app.db_database") {
		t.Error("Keys do not exists")
	} else if c2.Exists("switches.__switch__") {
		t.Error("Switch still exists")
	} else if c2.Exists("app.__switch__") {
		t.Error("Switch still exists")
	}

	if c2.String("version") != "b" {
		t.Log("Key: version")
		t.Log("Expected: b")
		t.Log("Result:", c2.String("version"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("branch.key") != "value" {
		t.Log("Key: branch.key")
		t.Log("Expected: value")
		t.Log("Result:", c2.String("branch.key"))
		t.Error("Expected value and result does not match")
	}
	if c2.Int("branch.int") != 42 {
		t.Log("Key: branch.int")
		t.Log("Expected: 42")
		t.Log("Result:", c2.Int("branch.int"))
		t.Error("Expected value and result does not match")
	}
	if c2.Float64("branch.float") != 32.12 {
		t.Log("Key: branch.float")
		t.Log("Expected: 32.12")
		t.Log("Result:", c2.Float64("branch.float"))
		t.Error("Expected value and result does not match")
	}
	if c2.Bool("branch.bool") != true {
		t.Log("Key: branch.bool")
		t.Log("Expected: true")
		t.Log("Result:", c2.Bool("branch.bool"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.1") != "one" {
		t.Log("Key: switches.1")
		t.Log("Expected: one")
		t.Log("Result:", c2.String("switches.1"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("switches.2") != "two" {
		t.Log("Key: switches.2")
		t.Log("Expected: two")
		t.Log("Result:", c2.String("switches.2"))
		t.Error("Expected value and result does not match")
	}

	if c2.String("app.db_database") != "myapp" {
		t.Log("Key: app.db_database")
		t.Log("Expected: myapp")
		t.Log("Result:", c2.String("app.db_database"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.db_username") != "appuser" {
		t.Log("Key: app.db_username")
		t.Log("Expected: appuser")
		t.Log("Result:", c2.String("app.db_username"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.db_password") != "apppass" {
		t.Log("Key: app.db_password")
		t.Log("Expected: apppass")
		t.Log("Result:", c2.String("app.db_password"))
		t.Error("Expected value and result does not match")
	}

	if c2.Bool("app.ssl") != true {
		t.Log("Key: app.ssl")
		t.Log("Expected: true")
		t.Log("Result:", c2.Bool("app.ssl"))
		t.Error("Expected value and result does not match")
	}
	if c2.String("app.domain") != "www.myapp.com" {
		t.Log("Key: app.domain")
		t.Log("Expected: www.myapp.com")
		t.Log("Result:", c2.String("app.domain"))
		t.Error("Expected value and result does not match")
	}
	if c2.Int("app.port") != 80 {
		t.Log("Key: app.port")
		t.Log("Expected: 80")
		t.Log("Result:", c2.Int("app.port"))
		t.Error("Expected value and result does not match")
	}
}


text:
/*
 * Created on Dec 23, 2003
*/
package net.sf.jolene.dom;

import net.sf.jolene.constants.Prefs;
import net.sf.jolene.constants.Tags;

import java.util.*;

/**
 * A Select in an html document.
 *
 * @author Dan Howard
 */

public final class Select extends HTMLElement {

    private boolean multiple;

    // Not public because we don't want the user to access the arraylist directly.
    // The only way to add a new option is to use the addOption method.
    List<Option> options = new ArrayList<Option>(3);

    /**
     * Default constructor.
     */
    public Select() {
        tag = Tags.select;
        multiple = false;
    }

    /**
     * Construct a select with the specified name.
     *
     * @param name name of the select.
     */
    public Select(String name) {
        this();
        setName(name);
    }

    /**
     * This method adds a new option to the available options for the select object.
     *
     * @param option An option object to add to the select list
     * @return int - the new size of the option list.
     */
    public int addOption(Option option) {
        int index = -1;
        //option.parent = this;

        StringTokenizer st = new StringTokenizer(getValue(), Prefs.SelectValueSeperator.getValue());
        String itemValue;
        while (st.hasMoreTokens()) {
            itemValue = st.nextToken();
            if (itemValue.equals(option.getValue())) {
                option.setSelected(true);
            }
        }

        options.add(option);
        index = options.size();
        return index;
    }

    /**
     * Clears the list of options on the select.
     */
    public void clearOptions() {
        options.clear();
    }

    /**
     * Returns a cloneElement of the select object.
     *
     * @return Select object.
     */
    @Override
    public Select cloneElement() {
        Select select = new Select();
        cloneProperties(this, select);
        cloneAttributes(this,select);

        for (int j = 0; j < options.size(); j++) {
            select.addOption(new Option(options.get(j).getValue(), options.get(j).getText()));
        }
        select.setValue(getValue());
        return select;
    }

    /**
     * Returns the specified option object by the numeric index.
     *
     * @param index the index of the option to retrive
     * @return Option object.
     */
    public Option options(int index) {
        return options.get(index);
    }

    /**
     * Gets the value of the select object.
     *
     * @return value of the select object.
     */
    @Override
    public String getValue() {
        String selectValue = super.getValue();

        // Ensure that exisiting options are flagged properly.
        setValue(selectValue);

        String value = "";

        // Loop through the options and add the values of the 'selected' options
        // to the value string + commas...
        String sep = Prefs.SelectValueSeperator.getValue();
        for (int j = 0; j < options.size(); j++) {
            Option option = options.get(j);

            if (option.isSelected()) {
                value += option.getValue() + sep;
            }
        }

        // Strip last comma
        int n = value.lastIndexOf(",");
        if (n > -1) {
            value = value.substring(0, n);
        }

        if (value.trim().length() == 0 && selectValue.trim().length() > 0) {
            // If there was no value found in the options list but the user
            // had set a value in the select object itself then return that
            // value but log a warning.
            value = selectValue;
            log.warn("Returning Select object " + getName() + " assigned value: " + value + " which does not exist in the options list.");
        }
        return value;
    }

    /**
     * Indicates if the select is a multiple select.
     *
     * @return mulitple
     */
    public boolean isMultiple() {
        return multiple;
    }

    /**
     * Set the name of the select object.
     *
     * @param name name of the select object.
     */
    @Override
    public void setName(String name) {
        super.setName(name);
        setAttribute("name", name);
    }

    /**
     * Sets if this select is a multiple select.
     *
     * @param multiple boolean.
     */
    public void setMultiple(boolean multiple) {

        this.multiple = multiple;
        if (multiple) {
            setAttribute("multiple", "multiple");
        } else {
            removeAttribute("multiple");
        }
    }

    /**
     * Sets the value for the select object. The value to  assign
     * may be a single value or multiple values seperate by a comma.
     *
     * @param value String value to set.
     */
    @Override
    public void setValue(String value) {
        super.setValue(value);

        // locate the 1st option whose itemValue = value
        // If multi-select value could be comma seperated?
        for (int j = 0; j < options.size(); j++) {

            Option option = options.get(j);

            option.setSelected(false);

            StringTokenizer st = new StringTokenizer(value, Prefs.SelectValueSeperator.getValue());
            while (st.hasMoreTokens()) {
                String itemValue = st.nextToken();
                String optionValue = option.getValue();

                if (optionValue.equals(itemValue)) {
                    option.setSelected(true);
                    break;
                }
            }
        }

    }

    /**
     * Sort the options on the select.
     */
    public void sortOptions() {
        Collections.sort(options, new Comparator<Option>() {

            public int compare(Option o1, Option o2) {
                String s1 = o1.getText();
                String s2 = o2.getText();
                return s1.compareTo(s2);
            }
        });
    }

    /**
     * Renders the select.
     *
     * @return The select as a html string.
     */
    @Override
    public String toString() {

        if (swapWith != null) {
            return swapWith;
        }

        if (!isRenderable() && !log.isDebugEnabled()) {
            return "";
        }

        // Used to ensure options are initialized properly.
        getValue();

        StringBuilder sb = new StringBuilder(super.toString());
        for (int j = 0; j < options.size(); j++) {
            sb.append(options.get(j).toString());
        }
        String ls = System.getProperty("line.separator");
        sb.append(ls);
        sb.append("</").append(tag).append(">");
        sb.append(ls);
        return sb.toString();
    }
}


text:
for key in $(ls ~/.ssh/ | grep identity | grep -v pub); do
  ssh-add ~/.ssh/$key;
done


text:
package CF1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//http://codeforces.com/problemset/problem/1/B

//not finished -> not ac

public class Spreadsheets1B {

    public static void main(String[] args) {
        //Scanner scanner = null;
        //try {
        //    scanner = new Scanner(new FileInputStream("sample/test1a.txt"));
        //} catch (FileNotFoundException e) {
        //    e.printStackTrace();
        //}
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        String cell = "";
        while (n-- > 0) {
            cell = scanner.next().trim();
            //System.out.println("cell: " + cell);
            if (cell.indexOf("R") >= 0) {
                convertRCtoAZ(cell);
            } else {
                convertAZtoRC(cell);
            }
        }
    }

    private static void convertAZtoRC(String cell) {
        Pattern pattern = Pattern.compile("[A-Z]+");
        Matcher matcher = pattern.matcher(cell);
        String col = "", row = "";
        if (matcher.find()) {
            col = cell.substring(matcher.start(), matcher.end());
            row = cell.substring(matcher.end());
        }
        int sum = 0, a = 0;
        for (int i = col.length() - 1, j = 0; i >= 0; i--, j++) {
            a = col.charAt(i) - 'A' + 1;
            sum = sum + (int) (Math.pow(26.0, j) * a);
        }
        System.out.println("R" + row + "C" + String.valueOf(sum));
    }

    private static void convertRCtoAZ(String cell) {
        int row = Integer.valueOf(cell.substring(1, cell.indexOf("C")));
        int col = Integer.valueOf(cell.substring(cell.indexOf("C") + 1));
        System.out.println(convertIntToLetter(col) + String.valueOf(row));
    }

    // 55 -> BC base=26
    private static String convertIntToLetter(int col) {
        Stack stack = new Stack();
        StringBuffer result = new StringBuffer("");
        int d=col, r=0, k=1;
        while (d >= 26) {
            r = d % 26;
            d = d / 26;
            if (r == 0) {
                d = d - 1;
                stack.push("Z");
            } else {
                stack.push(String.valueOf((char) (r + 'A' - 1)));
            }
        }
        if (d!=0){
            stack.push(String.valueOf((char) (d + 'A' - 1)));
        }
        while (!stack.empty()) {
            result.append(stack.pop());
        }
        return result.toString();
    }

}


text:
from ExpressionBuilder import ExpressionBuilder

def main():
    expr_str = "-2*(3+(4/2))"
    b  = ExpressionBuilder(expr_str)
    e = b.GetExpression()
    print ("Expression in String: %s " % expr_str)
    print ("AST: %s" % e)
    print ("Result: %d" % e.Evaluate())

if __name__ == "__main__":
    main()


text:
layout: post
section-type: post
title: Javascript variables
categories: ['programming']
tags: [ 'javascript']
---

# Javascript

![Javascript](/img/javascript.png)

# Journey Into Javascript

## Variables

- Declaration and assignment
- Referencing primitive values
- Variables rules
- Good naming conventions
- Bad naming conventions
- Example use cases

**Variable Declaration**
//Proper Declaration
> var name = 'Stevie Nicks';
> var song = 'Edge of Seventeen';

var name is the *Declaration*
'Stevie Nicks' is the *Assignment*

//Never Use
> newName = 'Eddie Money';
> newSong = 'take me home tonight';

This is a Bad convention: 'new___'

//Don't Use ( for now )
> window.newername = 'Charlie Parker';
> window.newerSong = 'Early in the morning';

**Rules and Conventions**
Declare and assign at the top of your scope/code
> var favBand = 'Earth,Wind and Fire';
> var favSong = 'Fantasy';
> console.log(favBand, favSong);

Good Examples ( Declarations Only )
> var songsArray; //Descriptive of the reference
> var artistName; //Single word
> var templeOfTheDog; //'camelCase': hungryHungryHungry

Bad Examples ( Declarations Only )
> var SongTitles; //Start with lowercase
> var tracknumber; //Use camelCase
> var newArray; //Of What?
> var &no$yb@ls; // Code will break

// Words not to use ( your code will break ):
// > var new, var, in, function, String, Number, break, typeof...
// Basically, If your editor highlights the word, don't use it!

> var firstName = 'David'; //Slot 1
> var lastname = 'Bowie'; //Slot 2
> firstNameAgain = firstName; //Slot 3

What is Javascript doing?
> firstName = 001;
> lastname = 002;
> firstNameAgain = 003;

*Variable Usage*

//Proper Declaration
> var firstName = 'Stevie';
> var lastname = 'Wonder';

//We want his full name
> firstName + lastName; // 'Stevie' + 'Wonder' = 'StevieWonder'

//Fix the formatting
> firstName + ' ' + lastname; // 'Stevie' + ' ' + 'Wonder' = 'Stevie Wonder'

//Print the fullName
> console.log(fullname); //???  Reference Error

//Declare before using
> var fullname = 'Scott Weiland';  //001
> var firstname = fullname.split(' ')[0]; //002

> console.log(fullname); //'Scott Weiland'  001
> console.log(firstname); //'Scott'  002

//What's going to happen?
> console.log(stoneTemplePilots); //undefined

'Declared' or 'namespaced' but not 'defined' before it's used.
Hence 'undefined'
> var stoneTemplePilots = fullname; // 'Scott Weiland' - Makes a copy for 'primitive' types  003

//Overwriting
> var fullName = 'Stone Temple Pilots'; // 004
> console.log(fullname); // 'Stone Temple Pilots' 004

**Variables - Key takeaways**
- Variables allow us to re-use values
- They just point to a value in memory
- Values don't depend on them, we do
- Use good, descriptive names
- What is an 'undefined' variable
- Declare variables before using them
- Always use the 'var' keyword when declaring

**Vocabulary**
- Declaration
- Assignment
- Hoisting
- namespace


text:
<?php

namespace Drupal\views\Plugin\views;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides an interface for all views handlers.
 */
interface ViewsHandlerInterface extends ViewsPluginInterface {

  /**
   * Run before the view is built.
   *
   * This gives all the handlers some time to set up before any handler has
   * been fully run.
   */
  public function preQuery();

  /**
   * Determines the entity type used by this handler.
   *
   * If this handler uses a relationship, the base class of the relationship is
   * taken into account.
   *
   * @return string
   *   The machine name of the entity type.
   */
  public function getEntityType();

  /**
   * Determines if the handler is considered 'broken', meaning it's a
   * placeholder used when a handler can't be found.
   */
  public function broken();

  /**
   * Ensure the main table for this handler is in the query. This is used
   * a lot.
   */
  public function ensureMyTable();

  /**
   * Check whether given user has access to this handler.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user account to check.
   *
   * @return bool
   *   TRUE if the user has access to the handler, FALSE otherwise.
   */
  public function access(AccountInterface $account);

  /**
   * Get the join object that should be used for this handler.
   *
   * This method isn't used a great deal, but it's very handy for easily
   * getting the join if it is necessary to make some changes to it, such
   * as adding an 'extra'.
   */
  public function getJoin();

  /**
   * Sanitize the value for output.
   *
   * @param $value
   *   The value being rendered.
   * @param $type
   *   The type of sanitization needed. If not provided,
   *   \Drupal\Component\Utility\Html::escape() is used.
   *
   * @return \Drupal\views\Render\ViewsRenderPipelineMarkup
   *   Returns the safe value.
   */
  public function sanitizeValue($value, $type = NULL);

  /**
   * Fetches a handler to join one table to a primary table from the data cache.
   *
   * @param string $table
   *   The table to join from.
   * @param string $base_table
   *   The table to join to.
   *
   * @return \Drupal\views\Plugin\views\join\JoinPluginBase
   */
  public static function getTableJoin($table, $base_table);

  /**
   * Shortcut to get a handler's raw field value.
   *
   * This should be overridden for handlers with formulae or other
   * non-standard fields. Because this takes an argument, fields
   * overriding this can just call return parent::getField($formula)
   */
  public function getField($field = NULL);

  /**
   * Run after the view is executed, before the result is cached.
   *
   * This gives all the handlers some time to modify values. This is primarily
   * used so that handlers that pull up secondary data can put it in the
   * $values so that the raw data can be used externally.
   */
  public function postExecute(&$values);

  /**
   * Shortcut to display the exposed options form.
   */
  public function showExposeForm(&$form, FormStateInterface $form_state);

  /**
   * Called just prior to query(), this lets a handler set up any relationship
   * it needs.
   */
  public function setRelationship();

  /**
   * Return a string representing this handler's name in the UI.
   */
  public function adminLabel($short = FALSE);

  /**
   * Breaks x,y,z and x+y+z into an array.
   *
   * @param string $str
   *   The string to split.
   * @param bool $force_int
   *   Enforce a numeric check.
   *
   * @return object
   *   A stdClass object containing value and operator properties.
   */
  public static function breakString($str, $force_int = FALSE);

  /**
   * Provide text for the administrative summary.
   */
  public function adminSummary();

}


text:
import '../client/crud/meteorInsert.spec.js'
import '../client/crud/meteorRemove.spec.js'
import '../client/crud/meteorUpdate.spec.js'
import '../client/meteorDatasource.spec.js'
import '../client/meteorMethod.spec.js'
import '../client/meteorSubscription.spec.js'


text:
    <title>Product List - Page 2</title>
    <meta name="description" content="Product listing page">
    <meta name="keywords" content="">
    <link href="css/bootstrap-flatly.css" rel="stylesheet">

Home

Product List - Page 2

Page: 1  2 3

Product Seven

$9.99

You think water moves fast? You should see ice. It moves like it has a mind. Like it knows it killed the world once and got a taste for murder. After the avalanche, it took us a week to climb out. Now, I don't know exactly when we turned on each other, but I know that seven of us survived the slide... and only five made it out.

Product Eight

$14.98

Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit? It actually says that in the little book that comes with it: the most popular gun in American crime. Like they're actually proud of that shit.

Product Nine

$18.00 - $34.99

Normally, both your asses would be dead as fucking fried chicken, but you happen to pull this shit while I'm in a transitional period so I don't wanna kill you, I wanna help you. But I can't give you this case, it don't belong to me. Besides, I've already been through too much shit this morning over this case to hand it over to your dumb ass.

Product Ten

$11.99 - $16.00

Now that we know who you are, I know who I am. I'm not a mistake! It all makes sense! In a comic, you know how you can tell who the arch-villain's going to be? He's the exact opposite of the hero. And most times they're friends, like you and me! I should've known way back when... You know why, David? Because of the kids. They called me Mr. Glass.

Product Eleven

$1.82 - $7.99

Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.

Product Twelve

$8.99

Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb.

© 2016 - Robert W. Dempsey All Rights Reserved

These pages were created for the Web Scraping and Data Mining Course


text:
require 'simple_spec_helper'

class WithLolitaExtensions
  include Lolita::Extensions
end

module Lolita::Extensions::Test
  class Proxy
    def initialize *args
    end
  end
end

describe Lolita::Extensions do
  let(:test_class){ WithLolitaExtensions.new }
  let(:object){
    klass = Object.new
    klass.class_eval{include Lolita::Extensions}
    klass
  }

  it "should load all extensions proxies" do
    Lolita::Extensions.add(:test)
    test_class.load_extensions_proxies(object)
    test_class.test_proxy.should be_a(Lolita::Extensions::Test::Proxy)
  end

  context "default extensions" do
    it "should have default extensions proxies" do
      test_class.load_extensions_proxies(object)
      Lolita::Extensions::EXTENSIONS.each do |name|
        test_class.send(:"#{name}_proxy").should be_a("Lolita::Extensions::#{name.to_s.camelize}::Proxy".constantize)
      end
    end
  end

  context "default configuration" do

    it "should have authentication adapter" do
      test_class.load_extensions_proxies(object)
      test_class.authentication_proxy.respond_to?(:adapter).should be_truthy
    end

  end
end


text:
<?php

namespace Netatmo\API\PHP\Common;

class WifiRssiThreshold
{
    const RSSI_THRESHOLD_0 = 86;/*bad signal*/
    const RSSI_THRESHOLD_1 = 71;/*middle quality signal*/
    const RSSI_THRESHOLD_2 = 56;/*good signal*/
}


text:
package com.flying.promotion.socket.client.exceptions;

public class ExitException extends RuntimeException {

	private static final long serialVersionUID = -6091789652946138177L;

}


text:
"use strict";

var cluster = require('cluster');
var log4js = require('../log4js');

/**
 * Takes a loggingEvent object, returns string representation of it.
 */
function serializeLoggingEvent(loggingEvent) {
	// JSON.stringify(new Error('test')) returns {}, which is not really useful for us.
	// The following allows us to serialize errors correctly.
	for (var i = 0; i < loggingEvent.data.length; i++) {
		var item = loggingEvent.data[i];
		if (item && item.stack && JSON.stringify(item) === '{}') {
			// Validate that we really are in this case
			loggingEvent.data[i] = { stack: item.stack };
		}
	}
	return JSON.stringify(loggingEvent);
}

/**
 * Takes a string, returns an object with
 * the correct log properties.
 *
 * This method has been "borrowed" from the `multiprocess` appender
 * by `nomiddlename` (https://github.com/nomiddlename/log4js-node/blob/master/lib/appenders/multiprocess.js)
 *
 * Apparently, node.js serializes everything to strings when using `process.send()`,
 * so we need smart deserialization that will recreate log date and level for further processing by log4js internals.
 */
function deserializeLoggingEvent(loggingEventString) {

	var loggingEvent;

	try {

		loggingEvent = JSON.parse(loggingEventString);
		loggingEvent.startTime = new Date(loggingEvent.startTime);
		loggingEvent.level = log4js.levels.toLevel(loggingEvent.level.levelStr);
		// Unwrap serialized errors
		for (var i = 0; i < loggingEvent.data.length; i++) {
			var item = loggingEvent.data[i];
			if (item && item.stack) {
				loggingEvent.data[i] = item.stack;
			}
		}
	} catch (e) {

		// JSON.parse failed, just log the contents probably a naughty.
		loggingEvent = {
			startTime: new Date(),
			categoryName: 'log4js',
			level: log4js.levels.ERROR,
			data: ['Unable to parse log:', loggingEventString]
		};
	}
	return loggingEvent;
}

/**
 * Creates an appender.
 *
 * If the current process is a master (`cluster.isMaster`), then this will be a "master appender".
 * Otherwise this will be a worker appender, that just sends loggingEvents to the master process.
 *
 * If you are using this method directly, make sure to provide it with `config.actualAppenders` array
 * of actual appender instances.
 *
 * Or better use `configure(config, options)`
 */
function createAppender(config) {

	if (cluster.isMaster) {

		var masterAppender = function masterAppender(loggingEvent) {

			if (config.actualAppenders) {
				var size = config.actualAppenders.length;
				for (var i = 0; i < size; i++) {
					if (!config.appenders[i].category || config.appenders[i].category === loggingEvent.categoryName) {
						// Relying on the index is not a good practice but otherwise the change would have been bigger.
						config.actualAppenders[i](loggingEvent);
					}
				}
			}
		};

		// Listen on new workers
		cluster.on('fork', function (worker) {

			worker.on('message', function (message) {
				if (message.type && message.type === '::log-message') {
					// console.log("master : " + cluster.isMaster + " received message: " + JSON.stringify(message.event));

					var loggingEvent = deserializeLoggingEvent(message.event);

					// Adding PID metadata
					loggingEvent.pid = worker.process.pid;
					loggingEvent.cluster = {
						master: process.pid,
						worker: worker.process.pid,
						workerId: worker.id
					};

					masterAppender(loggingEvent);
				}
			});
		});

		return masterAppender;
	} else {

		return function (loggingEvent) {
			// If inside the worker process, then send the logger event to master.
			if (cluster.isWorker) {
				// console.log("worker " + cluster.worker.id + " is sending message");
				process.send({ type: '::log-message', event: serializeLoggingEvent(loggingEvent) });
			}
		};
	}
}

function configure(config, options) {

	if (config.appenders && cluster.isMaster) {

		var size = config.appenders.length;
		config.actualAppenders = new Array(size);

		for (var i = 0; i < size; i++) {

			log4js.loadAppender(config.appenders[i].type);
			config.actualAppenders[i] = log4js.appenderMakers[config.appenders[i].type](config.appenders[i], options);
		}
	}

	return createAppender(config);
}

exports.appender = createAppender;
exports.configure = configure;

//# sourceMappingURL=clustered-compiled.js.map


text:
'use strict';

import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
chai.use(sinonChai);
const expect = chai.expect;
import * as sinon from 'sinon';
import * as deviceSubscriptions from '../../../../../src/lib/device/handler/deviceSubscriptions';

describe('./lib/device/handler/deviceSubscriptions.ts', () => {
  describe('deviceAdded', () => {
    it('should use the handler to forward deviceId', () => {
      const deviceId = '42';
      const handler = sinon.stub().resolves();

      return deviceSubscriptions.deviceAdded(handler, deviceId).then((response) => {
        expect(handler).to.have.been.calledWith(deviceId);
        expect(response.success).to.equal(true);
      });
    });
  });

  describe('deviceRemoved', () => {
    it('should use the handler to forward deviceId', () => {
      const deviceId = '42';
      const handler = sinon.stub().resolves();

      return deviceSubscriptions.deviceRemoved(handler, deviceId).then((response) => {
        expect(handler).to.have.been.calledWith(deviceId);
        expect(response.success).to.equal(true);
      });
    });
  });
});