text:
/*****************************************************************************/
/*!
 * \file search_rules.h
 * \brief Abstract proof rules interface to the simple search engine
 *
 * Author: Sergey Berezin
 *
 * Created: Mon Feb 24 14:19:48 2003
 *
 *

 *
 * License to use, copy, modify, sell and/or distribute this software
 * and its documentation for any purpose is hereby granted without
 * royalty, subject to the terms and conditions defined in the \ref
 * LICENSE file provided with this distribution.
 *
 *

 *
 */
/*****************************************************************************/

#ifndef _cvc3__search__search_rules_h_
#define _cvc3__search__search_rules_h_

namespace CVC3 {

  class Theorem;
  class Expr;

/*! \defgroup SE_Rules Proof Rules for the Search Engines
 * \ingroup SE
 */
  //! API to the proof rules for the Search Engines
  /*! \ingroup SE_Rules */
  class SearchEngineRules {
    /*! \addtogroup SE_Rules
     * @{
     */
  public:
    //! Destructor
    virtual ~SearchEngineRules() { }

    /*! Eliminate skolem axioms:
     * Gamma, Delta |- false => Gamma|- false
     * where Delta is a set of skolem axioms {|-Exists(x) phi (x) => phi(c)}
     * and gamma does not contain any of the skolem constants c.
     */
    virtual Theorem eliminateSkolemAxioms(const Theorem& tFalse,
				       const std::vector<Theorem>& delta) = 0;

    // !A |- FALSE ==> |- A
    /*! @brief Proof by contradiction:
      \f[\frac{\Gamma, \neg A \vdash\mathrm{FALSE}}{\Gamma \vdash A}\f]
    */
    /*! \f$\neg A\f$ does not have to be present in the assumptions.
     * \param a is the assumption \e A
     *
     * \param pfFalse is the theorem \f$\Gamma, \neg A \vdash\mathrm{FALSE}\f$
     */
    virtual Theorem proofByContradiction(const Expr& a,
					 const Theorem& pfFalse) = 0;

    // A |- FALSE ==> !A
    /*! @brief Negation introduction:
      \f[\frac{\Gamma, A \vdash\mathrm{FALSE}}{\Gamma\vdash\neg A}\f]
     */
    /*!
     * \param not_a is the formula \f$\neg A\f$.  We pass the negation
     * \f$\neg A\f$, and not just \e A, for efficiency: building
     * \f$\neg A\f$ is more expensive (due to uniquifying pointers in
     * Expr package) than extracting \e A from \f$\neg A\f$.
     *
     * \param pfFalse is the theorem \f$\Gamma, A \vdash\mathrm{FALSE}\f$
     */
    virtual Theorem negIntro(const Expr& not_a, const Theorem& pfFalse) = 0;

    // u1:A |- C, u2:!A |- C  ==>  |- C
    /*! @brief Case split:
      \f[\frac{\Gamma_1, A\vdash C \quad \Gamma_2, \neg A\vdash C}
              {\Gamma_1\cup\Gamma_2\vdash C}\f]
     */
    /*!
     * \param a is the assumption A to split on
     *
     * \param a_proves_c is the theorem \f$\Gamma_1, A\vdash C\f$
     *
     * \param not_a_proves_c is the theorem \f$\Gamma_2, \neg A\vdash C\f$
     */
    virtual Theorem caseSplit(const Expr& a,
			      const Theorem& a_proves_c,
			      const Theorem& not_a_proves_c) = 0;

    // Gamma, A_1,...,A_n |- FALSE ==> Gamma |- (OR !A_1 ... !A_n)
    /*! @brief Conflict clause rule:
      \f[\frac{\Gamma,A_1,\ldots,A_n\vdash\mathrm{FALSE}}
              {\Gamma\vdash\neg A_1\vee\cdots\vee \neg A_n}\f]
     */
    /*!
     * \param thm is the theorem
     * \f$\Gamma,A_1,\ldots,A_n\vdash\mathrm{FALSE}\f$
     *
     * \param lits is the vector of literals Ai.
     * They must be present in the set of assumptions of \e thm.
     *
     * \param gamma FIXME: document this!!
     */
    virtual Theorem conflictClause(const Theorem& thm,
				   const std::vector<Theorem>& lits,
				   const std::vector<Theorem>& gamma) = 0;

    // "Cut" rule: { G_i |- A_i };  G', { A_i } |- B ==> union(G_i)+G' |- B.
    /*! @brief Cut rule:
      \f[\frac{\Gamma_1\vdash A_1\quad\cdots\quad\Gamma_n\vdash A_n
                \quad \Gamma', A_1,\ldots,A_n\vdash B}
              {\bigcup_{i=1}^n\Gamma_i\cup\Gamma'\vdash B}\f]
     */
    /*!
     * \param thmsA is a vector of theorems \f$\Gamma_i\vdash A_i\f$
     *
     * \param as_prove_b is the theorem
     *    \f$\Gamma', A_1,\ldots,A_n\vdash B\f$
     * (the name means "A's prove B")
     */
    virtual Theorem cutRule(const std::vector<Theorem>& thmsA,
			    const Theorem& as_prove_b) = 0;

    // { G_j |- !A_j, j in [1..n]-{i} }
    // G |- (OR A_1 ... A_i ... A_n) ==> G, G_j |- A_i
    /*! @brief  Unit propagation rule:
      \f[\frac{\Gamma_j\vdash\neg A_j\mbox{ for }j\in[1\ldots n]-\{i\}
               \quad \Gamma\vdash A_1\vee\cdots\vee A_n}
              {\bigcup_{j\in[1\ldots n]-\{i\}}\Gamma_j\cup\Gamma\vdash A_i}\f]
     */
    /*!
     * \param clause is the proof of the clause \f$ \Gamma\vdash
     * A_1\vee\cdots\vee A_n\f$
     *
     * \param i is the index (0..n-1) of the literal to be unit-propagated
     *
     * \param thms is the vector of theorems \f$\Gamma_j\vdash\neg
     * A_j\f$ for all literals except Ai
     */
    virtual Theorem unitProp(const std::vector<Theorem>& thms,
			     const Theorem& clause, unsigned i) = 0;

    // { G_j |- !A_j, j in [1..n] } , G |- (OR A_1 ... A_n) ==> FALSE
    /*! @brief "Conflict" rule (all literals in a clause become FALSE)
      \f[\frac{\Gamma_j\vdash\neg A_j\mbox{ for }j\in[1\ldots n]
               \quad \Gamma\vdash A_1\vee\cdots\vee A_n}
              {\bigcup_{j\in[1\ldots n]}\Gamma_j\cup\Gamma
               \vdash\mathrm{FALSE}}\f]
     */
    /*!
     * \param clause is the proof of the clause \f$ \Gamma\vdash
     * A_1\vee\cdots\vee A_n\f$
     *
     * \param thms is the vector of theorems \f$\Gamma_j\vdash\neg
     * A_j\f$
     */
    virtual Theorem conflictRule(const std::vector<Theorem>& thms,
				 const Theorem& clause) = 0;

    // Unit propagation for AND
    virtual Theorem propAndrAF(const Theorem& andr_th,
			       bool left,
			       const Theorem& b_th) = 0;

    virtual Theorem propAndrAT(const Theorem& andr_th,
			       const Theorem& l_th,
			       const Theorem& r_th) = 0;

    virtual void propAndrLRT(const Theorem& andr_th,
			     const Theorem& a_th,
			     Theorem* l_th,
			     Theorem* r_th) = 0;

    virtual Theorem propAndrLF(const Theorem& andr_th,
			       const Theorem& a_th,
			       const Theorem& r_th) = 0;

    virtual Theorem propAndrRF(const Theorem& andr_th,
			       const Theorem& a_th,
			       const Theorem& l_th) = 0;

    // Conflicts for AND
    virtual Theorem confAndrAT(const Theorem& andr_th,
			       const Theorem& a_th,
			       bool left,
			       const Theorem& b_th) = 0;

    virtual Theorem confAndrAF(const Theorem& andr_th,
			       const Theorem& a_th,
			       const Theorem& l_th,
			       const Theorem& r_th) = 0;

    // Unit propagation for IFF
    virtual Theorem propIffr(const Theorem& iffr_th,
			     int p,
			     const Theorem& a_th,
			     const Theorem& b_th) = 0;

    // Conflicts for IFF
    virtual Theorem confIffr(const Theorem& iffr_th,
			     const Theorem& i_th,
			     const Theorem& l_th,
			     const Theorem& r_th) = 0;

    // Unit propagation for ITE
    virtual Theorem propIterIte(const Theorem& iter_th,
				bool left,
				const Theorem& if_th,
				const Theorem& then_th) = 0;

    virtual void propIterIfThen(const Theorem& iter_th,
				bool left,
				const Theorem& ite_th,
				const Theorem& then_th,
				Theorem* if_th,
				Theorem* else_th) = 0;

    virtual Theorem propIterThen(const Theorem& iter_th,
				 const Theorem& ite_th,
				 const Theorem& if_th) = 0;

    // Conflict for ITE
    virtual Theorem confIterThenElse(const Theorem& iter_th,
				     const Theorem& ite_th,
				     const Theorem& then_th,
				     const Theorem& else_th) = 0;

    virtual Theorem confIterIfThen(const Theorem& iter_th,
				   bool left,
				   const Theorem& ite_th,
				   const Theorem& if_th,
				   const Theorem& then_th) = 0;

    // CNF Rules

    //! AND(x1,...,xn) <=> v  |-  CNF[AND(x1,...,xn) <=> v]
    virtual Theorem andCNFRule(const Theorem& thm) = 0;
    //! OR(x1,...,xn) <=> v  |-  CNF[OR(x1,...,xn) <=> v]
    virtual Theorem orCNFRule(const Theorem& thm) = 0;
    //! (x1 => x2) <=> v  |-  CNF[(x1 => x2) <=> v]
    virtual Theorem impCNFRule(const Theorem& thm) = 0;
    //! (x1 <=> x2) <=> v  |-  CNF[(x1 <=> x2) <=> v]
    virtual Theorem iffCNFRule(const Theorem& thm) = 0;
    //! ITE(c, x1, x2) <=> v  |-  CNF[ITE(c, x1, x2) <=> v]
    virtual Theorem iteCNFRule(const Theorem& thm) = 0;
    //! ITE(c, f1, f2) |- (NOT c OR f1) AND (c OR f2)
    virtual Theorem iteToClauses(const Theorem& ite) = 0;
    //! e1 <=> e2 |- (NOT e1 OR e2) AND (e1 OR NOT e2)
    virtual Theorem iffToClauses(const Theorem& iff) = 0;

    virtual Theorem satProof(const Expr& queryExpr, const Proof& satProof) = 0;

    /*! @} */ // end of SE_Rules
  }; // end of class SearchEngineRules

} // end of namespace CVC3

#endif


text:
var git = require('../lib/git');

