text:
package vsphere

const (
	BaseOps = `---
- type: replace
  path: /azs
  value:
  - name: z1
    cloud_properties:
      datacenters:
      - name: ((vcenter_dc))
        clusters:
        - ((vcenter_cluster)):
            resource_pool: ((vcenter_rp))
  - name: z2
    cloud_properties:
      datacenters:
      - name: ((vcenter_dc))
        clusters:
        - ((vcenter_cluster)):
            resource_pool: ((vcenter_rp))
  - name: z3
    cloud_properties:
      datacenters:
      - name: ((vcenter_dc))
        clusters:
        - ((vcenter_cluster)):
            resource_pool: ((vcenter_rp))

- type: replace
  path: /compilation
  value:
    workers: 5
    reuse_compilation_vms: true
    az: z1
    vm_type: default
    network: default

- type: replace
  path: /disk_types/name=default/disk_size?
  value: 3000

- type: replace
  path: /networks
  value:
  - name: default
    type: manual
    subnets:
    - range: ((internal_cidr))
      gateway: ((internal_gw))
      azs: [z1, z2, z3]
      dns: [8.8.8.8]
      reserved: [((jumpbox__internal_ip))]
      cloud_properties:
        name: ((network_name))

- type: replace
  path: /vm_types/name=default/cloud_properties?
  value:
    cpu: 2
    ram: 8_192
    disk: 30_000

- type: replace
  path: /vm_types/name=large/cloud_properties?
  value:
    cpu: 2
    ram: 8_192
    disk: 640_000

- type: replace
  path: /vm_types/name=minimal/cloud_properties?
  value:
    cpu: 1
    ram: 4096
    disk: 10240

- type: replace
  path: /vm_types/name=small/cloud_properties?
  value:
    cpu: 2
    ram: 8192
    disk: 10240

- type: replace
  path: /vm_types/name=small-highmem/cloud_properties?
  value:
    cpu: 4
    ram: 32768
    disk: 10240

- type: replace
  path: /vm_extensions/name=50GB_ephemeral_disk/cloud_properties?
  value:
    disk: 51200

- type: replace
  path: /vm_extensions/name=100GB_ephemeral_disk/cloud_properties?
  value:
    disk: 102400

- type: replace
  path: /vm_extensions/name=500GB_ephemeral_disk/cloud_properties?
  value:
    disk: 512000

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: cf-tcp-router-network-properties

- type: replace
  path: /vm_extensions/-
  value:
    name: diego-ssh-proxy-network-properties
`
)


text:
/***********************************************************************/
/*                                                                     */
/*   SVMLight.h                                                        */
/*                                                                     */
/*   Author: Thorsten Joachims                                         */
/*   Date: 19.07.99                                                    */
/*                                                                     */
/*   Copyright (c) 1999  Universitaet Dortmund - All rights reserved   */
/*                                                                     */
/*   This software is available for non-commercial use only. It must   */
/*   not be modified and distributed without prior permission of the   */
/*   author. The author is not responsible for implications from the   */
/*   use of this software.                                             */
/*                                                                     */
/*   THIS INCLUDES THE FOLLOWING ADDITIONS                             */
/*   Generic Kernel Interfacing: Soeren Sonnenburg                     */
/*   Parallizations: Soeren Sonnenburg                                 */
/*   Multiple Kernel Learning: Gunnar Raetsch, Soeren Sonnenburg       */
/*   Linadd Speedup: Gunnar Raetsch, Soeren Sonnenburg                 */
/*                                                                     */
/***********************************************************************/
#ifndef _SVMLight_H___
#define _SVMLight_H___

#include <shogun/lib/config.h>

#ifdef USE_SVMLIGHT
#include <shogun/classifier/svm/SVM.h>
#include <shogun/lib/common.h>

namespace shogun
{

class CKernel;
//# define VERSION       "V3.50 -- correct??"
//# define VERSION_DATE  "01.11.00 -- correct??"

# define DEF_PRECISION 1E-14
# define MAXSHRINK 50000

#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** model */
struct MODEL {
/** sv num */
int32_t    sv_num;
/** at upper bound */
int32_t    at_upper_bound;
/** b */
float64_t b;
/** supvec */
int32_t*   supvec;
/** alpha */
float64_t *alpha;
/** index from docnum to position in model */
int32_t    *index;
/** number of training documents */
int32_t    totdoc;
/** kernel */
CKernel* kernel;

/* the following values are not written to file */
/** leave-one-out estimates */
float64_t loo_error;
/** leave-one-out estimates */
float64_t loo_recall;
/** leave-one-out estimates */
float64_t loo_precision;

/** xi/alpha estimates */
float64_t xa_error;
/** xi/alpha estimates */
float64_t xa_recall;
/** xi/alpha estimates */
float64_t xa_precision;
};

/** quadratic program */
typedef struct quadratic_program {
  /** number of variables */
  int32_t   opt_n;
  /** number of linear equality constraints */
  int32_t   opt_m;
  /** linear equality constraint */
  float64_t *opt_ce;
  /** linear equality constraint */
  float64_t *opt_ce0;
  /** hessian of objective */
  float64_t *opt_g;
  /** linear part of objective */
  float64_t *opt_g0;
  /** initial value for variables */
  float64_t *opt_xinit;
  /** low box constraint */
  float64_t *opt_low;
  /** up box constraint */
  float64_t *opt_up;
} QP;

/** the type used for storing feature ids */
typedef int32_t FNUM;

/** the type used for storing feature values */
typedef float64_t FVAL;

/** learning parameters */
struct LEARN_PARM {
  /** selects between regression and classification */
  int32_t   type;
  /** upper bound C on alphas */
  float64_t svm_c;
  /** regression epsilon (eps=-1.0 for classification */
  float64_t* eps;
  /** factor to multiply C for positive examples */
  float64_t svm_costratio;
  /** fraction of unlabeled examples to be */
  float64_t transduction_posratio;
  /* classified as positives */
  /** if nonzero, use hyperplane w*x+b=0 otherwise w*x=0 */
  int32_t   biased_hyperplane;
  /** if nonzero, it will use the shared slack variable mode in
   * svm_learn_optimization. It requires that the slackid is set for every
   * training example
   */
  int32_t   sharedslack;
  /** size q of working set */
  int32_t   svm_maxqpsize;
  /** new variables to enter the working set in each iteration */
  int32_t   svm_newvarsinqp;
  /** size of kernel cache in megabytes */
  int32_t   kernel_cache_size;
  /** tolerable error for distances used in stopping criterion */
  float64_t epsilon_crit;
  /** how much a multiplier should be above zero for shrinking */
  float64_t epsilon_shrink;
  /** iterations h after which an example can be removed by shrinking */
  int32_t   svm_iter_to_shrink;
  /** number of iterations after which the optimizer terminates, if there was
   * no progress in maxdiff
   */
  int32_t   maxiter;
  /** exclude examples with alpha at C and retrain */
  int32_t   remove_inconsistent;
  /** do not check KT-Conditions at the end of optimization for examples
   * removed by shrinking. WARNING: This might lead to sub-optimal solutions!
   */
  int32_t   skip_final_opt_check;
  /** if nonzero, computes leave-one-out estimates */
  int32_t   compute_loo;
  /** parameter in xi/alpha-estimates and for pruning leave-one-out range
   * [1..2]
   */
  float64_t rho;
  /** parameter in xi/alpha-estimates upper bounding the number of SV the
   * current alpha_t is distributed over
   */
  int32_t   xa_depth;
  /** file for predicitions on unlabeled examples in transduction */
  char predfile[200];
  /** file to store optimal alphas in. use empty string if alphas should not be
   * output
   */
  char alphafile[200];

  /* you probably do not want to touch the following */
  /** tolerable error on eq-constraint */
  float64_t epsilon_const;
  /** tolerable error on alphas at bounds */
  float64_t epsilon_a;
  /** precision of solver, set to e.g. 1e-21 if you get convergence problems */
  float64_t opt_precision;

  /* the following are only for internal use */
  /** do so many steps for finding optimal C */
  int32_t   svm_c_steps;
  /** increase C by this factor every step */
  float64_t svm_c_factor;
  /** costratio unlab */
  float64_t svm_costratio_unlab;
  /** unlabbound */
  float64_t svm_unlabbound;
  /** individual upper bounds for each var */
  float64_t *svm_cost;
};

/** timing profile */
struct TIMING {
  /** time kernel */
  int32_t   time_kernel;
  /** time opti */
  int32_t   time_opti;
  /** time shrink */
  int32_t   time_shrink;
  /** time update */
  int32_t   time_update;
  /** time model */
  int32_t   time_model;
  /** time check */
  int32_t   time_check;
  /** time select */
  int32_t   time_select;
};

/** shrink state */
struct SHRINK_STATE
{
  /** active */
  int32_t   *active;
  /** inactive since */
  int32_t   *inactive_since;
  /** deactnum */
  int32_t   deactnum;
  /** for shrinking with non-linear kernel */
  float64_t **a_history;
  /** maximum history */
  int32_t   maxhistory;
  /** for shrinking with linear kernel */
  float64_t *last_a;
  /** for shrinking with linear kernel */
  float64_t *last_lin;
};
#endif // DOXYGEN_SHOULD_SKIP_THIS

/** @brief class SVMlight */
class CSVMLight : public CSVM
{
 public:
  /** default constructor */
  CSVMLight();

  /** constructor
   *
   * @param C constant C
   * @param k kernel
   * @param lab labels
   */
  CSVMLight(float64_t C, CKernel* k, CLabels* lab);
  virtual ~CSVMLight();

  /** init SVM */
  void init();

  /** get classifier type
   *
   * @return classifier type LIGHT
   */
  virtual EMachineType get_classifier_type() { return CT_LIGHT; }

  /** get runtime
   *
   * @return runtime
   */
  int32_t   get_runtime();

  /** learn SVM */
  void   svm_learn();

  /** optimize to convergence
   *
   * @param docs the docs
   * @param label the label
   * @param totdoc the totdoc
   * @param shrink_state shrink state
   * @param inconsistent inconsistent
   * @param a a
   * @param lin lin
   * @param c c
   * @param timing_profile timing profile
   * @param maxdiff maximum diff
   * @param heldout held out
   * @param retrain retrain
   * @return something inty
   */
  int32_t optimize_to_convergence(
	int32_t* docs, int32_t* label, int32_t totdoc, SHRINK_STATE *shrink_state,
	int32_t *inconsistent, float64_t *a, float64_t *lin, float64_t *c,
	TIMING *timing_profile, float64_t *maxdiff, int32_t heldout,
	int32_t retrain);

  /** compute objective function
   *
   * @param a a
   * @param lin lin
   * @param c c
   * @param eps epsilon
   * @param label label
   * @param totdoc totdoc
   * @return something floaty
   */
  virtual float64_t compute_objective_function(
	float64_t *a, float64_t *lin, float64_t *c, float64_t* eps, int32_t *label,
	int32_t totdoc);

  /** clear index
   *
   * @param index index
   */
  void   clear_index(int32_t *index);

  /** add to index
   *
   * @param index index
   * @param elem element at index
   */
  void   add_to_index(int32_t *index, int32_t elem);