module.exports = function (options, cb) {
    if (!options.branch) { return cb(); }

    git.branch({
        branch   : options.branch
      , create   : true
      , checkout : true
    }, cb);
};

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace FileMove
{
    class Setting
    {
        public string From { get; set; }
        public string To { get; set; }
        public string[] Extentions { get; set; }
        public bool IsCopy { get; set; }

        public Setting(string from, string to, string extentions, string copy)
        {
            this.From = from;
            this.To = to;
            this.Extentions = extentions.Split(',');
            this.IsCopy = (copy == "True");
        }
    }

    class FileMove
    {
        public static void Main(string[] args)
        {
            var settings = from setting in XElement.Load("setting.xml").Elements()
                           select new Setting(setting.Element("from").Value,
                               setting.Element("to").Value, setting.Element("extentions").Value,
                               setting.Element("copy").Value);

            foreach (var setting in settings)
            {
                DoMoveFiles(setting);
            }
        }

        public static void DoMoveFiles(Setting setting)
        {
            checkSetting(setting);

            foreach (string file in Directory.GetFiles(setting.From))
            {
                string extention = Path.GetExtension(file).ToLower();

                if (setting.Extentions.Contains(extention) == false)
                    continue;

                string fileName = Path.GetFileName(file);
                string moveToFileName = determineFilename(setting.To + fileName);

                if (setting.IsCopy)
                {
                    File.Copy(file, moveToFileName);
                    Console.WriteLine(fileName + " has been copied!");
                }
                else
                {
                    File.Move(file, moveToFileName);
                    Console.WriteLine(fileName + " has been moved!");
                }
            }

            Console.WriteLine(" ");
        }

        private static void checkSetting(Setting setting)
        {
            if (Directory.Exists(setting.From) == false)
                throw new ApplicationException("Fromディレクトリが存在しません。");

            if (Directory.Exists(setting.To) == false)
                throw new ApplicationException("Toディレクトリが存在しません。");
        }

        private static string determineFilename(string filename)
        {
            string fileBody, fileExt;
            parseFilename(filename, out fileBody, out fileExt);

            int count = 0;
            while (File.Exists(filename))
            {
                count++;
                filename = fileBody + "_" + count.ToString() + fileExt;
            }
            return filename;
        }

        private static void parseFilename(string filename, out string body, out string ext)
        {
            int dotIndex = filename.LastIndexOf(".");
            if (dotIndex > 0)
            {
                body = filename.Substring(0, dotIndex);
                ext = filename.Substring(dotIndex,
                filename.Length - dotIndex);
            }
            else
            {
                body = filename;
                ext = string.Empty;
            }
        }
    }
}


text:
Rails.application.routes.draw do
  mount DtuBlacklightCommon::Engine, at: '/'
  devise_for :users
  get 'messages/new'

  get 'messages/create'

  get 'messages/message_params'

  scope "(:locale)", :locale => /en|da/ do

    get 'open_access/overview', to: 'open_access_indicator#overview'
    get 'open_access/development', to: 'open_access_indicator#development'
    get 'open_access/reports', to: 'open_access_indicator#reports'
    get 'open_access', to: 'open_access_indicator#overview'
    get '/selected', to: 'bookmarks#index'

    get 'statistics', to: 'statistics#index'

    # root :to => "catalog#index"
    # blacklight_for :catalog
    # root to: "catalog#index"
    blacklight_for :catalog
    # The priority is based upon order of creation: first created -> highest priority.
    # See how all your routes lay out with "rake routes".

    get 'citations/new', as: 'new_citations'
    get 'citations/preview', as: 'preview_citations'
    post 'citations/send', to: 'citations#send_citations', as: 'send_citations'
    # You can have the root of your site routed with "root"
  root 'pages#index'
  # For the visualization dataset. Use another URL (end path) than 'data':
  # get 'pages/data', :defaults => { :format => 'json' }

  # SEARCH
  # Don't do a 301 redirect:
  # get '/search', to: redirect('/')
  # get '/catalog', to: redirect('/')

  get '/search', to: 'pages#index'
  get '/catalog', to: 'pages#index'

  # ELITEFORSK AWARD
  get '/eliteforsk-award' => 'pages#eliteforsk_award'

  # ABOUT
  get 'about' => 'pages#about'
  get 'about/search-and-get' => 'pages#search_and_get'

  # get 'about/indicators' => 'pages#indicators'
  # get 'about/actuality' => 'pages#actuality'

  get 'about/data' => 'pages#data'
  get 'about/faq' => 'pages#faq'
  get 'about/contact' => 'pages#contact'
  get 'about/releases' => 'pages#releases'
  get 'about/privacy' => 'pages#privacy'

  get 'about/data/providers' => 'pages#data_providers'

  # OTHER
  get 'pattern-library' => 'pages#pattern_library'

  # FEEDBACK
  get 'contact', to: 'messages#new', as: 'contact'
  post 'contact', to: 'messages#create'

  # ROBOTS
  get '/robots', to: 'pages#robots'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
  end
end


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/recommender/v1/recommender_service.proto