  /** compute index
   *
   * @param binfeature binary feature
   * @param range range
   * @param index
   * @return something inty
   */
  int32_t   compute_index(int32_t *binfeature, int32_t range, int32_t *index);

  /** optimise SVM
   *
   * @param docs docs
   * @param label label
   * @param exclude_from_eq_const exclude from eq const
   * @param eq_target eq target
   * @param chosen chosen
   * @param active2dnum active 2D num
   * @param totdoc totdoc
   * @param working2dnum working 2D num
   * @param varnum var num
   * @param a a
   * @param lin lin
   * @param c c
   * @param aicache ai cache
   * @param qp QP
   * @param epsilon_crit_target epsilon crit target
   */
  void optimize_svm(
	int32_t* docs, int32_t* label, int32_t *exclude_from_eq_const,
	float64_t eq_target, int32_t *chosen, int32_t *active2dnum, int32_t totdoc,
	int32_t *working2dnum, int32_t varnum, float64_t *a, float64_t *lin,
	float64_t *c, float64_t *aicache, QP *qp, float64_t *epsilon_crit_target);

  /** compute matrices for optimization
   *
   * @param docs docs
   * @param label label
   * @param exclude_from_eq_const exclude from eq const
   * @param eq_target eq target
   * @param chosen chosen
   * @param active2dnum active 2D num
   * @param key key
   * @param a a
   * @param lin lin
   * @param c c
   * @param varnum var num
   * @param totdoc totdoc
   * @param aicache ai cache
   * @param qp QP
   */
  void compute_matrices_for_optimization(
	int32_t* docs, int32_t* label, int32_t *exclude_from_eq_const,
	float64_t eq_target, int32_t *chosen, int32_t *active2dnum, int32_t *key,
	float64_t *a, float64_t *lin, float64_t *c, int32_t varnum, int32_t totdoc,
	float64_t *aicache, QP *qp);

  /** compute matrices for optimization in parallel
   *
   * @param docs docs
   * @param label label
   * @param exclude_from_eq_const exclude from eq const
   * @param eq_target eq target
   * @param chosen chosen
   * @param active2dnum active 2D num
   * @param key key
   * @param a a
   * @param lin lin
   * @param c c
   * @param varnum var num
   * @param totdoc totdoc
   * @param aicache ai cache
   * @param qp QP
   */
  void compute_matrices_for_optimization_parallel(
	int32_t* docs, int32_t* label, int32_t *exclude_from_eq_const,
	float64_t eq_target, int32_t *chosen, int32_t *active2dnum, int32_t *key,
	float64_t *a, float64_t *lin, float64_t *c, int32_t varnum, int32_t totdoc,
	float64_t *aicache, QP *qp);

  /** calculate SVM model
   *
   * @param docs docs
   * @param label label
   * @param lin lin
   * @param a a
   * @param a_old old a
   * @param c c
   * @param working2dnum working 2D num
   * @param active2dnum active 2D num
   * @return something inty
   */
  int32_t   calculate_svm_model(
	int32_t* docs, int32_t *label,float64_t *lin, float64_t *a,
	float64_t* a_old, float64_t *c, int32_t *working2dnum, int32_t *active2dnum);

  /** check optimality
   *
   * @param label label
   * @param a a
   * @param lin lin
   * @param c c
   * @param totdoc totdoc
   * @param maxdiff maximum diff
   * @param epsilon_crit_org epsilon crit org
   * @param misclassified misclassified
   * @param inconsistent inconsistent
   * @param active2dnum active 2D num
   * @param last_suboptimal_at last suboptimal at
   * @param iteration iteration
   * @return something inty
   */
  int32_t   check_optimality(
	int32_t *label, float64_t *a, float64_t* lin, float64_t *c, int32_t totdoc,
	float64_t *maxdiff, float64_t epsilon_crit_org, int32_t *misclassified,
	int32_t *inconsistent,int32_t* active2dnum, int32_t *last_suboptimal_at,
	int32_t iteration);

  /** update linear component
   *
   * @param docs docs
   * @param label label
   * @param active2dnum active 2D num
   * @param a a
   * @param a_old old a
   * @param working2dnum working 2D num
   * @param totdoc totdoc
   * @param lin lin
   * @param aicache ai cache
   * @param c c
   */
  virtual void update_linear_component(
	int32_t* docs, int32_t *label, int32_t *active2dnum, float64_t *a,
	float64_t* a_old, int32_t *working2dnum, int32_t totdoc, float64_t *lin,
	float64_t *aicache, float64_t* c);

  /** helper for update linear component MKL linadd
   *
   * @param p p
   */
  static void* update_linear_component_mkl_linadd_helper(void* p);

  /** update linear component MKL
   *
   * @param docs docs
   * @param label label
   * @param active2dnum active 2D num
   * @param a a
   * @param a_old old a
   * @param working2dnum working 2D num
   * @param totdoc totdoc
   * @param lin lin
   * @param aicache ai cache
   */
  void update_linear_component_mkl(
		  int32_t* docs, int32_t *label, int32_t *active2dnum, float64_t *a,
		  float64_t* a_old, int32_t *working2dnum, int32_t totdoc, float64_t *lin,
		  float64_t *aicache);

  /** update linear component MKL
   *
   * @param docs docs
   * @param label label
   * @param active2dnum active 2D num
   * @param a a
   * @param a_old old a
   * @param working2dnum working 2D num
   * @param totdoc totdoc
   * @param lin lin
   * @param aicache ai cache
   */
  void update_linear_component_mkl_linadd(
		  int32_t* docs, int32_t *label, int32_t *active2dnum, float64_t *a,
		  float64_t* a_old, int32_t *working2dnum, int32_t totdoc, float64_t *lin,
		  float64_t *aicache);

  void call_mkl_callback(float64_t* a, int32_t* label, float64_t* lin);

  /** select next qp subproblem grad
   *
   * @param label label
   * @param a a
   * @param lin lin
   * @param c c
   * @param totdoc totdoc
   * @param qp_size size of qp
   * @param inconsistent inconsistent
   * @param active2dnum active 2D num
   * @param working2dnum working 2D num
   * @param selcrit selcrit
   * @param select select
   * @param cache_only cache only
   * @param key key
   * @param chosen chosen
   * @return something inty
   */
  int32_t select_next_qp_subproblem_grad(
	int32_t *label, float64_t *a, float64_t* lin, float64_t* c, int32_t totdoc,
	int32_t qp_size, int32_t *inconsistent, int32_t* active2dnum,
	int32_t* working2dnum, float64_t *selcrit, int32_t *select,
	int32_t cache_only, int32_t *key, int32_t *chosen);

  /** select next qp subproblem rand
   *
   * @param label label
   * @param a a
   * @param lin lin
   * @param c c
   * @param totdoc totdoc
   * @param qp_size size of qp
   * @param inconsistent inconsistent
   * @param active2dnum active 2D num
   * @param working2dnum working 2D num
   * @param selcrit selcrit
   * @param select select
   * @param key key
   * @param chosen chosen
   * @param iteration iteration
   * @return something inty
   */
  int32_t select_next_qp_subproblem_rand(
	int32_t* label, float64_t *a, float64_t *lin, float64_t *c,
	int32_t totdoc, int32_t qp_size, int32_t *inconsistent,
	int32_t *active2dnum, int32_t *working2dnum, float64_t *selcrit,
	int32_t *select, int32_t *key, int32_t *chosen, int32_t iteration);

  /** select top n
   *
   * @param selcrit selcrit
   * @param range range
   * @param select select
   * @param n n
   */
  void   select_top_n(
	float64_t *selcrit, int32_t range, int32_t *select, int32_t n);

  /** init shrink state
   *
   * @param shrink_state shrink state
   * @param totdoc totdoc
   * @param maxhistory maximum history
   */
  void   init_shrink_state(
	SHRINK_STATE *shrink_state, int32_t totdoc, int32_t maxhistory);

  /** cleanup shrink state
   *
   * @param shrink_state shrink state
   */
  void   shrink_state_cleanup(SHRINK_STATE *shrink_state);

  /** shrink problem
   *
   * @param shrink_state shrink state
   * @param active2dnum active 2D num
   * @param last_suboptimal_at last suboptimal at
   * @param iteration iteration
   * @param totdoc totdoc
   * @param minshrink minimal shrink
   * @param a a
   * @param inconsistent inconsistent
   * @param c c
   * @param lin lin
   * @param label label
   * @return something inty
   */
  int32_t shrink_problem(
	SHRINK_STATE *shrink_state, int32_t *active2dnum,
	int32_t *last_suboptimal_at, int32_t iteration, int32_t totdoc,
	int32_t minshrink, float64_t *a, int32_t *inconsistent, float64_t* c,
	float64_t* lin, int* label);

  /** reactivate inactive examples
   *
   * @param label label
   * @param a a
   * @param shrink_state shrink state
   * @param lin lin
   * @param c c
   * @param totdoc totdoc
   * @param iteration iteration
   * @param inconsistent inconsistent
   * @param docs docs
   * @param aicache ai cache
   * @param maxdiff maximum diff
   */
  virtual void   reactivate_inactive_examples(
	int32_t *label,float64_t *a,SHRINK_STATE *shrink_state, float64_t *lin,
	float64_t *c, int32_t totdoc,int32_t iteration, int32_t *inconsistent,
	int32_t *docs,float64_t *aicache, float64_t* maxdiff);

protected:
	/** compute kernel
	*
	* @param i at index i
	* @param j at index j
	* @return computed kernel item at index i, j
	*/
	virtual float64_t compute_kernel(int32_t i, int32_t j)
	{
		return kernel->kernel(i, j);
	}

	/** helper for compute kernel
	 *
	 * @param p p
	 */
	static void* compute_kernel_helper(void* p);

	/** helper for update linear component linadd
	 *
	 * @param p p
	 */
	static void* update_linear_component_linadd_helper(void* p);

	/** helper for reactivate inactive examples vanilla
	 *
	 * @param p p
	 */
	static void* reactivate_inactive_examples_vanilla_helper(void* p);

	/** helper for reactivate inactive examples linadd
	 *
	 * @param p p
	 */
	static void* reactivate_inactive_examples_linadd_helper(void* p);

	/** @return object name */
	virtual const char* get_name() const { return "SVMLight"; }

	/* interface to QP-solver */
	float64_t *optimize_qp( QP *qp,float64_t *epsilon_crit, int32_t nx,
			float64_t *threshold, int32_t& svm_maxqpsize);

	/** train SVM classifier
	 *
	 * @param data training data (parameter can be avoided if distance or
	 * kernel-based classifiers are used and distance/kernels are
	 * initialized with train data)
	 *
	 * @return whether training was successful
	 */
	virtual bool train_machine(CFeatures* data=NULL);

 protected:
  /** model */
  MODEL* model;
  /** learn parameters */
  LEARN_PARM* learn_parm;
  /** verbosity level (0-4) */
  int32_t   verbosity;

  /** init margin */
  float64_t init_margin;
  /** init iter */
  int32_t   init_iter;
  /** precision violations */
  int32_t precision_violations;
  /** model b */
  float64_t model_b;
  /** opt precision */
  float64_t opt_precision;
  /** primal */
  float64_t* primal;
  /** dual */
  float64_t* dual;