namespace Google\Cloud\Recommender\V1;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Request for the GetInsightTypeConfig` method.
 *
 * Generated from protobuf message google.cloud.recommender.v1.GetInsightTypeConfigRequest
 */
class GetInsightTypeConfigRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. Name of the InsightTypeConfig to get.
     * Acceptable formats:
     * * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     */
    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     *           Required. Name of the InsightTypeConfig to get.
     *           Acceptable formats:
     *           * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     *           * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     *           * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Cloud\Recommender\V1\RecommenderService::initOnce();
        parent::__construct($data);
    }

    /**
     * Required. Name of the InsightTypeConfig to get.
     * Acceptable formats:
     * * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Required. Name of the InsightTypeConfig to get.
     * Acceptable formats:
     * * `projects/[PROJECT_NUMBER]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `projects/[PROJECT_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     * * `organizations/[ORGANIZATION_ID]/locations/global/recommenders/[INSIGHT_TYPE_ID]/config`
     *
     * Generated from protobuf field string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = {
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}


text:
namespace QI4N.Framework.Runtime
{
    using System;

    public class StructureInjectionProvider : InjectionProvider
    {
        //[DebuggerStepThrough]
        ////[DebuggerHidden]
        public object ProvideInjection(InjectionContext context, InjectionAttribute attribute, Type fieldType)
        {
            if (fieldType == typeof(TransientBuilderFactory))
            {
                return context.ModuleInstance.TransientBuilderFactory;
            }
            if (fieldType == typeof(ObjectBuilderFactory))
            {
                return context.ModuleInstance.ObjectBuilderFactory;
            }
            if (fieldType == typeof(ValueBuilderFactory))
            {
                return context.ModuleInstance.ValueBuilderFactory;
            }
            if (fieldType == typeof(UnitOfWorkFactory))
            {
                return context.ModuleInstance.UnitOfWorkFactory;
            }
            if (fieldType == typeof(ServiceFinder))
            {
                return context.ModuleInstance.ServiceFinder;
            }
            if (fieldType == typeof(ModuleInstance))
            {
                return context.ModuleInstance;
            }
            if (fieldType == typeof(Layer))
            {
                return context.ModuleInstance.LayerInstance;
            }
            if (fieldType == typeof(Application))
            {
                return context.ModuleInstance.LayerInstance.ApplicationInstance;
            }
            //else if( typeof( Qi4j) ) || typeof( Qi4jSPI) )
            //{
            //    return context.ModuleInstance.layerInstance().applicationInstance().runtime();
            //}

            return null;
        }
    }
}


text:
<link rel="stylesheet" type="text/css" href="styles/global.css">
<link rel="stylesheet" type="text/css" href="styles/header.css">
<link rel="stylesheet" type="text/css" href="styles/footer.css">
<!-- Google Fonts: Open Sans -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<!-- Google Fonts: Aldrich -->
<link href='http://fonts.googleapis.com/css?family=Aldrich' rel='stylesheet' type='text/css'>

<!-- FAVICONS -->

<!-- Compiled from https://github.com/audreyr/favicon-cheat-sheet -->
<link rel="icon" sizes="16x16 32x32 48x48 64x64" href="favicon/favicon.ico">
<!--[if IE]><link rel="shortcut icon" href="favicon/favicon.ico"><![endif]-->

<!-- Touch icon for iOS 2.0+ and Android 2.1+: -->
<link rel="apple-touch-icon-precomposed" href="http://www.yourwebsite.com/favicon-152.png">
<!-- IE 10 Metro tile icon (Metro equivalent of apple-touch-icon): -->
<meta name="msapplication-TileColor" content="#FFFFFF">
<meta name="msapplication-TileImage" content="favicon/favicon-144.png">
<!-- For iPad with high-resolution Retina display running iOS ≥ 7: -->
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="favicon/favicon-152.png">
<!-- For iPad with high-resolution Retina display running iOS ≤ 6: -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="favicon/favicon-144.png">
<!-- For iPhone with high-resolution Retina display running iOS ≥ 7: -->
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="favicon/favicon-120.png">
<!-- For iPhone with high-resolution Retina display running iOS ≤ 6: -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="favicon/favicon-114.png">
<!-- For first- and second-generation iPad: -->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="favicon/favicon-72.png">
<!-- For non-Retina iPhone, iPod Touch, and Android 2.1+ devices: -->
<link rel="apple-touch-icon-precomposed" href="favicon/favicon-57.png">


text:
package com.github.mob41.osumer.daemon;

import com.github.mob41.osumer.Configuration;
import com.github.mob41.osumer.OsumerNative;
import com.github.mob41.osumer.debug.DebugDump;
import com.github.mob41.osumer.debug.DumpManager;

public class OverlayThread extends Thread{

	private final Configuration config;

	public OverlayThread(Configuration config) {
		super();
		this.config = config;
	}

	@Override
	public void run() {
		while (!this.isInterrupted()) {
			if (config.isOverlayEnabled()) {
				try {
					OsumerNative.injectOverlay();
				} catch (Throwable e) {
					DumpManager.addDump(new DebugDump(null, "Check is overlay enabled in configuration", "Ask native DLL to look for osu! for injection", "Sleep for 2500 ms", "Error calling DLL", false, e));
					break;
				}
			}

			try {
				Thread.sleep(2500);
			} catch (InterruptedException ignore) {
				break;
			}
		}
	}

}


text:
from typing import Dict, TYPE_CHECKING
import torch

from allennlp.training.callbacks.callback import TrainerCallback

if TYPE_CHECKING:
    from allennlp.training.gradient_descent_trainer import GradientDescentTrainer

@TrainerCallback.register("mixed_precision_backward")
class MixedPrecisionBackwardCallback(TrainerCallback):
    """
    Performs backpropagation for mixed precision training.
    """

    def on_backward(
        self,
        trainer: "GradientDescentTrainer",
        batch_outputs: Dict[str, torch.Tensor],
        backward_called: bool,
        **kwargs
    ) -> bool:
        if backward_called:
            raise OnBackwardException()
        trainer._scaler.scale(batch_outputs["loss"]).backward()  # type: ignore
        return True

class OnBackwardException(Exception):
    """
    The exception type raised if an `on_backward` callback
    attempts to call `backward` when `backward_called` is `True`.
    """

    def __init__(self, message="") -> None:
        super().__init__(
            "Backpropagation has already been performed"
            "and the computation graph has been erased, so"
            "calling `loss.backward` is not permitted. " + message
        )


text:
//Using module pattern as explained here: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

var myScripts = (function () {

    return {
        //Checks if the search box in the navigation bar is empty.
        CheckEmptySearchForm: function (word) {
            return (document.getElementById(word).value != "");
        },

        //Sets the scroll bar to the bottom in a box, e.g. in messages
        SetScrollBoxToBottom: function (box) {
            var myDiv = document.getElementById(box);
            myDiv.scrollTop = myDiv.scrollHeight;
        },

        //If you use Flash::overlay('...'), display the alert/modal.
        doModal: function () {
            $('#flash-overlay-modal').modal();
        },

        //Slide up non-important alerts/messages after 3 seconds.
        alertSlideUp: function () {
            $('div.alert').not('.alert-danger').delay(3000).slideUp(300);
        },

        //Initialize the python syntax highlighter
        initPythonSyntax: function () {
            editAreaLoader.init({
                id: "yourcode",          // textarea id
                syntax: "python",        // syntax to be uses for highlighting
                start_highlight: true    // to display with highlight mode on start-up
            });
        },

        changeElementColor: function (id, color) {
            document.getElementById(id).style.color = color;
        },

        changeDataSort: function (id) {
            var s = document.getElementById(id).getAttribute('data-sort');
            var ss = (s.search('asc') > -1) ? s.replace('asc', 'desc') : s.replace('desc', 'asc');
            document.getElementById(id).setAttribute('data-sort', ss);
        },

        switchDataSort: function (id) {
            document.getElementById(id).setAttribute("hidden", true);
            var children = document.getElementById(id).parentNode.childNodes;

            var siblingList = [];
            for (var n = children.length - 1; n >= 0; n--) {
                if (children[n].nodeName == "BUTTON") {
                    var herrderr = children[n].getElementsByTagName("SPAN")[0];
                    herrderr.style.display = "none";
                    siblingList.push(herrderr);
                }
            }

            console.log("hi", siblingList);
            /*document.getElementById(id).removeClass("active");*/
            if (id.search(1) > -1) {
                document.getElementById(id.replace('1', '2')).removeAttribute("hidden");
                document.getElementById(id.replace('1', '2')).getElementsByTagName("SPAN")[0].style.display = "inline";
                //document.getElementById(id.replace('1', '2')).addClass("active");
            } else {
                document.getElementById(id.replace('2', '1')).removeAttribute("hidden");
                document.getElementById(id.replace('2', '1')).getElementsByTagName("SPAN")[0].style.display = "inline";
                /*document.getElementById(s.replace('2', '1')).addClass("active");*/
            }
        },

        initializeMixItUp: function () {
            $('#mix-wrapper').mixItUp({
                animation: {
                    effects: 'fade',
                    duration: 300
                },
                callbacks: {
                    onMixEnd: function(state) {
                        console.log(state)
                    }
                },
                controls: {
                    activeClass: 'derp'
                },
                layout: {
                    display: 'block'
                },
                load: {
                    sort: 'title:asc'
                }
            });
        },

        ajaxPostNotificationsRead: function() {
            $(function (){
                $(".nav #notifclick").click(function() {
                    $.ajax({
                        type: 'POST',
                        url: 'http://localhost:8000/notificationsRead',

                        success: function(data) {
                            console.log('succes', data);
                        },
                        error: function(data) {
                            console.log('fail', data);
                        }
                    });
                });
            });
        }
    }
}());

//Example
/*
    var myNamespace = (function () {
        var myPrivateVar, myPrivateMethod;

        // A private counter variable
        myPrivateVar = 0;

        // A private function which logs any arguments
        myPrivateMethod = function( foo ) {
            console.log( foo );
        };

        return {
            // A public variable
            myPublicVar: "foo",

            // A public function utilizing privates
            myPublicFunction: function( bar ) {
                // Increment our private counter
                myPrivateVar++;

                // Call our private method using bar
                myPrivateMethod( bar );
            }
        };
    })();
 */


text:
package com.example.ezbluetooth.client.impl;

import android.os.Parcel;
import android.util.Log;

import com.example.ezbluetooth.client.AbsBluetoothClient;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.UUID;

/**
 *
 * Created by innocentevil on 17. 2. 4.
 */

public class SimpleEchoClient extends AbsBluetoothClient {

    public static final Creator<SimpleEchoClient> CREATOR = new Creator<SimpleEchoClient>() {
        @Override
        public SimpleEchoClient createFromParcel(Parcel source) {
            SimpleEchoClient echoClient = new SimpleEchoClient(source);
            return echoClient;
        }

        @Override
        public SimpleEchoClient[] newArray(int size) {
            return new SimpleEchoClient[0];
        }
    };

    private static final String TAG = SimpleEchoClient.class.getCanonicalName();
    private static final UUID SVC_UUID = UUID.fromString("604388f7-2241-45fa-9e78-e472b90b62d6");
    private static final String SVC_NAME = "SimpleEchoServer";
    private static final byte[] TEST_DATA;

    static {
        TEST_DATA = new byte[256];
        for (int i = 0;i < TEST_DATA.length; i++) {
            TEST_DATA[i] = (byte) i;
        }
    }

    private long lastTimeStamp;
    private Thread mClientThread;
    private int totalReceived;
    private int totalErrorCount;
    private WeakReference<Callback> wrCallback;

    public SimpleEchoClient() {
        super();
        init();
    }

    private void init() {
        totalErrorCount = 0;
        totalReceived = 0;
    }

    private SimpleEchoClient(Parcel source) {
        super(source);
        init();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags){
        if(isConnected()) {
            stop();
        }
        super.saveToParcel(dest,flags);
    }

    public void addCallback(Callback callback) {
        wrCallback = new WeakReference<Callback>(callback);
    }

    @Override
    protected int getReadSize() {
        return TEST_DATA.length;
    }

    @Override
    protected byte[] onDataReceived(byte[] rxBuffer) {
        byte nextRx = rxBuffer[0];
        int errCnt = 0;
        final Callback callback = wrCallback.get();
        for(byte rx : rxBuffer) {
            if(nextRx != rx) {
                errCnt++;
            }
            nextRx = (byte) (rx + 1);
        }
        totalReceived += rxBuffer.length;
        totalErrorCount += errCnt;
        if(totalReceived % (TEST_DATA.length << 3) == 0) {
            long timeStamp = System.currentTimeMillis();
            if(callback != null) {
                callback.onScoreUpdate(totalErrorCount, TEST_DATA.length << 3, timeStamp - lastTimeStamp);
            }
            lastTimeStamp = timeStamp;
            totalErrorCount = 0;
        }
        return null;
    }

    @Override
    public void onDisconnected() {
        if(mClientThread == null) {
            return;
        }
        try {
            mClientThread.join();
        } catch (InterruptedException e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
    }

    @Override
    public void onConnected() {
        Log.e(TAG, "Connected");
        totalReceived = 0;
        totalErrorCount = 0;
        lastTimeStamp = System.currentTimeMillis();
        if(wrCallback == null) {
            wrCallback = new WeakReference<Callback>(new Callback() {
                @Override
                public void onScoreUpdate(int errCount, int totalReceived, long updateInterval) {
                    Log.d(TAG, String.format(Locale.getDefault(), "Updated Score : (%d / %d) @ %d", errCount, totalReceived, updateInterval));
                }
            });
        }
        mClientThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(isConnected()) {
                    try {
                        write(TEST_DATA);
                    } catch (IOException e) {
                        Log.e(TAG, e.getLocalizedMessage());
                    }
                }
            }
        });
        mClientThread.start();
    }

    @Override
    public UUID getServiceUuid() {
        return SVC_UUID;
    }

    @Override
    public String getServiceName() {
        return SVC_NAME;
    }

    public interface Callback {
        void onScoreUpdate(int errCount, int totalReceived, long updateInterval);
    }
}


text:
module Core
  class CorporateReader < ArticleReader
    private

    def entity_class
      CorporateArticle
    end

    def repository
      Registry::Repository[:corporate]
    end
  end
end


text:
namespace Linky.Sandbox.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
'use strict';
var packArray = require('../../lib/packArray');
var Cesium = require('cesium');
var Cartesian2 = Cesium.Cartesian2;
var Cartesian3 = Cesium.Cartesian3;
var Cartesian4 = Cesium.Cartesian4;
var Matrix2 = Cesium.Matrix2;
var Matrix3 = Cesium.Matrix3;
var Matrix4 = Cesium.Matrix4;
var WebGLConstants = Cesium.WebGLConstants;

var cartesian2 = [new Cartesian2(0, 1), new Cartesian2(2, 3), new Cartesian2(4, 5),
    new Cartesian2(6, 7), new Cartesian2(8, 9), new Cartesian2(10, 11)];
var cartesian3 = [new Cartesian3(0, 1, 2), new Cartesian3(3, 4, 5),
    new Cartesian3(6, 7, 8), new Cartesian3(9, 10, 11)];
var cartesian4 = [new Cartesian4(0, 1, 2, 3), new Cartesian4(4, 5, 6, 7),
    new Cartesian4(8, 9, 10, 11)];

var packedCartesians = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

var matrix2 = [new Matrix2(0, 2,
                           1, 3)];
var matrix3 = [new Matrix3(0, 3, 6,
                           1, 4, 7,
                           2, 5, 8)];
var matrix4 = [new Matrix4( 0,  4,  8, 12,
                            1,  5,  9, 13,
                            2,  6, 10, 14,
                            3,  7, 11, 15 )];

var packedMatrix2 = [0, 1, 2, 3];
var packedMatrix3 = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var packedMatrix4 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

describe('packArray', function() {
    it('packs an array with numbers', function() {
        var packed = packArray(packedCartesians, WebGLConstants.FLOAT);
        expect(packed).toEqual(packedCartesians);
    });

    it('packs an array with Cartesians', function() {
        var array2 = packArray(cartesian2, WebGLConstants.FLOAT_VEC2);
        var array3 = packArray(cartesian3, WebGLConstants.FLOAT_VEC3);
        var array4 = packArray(cartesian4, WebGLConstants.FLOAT_VEC4);

        expect(array2).toEqual(packedCartesians);
        expect(array3).toEqual(packedCartesians);
        expect(array4).toEqual(packedCartesians);
    });

    it('packs an array with Matrices', function() {
        var array2 = packArray(matrix2, WebGLConstants.FLOAT_MAT2);
        var array3 = packArray(matrix3, WebGLConstants.FLOAT_MAT3);
        var array4 = packArray(matrix4, WebGLConstants.FLOAT_MAT4);

        expect(array2).toEqual(packedMatrix2);
        expect(array3).toEqual(packedMatrix3);
        expect(array4).toEqual(packedMatrix4);
    });
});


text:
import requests

class HeartbeatMachinesC:
    def heartbeat(self, args, daemon):
        r = requests.get(daemon+"/machines/heartbeat")
        return r.text


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Benchmarks</title>

<button id="start">Start Benchmarks</button>

<applet code="nano" archive="../../../vendor/benchmarkjs/nano.jar" style="display: none;"></applet>


text:
""" A very basic shop for FeinCMS that can be included as application content.
    It's currently only single-page for <20 items.
    Powered by Plata.
    Requires django-orderable: https://github.com/tkaemming/django-orderable
    Plata and FeinCMS.

    The admin is notificated via email. Therefore set those settings:

    PLATA_NOTIFICATION_EMAIL_ALWAYS = ['shopadmin@example.com']
    PLATA_NOTIFICATION_EMAIL_SHIPPING = ['warehouse@example.com']

"""
VERSION = (0, 1, 0)
__version__ = '.'.join(map(str, VERSION))


text:
CFX_BitmapStorer::CFX_BitmapStorer() {}

CFX_BitmapStorer::~CFX_BitmapStorer() {}

RetainPtr<CFX_DIBitmap> CFX_BitmapStorer::Detach() {
  return std::move(m_pBitmap);
}

void CFX_BitmapStorer::Replace(RetainPtr<CFX_DIBitmap>&& pBitmap) {
  m_pBitmap = std::move(pBitmap);
}

void CFX_BitmapStorer::ComposeScanline(int line,
                                       const uint8_t* scanline,
                                       const uint8_t* scan_extra_alpha) {
  uint8_t* dest_buf = m_pBitmap->GetWritableScanline(line);
  uint8_t* dest_alpha_buf =
      m_pBitmap->m_pAlphaMask
          ? m_pBitmap->m_pAlphaMask->GetWritableScanline(line)
          : nullptr;
  if (dest_buf)
    memcpy(dest_buf, scanline, m_pBitmap->GetPitch());

  if (dest_alpha_buf) {
    memcpy(dest_alpha_buf, scan_extra_alpha,
           m_pBitmap->m_pAlphaMask->GetPitch());
  }
}

bool CFX_BitmapStorer::SetInfo(int width,
                               int height,
                               FXDIB_Format src_format,
                               uint32_t* pSrcPalette) {
  auto pBitmap = pdfium::MakeRetain<CFX_DIBitmap>();
  if (!pBitmap->Create(width, height, src_format))
    return false;

  if (pSrcPalette)
    pBitmap->SetPalette(pSrcPalette);

  m_pBitmap = std::move(pBitmap);
  return true;
}


text:
package com.mcleodmoores.examples.simulated.loader.config;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.threeten.bp.Period;

import com.opengamma.analytics.math.interpolation.factory.LinearExtrapolator1dAdapter;
import com.opengamma.analytics.math.interpolation.factory.MonotonicConstrainedCubicSplineInterpolator1dAdapter;
import com.opengamma.core.config.impl.ConfigItem;
import com.opengamma.financial.analytics.curve.CurveConstructionConfiguration;
import com.opengamma.financial.analytics.curve.CurveGroupConfiguration;
import com.opengamma.financial.analytics.curve.CurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.DiscountingCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.IborCurveTypeConfiguration;
import com.opengamma.financial.analytics.curve.InterpolatedCurveDefinition;
import com.opengamma.financial.analytics.ircurve.strips.CashNode;
import com.opengamma.financial.analytics.ircurve.strips.CurveNode;
import com.opengamma.financial.analytics.ircurve.strips.SwapNode;
import com.opengamma.financial.convention.IborIndexConvention;
import com.opengamma.financial.convention.SwapFixedLegConvention;
import com.opengamma.financial.convention.VanillaIborLegConvention;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdSearch;
import com.opengamma.id.ExternalIdSearchType;
import com.opengamma.master.config.ConfigMaster;
import com.opengamma.master.config.ConfigMasterUtils;
import com.opengamma.master.convention.ConventionMaster;
import com.opengamma.master.convention.ConventionSearchRequest;
import com.opengamma.master.convention.ManageableConvention;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Tenor;

/**
 * Populates a config master with configurations for government bond curves.
 */
public class ExamplesIsdaCurveConfigsPopulator {
  private static final List<Currency> CCYS = Arrays.asList(/* Currency.AUD, /* Currency.CAD, */ Currency.CHF, Currency.EUR, Currency.GBP, Currency.JPY,
      /* Currency.NZD, */Currency.USD);

  /**
   * @param configMaster
   *          a config master, not null
   * @param conventionMaster
   *          a convention master, not null
   */
  public static void populateConfigMaster(final ConfigMaster configMaster, final ConventionMaster conventionMaster) {
    ArgumentChecker.notNull(configMaster, "configMaster");
    final ConventionSearchRequest request = new ConventionSearchRequest();
    request.setConventionType(SwapFixedLegConvention.TYPE);
    final List<ManageableConvention> fixedLegConventions = conventionMaster.search(request).getConventions();
    if (fixedLegConventions.isEmpty()) {
      throw new IllegalStateException("No fixed swap leg conventions found in convention master");
    }
    request.setConventionType(VanillaIborLegConvention.TYPE);
    final List<ManageableConvention> vanillaIborLegConventions = conventionMaster.search(request).getConventions();
    if (vanillaIborLegConventions.isEmpty()) {
      throw new IllegalStateException("No vanilla *IBOR swap leg conventions found in convention master");
    }
    final Map<Currency, Tenor> iborTenors = new HashMap<>();
    final Map<Currency, ExternalId> iborConventionIds = new HashMap<>();
    final Map<Currency, ExternalId> payLegIds = new HashMap<>();
    final Map<Currency, ExternalId> receiveLegIds = new HashMap<>();
    for (final ManageableConvention mc : fixedLegConventions) {
      final SwapFixedLegConvention convention = (SwapFixedLegConvention) mc;
      payLegIds.put(convention.getCurrency(), convention.getExternalIdBundle().iterator().next());
    }
    for (final ManageableConvention mc : vanillaIborLegConventions) {
      final VanillaIborLegConvention convention = (VanillaIborLegConvention) mc;
      request.setConventionType(IborIndexConvention.TYPE);
      request.setExternalIdSearch(ExternalIdSearch.of(ExternalIdSearchType.ANY, convention.getIborIndexConvention()));
      final IborIndexConvention iborConvention = (IborIndexConvention) conventionMaster.search(request).getSingleConvention();
      final Currency ccy = iborConvention.getCurrency();
      iborTenors.put(ccy, convention.getResetTenor());
      iborConventionIds.put(ccy, convention.getIborIndexConvention());
      receiveLegIds.put(ccy, convention.getExternalIdBundle().iterator().next());
    }
    for (final Currency ccy : CCYS) {
      final String cccName = ccy.getCode() + " ISDA";
      final String curveName = ccy.getCode() + " ISDA";
      final String idMapperName = ccy.getCode() + " " + iborTenors.get(ccy).toFormattedString().substring(1) + " Tickers";
      final DiscountingCurveTypeConfiguration dctc = new DiscountingCurveTypeConfiguration(ccy.getCode());
      final IborCurveTypeConfiguration ictc = new IborCurveTypeConfiguration(iborConventionIds.get(ccy), iborTenors.get(ccy));
      final Map<String, List<? extends CurveTypeConfiguration>> discountingCurveTypes = Collections
          .<String, List<? extends CurveTypeConfiguration>> singletonMap(curveName, Arrays.asList(dctc));
      final Map<String, List<? extends CurveTypeConfiguration>> iborCurveTypes = Collections
          .<String, List<? extends CurveTypeConfiguration>> singletonMap(curveName, Arrays.asList(ictc));
      final CurveGroupConfiguration discountingGroup = new CurveGroupConfiguration(0, discountingCurveTypes);
      final CurveGroupConfiguration iborGroup = new CurveGroupConfiguration(1, iborCurveTypes);
      final CurveConstructionConfiguration ccc = new CurveConstructionConfiguration(cccName, Arrays.asList(discountingGroup, iborGroup),
          Collections.<String> emptyList());
      final ConfigItem<CurveConstructionConfiguration> cccItem = ConfigItem.of(ccc);
      cccItem.setName(ccc.getName());
      ConfigMasterUtils.storeByName(configMaster, cccItem);
      final Set<CurveNode> curveNodes = new LinkedHashSet<>();
      curveNodes.add(new CashNode(Tenor.of(Period.ZERO), iborTenors.get(ccy), iborConventionIds.get(ccy), idMapperName));
      for (int i = 1; i <= 10; i++) {
        curveNodes.add(new SwapNode(Tenor.of(Period.ZERO), Tenor.ofYears(i), payLegIds.get(ccy), receiveLegIds.get(ccy), idMapperName));
      }
      final InterpolatedCurveDefinition interpolatedCurve = new InterpolatedCurveDefinition(curveName, curveNodes,
          MonotonicConstrainedCubicSplineInterpolator1dAdapter.NAME, LinearExtrapolator1dAdapter.NAME, LinearExtrapolator1dAdapter.NAME);
      final ConfigItem<InterpolatedCurveDefinition> curveItem = ConfigItem.of(interpolatedCurve);
      curveItem.setName(curveItem.getName());
      ConfigMasterUtils.storeByName(configMaster, curveItem);
    }
  }

}


text:
package com.evolveum.midpoint.repo.sql.util;

import com.evolveum.midpoint.init.RepositoryFactory;
import com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration;
import com.evolveum.midpoint.repo.sql.testing.TestSqlRepositoryFactory;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * This bean post processor is only used in {@link com.evolveum.midpoint.repo.sql.DataSourceTest} because that
 * test class needs hibernate property hibernate.hbm2ddl.auto set to update. Test configuration can be overridden
 * through system option -Dconfig=<properties file> so this processor guarantees that hbm2ddl is always set to
 * "update".
 *
 * @author lazyman
 */
public class DataSourceTestBeanPostprocessor implements BeanPostProcessor, ApplicationContextAware {

    private static final Trace LOGGER = TraceManager.getTrace(DataSourceTestBeanPostprocessor.class);

    private ApplicationContext context;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (!(bean instanceof RepositoryFactory)) {
            return bean;
        }

        System.out.println("Changing hibernate.hbm2ddl.auto to update");
        LOGGER.info("Changing hibernate.hbm2ddl.auto to update");

        TestSqlRepositoryFactory factory = context.getBean("testSqlRepositoryFactory", TestSqlRepositoryFactory.class);
        SqlRepositoryConfiguration config = factory.getSqlConfiguration();
        config.setHibernateHbm2ddl("update");

        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}


text:
import requests
# import bs4
from bs4 import BeautifulSoup

# Specify the urls to parse

Colgate_Palmolive2012 = 'http://www.sec.gov/Archives/edgar/data/21665/000144530513000275/cl-12312012x10k.htm'
Colgate_Palmolive2013 = 'http://www.sec.gov/Archives/edgar/data/21665/000154554714000003/cl-12312013x10k.htm'
Colgate_Palmolive2014 = 'http://www.sec.gov/Archives/edgar/data/21665/000162828015000846/cl-12312014x10k.htm'

Procter_Gamble2012 = 'http://www.sec.gov/Archives/edgar/data/80424/000008042412000063/fy2012financialstatementsf.htm'
Procter_Gamble2013 = 'http://www.sec.gov/Archives/edgar/data/80424/000008042413000063/fy201310kannualreport.htm'
Procter_Gamble2014 = 'https://www.sec.gov/Archives/edgar/data/80424/000008042414000057/fy201410kannualreport.htm'

Johnson_Johnson2012 = 'http://www.sec.gov/Archives/edgar/data/200406/000020040613000038/a2012123010-k.htm'
Johnson_Johnson2013 = 'http://www.investor.jnj.com/secfiling.cfm?filingID=200406-14-33&CIK=200406'
Johnson_Johnson2014 = 'http://www.sec.gov/Archives/edgar/data/200406/000020040615000004/a2014122810-k.htm'

url =  # CP2012

# Set up http connection
response = requests.get(url)

# read response into a markup
html = response.content

# make soup!
soup = BeautifulSoup(html, "html.parser")

# find text
soup.findAll('a')

# NLP
import nltk
from nltk.corpus import stopwords
print stopwords.words("english")

import re
# Use regular expressions to do a find-and-replace
letters_only = re.sub("[^a-zA-Z]",           # The pattern to search for
                      " ",                   # The pattern to replace it with
                      example1.get_text())  # The text to search
print letters_only
lower_case = letters_only.lower()        # Convert to lower case
words = lower_case.split()
words = [w for w in words if not w in stopwords.words("english")]
print words
# Split into words

# import the finance dictionary

# Let's use pandas

import pandas as pd
Library = pd.DataFrame(pd.read_csv(
    "LoughranMcDonald_MasterDictionary_2014.csv"))

import csv
# route of the file has to be changed
with open('LoughranMcDonald_MasterDictionary_2014.csv', mode='r') as infile:
    reader = csv.reader(infile, delimiter=',')
    with open('LoughranMcDonald_MasterDictionary_2014_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = {rows[0]: rows[1] for rows in reader}

# Word Count
from collections import Counter
cnt = Counter(Texts)

##########################################################################
# Table Count

def table_count(url):
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html, "html.parser")
    # Mihir Comments: Seems to find all words in the text which are table not
    table = soup.find_all("table")
    return len(table)

# Image Count

def img_count(url):
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html, "html.parser")
    img = soup.find_all("img")
    return len(img)

# Page Count

def pages_count(url):
    response = requests.get(url)
    html = response.content
    soup = BeautifulSoup(html, "html.parser")
    lines = soup.find_all("hr")
    return len(lines) - 1
##########################################################################

# Code to find number of characters in the document
for script in soup(["script", "style"]):
    script.extract()    # rip it out
# get text
text = soup.get_text()
# break into lines and remove leading and trailing space on each
lines = (line.strip() for line in text.splitlines())
# break multi-headlines into a line each
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
# drop blank lines
text = '\n'.join(chunk for chunk in chunks if chunk)
print len(text)

# Text stemming
# Remove stopwords
from nltk.corpus import stopwords
pattern = re.compile(
    r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*')
noStopText = pattern.sub('', originalText)

##########################################################################
# Code for summarizing stats for the 10-K file
import requests
import re
from bs4 import BeautifulSoup
from collections import Counter
from nltk.corpus import stopwords
url = 'http://www.sec.gov/Archives/edgar/data/21665/000144530513000275/cl-12312012x10k.htm'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
text1 = soup.get_text()
b = len(text1.split(" "))
print b
for script in soup(["script", "style"]):
    script.extract()
text = soup.get_text()
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
text = '\n'.join(chunk for chunk in chunks if chunk)
#scores = soup.find_all(text=re.compile('Management'))
a = len(text.split(" "))
print a
c = len(text)
print c
table = soup.find_all("table")
print len(table)
img = soup.find_all("img")
print len(img)
pg = soup.find_all("hr")
print len(pg) - 1
cnt = Counter(text1.split())
# print cnt
pattern = re.compile(
    r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*')
noStopText = pattern.sub('', text)
cnt1 = Counter(noStopText.split())
print cnt1

##########################################################################
# Code with Stemming

# Import Libraries
import requests
import bs4
import nltk
import re
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
from nltk import stem
stemmer = stem.PorterStemmer()
response = requests.get(url)

html = response.content
soup = BeautifulSoup(html, "html.parser")
text = soup.get_text()
table = soup.find_all("table")
print "\nNumber of Tables", len(table)
img = soup.find_all("img")
print "Number of Images", len(img)
pg = soup.find_all("hr")
print "Number of Pages", len(pg) - 1

letters_only = re.sub("[^a-zA-Z]", " ", text)
lower_case = letters_only.lower()
words = lower_case.split()
words = [w for w in words if not w in stopwords.words("english")]
words = [stemmer.stem(word) for word in words]
word_count = Counter(words)

for key, value in sorted(word_count.iteritems(), key=lambda (k, v): (v, k)):
    print "%s: %s" % (key, value)
##########################################################################
# Rcode for BarPLot and WordClouds
mydata < - read.csv("IE242.csv")
library(tm)
library(SnowballC)
library(wordcloud)
library(RColorBrewer)
wordcloud(words=mydata$Word, freq=mydata$Frequency, min.freq=1,
          max.words=200, random.order=FALSE, rot.per=0.35,
          colors=brewer.pal(8, "Dark2"))
barplot(mydata[1:16, ]$Frequency, las=2, names.arg=mydata[1:16, ]$Word,
        col="lightblue", main="Most frequent words",
        ylab="Word frequencies")


text:
package org.hawkular.client.core;

import java.io.IOException;
import java.util.Arrays;

import javax.ws.rs.core.Response;

import org.hawkular.client.core.jaxrs.Empty;
import org.hawkular.client.core.jaxrs.ResponseCodes;
import org.hawkular.client.core.jaxrs.fasterxml.jackson.ClientObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DefaultClientResponse<T> implements ClientResponse<T>  {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultClientResponse.class);

    private int statusCode;
    private String errorMsg;
    private T entity;
    private boolean isSuccess = false;
    private String rawEntity;

    private final JavaType javaType;
    private final ResponseCodes expectedCode;

    public DefaultClientResponse() {
        this.javaType = null;
        this.expectedCode =  ResponseCodes.NO_CONTENT_204;
    }

    public DefaultClientResponse(JavaType javaType, Response serverResponse, ResponseCodes expectedCode) {
        this.javaType = javaType;
        this.expectedCode = expectedCode;

        validateResponse(serverResponse, expectedCode);
    }

    private void validateResponse(Response serverResponse, ResponseCodes expectedCode) {
        try {
            setStatusCode(serverResponse.getStatus());
            setSuccess(expectedCode.value() == serverResponse.getStatus());
            setRawEntity(serverResponse.readEntity(String.class));
        } finally {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Client Response: {}", toString());
            }
        }
    }

    private void parse() {
        if (isSuccess()) {
            if (!javaType.getRawClass().isAssignableFrom(Empty.class)) {
                try {
                    ObjectMapper objectMapper = new ClientObjectMapper();
                    setEntity(objectMapper.readValue(getRawEntity(), javaType));
                } catch (IOException ex) {
                    LOG.error("Failed to parse: {}", ex);

                    setErrorMsg("Failed to parse: " + ex.toString());
                    setSuccess(Boolean.FALSE);
                }
            }
        } else {
            setErrorMsg("Expected code '" + expectedCode.toString() + "' but got '" + getStatusCode() + "'");
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        this.isSuccess = success;
    }

    public T getEntity() {
        if (entity == null) {
            parse();
        }

        return entity;
    }

    public void setEntity(T entity) {
        this.entity = entity;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public String getRawEntity() {
        return rawEntity;
    }

    public void setRawEntity(String rawEntity) {
        this.rawEntity = rawEntity;
    }

    @SuppressWarnings("unchecked")
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Status Code:").append(getStatusCode())
            .append(", Is Success:").append(isSuccess())
            .append(", Error Message:").append(getErrorMsg() == null ? "-" : getErrorMsg())
            .append(", Raw Entity:").append(getRawEntity());

        if (getEntity() instanceof Object[]) {
            builder.append(", Entity:").append(Arrays.toString((T[])getEntity()));
        } else {
            builder.append(", Entity:[").append(getEntity()).append("]");
        }

        return builder.toString();
    }
}


text:
package org.apache.pig.pen;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.jobcontrol.Job;
import org.apache.hadoop.mapred.jobcontrol.JobControl;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.pig.PigException;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceOper;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapBase;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapReduce;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.POUserFunc;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POLoad;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POPackage;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.relationalOperators.POStore;
import org.apache.pig.backend.hadoop.executionengine.physicalLayer.util.PlanHelper;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.apache.pig.impl.PigContext;
import org.apache.pig.impl.builtin.ReadScalars;
import org.apache.pig.impl.io.FileLocalizer;
import org.apache.pig.impl.io.NullableTuple;
import org.apache.pig.impl.io.PigNullableWritable;
import org.apache.pig.impl.plan.DepthFirstWalker;
import org.apache.pig.impl.plan.OperatorKey;
import org.apache.pig.impl.plan.VisitorException;
import org.apache.pig.impl.util.ConfigurationValidator;
import org.apache.pig.impl.util.ObjectSerializer;
import org.apache.pig.impl.util.Pair;
import org.apache.pig.newplan.logical.relational.LOLoad;
import org.apache.pig.newplan.logical.relational.LogicalRelationalOperator;
import org.apache.pig.pen.util.LineageTracer;

/**
 * Main class that launches pig for Map Reduce
 *
 */
public class LocalMapReduceSimulator {

    private MapReduceLauncher launcher = new MapReduceLauncher();

    private Map<PhysicalOperator, PhysicalOperator> phyToMRMap = new HashMap<PhysicalOperator, PhysicalOperator>();;

    @SuppressWarnings("unchecked")
    public void launchPig(PhysicalPlan php, Map<LOLoad, DataBag> baseData,
                              LineageTracer lineage,
                              IllustratorAttacher attacher,
                              ExampleGenerator eg,
                              PigContext pc) throws PigException, IOException, InterruptedException {
        phyToMRMap.clear();
        MROperPlan mrp = launcher.compile(php, pc);

        ConfigurationValidator.validatePigProperties(pc.getProperties());
        Configuration conf = ConfigurationUtil.toConfiguration(pc.getProperties());

        JobControlCompiler jcc = new JobControlCompiler(pc, conf);

        JobControl jc;
        int numMRJobsCompl = 0;
        DataBag input;
        List<Pair<PigNullableWritable, Writable>> intermediateData = new ArrayList<Pair<PigNullableWritable, Writable>>();

        Map<Job, MapReduceOper> jobToMroMap = jcc.getJobMroMap();
        HashMap<String, DataBag> output = new HashMap<String, DataBag>();
        Configuration jobConf;
        // jc is null only when mrp.size == 0
        boolean needFileInput;
        final ArrayList<OperatorKey> emptyInpTargets = new ArrayList<OperatorKey>();
        while(mrp.size() != 0) {
            jc = jcc.compile(mrp, "Illustrator");
            if(jc == null) {
                throw new ExecException("Native execution is not supported");
            }
            List<Job> jobs = jc.getWaitingJobs();
            for (Job job : jobs) {
                jobConf = job.getJobConf();
                FileLocalizer.setInitialized(false);
                ArrayList<ArrayList<OperatorKey>> inpTargets =
                    (ArrayList<ArrayList<OperatorKey>>)
                      ObjectSerializer.deserialize(jobConf.get("pig.inpTargets"));
                intermediateData.clear();
                MapReduceOper mro = jobToMroMap.get(job);
                PigSplit split = null;
                List<POStore> stores = null;
                PhysicalOperator pack = null;
                // revisit as there are new physical operators from MR compilation
                if (!mro.mapPlan.isEmpty())
                    attacher.revisit(mro.mapPlan);
                if (!mro.reducePlan.isEmpty()) {
                    attacher.revisit(mro.reducePlan);
                    pack = mro.reducePlan.getRoots().get(0);
                }

                List<POLoad> lds = PlanHelper.getPhysicalOperators(mro.mapPlan, POLoad.class);
                if (!mro.mapPlan.isEmpty()) {
                    stores = PlanHelper.getPhysicalOperators(mro.mapPlan, POStore.class);
                }
                if (!mro.reducePlan.isEmpty()) {
                    if (stores == null)
                        stores = PlanHelper.getPhysicalOperators(mro.reducePlan, POStore.class);
                    else
                        stores.addAll(PlanHelper.getPhysicalOperators(mro.reducePlan, POStore.class));
                }

                for (POStore store : stores) {
                    output.put(store.getSFile().getFileName(), attacher.getDataMap().get(store));
                }

                OutputAttacher oa = new OutputAttacher(mro.mapPlan, output);
                oa.visit();

                if (!mro.reducePlan.isEmpty()) {
                    oa = new OutputAttacher(mro.reducePlan, output);
                    oa.visit();
                }
                int index = 0;
                for (POLoad ld : lds) {
                    input = output.get(ld.getLFile().getFileName());
                    if (input == null && baseData != null) {
                        for (LogicalRelationalOperator lo : baseData.keySet()) {
                            if (((LOLoad) lo).getSchemaFile().equals(ld.getLFile().getFileName()))
                            {
                                 input = baseData.get(lo);
                                 break;
                            }
                        }
                    }
                    if (input != null)
                        mro.mapPlan.remove(ld);
                }
                for (POLoad ld : lds) {
                    // check newly generated data first
                    input = output.get(ld.getLFile().getFileName());
                    if (input == null && baseData != null) {
                        if (input == null && baseData != null) {
                            for (LogicalRelationalOperator lo : baseData.keySet()) {
                                if (((LOLoad) lo).getSchemaFile().equals(ld.getLFile().getFileName()))
                                {
                                     input = baseData.get(lo);
                                     break;
                                }
                            }
                        }
                    }
                    needFileInput = (input == null);
                    split = new PigSplit(null, index, needFileInput ? emptyInpTargets : inpTargets.get(index), 0);
                    ++index;
                    Mapper<Text, Tuple, PigNullableWritable, Writable> map;

                    if (mro.reducePlan.isEmpty()) {
                        // map-only
                        map = new PigMapOnly.Map();
                        ((PigMapBase) map).setMapPlan(mro.mapPlan);
                        Mapper<Text, Tuple, PigNullableWritable, Writable>.Context context = ((PigMapOnly.Map) map)
                          .getIllustratorContext(jobConf, input, intermediateData, split);
                        map.run(context);
                    } else {
                        if ("true".equals(jobConf.get("pig.usercomparator")))
                            map = new PigMapReduce.MapWithComparator();
                        else if (!"".equals(jobConf.get("pig.keyDistFile", "")))
                            map = new PigMapReduce.MapWithPartitionIndex();
                        else
                            map = new PigMapReduce.Map();
                        Mapper<Text, Tuple, PigNullableWritable, Writable>.Context context = ((PigMapBase) map)
                          .getIllustratorContext(jobConf, input, intermediateData, split);
                        ((PigMapBase) map).setMapPlan(mro.mapPlan);
                        map.run(context);
                    }
                }

                if (!mro.reducePlan.isEmpty())
                {
                    if (pack instanceof POPackage)
                        mro.reducePlan.remove(pack);
                    // reducer run
                    PigMapReduce.Reduce reduce;
                    if ("true".equals(jobConf.get("pig.usercomparator")))
                        reduce = new PigMapReduce.ReduceWithComparator();
                    else
                        reduce = new PigMapReduce.Reduce();
                    reduce.setReducePlan(mro.reducePlan);
                    Reducer<PigNullableWritable, NullableTuple, PigNullableWritable, Writable>.Context
                        context = reduce.getIllustratorContext(job, intermediateData, (POPackage) pack);
                    reduce.run(context);
                }
                for (PhysicalOperator key : mro.phyToMRMap.keySet())
                    for (PhysicalOperator value : mro.phyToMRMap.get(key))
                        phyToMRMap.put(key, value);
            }

            int removedMROp = jcc.updateMROpPlan(new LinkedList<Job>());

            numMRJobsCompl += removedMROp;
        }

        jcc.reset();
    }

    private class OutputAttacher extends PhyPlanVisitor {
        private Map<String, DataBag> outputBuffer;
        OutputAttacher(PhysicalPlan plan, Map<String, DataBag> output) {
            super(plan, new DepthFirstWalker<PhysicalOperator, PhysicalPlan>(
                    plan));
            this.outputBuffer = output;
        }

        @Override
        public void visitUserFunc(POUserFunc userFunc) throws VisitorException {
            if (userFunc.getFunc() != null && userFunc.getFunc() instanceof ReadScalars) {
                ((ReadScalars) userFunc.getFunc()).setOutputBuffer(outputBuffer);
            }
        }
    }
    public Map<PhysicalOperator, PhysicalOperator> getPhyToMRMap() {
        return phyToMRMap;
    }
}


text:
H261Codec::H261Codec() {
    addSlider("Quantization", "q:v", "24", "1", "51");
    addCheckBox("Motion vectors", "-vf codecview=mv=pf+bf+bb", false);
    addParameter("GOP size", "g", "", "50");
    addParameter("B frames limit", "bf", "", "50");
    addCheckBox("Aspect ratio correction", "-vf setdar=r=a", true);

    QMap<QString, QString> resolutions;
    resolutions.insert("176:144", "176x144");
    resolutions.insert("352:288", "352x288");
    addComboBox("Resolution", "s", resolutions, "176:144");
}


text:
<?php
/**
 * @package WPSEO\Admin\Roles
 */

/**
 * VIP implementation of the Role Manager.
 */
final class WPSEO_Role_Manager_VIP extends WPSEO_Abstract_Role_Manager {
	/**
	 * Adds a role to the system.
	 *
	 * @param string $role         Role to add.
	 * @param string $display_name Name to display for the role.
	 * @param array  $capabilities Capabilities to add to the role.
	 *
	 * @return void
	 */
	protected function add_role( $role, $display_name, array $capabilities = array() ) {
		$enabled_capabilities  = array();
		$disabled_capabilities = array();

		// Build lists of enabled and disabled capabilities.
		foreach ( $capabilities as $capability => $grant ) {
			if ( $grant ) {
				$enabled_capabilities[] = $capability;
			}

			if ( ! $grant ) {
				$disabled_capabilities[] = $capability;
			}
		}

		wpcom_vip_add_role( $role, $display_name, $enabled_capabilities );
		if ( $disabled_capabilities !== array() ) {
			wpcom_vip_remove_role_caps( $role, $disabled_capabilities );
		}
	}

	/**
	 * Removes a role from the system.
	 *
	 * @param string $role Role to remove.
	 *
	 * @return void
	 */
	protected function remove_role( $role ) {
		remove_role( $role );
	}
}


text:
![state_transfer][pic1]
# Description
This simulation system can simulate ONE robot soccer player for RoboCup Middle Size League. It can be adapted for other purposes. Note that this package is only designed for demonstration. If you want to test multi-robot cooperation strategies, please refer to another repository: [gazebo_visual][1]. However, the tutorial regarding compliation and etc. is still useful.

Please read the paper ["Weijia Yao et al., A Simulation System Based on ROS and Gazebo for RoboCup Middle Size League, 2015"][2] for more information.

- Maintainer status: maintained
- Maintainer: Weijia Yao <weijia.yao.nudt <AT> gmail.com>
- Author: Weijia Yao <weijia.yao.nudt <AT> gmail.com>
- License: Apache
- Bug / feature tracker: https://github.com/nubot-nudt/single_nubot_gazebo/issues
- Source: git https://github.com/nubot-nudt/single_nubot_gazebo (branch: master)

# Recommended Operating Environment
1. Ubuntu 14.04;
2. ROS Indigo or ROS Jade. (It is recommended to install ROS Jade)
3. Gazebo 5.0 or above;
4. gazebo_ros_pkgs; (please read the **NOTE** below for more information)
5. If you decide to use coach4sim with a GUI, you should make sure you have installed Qt5. The recommended install place is /opt.
Other versions of Ubuntu, ROS or Gazebo may also work, but we have not tested yet.

**NOTE:**
Concerning how to install appropriate **gazebo_ros_pkgs**, please read the following according to your own situation:
 - 1.  If you decide to use **ROS Indigo**, please read the following:
If you choose "desktop-full" install of ROS Indigo, there is a Gazebo 2.0 included initially. In order to install Gazebo 5.0/5.1, you should first remove Gazebo 2.0 by running:
(**The following command is dangerous; it might delete the whole ROS, so please do it carefully or you may find other ways to delete gazebo2**)
` $ sudo apt-get remove gazebo2* `
Then you should be able to install Gazebo 5.0 now. To install gazebo_ros_pkgs compatible with Gazebo
5.0/5.1, run this command:
` $ sudo apt-get install ros-indigo-gazebo5-ros-pkgs ros-indigo-gazebo5-ros-control`
HOWEVER,    if the above command does now work, these packages may be moved to other places. You can check out [gazebo_ros][3] and download and install the correct version.
 - 2. If you decide to use **ROS Jade** with **gazebo 5.0 or 5.1**, read the following
ROS Jade has gazebo_ros_pkgs with it; so you don't have to install gazebo_ros_pkgs again.
However, you should do the following steps to fix some of the bugs in ROS Jade related to Gazebo:
  -  (a) `$ sudo gedit /opt/ros/jade/lib/gazebo_ros/gazebo`
In this file, go to line 24 and delete the last '/'. So
`setup_path=$(pkg-config --variable=prefix gazebo)/share/gazebo/`
is changed to
`setup_path=$(pkg-config --variable=prefix gazebo)/share/gazebo`
You can read this link for more [information][4]
  -  (b) Install Gazebo 5.
   `$ sudo apt-get install gazebo5`
If this fails, try to run the ['gazebo5_install.sh'][5](obtained from Gazebo's official website).
Read for more [information][6]
  -  (c) Optional: copy resource files to the new gazebo folder.
   `$ sudo cp -r /usr/share/gazebo-5.0/* /usr/share/gazebo-5.1`
 - 3. If you decide to use **ROS Jade** with **gazebo 7.1**, read the following,
  -  (1) Install gazebo 7.0 by running [gazebo7_install.sh][7](obtained from Gazebo's official website);
  -  (2) Then run this in the terminal:
  -  ` $ sudo apt-get install ros-jade-gazebo7-ros-pkgs`

# Complie
1. Go to the package root directory (single_nubot_gazebo)
2. If you already have CMakeLists.txt in the "src" folder, then you can skip this step.
   If not, run these commands:

    ```
    $ cd src
    $ catkin_init_workspace
    $ cd ..
    ```
3. $ ./configure
You may encounter errors related to Git. In this case, if you did not use Git, you could just ignore these errors.
4. $ catkin_make

# Tutorials

## Part I. Overview
The robot movement is realized by a Gazebo model plugin which is called "NubotGazebo" generated by source files "nubot_gazebo.cc" and "nubot_gazebo.hh". Basically the essential part of the plugin is realizing basic motions: omnidirectional locomotion, ball-dribbling and ball-kicking.

Basically, this plugin subscribes to topic **"/nubotcontrol/velcmd"** for omnidirecitonal movement and subscribes to service **"/BallHandle"** and **"/Shoot"** for ball-dribbling and ball-kicking respectively. You can customize this code for your robot based on these messages and services as a convenient interface. The types and definitions of the topics and servivces are listed in the following table:

Topic/Service	|	Type	|	Definition |
:-------------: |:-------:|:------------|
**/nubotcontrol/velcmd**	|	nubot_common/VelCmd 	|	float32 Vx
 float32 Vy
  float32 w   |
**/BallHandle**   |  nubot_common/BallHandle       |  int64 enable
 ---
  int64 BallIsHolding |
**/Shoot**        |  nubot_common/Shoot            | int64 strength
 int64 ShootPos
  ---
 int64 ShootIsDone |

For the definition of /BallHandle service, when "enable" equals to a non-zero number, a dribble request would be sent. If the robot meets the conditions to dribble the ball, the service response "BallIsHolding" is true.

For the definition of /Shoot service, when "ShootPos" equals to -1, this is a ground pass. In this case, "strength" is the inital speed you would like the soccer ball to have. When "ShootPos" equals to 1, this is a lob shot. In this case, "strength" is useless since the strength is calculated by the Gazebo plugin automatically and the soccer ball would follow a parabola path to enter the goal area. If the robot successfully kicks the ball out even if it failed to goal, the service response "ShootIsDone" is true.

As for ball-dribbling, there are three ways for a robot to dribble a ball, i.e.

Method  | Description
:-----: | -------------
(a) Setting ball pose continually  | This is the most accurate one; nubot would hardly lose control of the ball, but the visual effect is not very good (the ball does not rotate).
(b) Setting ball secant velocity  | This is less acurate than method (a) but more accurate than method (c).
(c) Setting ball tangential velocity |  This is the least accurate. If the robot moves fast, such as 3 m/s, it would probably lose control of the ball. However, this method achieves the best visual effect under low-speed condition.
**By default, we use method (c) for ball-dribbling.**

 As for Gaussian noise, **by default, Gaussian noise is NOT added**, but you can add it by changing the flag in the function update_model_info() in the file nubot_gazebo.cc;