  // MKL stuff

  /** Matrix that stores the contribution by each kernel for each example (for
   * current alphas)
   */
  float64_t* W;
  /** number of iteration */
  int32_t count;
  /** current alpha gap */
  float64_t mymaxdiff;
  /** if kernel cache is used */
  bool use_kernel_cache;
  /** mkl converged */
  bool mkl_converged;
};
}
#endif //USE_SVMLIGHT
#endif //_SVMLight_H___

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Threading.Tasks;

namespace Evol.UnitOfWork.Abstractions
{
    public abstract class UnitOfWorkBase : IUnitOfWork ,IDisposable
    {
        public Guid Key { get; protected set; }

        public IUnitOfWork Parent { get; set; }

        public IUnitOfWork Child { get; set; }

        public UnitOfWorkOption Option { get; private set; }

        public bool IsDisposed { get; private set; }

        public event EventHandler Committed;

        public event EventHandler<UnitOfWorkFailedEventArgs> Failed;

        public event EventHandler Disposed;

        private bool _isBeginCalledBefore;

        private bool _successed;
        protected abstract void BeginUow();

        public void Begin(UnitOfWorkOption option)
        {
            if (_isBeginCalledBefore)
                return;
            Option = option;
            BeginUow();
            _isBeginCalledBefore = true;
        }

        public void Begin()
        {
            Begin(new UnitOfWorkOption());
        }

        protected abstract Task CommitUowAsync();

        public async Task CommitAsync()
        {
            try
            {
                await CommitUowAsync();
                _successed = true;
                OnCommitted();
            }
            catch (Exception ex)
            {
                _exception = ex;
                throw ex;
            }

        }

        public abstract void Rollback();

        public virtual void Dispose()
        {
            if (!_isBeginCalledBefore || IsDisposed)
                return;
            IsDisposed = true;

            if (!_successed)
                OnFailed(_exception);

            OnDisposed();
        }

        private Exception _exception;

        protected virtual void OnCommitted()
        {
            if (Committed == null)
                return;
            Committed.Invoke(this, new EventArgs());
        }

        protected virtual void OnFailed(Exception ex)
        {
            if (Failed == null)
                return;
            Failed.Invoke(this, new UnitOfWorkFailedEventArgs(ex));
        }

        protected virtual void OnDisposed()
        {
            if (Disposed == null)
                return;
            Disposed.Invoke(this, new EventArgs());
        }

        public abstract TDbContext GetDbContext<TDbContext>() where TDbContext : class;

        public abstract void AddDbContext<TDbContext>(TDbContext dbContext) where TDbContext : class;
    }

}


text:
import {toCamelCase, toKebabCase} from './../src/change-case';

describe('change case', function () {

  describe('toCamelCase', function () {

    it('should keep simple string unchanged', function () {
      const input = 'aaa';
      const expectation = 'aaa';
      expect(toCamelCase(input)).toEqual(expectation);
    });

    it('should convert spaces', function () {
      const input = 'aaa bbb';
      const expectation = 'aaaBbb';
      expect(toCamelCase(input)).toEqual(expectation);
    });

    it('should convert dashes', function () {
      const input = 'aaa-bbb';
      const expectation = 'aaaBbb';
      expect(toCamelCase(input)).toEqual(expectation);
    });

    it('should convert underscores', function () {
      const input = 'aaa_bbb';
      const expectation = 'aaaBbb';
      expect(toCamelCase(input)).toEqual(expectation);
    });

    it('should convert correctly if delimiter is at end of input', function () {
      const input = 'aaa ';
      const expectation = 'aaa';
      expect(toCamelCase(input)).toEqual(expectation);
    });

  });

  describe('toKebabCase', function () {

    it('should keep simple string unchanged', function () {
      const input = 'aaa';
      const expectation = 'aaa';
      expect(toKebabCase(input)).toEqual(expectation);
    });

    it('should convert spaces', function () {
      const input = 'aaa bbb';
      const expectation = 'aaa-bbb';
      expect(toKebabCase(input)).toEqual(expectation);
    });

    it('should convert uppercase', function () {
      const input = 'aaaBbb';
      const expectation = 'aaa-bbb';
      expect(toKebabCase(input)).toEqual(expectation);
    });

    it('should convert underscores', function () {
      const input = 'aaa_bbb';
      const expectation = 'aaa-bbb';
      expect(toKebabCase(input)).toEqual(expectation);
    });

  });

});


text:
/*
--Table Of Contents

1.0 - Skinning Variables

2.0 - HTML elements

3.0 - Fiesta Global Elements

4.0 - Fiesta Unique Elements
	4.1 - Header
		4.1.1 - Common
		4.1.2 - Mast
		4.1.3 - SiteNav
	4.2 - Body
		4.2.1 - Common
		4.2.2 - SiteNav
		4.2.3 - PageBar
		4.2.4 - PageInfo
			4.2.4.1 - Tags
			4.2.4.2 - Languages
			4.2.4.3 - File Attachments
			4.2.4.4 - Images
			4.2.4.5 - Comments

		4.2.5 - Dropdown Menus
		4.2.6 - Special
		4.2.7 - Admin

5.0 - Internet Explorer 6 CSS
*/

/*-------------------------------------------------------------------
1.0 Skinning Variables
---------------------------------------------------------------------*/
@variables {
    tabletop_border: 1px dotted #b8d6de;

    linkcolor: #0000ff;
    linkcolor_hover: #ef9c1e;

	button_color: #333333;
	buttonhover_color: #ffffff;

	sitenavhome_color: #333;
	sitenavhomehover_color: #ef9c1e;

	sitenav_color: #666;
	sitenavhover_color: #000;

	sitenavselected_color: #000;

	pagerevision_color: #000;
	pagerevisionlink_color: #000;

	dropmenu_border: 1px solid #c2c2c2;
	dropmenu_bgimage: url(tools_menu_bg.gif);
	dropmenu_bgcolor: #eeeeee;

	pageinfoheader_color: #333333;

	pagebar_color: #fff;
	pagebarhover_color: #666;
	pagebarhover_bg: #F8DF95;
	pagebardisabled_color: #f9e4a0;

	specialh2_color: #789bbd;
	specialfieldset_border: 1px solid #b8d6de;

	table_bg1: ;
	table_bg2: #f1f7f9;
	tableth_border: 1px solid #7c784e;
}

/*-------------------------------------------------------------------
2.0 HTML elements
---------------------------------------------------------------------*/
a {
	color: var(linkcolor);
}
a:hover {
	color: var(linkcolor_hover);
}
body {
	background-repeat: repeat-x;
	background-color:#aaa676;
}
/*-------------------------------------------------------------------
3.0 Fiesta Global Elements
---------------------------------------------------------------------*/
.global {
	background-attachment: fixed;
	background-repeat: repeat-x;
	background-position: center 0px;
	background-image: url(global_bg.gif);

}
.page {
	background-color: #fff;
}
table.table tr th,
.table table tr th,
.atable table th {
	color:#333;
	border-top: var(tableth_border);
	border-bottom: var(tableth_border);
	background-image: url(admin_th_bg.gif);
}
table.table tr.bg1 td,
.table table tr td.bg1,
.atable table td.bg1 {
	background: var(table_bg1);
}
table.table tr.bg2 td,
.table table tr td.bg2,
.atable table td.bg2 {
	background: var(table_bg2);
}
button,
input.historysubmit,
input[type=submit],
input[type=button],
input[type=file] {
	color: var(button_color);
}
.userAuth a.userLogout,
.userAuth a.userLogin,
.file div.fileAdd a,
.userRegister a,
#comments div.comments div.comment form a {
	color: var(button_color);
}
button:hover,
input.historysubmit:hover,
input[type=submit]:hover,
input[type=button]:hover {
	color: var(buttonhover_color);
}
.userAuth a.userLogout:hover,
.userAuth a.userLogin:hover,
.file div.fileAdd a:hover,
.userRegister a:hover,
#comments div.comments div.comment form a:hover {
	color: var(buttonhover_color);
}
/*-------------------------------------------------------------------
4.0 Fiesta Unique Elements
---------------------------------------------------------------------*/

/*---- 4.1  Header*/

/*---- ---- 4.1.1  Common*/

/*---- ---- 4.1.2  Mast*/

/*---- ---- 4.1.3  SiteNav*/

.header .siteNav .userAuth a.userPage:hover {
	color: var(linkcolor_hover);
}

#siteNavTree a {
	color: var(sitenav_color);
}

#siteNavTree a:hover {
	color: var(sitenavhover_color);
}

#siteNavTree div.selectedChild a:hover {
	color: var(sitenavhover_color);
}

#siteNavTree div.dockedNode a {
	color: var(sitenavhome_color);
}

#siteNavTree div.dockedNode:hover a {
	color: var(sitenavhover_color);
}

#siteNavTree div.homeNode a:hover {
	color: var(sitenavhomehover_color);
}

#siteNavTree div.selected a {
	color: var(sitenavselected_color);
}

/*----4.2  Body*/

/*---- ---- 4.2.1  Common*/

/*---- ---- 4.2.2  SiteNav*/

/*---- ---- 4.2.3  PageBar*/

.pageBar ul li a:hover {
	background-color: var(pagebarhover_bg);
	color: var(pagebarhover_color);
}

.pageBar ul li a.disabled,
.pageBar ul li a.disabled:hover {
	color: var(pagebardisabled_color);
}

.pageRevision {
	color: var(pagerevision_color);
}

.pageRevision a {
	color: var(pagerevisionlink_color);
	text-decoration:underline;
}

.pageRevision a:hover {
	text-decoration:none;
}

.pageBar ul li a {
	color: var(pagebar_color);
}

.body .pageBar ul li.pageMore a {
	background-image: url(../drop_white.gif);
}

.body .pageBar ul li.pageMore a:hover {
	background-image: url(../drop_grey.gif);
}

/*---- ---- 4.2.4  PageInfo*/

.pageInfo dt.pageTags,
.file h2,
.gallery h2,
#comments h2,
.commentMore,
#comments .commentForm .commentHeader,
.pageInfo dd.pageTags div.relatedpages strong {
	color: var(pageinfoheader_color);
}
/*---- ---- ---- 4.2.4.1  Tags*/

/*---- ---- ---- 4.2.4.2  Languages*/

/*---- ---- ---- 4.2.4.3  File Attachments*/
#pageGallery div.preControls,
.file table tr td,
.pageInfo dd.pageTags div.relatedpages {
	border-top: var(tabletop_border);
}

.file table tr th {
	color:#666;
}

/*---- ---- ---- 4.2.4.4  Images*/
#pageGallery div.galleryCell img.image {
	border:1px solid #666;
}

#pageGallery div.galleryCell div.desctext span.desctext {
	color:#666;
}

.nodescription {
	color:#999;
}

/*---- ---- ---- 4.2.4.5  Comments*/
#comments div.comments div.comment {
	border-top:var(tabletop_border);
}

#comments div.comments div.comment div.commentNum {
	background-color: var(table_bg2);
	border: var(specialfieldset_border);
}