## Part II. Single robot automatic movement
 The robot will do motions according to states transfer graph. Steps are as follows:
 1. Go to the package root directory (single_nubot_gazebo)
 2. source the setup.bash file:
   ` $ source devel/setup.bash`
 3.  `$ roslaunch nubot_gazebo sdf_nubot.launch`

>  **Note:** Every time you open a new terminal, you have to do step 2. You can also write this command into the ~/.bashrc file so that you don't have to source it every time.

Finally, the robot rotates and translates with trajectory planning. That is, the robot accelerates at constant acceleration and stays at constant speed when it reaches the maximum velocity.

You could click the 'Edit->Reset World' from the menu (or press ctrl-shift-r) to reset the simulation world and the robot would do the basic motions again.

When the robot finally reaches its last state: HOME, you could run
` $ rosrun nubot_gazebo nubot_teleop_keyboard`
to control the movement of the robot.

## Part III. Keyboad control robot movement
 1. In nubot_gazebo.cc, comment "nubot_auto_control();" and uncomment "nubot_be_control();" in function UpdateChild().
 2. Compile again and follow steps 1-3 listed in Part II.
 3. ` $ rosrun nubot_gazebo nubot_teleop_keyboard`

## Part IV. NubotGazebo API
For the detailed infomation and usage of the NubotGazebo class, please refer to the [doc/][8] folder.