#comments div.comments div.comment div.commentNum a {
	color:#333;
}

#comments .commentActions input.commentDelete {
	color: var(linkcolor);
}

#comments .commentActions input.commentDelete:hover {
	color: var(linkcolor_hover);
}

/*---- ---- 4.2.5  Dropdown Menus*/

#menuPageContent .pageToc,
#menuPageOptions {
	border: var(dropmenu_border);
	background-color:var(dropmenu_bgcolor);
	background-image: var(dropmenu_bgimage);
}

#menuTools {
	border: var(dropmenu_border);
	background-color: var(dropmenu_bgcolor);
	background-image: var(dropmenu_bgimage);
}

#menuFiller .dmenu-wrap {
	border: var(dropmenu_border);
	background-color: var(dropmenu_bgcolor);
}

/*---- ---- 4.2.6  Special*/

#pagehistory tr td {
	border-top:var(tabletop_border);
}

#pageText #pageTypeSpecial h2,
#pageText #pageTypeSpecial div#logindivid fieldset legend {
	color: var(specialh2_color);
}

#pageTypeSpecial div.searchPagination {
	border-top:var(tabletop_border);
	color:#666;
}

#pageTypeSpecial div#searchResults ul li{
	border-top: var(tabletop_border);
}

/*---- ---- 4.2.7  Admin*/

#pageText #pageTypeAdmin fieldset legend,
#pageText #pageTypeAdmin h2 {
	color: var(specialh2_color);
}

#pageTypeAdmin fieldset {
	border: var(specialfieldset_border);
}

/*-------------------------------------------------------------------
5.0 Internet Explorer 6 CSS
---------------------------------------------------------------------*/


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DbScriptDeploy.BLL.Data;
using DbScriptDeploy.BLL.Exceptions;
using DbScriptDeploy.BLL.Models;
using DbScriptDeploy.BLL.Security;
using DbScriptDeploy.BLL.Validators;

namespace DbScriptDeploy.BLL.Commands
{
    public interface IUserCreateCommand
    {
        UserModel Execute(string userName, string password);
    }
    public class UserCreateCommand : IUserCreateCommand
    {
        private readonly IDbContext _dbContext;
        private readonly IUserValidator _userValidator;
        private readonly IPasswordProvider _passwordProvider;

        public UserCreateCommand(IDbContext dbContext, IUserValidator userValidator, IPasswordProvider passwordProvider)
        {
            _dbContext = dbContext;
            _userValidator = userValidator;
            _passwordProvider = passwordProvider;
        }

        public UserModel Execute(string userName, string password)
        {
            UserModel user = new UserModel();
            user.UserName = userName;
            user.Password = password;
            user.PasswordExpired = true;
            user.CreateDate = DateTime.UtcNow;

            // validate before we try to hash the password
            ValidationResult result = _userValidator.Validate(user);
            if (!result.Success)
            {
                throw new ValidationException(result.Messages);
            }

            // hash the password
            user.Password = _passwordProvider.HashPassword(password, _passwordProvider.GenerateSalt());

            // insert new record
            string createDate = user.CreateDate.ToString(SQLiteDbContext.DateTimeFormat);
            string sql = $"INSERT INTO User (Id, UserName, Password, PasswordExpired, CreateDate) VALUES (@Id, @UserName, @Password, 1, '{createDate}')";
            _dbContext.ExecuteNonQuery(sql, user);

            return user;
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 46(2): 298 (1994)

#### Original name
Oxydothis nypicola K.D. Hyde, 1994

### Remarks
null


text:
Table point_2d holds the coordinates (x,y) of some unique points (more than two) in a plane.
Write a query to find the shortest distance between these points rounded to 2 decimals.
```
| x  | y  |
|----|----|
| -1 | -1 |
| 0  | 0  |
| -1 | -2 |
```
The shortest distance is 1.00 from point (-1,-1) to (-1,2). So the output should be:
```
| shortest |
|----------|
| 1.00     |
```
Note: The longest distance among all the points are less than 10000.


text: module.exports = require('./lib/forward');


text:
package org.apache.hawq.pxf.api;

/**
 * Abstract class that defines getting metadata of a table.
 */
public abstract class MetadataFetcher {
    protected Metadata metadata;

    /**
     * Constructs a MetadataFetcher.
     *
     */
    public MetadataFetcher() {

    }

    /**
     * Gets a metadata of a given table
     *
     * @param tableName table name
     * @return metadata of given table
     * @throws Exception if metadata information could not be retrieved
     */
    public abstract Metadata getTableMetadata(String tableName) throws Exception;
}


text:
:- module(ctrlcclean, [ctrlc_clean/1, delete_on_ctrlc/2, ctrlcclean/0],
	[assertions]).

:- use_module(library(system), [delete_file/1, working_directory/2]).

:- meta_predicate(ctrlc_clean(goal)).

ctrlc_clean(Goal) :- catch(Goal, control_c, ctrlcclean).

:- data delOnCtrlC/2.

delete_on_ctrlc(File, Ref) :-
        working_directory(Dir, Dir),
        asserta_fact(delOnCtrlC(Dir, File), Ref).

ctrlcclean :-
        retract_fact(delOnCtrlC(Dir, File)),
        working_directory(_, Dir),
        delete_file(File),
        fail.
ctrlcclean :- halt.


text:
<?php
class Producto_model extends CI_Model{
    public $ID,$nombre,$precio,$idCategoria;
    public function insert($arrayData){
        return $this->db->insert('productos',$arrayData);
    }

    public function getData(){
      //Nota a tener en cuenta: a Codeigniter no le mola que los nombres de los campos de las tablas sean iguales,
      //es decir, producto.nombre y categoria.nombre... El nombre tiene que ser distinto para que te devuelva los
      //valores que quieres exactamente :D :D
      $sql = "SELECT p.ID, p.nombreP, p.precio,c.nombre FROM productos p, categorias c WHERE c.ID= p.IDCategoria";
      $result = $this->db->query($sql)->result();
      return $result;
    }

    public function borrar($data){
        $sql = "DELETE FROM PRODUCTOS WHERE ID=". $data;
       return $this->db->simple_query($sql);
    }

    public function getLastId(){
        $sql = "SELECT ID FROM PRODUCTOS order by ID DESC LIMIT 1";
        $result = $this->db->query($sql)->result();
        if($result==''){
            return 0;
        }
        else{
            return $result;
        }

    }
}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.webshare;

import org.chromium.content_public.browser.WebContents;
import org.chromium.services.service_manager.InterfaceFactory;
import org.chromium.webshare.mojom.ShareService;

/**
 * Factory that creates instances of ShareService.
 */
public class ShareServiceImplementationFactory implements InterfaceFactory<ShareService> {
    private final WebContents mWebContents;

    public ShareServiceImplementationFactory(WebContents webContents) {
        mWebContents = webContents;
    }

    @Override
    public ShareService createImpl() {
        return new ShareServiceImpl(mWebContents);
    }
}


text:
package Team4450.Lib;

import java.util.EventObject;
import java.util.EventListener;
import java.util.HashSet;
import java.util.Set;

import edu.wpi.first.wpilibj.Joystick;

/**
* This class handles the interface to the GamePad buttons. It monitors
* the state of the GP buttons and raises events when button state changes.
*/

public class GamePad
{
	private final Object	caller;
	private final Joystick	joyStick;
	private 				Set<GamePadEventListener> listeners = new HashSet<GamePadEventListener>();
	private					Set<GamePadButton> buttons = new HashSet<GamePadButton>();
	private Thread			monitorGamePadThread;
	private String			gamePadName = "";

	private static GamePadButton	povButton;

	public  double			deadZone = 0.1;

	/**
	 * Constructor which adds all GamePad buttons to be monitored.
	 * @param joyStick JoyStick object representing the GamePad.
	 * @param name Identifying name for the pad.
	 * @param caller calling class instance (use 'this').
	 */

	public GamePad(Joystick joyStick, String name, Object caller)
	{
		GamePadButton	button;

		Util.consoleLog("%s (all buttons)", name);

		this.joyStick = joyStick;
		gamePadName = name;
		this.caller = caller;

		// Add all the gamepad buttons to be monitored.

		button = new GamePadButton(GamePadButtonIDs.A);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.B);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.X);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.Y);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.LEFT_BUMPER);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.RIGHT_BUMPER);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.BACK);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.START);
		buttons.add(button);

		button = new GamePadButton(GamePadButtonIDs.POV);
		buttons.add(button);

		Start();
	}

	/**
	 * Constructor which adds single button to be monitored.
	 * @param joyStick JoyStick object representing the GamePad.
	 * @param name Identifying name for the pad.
	 * @param button Enum value identifying button to add.
	 * @param caller Calling class instance (use 'this').
	 */

	GamePad(Joystick joyStick, String name, GamePadButtonIDs	button, Object caller)
	{
		Util.consoleLog("%s (single button)", name);

		this.joyStick = joyStick;
		gamePadName = name;
		this.caller = caller;

		AddButton(button);
	}

	/**
	 * Add additonal GamePadButton button to be monitored.
	 * @param button Enum value identifying button to add.
	 * @return New button added or existing button.
	 */

	public GamePadButton AddButton(GamePadButtonIDs button)
	{
		Util.consoleLog("%s (%s)", gamePadName, button.name());

		GamePadButton gpButton = FindButton(button);

		if (gpButton == null)
		{
			gpButton = new GamePadButton(button);
			buttons.add(gpButton);
		}

		return gpButton;
	}

	/**
	 * Find GamePadButton button by type in the list of configured buttons.
	 * @param buttonID Enum value identifying button to find.
	 * @return Button or null.
	 */

	public GamePadButton FindButton(GamePadButtonIDs button)
	{
		Util.consoleLog("%s (%s)", gamePadName, button.name());

        for (GamePadButton gpButton: buttons)
        	if (gpButton.id.value == button.value) return gpButton;

        return null;
	}

	/**
	 *  Call to start GamePad button monitoring once all buttons are added.
	 */

	public void Start()
	{
		Util.consoleLog(gamePadName);

		monitorGamePadThread = new MonitorGamePad();
		monitorGamePadThread.start();
	}

	/**
	 * Call to stop monitoring GamePad buttons.
	 */
	public void Stop()
	{
		Util.consoleLog(gamePadName);

		monitorGamePadThread.interrupt();
	}

	public void dispose()
	{
		Util.consoleLog(gamePadName);

		monitorGamePadThread.interrupt();
	}

	public double GetLeftX()
	{
		double x;

		x = joyStick.getRawAxis(0);
		if (Math.abs(x) < deadZone) x = 0.0;
		return x;
	}

	public double GetLeftY()
	{
		double y;

		y = joyStick.getRawAxis(1);
		if (Math.abs(y) < deadZone) y = 0.0;
		return y;
	}

	public double GetRightX()
	{
		double x;

		x = joyStick.getRawAxis(4);
		if (Math.abs(x) < deadZone) x = 0.0;
		return x;
	}

	public double GetRightY()
	{
		double y;

		y = joyStick.getRawAxis(5);
		if (Math.abs(y) < deadZone) y = 0.0;
		return y;
	}

	public double GetRightTrigger()
	{
		double x;

		x = joyStick.getRawAxis(2);
		if (Math.abs(x) < deadZone) x = 0.0;
		return x;
	}

	public double GetLeftTrigger()
	{
		double y;

		y = joyStick.getRawAxis(3);
		if (Math.abs(y) < deadZone) y = 0.0;
		return y;
	}

	/**
	 * Get the actual instantaneous POV angle value directly from the GamePad.
	 * @return Angle in degrees.
	 */
	public int GetPOVAngle()
	{
		return joyStick.getPOV();
	}

	/**
	 * Get the last set POV angle. Only works if POV button is being monitored.
	 * @return Last POV angle in degrees or -1 if not set or button not defined.
	 */
	public int GetLastPOVangle()
	{
		if (povButton == null) povButton = FindButton(GamePadButtonIDs.POV);

		if (povButton != null) return povButton.lastPOVAngle;

		return -1;
	}

	// GamePad Button Monitor thread.

	private class MonitorGamePad extends Thread
	{
		boolean previousState;
		int		previousPOVAngle;

		MonitorGamePad()
		{
			this.setName("Monitor " + gamePadName);
	    }

	    public void run()
	    {
	    	Util.consoleLog(gamePadName);

	    	try
	    	{
    	    	while (!isInterrupted())
    	    	{
    	    		// Loop through the set of Game Pad buttons and read the value of each
    	    		// saving the button state and raising events for change in button state.

    	            for (GamePadButton button: buttons)
    	            {
    	            	if (button.id == GamePadButtonIDs.POV)
    	            	{
    	            		previousPOVAngle = button.povAngle;

    	            		button.povAngle = joyStick.getPOV();

     	            		if (button.povAngle != previousPOVAngle) notifyButtonDown(button);

     	            		if (button.povAngle != -1) button.lastPOVAngle = button.povAngle;
    	            	}
    	            	else
    	            	{
              	    		if (joyStick.getRawButton(button.id.value))
              				{
              					previousState = button.currentState;
              					button.currentState = true;

              					//if (button.id.equals(GamePadButtons.TOP_MIDDLE)) LCD.consoleLog("button=%s-%s true", joyStickName, button.id.name());

              					if (!previousState)
              					{
              						button.latchedState = !button.latchedState;

              						notifyButtonDown(button);
              					}
              				}
              				else
              				{
              					previousState = button.currentState;
              					button.currentState = false;

              					//if (button.equals(GamePadButtons.TOP_MIDDLE)) LCD.consoleLog("button=%s-%s false", joyStickName, button.id.name());

              					if (previousState) notifyButtonUp(button);
              				}
    	            	}
    	            }

    	            sleep(50);
    	    	}
	    	}
	    	catch (InterruptedException e) {}
	    	catch (Throwable e) {e.printStackTrace(Util.logPrintStream);}
	    }
	}	// end of MonitorJoystick thread class.

	/**
	 * Get the current state of the button.
	 * @param button Enum identifying button.
	 * @return True if pressed.
	 */
	public boolean GetCurrentState(GamePadButtonIDs button)
	{
      for (GamePadButton gpButton: buttons)
      	if (gpButton.id.equals(button)) return gpButton.currentState;

      return false;
	}

	/**
	 * Get the latched state of the button. This is toggled by each button press.
	 * @param button Enum identifying button.
	 * @return True or false as set by last button press.
	 */
	public boolean GetLatchedState(GamePadButtonIDs button)
	{
      for (GamePadButton gpButton: buttons)
      	if (gpButton.id.equals(button)) return gpButton.latchedState;

      return false;
	}

  // Event Handling classes.

  /**
   *  Event description class returned to event handlers.
   */

  public class GamePadEvent extends EventObject
  {
	  private static final long serialVersionUID = 1L;

	  public GamePadButton	button;

	  public GamePadEvent(Object source, GamePadButton button)
	  {
		  super(source);
		  this.button = button;
	  }
  }

  /**
   *  Interface defintion for event listener. Actual listener implements
   *  the actions associated with button up and down events.
   */

  public interface GamePadEventListener extends EventListener
  {
      public void ButtonDown(GamePadEvent GamePadEvent);

      public void ButtonUp(GamePadEvent GamePadEvent);
  }

  /**
   *  Add (register) an event listener.
   * @param listener function to register
   */

  public void addGamePadEventListener(GamePadEventListener listener)
  {
      this.listeners.add(listener);
  }

  /**
   *  Remove an event listener registration.
   * @param listener function to unregister
   */

  public void removeGamePadEventListener(GamePadEventListener listener)
  {
      this.listeners.remove(listener);
  }

  // Notify all registered handlers of button up event.

  private void notifyButtonUp(GamePadButton button)
  {
      for (GamePadEventListener GamePadEventListener: listeners)
      {
          GamePadEventListener.ButtonUp(new GamePadEvent(caller, button));
      }
  }

  // Notify all registered handlers of button down event.

  private void notifyButtonDown(GamePadButton button)
  {
      for (GamePadEventListener GamePadEventListener: listeners)
      {
          GamePadEventListener.ButtonDown(new GamePadEvent(caller, button));
      }
  }

  /**
  *  Button object which contains button id and current and latched state and POV value of the button
  *  when contained in an event and if you directly request button state.
  **/

  public class GamePadButton
  {
	  public GamePadButtonIDs	id;
      public boolean		currentState, latchedState;
      public int			povAngle = -1, lastPOVAngle;

      public GamePadButton(GamePadButtonIDs buttonID)
      {
    	  id = buttonID;
      }
  }

  /**
   *  Gamepad button id enumeration.
   **/

  public enum GamePadButtonIDs
  {
      A (1),
      B (2),
      X (3),
      Y (4),
      LEFT_BUMPER (5),
      RIGHT_BUMPER (6),
      BACK (7),
      START (8),
      POV (9);

      private int value;

      private GamePadButtonIDs(int value)
      {
    	  this.value = value;
      }
  }
}