## Part V. How you could use it to do more stuff
The main purpose of the simulation system is to test multi-robot collaboration algorithm. So to achieve this purpose, you need to know how to control the movement of each robot in the simulation. As you have experienced in turotial Part III to control a robot by keyboard, you could read its [source code][9] and make use of the topic publishing and service calling. In a word, if you want to control the movement of  the robots, publish velocity commands on the topic "/nubotcontrol/velcmd". If you want the robot to dribble the ball, after it is close enough to the ball, call the ROS service named "/BallHandle" and kick the ball by calling the service named"/Shoot" . The types and definitions of theses topics and services are presented in Part I.

## Part VI. Appendix
  1. To launch an empty soccer field:
  ` $ roslaunch nubot_gazebo empty_field.launch`
  2. To launch the simulation world with rqt_plot of nubot or ball's velocity:
  ` $ roslaunch nubot_gazebo sdf_nubot.launch plot:=true`

## Q&A

# Citation
If you use this simulation system, please cite our work.

```
@inproceedings{yao2015simulation,
  title={A simulation system based on ros and gazebo for robocup middle size league},
  author={Yao, Weijia and Dai, Wei and Xiao, Junhao and Lu, Huimin and Zheng, Zhiqiang},
  booktitle={Robotics and Biomimetics (ROBIO), 2015 IEEE International Conference on},
  pages={54--59},
  year={2015},
  organization={IEEE}
}

@incollection{xiao2017building,
  title={Building software system and simulation environment for robocup Msl soccer robots based on ros and gazebo},
  author={Xiao, Junhao and Xiong, Dan and Yao, Weijia and Yu, Qinghua and Lu, Huimin and Zheng, Zhiqiang},
  booktitle={Robot operating system (ROS)},
  pages={597--631},
  year={2017},
  publisher={Springer}
}
```