text:
class Refinery::BasePresenter

  DEFAULT_FIELDS = {
    :title              => Proc.new { |p| p.model.present? ? p.model.class.name.titleize : nil },
    :path               => Proc.new { |p| p.title },
    :browser_title      => nil,
    :meta_description   => nil,
    :meta_keywords      => nil
  }

  attr_reader :model

  def initialize(obj)
    @model = obj
  end

  def method_missing(method, *args)
    if @model.respond_to? method
      @model.send method
    elsif DEFAULT_FIELDS.has_key? method
      (value = DEFAULT_FIELDS[method]).is_a?(Proc) ? value.call(self) : value
    else
      raise NoMethodError.new("#{self.class.name} doesn't know #{method}. Define or delegate it.", method)
    end
  end

end


text:
[![CI Status](http://img.shields.io/travis/qiaokai/QBPwdModule.svg?style=flat)](https://travis-ci.org/qiaokai/QBPwdModule)
[![Version](https://img.shields.io/cocoapods/v/QBPwdModule.svg?style=flat)](http://cocoapods.org/pods/QBPwdModule)
[![License](https://img.shields.io/cocoapods/l/QBPwdModule.svg?style=flat)](http://cocoapods.org/pods/QBPwdModule)
[![Platform](https://img.shields.io/cocoapods/p/QBPwdModule.svg?style=flat)](http://cocoapods.org/pods/QBPwdModule)

```
platform :ios, '8.0'
target 'target_name' do
pod 'QBPwdModule'
end
```

SDK使用说明:

---------------

>1.初始化:

```
#import "QBKeyboard.h"

QBKeyboard *keyboard = [[QBKeyboard alloc] initWithFrame:CGRectZero];
keyboard.keyboardType = QBKeyboardTypeNumandX;
keyboard.delegate = self;
textField.inputView = keyboard;

----- or----
#import "UITextField+QBKeyboard.h"

[self.textfield addKeyBoardViewWithType:QBKeyboardTypeNumandABC title:@"廊坊安全键盘"];
```

>2.实现协议:

```
- (BOOL)keyboard:(QBKeyboard *)keyboard shouldInsertText:(NSString *)text;
```

```
- (BOOL)keyboardShouldReturn:(QBKeyboard *)keyboard;
```

```
- (BOOL)keyboardShouldDeleteBackward:(QBKeyboard *)keyboard;
```

## Example

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

QBPwdModule is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "QBPwdModule"
```

## Author

qiaokai, qiaokai@qianbao.com

## License

QBPwdModule is available under the MIT license. See the LICENSE file for more info.


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller{

  public function __construct()
  {
    parent::__construct();
    $this->load->model('General');
    $this->load->helper(array('url'));
  }

  function index()
  {
    $this->load->model('user_model');
    $data = array();

    $data['view_rent'] = $this->general->get_rumah_kontrakan();
    $data['view_kos'] = $this->general->get_rumah_kos();

        $page=$this->uri->segment(3);
          	$limit=8;
    		if(!$page):
    		$offset = 0;
    		else:
    		$offset = $page;
    		endif;
        $jumlah_data = $this->user_model->jumlah_data();
        $this->load->library('pagination');
        $config['base_url'] = base_url().'welcome/index/';
        $config['total_rows'] = $jumlah_data;
        $config['per_page'] = 4;
        $from = $this->uri->segment(3);
        $this->pagination->initialize($config);
        $data['get_rumah_kos'] = $this->user_model->get_rumah_kos($config['per_page'],$from);
        $data['get_rumah_kontrakan'] = $this->user_model->get_rumah_kontrakan($config['per_page'],$from);

        $this->general->view('dashboard/menu',$data );

  }

  public function TermsAndCondition()
  {

      $data['master_termscondition'] = $this->db->get('master_termscondition')->result_array();
      $this->general->load('dashboard/TermsAndCondition', $data);

  }
  public function Blog()
  {
    $this->load->model('user_model');

    $data = array();
    $page=$this->uri->segment(3);
        $limit=8;
    if(!$page):
    $offset = 0;
    else:
    $offset = $page;
    endif;
    $jumlah_data = $this->user_model->jumlah_data();
    $this->load->library('pagination');
    $config['base_url'] = base_url().'welcome/Blog/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 4;
    $from = $this->uri->segment(3);
    $this->pagination->initialize($config);

    $data['blog_kos'] = $this->user_model->get_rumah_kos($config['per_page'],$from);
    $data['blog_kontrakan'] = $this->user_model->get_rumah_kontrakan($config['per_page'],$from);
    $this->general->load('dashboard/Blog/menu',$data);
  }
  public function Blog_kos()
  {
    $this->load->model('user_model');
    $page=$this->uri->segment(3);
        $limit=8;
    if(!$page):
    $offset = 0;
    else:
    $offset = $page;
    endif;
    $jumlah_data = $this->user_model->jumlah_data();
    $this->load->library('pagination');
    $config['base_url'] = base_url().'welcome/Blog_kos/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 4;
    $from = $this->uri->segment(3);
    $this->pagination->initialize($config);

    $data['blog_kos'] = $this->user_model->get_rumah_kos($config['per_page'],$from);
    $this->general->load('dashboard/Blog/menu_kos',$data);
  }
  public function Blog_kontrakan()
  {

    $this->load->model('user_model');
    $page=$this->uri->segment(3);
        $limit=8;
    if(!$page):
    $offset = 0;
    else:
    $offset = $page;
    endif;
    $jumlah_data = $this->user_model->jumlah_data();
    $this->load->library('pagination');
    $config['base_url'] = base_url().'welcome/Blog_kontrakan/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 4;
    $from = $this->uri->segment(3);
    $this->pagination->initialize($config);
    $data['blog_kontrakan'] = $this->user_model->get_rumah_kontrakan($config['per_page'],$from);
    $this->general->load('dashboard/Blog/menu_kontrakan',$data);
  }
  public function Blog_termsandcondition()
  {
    $data['master_termscondition'] = $this->db->get('master_termscondition')->result_array();
    $this->general->load('dashboard/Blog/menu_termsandcondition', $data);
  }
  public function Blog_faqandhelp()
  {
    $this->general->load('dashboard/Blog/menu_faqandhelp');
  }
  public function detail_rumah_kos($idkos)
  {
    $data = array();
    $data['master_rumah_kos'] = $this->db->get('master_rumah_kos')->result_array();
    $data['master_rumah_kos'] = $this->db->where_in('id',$idkos)->get('master_rumah_kos')->row_array();
    $this->general->load('DetailRumah/detail_kos', $data);
  }
public function tesmaps()
{
  $data = array();

  $data['view_rent'] = $this->general->get_rumah_kontrakan();
  $data['view_kos'] = $this->general->get_rumah_kos();
  $this->load->view('tesmaps', $data);
}

}


text:
package com.company;

import java.util.Date;

public class User{

    private static final String FIELD_SEX = "sex";
    private static final String FIELD_DESC = "desc";
    private static final String FIELD__ID = "_id";
    private static final String FIELD_NAME = "name";
    private static final String FIELD_AVATAR = "avatar";

    private int sex;
    private String desc;
    private Long _id;
    private String name;
    private String avatar;

    public User(){

    }

    public void set_sex(int sex) {
        sex = sex;
    }

    public int get_sex() {
        return sex;
    }

    public void set_desc(String desc) {
        desc = desc;
    }

    public String get_desc() {
        return desc;
    }

    public void set__id(Long _id) {
        _id = _id;
    }

    public Long get__id() {
        return _id;
    }

    public void set_name(String name) {
        name = name;
    }

    public String get_name() {
        return name;
    }

    public void set_avatar(String avatar) {
        avatar = avatar;
    }

    public String get_avatar() {
        return avatar;
    }

    @Override
    public String toString(){
        return "sex = " + sex + ", desc = " + desc + ", _id = " + _id + ", name = " + name + ", avatar = " + avatar;
    }

}


text:
This D3 plugin makes it easy to generate hexmaps from data that uses the Open Data Institute's [HexJSON format](https://odileeds.org/projects/hexmaps/hexjson.html). The plugin provides a single function that takes a HexJSON object and adds the properties needed to render it as a hexmap of a given size. The `renderHexJSON` function calculates the hex size necessary to render the hexmap within an svg of the specified dimensions, and generates the position and the points for each hex. This data is returned as an array of hexes that you can render directly with D3 as polygons, by using the *x* and *y* coordinates to position each hex, and the *points* property as the *points* attribute of its polygon. Hex coordinates are rendered according to the [coordinate system](http://www.redblobgames.com/grids/hexagons/#coordinates) specified by the *layout* property of the HexJSON provided.

## Installing

If you use NPM, `npm install d3-hexjson`. Otherwise, download the [latest release](https://github.com/olihawkins/d3-hexjson/releases/latest) and use **d3-hexjson.min.js**, which can be found in the build directory. The module is designed to be used in conjunction with the core [D3 library](https://github.com/d3/d3) (see the [example](#example) below).

## API Reference

# d3.renderHexJSON(hexjson, width, height)

Returns an array of hexes from a HexJSON object, adding to each hex the properties needed to render them as a hexmap with D3. The function calculates the appropriate size to render the hexes within an svg of the given width and height. The central pixel coordinates of each hex are stored in *x* and *y* properties, while the *vertices* property holds an array of coordinate pairs, which specify the position of each vertex relative to x and y. The *points* property contains the vertex coordinates as a string that can be inserted directly into the *points* attribute of a polygon. The key used to reference each hex within the HexJSON object is stored within each hex in the *key* property. As these properties are added to the hexes stored in the source HexJSON, the hexes and their properties can be accessed either through the returned array or through the original HexJSON object (if you need to merge additional data based on the key, for example).

The full list of properties that the function adds to each hex is as follows:

* **key** - The key against which the hex is stored in the source HexJSON
* **qc** - The absolute column number of the hex, measured left to right from zero
* **rc** - The absolute row number of the hex, measured top to bottom from zero
* **x** - The pixel coordinate of the centre of the hex within the svg on the x-axis
* **y** - The pixel coordinate of the centre of the hex within the svg on the y-axis
* **vertices** - The pixel coordinates of the vertices **relative to x and y**
* **points** - The vertex positions represented as a string for use in an svg polygon

Note that while the absolute row numbers of each hex are represented internally in the *rc* property from top to bottom, the *r* property of the HexJSON data represents row numbers from **bottom to top**. This follows the row numbering convention used in the example HexJSON implementation provided by the ODI in their hexmap of [UK Parliamentary constituencies](https://odileeds.org/projects/hexmaps/constituencies.html).

# d3.getGridForHexJSON(hexjson)

Returns a new hexjson object representing the complete grid for a hexjson dataset. The returned grid has the same *layout* as the hexjson provided, and the same number of columns and rows needed to represent the data. The main purpose of this function is to produce the hex data needed to display a background grid for the given dataset (see the [example with background grid](#example-with-background-grid) below), but it also provides a convenient way to generate hex grids for other uses.

## Example

The following example shows the most common usage. See the code in action in this [block](https://bl.ocks.org/henryjameslau/5daca6e4667c41ae85959da614a37787) by [Henry Lau](https://github.com/henryjameslau).

Given this HexJSON stored in the file *example.hexjson*:

```javascript
{
	"layout":"odd-r",
	"hexes":{
		"Q0R0":{"q":0,"r":0},
		"Q1R0":{"q":1,"r":0},
		"Q2R0":{"q":2,"r":0},
		"Q3R0":{"q":3,"r":0},
		"Q0R1":{"q":0,"r":1},
		"Q1R1":{"q":1,"r":1},
		"Q2R1":{"q":2,"r":1},
		"Q3R1":{"q":3,"r":1},
		"Q0R2":{"q":0,"r":2},
		"Q1R2":{"q":1,"r":2},
		"Q2R2":{"q":2,"r":2},
		"Q3R2":{"q":3,"r":2},
		"Q0R3":{"q":0,"r":3},
		"Q1R3":{"q":1,"r":3},
		"Q2R3":{"q":2,"r":3},
		"Q3R3":{"q":3,"r":3}
	}
}
```

A hexmap of the data can be rendered in the following way:

```html
<html>
<head>
<style>
#vis {
	margin: 0;
	padding: 0;
	text-align: center;
	font-family: sans-serif;
	font-size: 10pt;
}
</style>
</head>
<body>
<div id="vis"></div>
<script src="d3.min.js"></script>
<script src="d3-hexjson.min.js"></script>
<script>

d3.json("example.hexjson", function(error, hexjson) {

	// Set the size and margins of the svg
	var margin = {top: 10, right: 10, bottom: 10, left: 10},
		width = 500 - margin.left - margin.right,
		height = 420 - margin.top - margin.bottom;

	// Create the svg element
	var svg = d3
		.select("#vis")
		.append("svg")
		.attr("width", width + margin.left + margin.right)
		.attr("height", height + margin.top + margin.bottom)
		.append("g")
		.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	// Render the hexes
	var hexes = d3.renderHexJSON(hexjson, width, height);

	// Bind the hexes to g elements of the svg and position them
	var hexmap = svg
		.selectAll("g")
		.data(hexes)
		.enter()
		.append("g")
		.attr("transform", function(hex) {
			return "translate(" + hex.x + "," + hex.y + ")";
		});

	// Draw the polygons around each hex's centre
	hexmap
		.append("polygon")
		.attr("points", function(hex) {return hex.points;})
		.attr("stroke", "white")
		.attr("stroke-width", "2")
		.attr("fill", "#b0e8f0");

	// Add the hex codes as labels
	hexmap
		.append("text")
		.append("tspan")
		.attr("text-anchor", "middle")
		.text(function(hex) {return hex.key;});
});

</script>
</body>
</html>
```

The example will look like this:

![alt text](examples/example.png "Example hexmap")

## Example With Background Grid

The following example shows how to render hexjson data as a hexmap with a background grid. Use the `getGridForHexJSON` function to generate a hexjson object representing the background grid for the source data, then render the background hexes **before** rendering the data hexes on top. [See it in action in this block](https://bl.ocks.org/henryjameslau/4057a986db97e475b1a154c9fcf1fa7d).

Given this HexJSON stored in the file *example-grid.hexjson*:

```javascript
{
	"layout":"odd-r",
	"hexes": {
		"Q0R0":{"q":0,"r":0},
		"Q1R1":{"q":1,"r":1},
		"Q1R2":{"q":1,"r":2},
		"Q2R3":{"q":2,"r":3}
	}
}
```

A hexmap of the data with a background grid can be rendered in the following way:

```html
<html>
<head>
<style>
#vis {
	margin: 0;
	padding: 0;
	text-align: center;
	font-family: sans-serif;
	font-size: 10pt;
}
</style>
</head>
<body>
<div id="vis"></div>
<script src="d3.min.js"></script>
<script src="d3-hexjson.min.js"></script>
<script>

d3.json("example-grid.hexjson", function(error, hexjson) {

	// Set the size and margins of the svg
	var margin = {top: 10, right: 10, bottom: 10, left: 10},
		width = 500 - margin.left - margin.right,
		height = 420 - margin.top - margin.bottom;

	// Create the svg element
	var svg = d3
		.select("#vis")
		.append("svg")
		.attr("width", width + margin.left + margin.right)
		.attr("height", height + margin.top + margin.bottom)
		.append("g")
		.attr("transform", "translate(" + margin.left + "," + margin.top + ")");

	// Create the grid hexes and render them
	var grid = d3.getGridForHexJSON(hexjson);
	var gridHexes = d3.renderHexJSON(grid, width, height);

	// Render the data hexes
	var hexes = d3.renderHexJSON(hexjson, width, height);

	// Draw the background grid BEFORE the data

	// Bind the grid hexes to g.grid elements of the svg and position them
	var hexgrid = svg
		.selectAll("g.grid")
		.data(gridHexes)
		.enter()
		.append("g")
		.attr("transform", function(hex) {
			return "translate(" + hex.x + "," + hex.y + ")";
		});

	// Draw the polygons around each grid hex's centre
	hexgrid
		.append("polygon")
		.attr("points", function(hex) {return hex.points;})
		.attr("stroke", "#b0b0b0")
		.attr("stroke-width", "1")
		.attr("fill", "#f0f0f0");

	// Bind the data hexes to g.data elements of the svg and position them
	var hexmap = svg
		.selectAll("g.data")
		.data(hexes)
		.enter()
		.append("g")
		.attr("transform", function(hex) {
			return "translate(" + hex.x + "," + hex.y + ")";
		});

	// Draw the polygons around each data hex's centre
	hexmap
		.append("polygon")
		.attr("points", function(hex) {return hex.points;})
		.attr("stroke", "white")
		.attr("stroke-width", "2")
		.attr("fill", "#b0e8f0");

	// Add the codes for the data hexes as labels
	hexmap
		.append("text")
		.append("tspan")
		.attr("text-anchor", "middle")
		.text(function(hex) {return hex.key;});
});

</script>
</body>
</html>
```

The example will look like this:

![alt text](examples/example-grid.png "Example hexmap with background grid")

These examples can also be found in the *examples* directory.


text:
using System;
using System.Linq;
using System.Collections.Generic;
using ChristmasPi.Data.Models.Hardware;
using ChristmasPi.Data.Exceptions;
using ChristmasPi.Data.Models;
using ChristmasPi.Data;
using ChristmasPi.Hardware.Factories;

namespace ChristmasPi.Hardware {
    public class HardwareManager {
        #region Singleton Methods
        private static readonly HardwareManager _instance = new HardwareManager();
        public static HardwareManager Instance { get { return _instance; } }
        #endregion

        public Dictionary<int, RPI_Type> RPITypeDict { get; private set; }
        private Hardware_Type hardwareType;

        public void Init(bool defaultToRpi = false) {
            RPITypeDict = RPIType.GetTypeDictionary();
            hardwareType = HardwareType.GetHardwareType(defaultToRpi);
        }

        /// <summary>
        /// Gets list of renderers and necessary info about the renderer for setup
        /// </summary>
        /// <returns>An array of HardwareInfoResult's</returns>
        public HardwareInfoResult[] GetRendererInfo() {
            RendererType[] rendererTypes = (RendererType[])Enum.GetValues(typeof(RendererType));
            // filter out unknown
            rendererTypes = rendererTypes.Where(rt => rt != RendererType.UNKNOWN).ToArray();
            List<RendererType> supportedRendererTypes = new List<RendererType>();
            foreach (RendererType type in rendererTypes) {
                if (type == RendererType.TEST_RENDER && !ConfigurationManager.Instance.RuntimeConfiguration.AllowTestRenderer)
                    continue;
                if (RenderFactory.GetSupportedHardwareForRenderer(type).HasFlag(hardwareType))
                    supportedRendererTypes.Add(type);
            }
            List<HardwareInfoResult> results = new List<HardwareInfoResult>();
            foreach (RendererType type in supportedRendererTypes) {
                RendererHardwareInfo info = RenderFactory.GetRendererHardwareInfoForRenderer(type);
                results.Add(new HardwareInfoResult() {
                    Name = Enum.GetName(typeof(RendererType), type),
                    Placeholder = info.GetPlaceholderValue(),
                    Image = info.GetImageUrl(),
                    ValidationString = info.GetValidationString()
                });
            }
            return results.ToArray();
        }
    }
    public class HardwareInfoResult {
        /// <summary>
        /// The name of the renderer
        /// </summary>
        public string Name;
        /// <summary>
        /// The default pin or port needed to setup the renderer
        /// </summary>
        public string Placeholder;
        /// <summary>
        /// Image URL for any hardware diagrams
        /// </summary>
        public string Image;
        /// <summary>
        /// The validation string
        /// </summary>
        /// <notes>This is either a csv or an empty string.
        /// The csv denotes acceptable values while an empty string allows all values</notes>
        public string ValidationString;
    }
}


text:
using System;
using CoreGraphics;
using System.Collections.Generic;
using UIKit;

namespace BasicTable {
	public class HomeScreen : UIViewController {
		UITableView table;

		public HomeScreen ()
		{
		}

		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			var width = View.Bounds.Width;
			var height = View.Bounds.Height;

			table = new UITableView(new CGRect(0, 0, width, height));
			table.AutoresizingMask = UIViewAutoresizing.All;
			CreateTableItems();
			Add (table);
		}

		protected void CreateTableItems ()
		{
			List<string> tableItems = new List<string> ();
			tableItems.Add ("Vegetables");
			tableItems.Add ("Fruits");
			tableItems.Add ("Flower Buds");
			tableItems.Add ("Legumes");
			tableItems.Add ("Bulbs");
			tableItems.Add ("Tubers");
			table.Source = new TableSource(tableItems.ToArray(), this);
		}

		public override bool PrefersStatusBarHidden ()
		{
			return true;
		}
	}
}


text:
title: Quick Start
description: Get up and running with your first Ubiquits application as quick as possible. What are you waiting for?
date: 2016-06-02
collection: guide
collectionSort: 0
layout: guide.hbs
-----------------

## Prerequisites
* Node installed (v6.2.0 is recommended)

## Installation

Ubiquits uses a commandline tool `u` to initialize a new project, and manage the building/watching/deployment/debugging etc within it's own shell.

To get started, run the following command in your console *in an empty directory*:

```bash
npm install -g @ubiquits/toolchain && u
```

This will install the toolchain then initialize a new project by cloning the boilerplate, and running installation.

Once installation is complete, you will be taken on a brief tour of the features to get you familiarized with the cli.

For more information, visit the [cli guide page](/guide/cli)


text:
package afc.ant.modular;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collections;

import junit.framework.TestCase;

public class ModuleUtilTest extends TestCase
{
    public void testIsModule_NullValue()
    {
        assertFalse(ModuleUtil.isModule(null));
    }

    public void testIsModule_NotModule()
    {
        assertFalse(ModuleUtil.isModule(new Object()));
    }

    public void testIsModule_ModuleInfo()
    {
        assertFalse(ModuleUtil.isModule(new ModuleInfo("foo", new MockModuleLoader())));
    }

    public void testIsModule_Module()
    {
        assertTrue(ModuleUtil.isModule(new Module("foo/")));
    }

    public void testIsModule_Module_DifferentClassLoader() throws Exception
    {
        final Object module = createModuleWithDifferentClassLoader("foo/", new ModuleClassLoader());

        assertTrue(ModuleUtil.isModule(module));
    }

    public void testGetPath_NullModule()
    {
        try {
            ModuleUtil.getPath(null);
            fail();
        }
        catch (NullPointerException ex) {
            assertEquals("module", ex.getMessage());
        }
    }

    public void testGetPath_NonModule()
    {
        try {
            ModuleUtil.getPath(new Object());
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + Object.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetPath_ModuleInfo()
    {
        try {
            ModuleUtil.getPath(new ModuleInfo("foo/", new MockModuleLoader()));
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + ModuleInfo.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetPath_Module()
    {
        assertSame("foo/", ModuleUtil.getPath(new Module("foo/")));
    }

    public void testGetPath_Module_DifferentClassLoader() throws Exception
    {
        assertSame("foo/", ModuleUtil.getPath(createModuleWithDifferentClassLoader("foo/", new ModuleClassLoader())));
    }

    public void testGetDependencies_NullModule()
    {
        try {
            ModuleUtil.getDependencies(null);
            fail();
        }
        catch (NullPointerException ex) {
            assertEquals("module", ex.getMessage());
        }
    }

    public void testGetDependencies_NonModule()
    {
        try {
            ModuleUtil.getDependencies(new Object());
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + Object.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetDependencies_ModuleInfo()
    {
        try {
            ModuleUtil.getDependencies(new ModuleInfo("foo/", new MockModuleLoader()));
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + ModuleInfo.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetDependencies_Module()
    {
        final Module module = new Module("foo/");
        final Module dep1 = new Module("bar/");
        final Module dep2 = new Module("baz/");
        module.setDependencies(new Module[]{dep1, dep2});

        assertSame(module.getDependencies(), ModuleUtil.getDependencies(module));
        assertEquals(TestUtil.set(dep1, dep2), ModuleUtil.getDependencies(module));
    }

    public void testGetDependencies_Module_DifferentClassLoader() throws Exception
    {
        final ModuleClassLoader classLoader = new ModuleClassLoader();
        final Object module = createModuleWithDifferentClassLoader("foo/", classLoader);
        final Object dep = createModuleWithDifferentClassLoader("bar/", classLoader);
        final Object depArray = createModuleArrayWithDifferentClassLoader(1, classLoader);
        Array.set(depArray, 0, dep);

        // invoking module.setDependencies(depArray) via reflection
        final Method setDependencies = module.getClass().getDeclaredMethod("setDependencies", depArray.getClass());
        setDependencies.setAccessible(true);
        setDependencies.invoke(module, depArray);

        assertEquals(Collections.singleton(dep), ModuleUtil.getDependencies(module));
    }

    public void testGetAttributes_NullModule()
    {
        try {
            ModuleUtil.getAttributes(null);
            fail();
        }
        catch (NullPointerException ex) {
            assertEquals("module", ex.getMessage());
        }
    }

    public void testGetAttributes_NonModule()
    {
        try {
            ModuleUtil.getAttributes(new Object());
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + Object.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetAttributes_ModuleInfo()
    {
        try {
            ModuleUtil.getAttributes(new ModuleInfo("foo/", new MockModuleLoader()));
            fail();
        }
        catch (IllegalArgumentException ex) {
            assertEquals("Unsupported module type. Expected: '" + Module.class.getName() +
                    "', was: '" + ModuleInfo.class.getName() + "'.", ex.getMessage());
        }
    }

    public void testGetAttributes_Module()
    {
        final Module module = new Module("foo/");
        module.addAttribute("123", "222");
        module.addAttribute("444", "111");

        assertSame(module.getAttributes(), ModuleUtil.getAttributes(module));
        assertEquals(TestUtil.map("123", "222", "444", "111"), ModuleUtil.getAttributes(module));
    }

    public void testGetAttributes_Module_DifferentClassLoader() throws Exception
    {
        final Object module = createModuleWithDifferentClassLoader("foo/", new ModuleClassLoader());
        // invoking module.addDependency(dep) via reflection
        final Method addDependency = module.getClass().getDeclaredMethod("addAttribute", String.class, Object.class);
        addDependency.setAccessible(true);
        addDependency.invoke(module, "123", "456");

        assertEquals(Collections.singletonMap("123", "456"), ModuleUtil.getAttributes(module));
    }

    private static Object createModuleWithDifferentClassLoader(final String path, final ClassLoader cl) throws Exception
    {
        final Class<?> c = cl.loadClass(Module.class.getName());

        assertNotSame(c, Module.class);

        final Constructor<?> constructor = c.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);

        return constructor.newInstance(path);
    }

    private static Object createModuleArrayWithDifferentClassLoader(final int size, final ClassLoader cl) throws Exception
    {
        final Class<?> c = cl.loadClass(Module.class.getName());

        assertNotSame(c, Module.class);

        return Array.newInstance(c, size);
    }

    private static class ModuleClassLoader extends ClassLoader
    {
        public ModuleClassLoader() throws IOException
        {
            /* Defining Module and its nested classes explicitly so that
             * this class loader does not ask the parent class loader to load them,
             * and a brand new classes are associated with this class loader.
             */
            defineClass(Module.class.getName());
            // This code is consistent: the binary name of the class ArrayListSet is used.
            defineClass(Module.class.getName() + "$ArraySet");
        }

        private void defineClass(final String className) throws IOException
        {
            final InputStream in = Module.class.getClassLoader().getResourceAsStream(
                    className.replace('.', '/') + ".class");

            try {
                final BufferedInputStream bufferedIn = new BufferedInputStream(in);
                final ByteArrayOutputStream buf = new ByteArrayOutputStream();

                int b;
                while ((b = bufferedIn.read()) >= 0) {
                    buf.write(b);
                }

                defineClass(className, buf.toByteArray(), 0, buf.size());
            }
            finally {
                in.close();
            }
        }
    }
}


text:
.. _api:

*************
API Reference
*************

Radiative transfer
------------------

Milne
^^^^^

.. currentmodule:: pyiacsun.radtran
.. autosummary::

   milne

Atlas
-----

.. currentmodule:: pyiacsun.atlas
.. autosummary::

   ftsread
   Delbouille73
   Neckel87


text:
"""GUI elements to display usage statistics."""

from grr.gui import renderers
from grr.gui.plugins import statistics
from grr.lib import aff4
from grr.lib import rdfvalue

class MostActiveUsers(statistics.PieChart):
  category = "/Server/User Breakdown/ 7 Day"
  description = "Active User actions in the last week."

  filtered_users = set(["GRRWorker", "GRREnroller", "GRRCron"])

  def Layout(self, request, response):
    """Filter the last week of user actions."""
    try:
      # TODO(user): Replace with Duration().
      now = int(rdfvalue.RDFDatetime().Now())
      fd = aff4.FACTORY.Open("aff4:/audit/log", aff4_type="VersionedCollection",
                             token=request.token)

      counts = {}
      for event in fd.GenerateItems(
          timestamp=(now - 7 * 24 * 60 * 60 * 1000000, now)):
        counts.setdefault(event.user, 0)
        counts[event.user] += 1

      self.graph = rdfvalue.Graph(title="User activity breakdown.")
      self.data = []
      for user, count in counts.items():
        if user not in self.filtered_users:
          self.graph.Append(label=user, y_value=count)
          self.data.append(dict(label=user, data=count))
    except IOError:
      pass
    return super(MostActiveUsers, self).Layout(request, response)

class StackChart(statistics.Report):
  """Display category data in stacked histograms."""

  layout_template = renderers.Template("""

{% if this.data %}

{{this.title|escape}}

  {{this.description|escape}}

Hover to show exact numbers.

{% else %}

No data Available

{% endif %}

""")

class UserActivity(StackChart):
  """Display user activity by week."""
  category = "/Server/User Breakdown/Activity"
  description = "Number of flows ran by each user over the last few weeks."

  filtered_users = set(["GRRWorker", "GRREnroller", "GRRCron"])

  WEEKS = 10

  def Layout(self, request, response):
    """Filter the last week of user actions."""
    try:
      # TODO(user): Replace with Duration().
      now = int(rdfvalue.RDFDatetime().Now())
      week_duration = 7 * 24 * 60 * 60 * 1000000

      fd = aff4.FACTORY.Open("aff4:/audit/log", aff4_type="VersionedCollection",
                             token=request.token)

      self.user_activity = {}

      for week in range(self.WEEKS):
        start = now - week * week_duration

        for event in fd.GenerateItems(timestamp=(start, start + week_duration)):
          self.weekly_activity = self.user_activity.setdefault(
              event.user, [[x, 0] for x in range(-self.WEEKS, 0, 1)])
          self.weekly_activity[-week][1] += 1

      self.data = []
      for user, data in self.user_activity.items():
        if user not in self.filtered_users:
          self.data.append(dict(label=user, data=data))

      self.data = renderers.JsonDumpForScriptContext(self.data)

    except IOError:
      pass

    return super(UserActivity, self).Layout(request, response)

class FlowsUsed(StackChart):
  """Display Flows issued by week."""
  category = "/Server/Flows/Activity"
  description = "Number of flows issued over the last few weeks."

  WEEKS = 10

  def Layout(self, request, response):
    """Filter the last week of flows."""
    try:
      # TODO(user): Replace with Duration().
      now = int(rdfvalue.RDFDatetime().Now())
      week_duration = 7 * 24 * 60 * 60 * 1000000

      fd = aff4.FACTORY.Open("aff4:/audit/log", aff4_type="VersionedCollection",
                             token=request.token)

      self.flow_activity = {}

      for week in range(self.WEEKS):
        start = now - week * week_duration

        for event in fd.GenerateItems(timestamp=(start, start + week_duration)):
          self.weekly_activity = self.flow_activity.setdefault(
              event.flow, [[x, 0] for x in range(-self.WEEKS, 0, 1)])
          self.weekly_activity[-week][1] += 1

      self.data = []
      for flow, data in self.flow_activity.items():
        self.data.append(dict(label=flow, data=data))

      self.data = renderers.JsonDumpForScriptContext(self.data)

    except IOError:
      pass

    return super(FlowsUsed, self).Layout(request, response)

class ClientActivity(StackChart):
  """Display client activity by week."""
  category = "/Server/Clients/Activity"
  description = ("Number of flows issued against each client over the "
                 "last few weeks.")

  WEEKS = 10

  def Layout(self, request, response):
    """Filter the last week of flows."""
    try:
      # TODO(user): Replace with Duration().
      now = int(rdfvalue.RDFDatetime().Now())
      week_duration = 7 * 24 * 60 * 60 * 1000000

      fd = aff4.FACTORY.Open("aff4:/audit/log", aff4_type="VersionedCollection",
                             token=request.token)

      self.client_activity = {}

      for week in range(self.WEEKS):
        start = now - week * week_duration

        for event in fd.GenerateItems(timestamp=(start, start + week_duration)):
          self.weekly_activity = self.client_activity.setdefault(
              event.client, [[x, 0] for x in range(-self.WEEKS, 0, 1)])
          self.weekly_activity[-week][1] += 1

      self.data = []
      for client, data in self.client_activity.items():
        if client:
          self.data.append(dict(label=str(client), data=data))

      self.data = renderers.JsonDumpForScriptContext(self.data)

    except IOError:
      pass

    return super(ClientActivity, self).Layout(request, response)


text:
#ifndef SRC_PUSHER_MEDIAPUSHER_H_
#define SRC_PUSHER_MEDIAPUSHER_H_

#include <memory>
#include <string>
#include "PusherBase.h"
#include "Thread/TaskExecutor.h"
using namespace toolkit;

namespace mediakit {

class MediaPusher : public PusherImp<PusherBase,PusherBase> {
public:
    typedef std::shared_ptr<MediaPusher> Ptr;

    MediaPusher(const string &schema,
                const string &vhost,
                const string &app,
                const string &stream,
                const EventPoller::Ptr &poller = nullptr);

    MediaPusher(const MediaSource::Ptr &src,
                const EventPoller::Ptr &poller = nullptr);

    virtual ~MediaPusher();

    void publish(const string &url) override;
    EventPoller::Ptr getPoller();
    void setOnCreateSocket(Socket::onCreateSocket cb);

private:
    std::weak_ptr<MediaSource> _src;
    EventPoller::Ptr _poller;
    Socket::onCreateSocket _on_create_socket;
};

} /* namespace mediakit */

#endif /* SRC_PUSHER_MEDIAPUSHER_H_ */


text:
<?php

/**
* model class for Orders table
*/
class Orders_model extends CI_Model {

	function __construct() {
		$this->load->database();
	}
}


text:
package org.apache.flink.table.examples.java.basics;

import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;

/** The famous word count example that shows a minimal Flink SQL job in batch execution mode. */
public final class WordCountSQLExample {

    public static void main(String[] args) throws Exception {

        // set up the Table API
        final EnvironmentSettings settings =
                EnvironmentSettings.newInstance().inBatchMode().build();
        final TableEnvironment tableEnv = TableEnvironment.create(settings);

        // execute a Flink SQL job and print the result locally
        tableEnv.executeSql(
                        // define the aggregation
                        "SELECT word, SUM(frequency) AS `count`\n"
                                // read from an artificial fixed-size table with rows and columns
                                + "FROM (\n"
                                + "  VALUES ('Hello', 1), ('Ciao', 1), ('Hello', 2)\n"
                                + ")\n"
                                // name the table and its columns
                                + "AS WordTable(word, frequency)\n"
                                // group for aggregation
                                + "GROUP BY word")
                .print();
    }
}


text:
package ru.job4j.oop;

/**
 * Class Teacher Решение задачи 1. Реализация профессий в коде [#6837]
 * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
 * @since 01.12.2017
 */
public class Teacher extends Profession {

    private double workExpirience;
    private double salary;

    /**
     * Конструктор класса.
     */
    public Teacher(String name,
                   String specialization,
                   Education education,
                   double workExpirience, double salary) {
        super(name, specialization, education);
        this.workExpirience = workExpirience;
        this.salary = salary;
    }

    /**
     * геттер.
     * @return информация о стаже работы.
     */
    public double getWorkExpirience() {
        return workExpirience;
    }

    /**
     * сеттер.
     * @param workExpirience стаж работы.
     */
    public void setWorkExpirience(double workExpirience) {
        this.workExpirience = workExpirience;
    }

    /**
     * геттер.
     * @return информация о зарплате.
     */
    public double getSalary() {
        return salary;
    }

    /**
     * сеттер.
     * @param salary заработная плата.
     */
    public void setSalary(double salary) {
        this.salary = salary;
    }

    /**
     * Метод учит студента.
     * @param student студент.
     * @return Возвращает результат обучения (оценку).
     */
    Estimate teach(Student student) {
        // возвращает информацию о результате обучения студента
        // в виде оценки
        Estimate estimate = new Estimate();
        return estimate;
    }

    /**
     * Метод корректирует учебную программу.
     * @param requirements требования Министерства образования.
     * @return возвращает скорректированную учебную программу.
     */
    StudyProgram correctStudyProgram(EducationMinistryRequirements requirements) {
        StudyProgram studyProgram = new StudyProgram();
        // корректируем учебную программу
        return studyProgram;
    }

    /**
     * Метод замещает коллегу.
     * @param teacher коллега.
     */
    void replaceColleaugue(Teacher teacher) {
        // заместить коллегу
    }

    /**
     * Class Вспомогательный класс
     * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
     * @since 01.12.2017
     */
    private class Estimate {
        // оценка работы студента
    }

    /**
     * Class Вспомогательный класс
     * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
     * @since 01.12.2017
     */
    private class Student {
        // информация о студенте
    }

    /**
     * Class Вспомогательный класс
     * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
     * @since 01.12.2017
     */
    private class StudyProgram {
        // информация о текущей учебной программе
    }

    /**
     * Class Вспомогательный класс
     * @author Aleksey Sidorenko (mailto:sidorenko.aleksey@gmail.com)
     * @since 01.12.2017
     */
    private class EducationMinistryRequirements {
        // информация о требованиях Министерства образования
        // к разработке учебной программы
    }
}