[1]: https://github.com/nubot-nudt/gazebo_visual
[2]: https://www.trustie.net/organizations/23/publications
[3]: https://github.com/ros-simulation/gazebo_ros_pkgs.git
[4]: http://answers.ros.org/question/215796/problem-for-install-gazebo_ros_package/
[5]: gazebo5_install.sh
[6]: http://answers.ros.org/question/217970/ros-jade-and-gazebo-50-migration-problem/
[7]: https://github.com/nubot-nudt/simatch/blob/master/gazebo7_install.sh
[8]: doc
[9]: src/nubot_simulation/nubot_gazebo/plugins/nubot_teleop_keyboard.cc
[pic1]: pics/state_transfer.png


text:
require 'simplecov'
SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)

require 'e_invoice'
require 'coveralls'

RSpec.configure do |config|
  # some (optional) config here
end


text:
CREATE TABLE country (id VARCHAR(2) NOT NULL, name VARCHAR(64) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

INSERT INTO `country` (`id`, `name`) VALUES ('ak', 'riakan');
INSERT INTO `country` (`id`, `name`) VALUES ('am', 'riamarik');
INSERT INTO `country` (`id`, `name`) VALUES ('ar', 'riarab');
INSERT INTO `country` (`id`, `name`) VALUES ('be', 'ribɛlɔrís');
INSERT INTO `country` (`id`, `name`) VALUES ('bn', 'ribɛngáli');
INSERT INTO `country` (`id`, `name`) VALUES ('my', 'ribirmán');
INSERT INTO `country` (`id`, `name`) VALUES ('bg', 'ribulgarí');
INSERT INTO `country` (`id`, `name`) VALUES ('cs', 'ricɛ́k');
INSERT INTO `country` (`id`, `name`) VALUES ('zh', 'ricinɔá');
INSERT INTO `country` (`id`, `name`) VALUES ('de', 'ridjɛrman');
INSERT INTO `country` (`id`, `name`) VALUES ('el', 'rigrɛ́k');
INSERT INTO `country` (`id`, `name`) VALUES ('ig', 'riigbo');
INSERT INTO `country` (`id`, `name`) VALUES ('hi', 'riíndí');
INSERT INTO `country` (`id`, `name`) VALUES ('id', 'riindonɛsí');
INSERT INTO `country` (`id`, `name`) VALUES ('en', 'riingɛrís');
INSERT INTO `country` (`id`, `name`) VALUES ('it', 'riitalyɛ́n');
INSERT INTO `country` (`id`, `name`) VALUES ('ja', 'rijapɔ́ŋ');
INSERT INTO `country` (`id`, `name`) VALUES ('jv', 'rijawanɛ́');
INSERT INTO `country` (`id`, `name`) VALUES ('ha', 'rikaksa');
INSERT INTO `country` (`id`, `name`) VALUES ('km', 'rikmɛr');
INSERT INTO `country` (`id`, `name`) VALUES ('ko', 'rikɔrɛɛ́');
INSERT INTO `country` (`id`, `name`) VALUES ('ksf', 'rikpa');
INSERT INTO `country` (`id`, `name`) VALUES ('es', 'rikpanyá');
INSERT INTO `country` (`id`, `name`) VALUES ('ms', 'rimalaí');
INSERT INTO `country` (`id`, `name`) VALUES ('ne', 'rinepalɛ́');
INSERT INTO `country` (`id`, `name`) VALUES ('nl', 'riɔlándɛ́');
INSERT INTO `country` (`id`, `name`) VALUES ('hu', 'riɔngrɔá');
INSERT INTO `country` (`id`, `name`) VALUES ('pa', 'ripɛnjabí');
INSERT INTO `country` (`id`, `name`) VALUES ('fr', 'ripɛrɛsǝ́');
INSERT INTO `country` (`id`, `name`) VALUES ('fa', 'ripɛrsán');
INSERT INTO `country` (`id`, `name`) VALUES ('pl', 'ripɔlɔ́n');
INSERT INTO `country` (`id`, `name`) VALUES ('pt', 'ripɔrtugɛ́');
INSERT INTO `country` (`id`, `name`) VALUES ('ru', 'rirís');
INSERT INTO `country` (`id`, `name`) VALUES ('ro', 'rirɔmán');
INSERT INTO `country` (`id`, `name`) VALUES ('rw', 'rirwanda');
INSERT INTO `country` (`id`, `name`) VALUES ('so', 'risomalí');
INSERT INTO `country` (`id`, `name`) VALUES ('sv', 'riswɛ́dǝ');
INSERT INTO `country` (`id`, `name`) VALUES ('th', 'ritaí');
INSERT INTO `country` (`id`, `name`) VALUES ('ta', 'ritamúl');
INSERT INTO `country` (`id`, `name`) VALUES ('tr', 'riturk');
INSERT INTO `country` (`id`, `name`) VALUES ('uk', 'riukrɛ́n');
INSERT INTO `country` (`id`, `name`) VALUES ('ur', 'riurdú');
INSERT INTO `country` (`id`, `name`) VALUES ('vi', 'riwyɛtnám');
INSERT INTO `country` (`id`, `name`) VALUES ('yo', 'riyúuba');
INSERT INTO `country` (`id`, `name`) VALUES ('zu', 'rizúlu');


text:
var path = require('path');
var pathsHelper = require('../helpers/paths.helper');
var baseWebpackConfig = require('./webpack.base.conf');
var utils = require('./webpack.utils');
var webpack = require('webpack');
var merge = require('webpack-merge');
var StyleLintPlugin = require('stylelint-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

module.exports = merge.strategy({ entry: 'replace' })(baseWebpackConfig, {
  watch: true,
  devtool: 'source-map', // needs to be source-map for the sass files
  output: {
    path: pathsHelper.tmp,
    publicPath: '/',
  },
  entry: {
    [pathsHelper.webpackEntries.js]: pathsHelper.mainJs,
    [pathsHelper.webpackEntries.css]: pathsHelper.mainScss
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': utils.config.dev.env
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    new StyleLintPlugin({ syntax: 'scss' }),
    new ExtractTextPlugin({
      filename: '[name]',
      allChunks: true,
    })
  ],
});


text:
<resources>
    <!-- TheMovieDB Api Config -->
    <string name="api_key" translatable="false">API_KEY_VALUE</string>

    <!-- AdsConfigs -->
    <string name="application_id_ad" translatable="false">XXXXXX</string>
    <string name="banner_ad_unit_id_home" translatable="false">XXXXXX</string>
    <string name="banner_ad_unit_id_search_show" translatable="false">XXXXXX</string>
    <string name="banner_ad_unit_id_popular_shows" translatable="false">XXXXXX</string>
    <string name="banner_ad_unit_id_detail_show" translatable="false">XXXXXX</string>
    <string name="device_id_test1" translatable="false">XXXXXX</string>

</resources>


text:
package com.intellij.openapi.util;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * An open-ended range of build numbers.
 */
public class BuildRange {
  private final BuildNumber since;
  private final BuildNumber until;

  public BuildRange(@NotNull BuildNumber since, @NotNull BuildNumber until) {
    this.since = since;
    this.until = until;
    if (since.compareTo(until) > 0) {
      throw new IllegalArgumentException("Invalid range: [" + since + "; " + until + "]");
    }
  }

  public boolean inRange(@NotNull BuildNumber build) {
    return since.compareTo(build) <= 0 && build.compareTo(until) <= 0;
  }

  @Contract("null, _ -> null; _, null -> null")
  public static BuildRange fromStrings(@Nullable String sinceVal, @Nullable String untilVal) {
    BuildNumber since = BuildNumber.fromString(sinceVal);
    BuildNumber until = BuildNumber.fromString(untilVal);
    return since != null && until != null ? new BuildRange(since, until) : null;
  }
}


text:
namespace lvm {

enum class ObjType {
  STRING
};

class Object : public Copyable {
  ObjType type_;
public:
  Object(ObjType t);
  virtual ~Object(void) {}

  ObjType get_type(void) const { return type_; }
  bool is_string(void) const { return type_ == ObjType::STRING; }

  virtual bool is_equal(const Object* r) const { return this == r; }
  virtual bool is_truthy(void) const { return false; }
  virtual std::string stringify(void) const { return "object"; }
};

class StringObject : public Object {
};

}


text:
package com.azure.resourcemanager.elastic.implementation;

import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.elastic.fluent.AllTrafficFiltersClient;
import com.azure.resourcemanager.elastic.fluent.models.ElasticTrafficFilterResponseInner;
import com.azure.resourcemanager.elastic.models.AllTrafficFilters;
import com.azure.resourcemanager.elastic.models.ElasticTrafficFilterResponse;

public final class AllTrafficFiltersImpl implements AllTrafficFilters {
    private static final ClientLogger LOGGER = new ClientLogger(AllTrafficFiltersImpl.class);

    private final AllTrafficFiltersClient innerClient;

    private final com.azure.resourcemanager.elastic.ElasticManager serviceManager;

    public AllTrafficFiltersImpl(
        AllTrafficFiltersClient innerClient, com.azure.resourcemanager.elastic.ElasticManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public Response<ElasticTrafficFilterResponse> listWithResponse(
        String resourceGroupName, String monitorName, Context context) {
        Response<ElasticTrafficFilterResponseInner> inner =
            this.serviceClient().listWithResponse(resourceGroupName, monitorName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new ElasticTrafficFilterResponseImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public ElasticTrafficFilterResponse list(String resourceGroupName, String monitorName) {
        ElasticTrafficFilterResponseInner inner = this.serviceClient().list(resourceGroupName, monitorName);
        if (inner != null) {
            return new ElasticTrafficFilterResponseImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    private AllTrafficFiltersClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.elastic.ElasticManager manager() {
        return this.serviceManager;
    }
}


text:
var puts;
(function(puts) {
    puts.Error = Error;
    puts.TypeError = TypeError;
    puts.ReferenceError = ReferenceError;
    puts.ParseError = ParseError;
    puts.EvalError = EvalError;
    puts.URIError = URIError;
    puts.SyntaxError = SyntaxError;
})(puts || (puts = {}));


text:
package org.elasticsearch.transport;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

public class TestResponse extends TransportResponse {

    String value;

    public TestResponse(String value) {
        this.value = value;
    }

    public TestResponse(StreamInput in) throws IOException {
        super(in);
        this.value = in.readString();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeString(value);
    }
}


text:
var Backbone = require('backbone');
var $ = Backbone.$ = require('jquery');
require('jquery-ui');
var _ = require('underscore');
var Handlebars = require('handlebars');
var templates = require('../../compiled/templates.js')( Handlebars );
var ChannelListingView = require('../views/channel_listing.js');

module.exports = Backbone.View.extend({
	template: templates.channels,
	initialize: function( data, config ){
		_(this).bindAll( 'render', 'renderChannel' );
		this.listenTo( this.collection, 'add', this.renderChannel );
		this.render();
	},
	render: function(){
		var html = this.template();
		this.$el.html( html );
		this.$channels = this.$el.find('ul.list');
		this.collection.each( this.renderChannel );
		this.$channels.sortable({
			axis: 'y',
			revert: 100
		});
		return this;
	},
	renderChannel: function( channel ){
		var channel_view = new ChannelListingView({ model: channel });
		this.$channels.append( channel_view.$el );
	}
});


text:
package com.xhachi.gae4s.datastore

import java.math
import java.math.BigInteger
import java.util.Date

import com.google.appengine.api.blobstore.BlobKey
import com.google.appengine.api.datastore._
import com.google.appengine.api.users
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig
import com.xhachi.gae4s.datastore.meta.property
import com.xhachi.gae4s.tests.AppEngineTestSuite
import org.scalatest.FunSuite

class SimpleValueEntityTest extends FunSuite with AppEngineTestSuite {

  override def getConfig = new LocalDatastoreServiceTestConfig :: super.getConfig

  test("SimpleValueEntityのMetaが正しく生成されること") {

    val meta = EntityMeta.createMeta[SimpleValueEntity]

    assert(meta.properties.size == 27)

    for (p <- meta.properties) {
      assert(!p.isInstanceOf[IndexedProperty[_]], p.name)
      assert(!p.isInstanceOf[OptionProperty[_]], p.name)
    }

    def assertProperty(name: String, propertyType: Class[_]) = {
      assert(meta.property(name).isDefined)
      assert(meta.property(name).get.isInstanceOf[ValueProperty[_]])
      assert(meta.property(name).get.asInstanceOf[ValueProperty[_]].propertyType == propertyType)
    }

    assert(meta.property("userKey").get.isInstanceOf[KeyProperty[_]])
    assertProperty("string", classOf[String])
    assertProperty("int", classOf[Int])
    assertProperty("long", classOf[Long])
    assertProperty("double", classOf[Double])
    assertProperty("bool", classOf[Boolean])
    assertProperty("date", classOf[Date])
    assertProperty("geoPt", classOf[GeoPt])
    assertProperty("text", classOf[Text])
    assertProperty("shortBlob", classOf[ShortBlob])
    assertProperty("blob", classOf[Blob])
    assertProperty("postalAddress", classOf[PostalAddress])
    assertProperty("phoneNumber", classOf[PhoneNumber])
    assertProperty("email", classOf[Email])
    assertProperty("user", classOf[users.User])
    assertProperty("imHandle", classOf[IMHandle])
    assertProperty("link", classOf[Link])
    assertProperty("category", classOf[Category])
    assertProperty("rating", classOf[Rating])
    assertProperty("blobKey", classOf[BlobKey])
    assertProperty("bigInt", classOf[BigInt])
    assertProperty("bigDecimal", classOf[BigDecimal])

    assert(meta.property("javaEnum").get.isInstanceOf[StringStoreProperty[_]])
    assert(meta.property("scalaEnum").get.isInstanceOf[StringStoreProperty[_]])
    assert(meta.property("byteArray").get.isInstanceOf[ByteArrayProperty])
    assert(meta.property("json").get.isInstanceOf[JsonProperty[_]])
    assert(meta.property("json").get.propertyType == classOf[JsonValue])
    assert(meta.property("serializable").get.isInstanceOf[SerializableProperty[_]])
    assert(meta.property("serializable").get.propertyType == classOf[SerializableValue])
  }

  test("保存して読み込めること") {

    val key = Datastore.allocateKey[SimpleValueEntity]
    val e = new SimpleValueEntity(key)
    e.userKey = Datastore.allocateKey[User]
    e.string = "test_string"
    e.int = 1
    e.long = 2
    e.double = 3
    e.bool = true
    e.date = new Date(5)
    e.geoPt = new GeoPt(6, 7)
    e.text = new Text("text7")
    e.shortBlob = new ShortBlob("8".getBytes("UTF-8"))
    e.blob = new Blob("9".getBytes("UTF-8"))
    e.postalAddress = new PostalAddress("123-4567")
    e.phoneNumber = new PhoneNumber("0120-123-456")
    e.email = new Email("test@example.com")
    e.user = new com.google.appengine.api.users.User("test2@example.com", "example.com")
    e.imHandle = new IMHandle(IMHandle.Scheme.sip, "test3")
    e.link = new Link("http://facebook.com")
    e.category = new Category("test_category")
    e.rating = new Rating(99)
    e.blobKey = new BlobKey("123")
    e.bigInt = new BigInt(new BigInteger("12345678"))
    e.bigDecimal = new BigDecimal(new math.BigDecimal("12345678"))
    e.javaEnum = JavaEnum.JAVA_ENUM2
    e.scalaEnum = ScalaEnum.ScalaEnum2
    e.byteArray = "test_byte_array".getBytes("UTF-8")
    e.json = JsonValue("hoge")
    e.serializable = SerializableValue("fuga")
    Datastore.put(e)

    val a = Datastore.get(key)
    assert(e.userKey == a.userKey)
    assert(e.string == a.string)
    assert(e.int == a.int)
    assert(e.long == a.long)
    assert(e.double == a.double)
    assert(e.bool == a.bool)
    assert(e.date == a.date)
    assert(e.geoPt == a.geoPt)
    assert(e.text == a.text)
    assert(e.shortBlob == a.shortBlob)
    assert(e.blob == a.blob)
    assert(e.postalAddress == a.postalAddress)
    assert(e.phoneNumber == a.phoneNumber)
    assert(e.email == a.email)
    assert(e.user == a.user)
    assert(e.imHandle == a.imHandle)
    assert(e.link == a.link)
    assert(e.category == a.category)
    assert(e.rating == a.rating)
    assert(e.blobKey == a.blobKey)
    assert(e.bigInt == a.bigInt)
    assert(e.bigDecimal == a.bigDecimal)
    assert(e.javaEnum == a.javaEnum)
    assert(e.scalaEnum == a.scalaEnum)
    assert(e.byteArray.zip(a.byteArray).filterNot(b => b._1 == b._2).isEmpty)
    assert(e.json == a.json)
    assert(e.serializable == a.serializable)

  }
}

trait DefaultEntityProperty {
  var sample: String = ""
}

class SimpleValueEntity(val key: Key[SimpleValueEntity]) extends Entity[SimpleValueEntity] with DefaultEntityProperty {
  var userKey: Key[User] = Datastore.allocateKey[User]
  var string: String = ""
  var int: Int = 0
  var long: Long = 0
  var double: Double = 0
  var bool: Boolean = false
  var date: Date = new Date(0)
  var geoPt: GeoPt = new GeoPt(0, 0)
  var text: Text = new Text(null)
  var shortBlob: ShortBlob = new ShortBlob("shot_blob".getBytes("UTF-8"))
  var blob: Blob = new Blob("blob".getBytes("UTF-8"))
  var postalAddress: PostalAddress = new PostalAddress("060-0806")
  var phoneNumber: PhoneNumber = new PhoneNumber("0120-501353")
  var email: Email = new Email("eample@example.com")
  var user: com.google.appengine.api.users.User = new com.google.appengine.api.users.User("sample@example.com", "example.com")
  var imHandle: IMHandle = null
  var link: Link = new Link("http://google.com")
  var category: Category = new Category("category")
  var rating: Rating = new Rating(0)
  var blobKey: BlobKey = new BlobKey("")
  var bigInt: BigInt = BigInt(0)
  var bigDecimal: BigDecimal = BigDecimal(0)
  var javaEnum: JavaEnum = JavaEnum.JAVA_ENUM1
  var scalaEnum: ScalaEnum.Value = ScalaEnum.ScalaEnum1
  var byteArray: Array[Byte] = "byte_array".getBytes("UTF-8")
  @property(json = true)  var json: JsonValue = JsonValue("test")
  @property(serialize = true)  var serializable: SerializableValue = SerializableValue("")
}

case class SerializableValue(name: String) extends Serializable

case class JsonValue(name: String)