text:
<?php

class Object_Concrete_Resource extends Object_Abstract_Resource {

    /**
     * Contains all valid columns in the database table
     *
     * @var array
     */
    protected $validColumnsObjectConcrete = array();

    /**
     * @var Object_Concrete_Resource_InheritanceHelper
     */
    protected $inheritanceHelper = null;

    /**
     * @see Object_Abstract_Resource::init
     */
    public function init() {
        parent::init();
        $this->inheritanceHelper = new Object_Concrete_Resource_InheritanceHelper($this->model->getO_classId());
    }

    /**
     * Get the data for the object from database for the given id
     *
     * @param integer $id
     * @return void
     */
    public function getById($id) {
        try {
            $data = $this->db->fetchRow("SELECT * FROM objects WHERE o_id = ?", $id);

            if ($data["o_id"]) {
                $this->assignVariablesToModel($data);
                $this->getData();

                $this->loadLocks();
            }
            else {
                throw new Exception("Object with the ID " . $id . " doesn't exists");
            }

        }
        catch (Exception $e) {
            Logger::warning($e);
        }
    }

    /**
     * @param  string $fieldName
     * @return array
     */
    public function getRelationIds($fieldName) {
        $relations = array();
        $allRelations = $this->db->fetchAll("SELECT * FROM object_relations_" . $this->model->getO_classId() . " WHERE fieldname = ? AND src_id = ? AND ownertype = 'object' ORDER BY `index` ASC", array($fieldName, $this->model->getO_id()));
        foreach ($allRelations as $relation) {
            $relations[] = $relation["dest_id"];
        }
        return $relations;
    }

    /**
     * @param  string $field
     * @return array
     */
    public function getRelationData($field, $forOwner, $remoteClassId) {

        $id = $this->model->getO_id();
        if ($remoteClassId) {
            $classId = $remoteClassId;
        } else {
            $classId = $this->model->getO_classId();
        }

        $params = array($field, $id, $field, $id, $field, $id);

        $dest = "dest_id";
        $src = "src_id";
        if (!$forOwner) {
            $dest = "src_id";
            $src = "dest_id";
        }

        $relations = $this->db->fetchAll("SELECT r." . $dest . " as dest_id, r." . $dest . " as id, r.type, o.o_className as subtype, concat(o.o_path ,o.o_key) as path , r.index
            FROM objects o, object_relations_" . $classId . " r
            WHERE r.fieldname= ?
            AND r.ownertype = 'object'
            AND r." . $src . " = ?
            AND o.o_id = r." . $dest . "
            AND r.type='object'

            UNION SELECT r." . $dest . " as dest_id, r." . $dest . " as id, r.type,  a.type as subtype,  concat(a.path,a.filename) as path, r.index
            FROM assets a, object_relations_" . $classId . " r
            WHERE r.fieldname= ?
            AND r.ownertype = 'object'
            AND r." . $src . " = ?
            AND a.id = r." . $dest . "
            AND r.type='asset'

            UNION SELECT r." . $dest . " as dest_id, r." . $dest . " as id, r.type, d.type as subtype, concat(d.path,d.key) as path, r.index
            FROM documents d, object_relations_" . $classId . " r
            WHERE r.fieldname= ?
            AND r.ownertype = 'object'
            AND r." . $src . " = ?
            AND d.id = r." . $dest . "
            AND r.type='document'

            ORDER BY `index` ASC", $params);

        if (is_array($relations) and count($relations) > 0) {
            return $relations;
        } else return array();
    }

    /**
     * Get the data-elements for the object from database for the given path
     *
     * @return void
     */
    public function getData() {

        $data = $this->db->fetchRow('SELECT * FROM object_store_' . $this->model->getO_classId() . ' WHERE oo_id = ?', $this->model->getO_id());

        foreach ($this->model->geto_class()->getFieldDefinitions() as $key => $value) {
            if (method_exists($value, "load")) {
                // datafield has it's own loader
                $value = $value->load($this->model);
                if($value === 0 || !empty($value)) {
                    $this->model->setValue($key, $value);
                }
            } else {
                // if a datafield requires more than one field
                if (is_array($value->getColumnType())) {
                    $multidata = array();
                    foreach ($value->getColumnType() as $fkey => $fvalue) {
                        $multidata[$key . "__" . $fkey] = $data[$key . "__" . $fkey];
                    }
                    $this->model->setValue( $key, $this->model->geto_class()->getFieldDefinition($key)->getDataFromResource($multidata));

                } else {
                    $this->model->setValue( $key, $value->getDataFromResource($data[$key]));
                }
            }
        }
    }

    /**
     * Create a new record for the object in database
     *
     * @return boolean
     */
    /*public function create() {

        parent::create();

        //$this->createDataRows();
        //$this->model->save();
    }*/

    /**
     * create data rows for query table and for the store table
     *
     * @return void
     */
    /*protected function createDataRows() {
        try {
            $this->db->insert("object_store_" . $this->model->getO_classId(), array("oo_id" => $this->model->getO_id()));
        }
        catch (Exception $e) {
        }

        try {
            $this->db->insert("object_query_" . $this->model->getO_classId(), array("oo_id" => $this->model->getO_id()));
        }
        catch (Exception $e) {
        }
    }*/

    /**
     * Save changes to database, it's an good idea to use save() instead
     *
     * @return void
     */
    public function update() {

        // check if the rows must be inserted or updated in the query and store table
        if($this->model->getId()) {
            try {
                $this->insertOrUpdate = $this->db->fetchRow("SELECT
                  object_store_" . $this->model->getO_classId() . ".oo_id as store, object_query_" . $this->model->getO_classId() . ".oo_id as query, object.o_id as object
                FROM
                  (SELECT o_id FROM objects WHERE o_id = " . $this->model->getId() . ") as object LEFT JOIN
                  object_store_" . $this->model->getO_classId() . " ON object.o_id = object_store_" . $this->model->getO_classId() . ".oo_id LEFT JOIN
                  object_query_" . $this->model->getO_classId() . " ON object.o_id = object_query_" . $this->model->getO_classId() . ".oo_id;");
            } catch (Exception $e) {
                $this->insertOrUpdate = null;
            }
        }

        if(empty($this->insertOrUpdate)) {
            $this->insertOrUpdate = array("query" => null, "store" => null, "object" => null);
        }

        parent::update();

        //$this->createDataRows();

        // get fields which shouldn't be updated
        $fd = $this->model->geto_class()->getFieldDefinitions();
        $untouchable = array();
        foreach ($fd as $key => $value) {
            if (method_exists($value, "getLazyLoading") && $value->getLazyLoading()) {
                if (!in_array($key, $this->model->getLazyLoadedFields())) {
                    //this is a relation subject to lazy loading - it has not been loaded
                    $untouchable[] = $key;
                }
            }
        }

        // empty relation table except the untouchable fields (eg. lazy loading fields)
        if (count($untouchable) > 0) {
            $untouchables = "'" . implode("','", $untouchable) . "'";
            $this->db->delete("object_relations_" . $this->model->getO_classId(), $this->db->quoteInto("src_id = ? AND fieldname not in (" . $untouchables . ") AND ownertype = 'object'", $this->model->getO_id()));
        } else {
            $this->db->delete("object_relations_" . $this->model->getO_classId(), $this->db->quoteInto("src_id = ? AND ownertype = 'object'",  $this->model->getO_id()));
        }

        $inheritedValues = Object_Abstract::doGetInheritedValues();
        Object_Abstract::setGetInheritedValues(false);

        $data = array();
        $data["oo_id"] = $this->model->getO_id();
        foreach ($fd as $key => $value) {

            $getter = "get" . ucfirst($key);

            if (method_exists($value, "save")) {
                // for fieldtypes which have their own save algorithm eg. fieldcollections, objects, multihref, ...
                $value->save($this->model);
            } else if ($value->getColumnType()) {
                // pimcore saves the values with getDataForResource
                if (is_array($value->getColumnType())) {
                    $insertDataArray = $value->getDataForResource($this->model->$getter(), $this->model);
                    if(is_array($insertDataArray)) {
                        $data = array_merge($data, $insertDataArray);
                    }
                } else {
                    $insertData = $value->getDataForResource($this->model->$getter(), $this->model);
                    $data[$key] = $insertData;
                }
            }
        }

        if($this->insertOrUpdate["store"]) {
            $this->db->update("object_store_" . $this->model->getO_classId(), $data, $this->db->quoteInto("oo_id = ?", $this->model->getO_id()));
        } else {
            $this->db->insert("object_store_" . $this->model->getO_classId(), $data);
        }

        // get data for query table
        // this is special because we have to call each getter to get the inherited values from a possible parent object
        Object_Abstract::setGetInheritedValues(true);

        $object = get_object_vars($this->model);

        $data = array();
        $this->inheritanceHelper->resetFieldsToCheck();
        $oldData = $this->db->fetchRow("SELECT * FROM object_query_" . $this->model->getO_classId() . " WHERE oo_id = ?", $this->model->getId());

        foreach ($object as $key => $value) {
            $fd = $this->model->geto_class()->getFieldDefinition($key);

            if ($fd) {
                if ($fd->getQueryColumnType()) {
                    //exclude untouchables if value is not an array - this means data has not been loaded
                    if (!(in_array($key, $untouchable) and !is_array($this->model->$key))) {
                        $method = "get" . $key;
                        $insertData = $fd->getDataForQueryResource($this->model->$method(), $this->model);
                        if (is_array($insertData)) {
                            $data = array_merge($data, $insertData);
                        }
                        else {
                            $data[$key] = $insertData;
                        }

                        //get changed fields for inheritance
                        if($fd->isRelationType()) {
                            if (is_array($insertData)) {
                                $doInsert = false;
                                foreach($insertData as $insertDataKey => $insertDataValue) {
                                    if($oldData[$insertDataKey] != $insertDataValue) {
                                        $doInsert = true;
                                    }
                                }

                                if($doInsert) {
                                    $this->inheritanceHelper->addRelationToCheck($key, array_keys($insertData));
                                }
                            } else {
                                if($oldData[$key] != $insertData) {
                                    $this->inheritanceHelper->addRelationToCheck($key);
                                }
                            }

                        } else {
                            if (is_array($insertData)) {
                                foreach($insertData as $insertDataKey => $insertDataValue) {
                                    if($oldData[$insertDataKey] != $insertDataValue) {
                                        $this->inheritanceHelper->addFieldToCheck($insertDataKey);
                                    }
                                }
                            } else {
                                if($oldData[$key] != $insertData) {
                                    $this->inheritanceHelper->addFieldToCheck($key);
                                }
                            }
                        }

                    } else {
                        Logger::debug("Excluding untouchable query value for object [ " . $this->model->getId() . " ]  key [ $key ] because it has not been loaded");
                    }
                }
            }
        }
        $data["oo_id"] = $this->model->getO_id();

        if($this->insertOrUpdate["query"]) {
            $this->db->update("object_query_" . $this->model->getO_classId(), $data, $this->db->quoteInto("oo_id = ?", $this->model->getO_id()));
        } else {
            $this->db->insert("object_query_" . $this->model->getO_classId(), $data);
        }

        Object_Abstract::setGetInheritedValues($inheritedValues);

        unset($this->insertOrUpdate);
    }

    public function saveChilds() {
        $this->inheritanceHelper->doUpdate($this->model->getId());
        $this->inheritanceHelper->resetFieldsToCheck();
    }

    /**
     * Save object to database
     *
     * @return void
     */
    public function delete() {
        $this->db->delete("object_query_" . $this->model->getO_classId(), $this->db->quoteInto("oo_id = ?", $this->model->getO_id()));
        $this->db->delete("object_store_" . $this->model->getO_classId(), $this->db->quoteInto("oo_id = ?", $this->model->getO_id()));
        $this->db->delete("object_relations_" . $this->model->getO_classId(), $this->db->quoteInto("src_id = ?", $this->model->getO_id()));
        $this->db->delete("object_relations_" . $this->model->getO_classId(), $this->db->quoteInto("dest_id = ?", $this->model->getO_id()));

        // delete fields wich have their own delete algorithm
        foreach ($this->model->geto_class()->getFieldDefinitions() as $fd) {
            if (method_exists($fd, "delete")) {
                $fd->delete($this->model);
            }
        }

        parent::delete();
    }

    /**
     * get versions from database, and assign it to object
     *
     * @return array
     */
    public function getVersions() {
        $versionIds = $this->db->fetchCol("SELECT id FROM versions WHERE cid = ? AND ctype='object' ORDER BY `id` DESC", $this->model->getO_Id());

        $versions = array();
        foreach ($versionIds as $versionId) {
            $versions[] = Version::getById($versionId);
        }

        $this->model->setO_Versions($versions);

        return $versions;
    }

    /**
     * Get latest available version, using $force always returns a version no matter if it is the same as the published one
     * @param bool $force
     * @return array
     */
    public function getLatestVersion($force = false) {
        $versionData = $this->db->fetchRow("SELECT id,date FROM versions WHERE cid = ? AND ctype='object' ORDER BY `id` DESC LIMIT 1", $this->model->getO_Id());

        if(($versionData["id"] && $versionData["date"] > $this->model->getO_modificationDate()) || $force) {
            $version = Version::getById($versionData["id"]);
            return $version;
        }
        return;
    }

    /**
     * @return void
     */
    public function deleteAllTasks() {
        $this->db->delete("schedule_tasks", "cid='" . $this->model->getO_Id() . "' AND ctype='object'");
        $this->db->delete("schedule_tasks", $this->db->quoteInto("cid = ? AND ctype='object'", $this->model->getO_Id()));
    }
}


text:
using UnityEngine;
using System.Collections;

public class SlowEffect : MonoBehaviour {

	public float slowDuration = 4;
	public float slowPercentage  = 0.3f;

	private float remainingSlowDuration;

	// Use this for initialization
	void Start () {
		remainingSlowDuration = slowDuration;
	}

	// Update is called once per frame
	void Update () {
		remainingSlowDuration -= Time.deltaTime;

		if(remainingSlowDuration <= 0){
			Destroy(this);
		}
	}

	public float GetSlowAmount(){
		return 1 - slowPercentage;
	}
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(grunt) {

	// I don't know if this is important
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
	});

	// Loads the different modules used by this gruntfile
	// release
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-concat');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-sass');
	grunt.loadNpmTasks('grunt-ts');
	grunt.loadNpmTasks('grunt-angular-templates');

	// debug
	grunt.loadNpmTasks('grunt-concurrent');
	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-karma');
	grunt.loadNpmTasks('grunt-protractor-runner');
	grunt.loadNpmTasks('grunt-tslint');

	// load the configs of all tasks defined under /config
	var configs = require('load-grunt-configs')(grunt);
	grunt.initConfig(configs);

	// this task updates all distributions - launch it once before each release
	grunt.registerTask('dist', ["clean:dist", "ts:dist", "ngtemplates:dist", 'concat:standard', 'uglify:standard', 'sass:dist', "copy:tsdefinitions", "copy:demolibs"]);

	// use this tasks when you are developping
	grunt.registerTask('debug', ["dist", "sass:demo", "clean:tests", "ts:test", "connect:server", "concurrent:debug"]);
	// // use this one when you're coding e2e tests
	grunt.registerTask('e2e', ["dist", "ts:e2e", "connect", "protractor:singlerun", "concurrent:e2e"]);
	// this updates the dists and tests it, creates karma coverage
	grunt.registerTask('test', ["dist", "clean:tests", "ts:test", 'karma:debug', 'karma:coverage', "connect:server", "protractor:singlerun", "jshint"]);

	// default task
	grunt.registerTask('default', ['debug']);

	// used for travis integration
	grunt.registerTask('travis-karma', ["ts:test", 'karma:travis']);
	// grunt.registerTask('travis-protractor', ["ts:e2e", "connect", "protractor:saucelab"]);
	grunt.registerTask('jenkins-karma', ["ts:test", "karma:coverage"]);
	grunt.registerTask('jenkins-protractor', ["ts:e2e", "connect", "protractor:singlerun"]);
};


text:
/*
 * drakeUtil.h
 *
 *  Created on: Jun 19, 2013
 *      Author: russt
 */

#include "mex.h"
#include <stdexcept>
#include <vector>
#include <utility>
#include <Eigen/Core>

#ifndef DRAKE_UTIL_H_
#define DRAKE_UTIL_H_

#undef DLLEXPORT
#if defined(WIN32) || defined(WIN64)
  #if defined(drakeUtil_EXPORTS)
    #define DLLEXPORT __declspec( dllexport )
  #else
    #define DLLEXPORT __declspec( dllimport )
  #endif
#else
    #define DLLEXPORT
#endif

// Helper routines
DLLEXPORT bool isa(const mxArray* mxa, const char* class_str);
DLLEXPORT bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename);

// Mex pointers shared through matlab
DLLEXPORT mxArray* createDrakeMexPointer(void* ptr, const char* name="", int num_additional_inputs=0, mxArray *delete_fcn_additional_inputs[] = NULL, const char* subclass_name=NULL);  // increments lock count
// Note: the same mex function which calls this method will be called with the syntax mexFunction(drake_mex_ptr) as the destructor

DLLEXPORT void* getDrakeMexPointer(const mxArray* mx);

template <typename Derived> inline void destroyDrakeMexPointer(const mxArray* mx)
{
  Derived typed_ptr = (Derived) getDrakeMexPointer(mx);

  //mexPrintf("deleting drake mex pointer\n");
  delete typed_ptr;
  mexUnlock();  // decrement lock count

//  mexPrintf(mexIsLocked() ? "mex file is locked\n" : "mex file is unlocked\n");
}

template <typename Derived>
DLLEXPORT mxArray* eigenToMatlabSparse(Eigen::MatrixBase<Derived> const & M, int & num_non_zero);

template <typename DerivedA>
mxArray* eigenToMatlab(const DerivedA &m)
{
  // this avoids zero initialization that would occur using mxCreateDoubleMatrix with nonzero dimensions.
  // see https://classes.soe.ucsc.edu/ee264/Fall11/cmex.pdf, page 8
  mxArray* pm = mxCreateDoubleMatrix(0, 0, mxREAL);
  int rows = static_cast<int>(m.rows());
  int cols = static_cast<int>(m.cols());
  int numel = rows * cols;
  mxSetM(pm, rows);
  mxSetN(pm, cols);
  if (numel)
    mxSetData(pm, mxMalloc(sizeof(double) * numel));
  memcpy(mxGetPr(pm), m.data(), sizeof(double)* numel);
  return pm;
}

template<int RowsAtCompileTime, int ColsAtCompileTime>
Eigen::Matrix<double, RowsAtCompileTime, ColsAtCompileTime> matlabToEigen(const mxArray* matlab_array)
{
  const mwSize* size_array = mxGetDimensions(matlab_array);
  Eigen::Matrix<double, RowsAtCompileTime, ColsAtCompileTime> ret(size_array[0], size_array[1]);
  memcpy(ret.data(), mxGetPr(matlab_array), sizeof(double) * ret.size());
  return ret;
}

template <typename Scalar>
mxArray* stdVectorToMatlab(const std::vector<Scalar>& vec) {
  mxArray* pm = mxCreateDoubleMatrix(static_cast<int>(vec.size()), 1, mxREAL);
  for (int i = 0; i < static_cast<int>(vec.size()); i++) {
    mxGetPr(pm)[i] = (double) vec[i];
  }
  return pm;
}

DLLEXPORT const std::vector<double> matlabToStdVector(const mxArray* in);

DLLEXPORT int sub2ind(mwSize ndims, const mwSize* dims, const mwSize* sub);

void baseZeroToBaseOne(std::vector<int>& vec)
{
  for (std::vector<int>::iterator iter=vec.begin(); iter!=vec.end(); iter++)
    (*iter)++;
}

DLLEXPORT double angleAverage(double theta1, double theta2);

DLLEXPORT std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane);

DLLEXPORT double *mxGetPrSafe(const mxArray *pobj);

DLLEXPORT mxArray* mxGetPropertySafe(const mxArray* array, std::string const& field_name);
DLLEXPORT mxArray* mxGetFieldSafe(const mxArray* array, std::string const& field_name);
DLLEXPORT mxArray* mxGetPropertySafe(const mxArray* array, size_t index, std::string const& field_name);
DLLEXPORT mxArray* mxGetFieldSafe(const mxArray* array, size_t index, std::string const& field_name);

DLLEXPORT void mxSetFieldSafe(mxArray* array, size_t index, std::string const & fieldname, mxArray* data);

DLLEXPORT void sizecheck(const mxArray* mat, int M, int N);

#endif /* DRAKE_UTIL_H_ */


text:
	<template ngSwitchWhen="object">

				{{propNameToLabel(prop)}}

					<object-display (selectobject)="objectSelected($event)" [display-object]="displayObject[prop]"></object-display>

	</template>
	<template ngSwitchWhen="array">

				<object-display [collapsed]="getTheType(val)==='object'" (selectobject)="objectSelected($event)" [display-object]="val"></object-display>

	</template>
	<template ngSwitchWhen="date">
        {{displayObject | date:'MM/dd/yyyy'}}
        {{displayObject | date:'hh:mm:ss tt'}}
	</template>
	<template ngSwitchDefault>
		{{displayObject}}
	</template>


text:
  Если Ваш проект требует очистки рабочей директории перед каждой сборкой, выберите этоту опцию.
  В этом случае система удалит все файлы внутри рабочей директории перед началом каждой сборки.
  Это может быть полезно если Вы хотите получать свежую копию исходных кодов из SCM системы перед каждой сборкой.

  Для этого свойства возможно использовать Проектное каскадирование. Детали доступны в
  этом документе.


text:
package com.flyingspaniel.nava.callback;

import java.util.concurrent.*;

public class Callbacks {

   private Callbacks() {}  // utility class

   static final Object[] EMPTY = new Object[0];

   /**
    * Create a chain of Callbacks, by setting nextCallback along the line...
    * @param first
    * @param others
    * @return first
    */
   public static Callback chainUp(Callback first, Callback...others) {
      Callback head = first;
      for (Callback c : others) {
         head.setNextCallback(c);
         head = c;
      }
      // terminate the end
      head.setNextCallback(null);

      return first;
   }

   /**
    * Runs a callback (and any associated chain) synchronously
    * @param callback  first callback, if null, data will be returned immediately
    * @param data      input to first callback
    * @return          result from the final callback
    * @throws Exception
    */
   @SuppressWarnings("unchecked")
   public static Object runSync(Callback callback, Object data, Object...more) throws Exception {
      Exception ex = null;

      while (callback != null) {

         if (callback instanceof Callback.ProducesMultiple)
            throw new IllegalStateException("Callbacks.runSync() cannot handle a Callback.ProducesMultiple");

         try {
            data = callback.callback(ex, data, more);
         } catch (Exception e) {
            ex = e;
         }

         more = getMore(callback);
         callback = callback.getNextCallback();
      }

      if (ex != null)
         throw ex;

      return data;
   }

   /**
    * Wraps runSync() in a Callable so it can be run in another thread
    *
    * @param first   if null, returns inData
    * @param inData  inputs to the first callback
    * @param more    inputs to the first callback
    * @return        result from the final callback
    */
   public static Callable callableRunSync(final Callback first, final Object inData, final Object...more) {
      return new Callable() {
         @Override
         public Object call() throws Exception {
            return runSync(first, inData, more);
         }
      };
   }

   /**
    * Runs a completedCallback (and any associated chain) using an ExecutorService
    * However, since we wait for the Futures "in line" here, no real speed gain (see runASyncInLine)
    *
    * @param xs       if null, they get run sync
    * @param callback if null, returns inData
    * @param data     inputs to the first callback
    * @param more     inputs to the first callback
    * @return         result from the final callback
    * @throws Exception
    */
   @SuppressWarnings("unchecked")
   public static Object runASyncInLine(ExecutorService xs, Callback callback,
                                       Object data, Object...more) throws Exception {
      Exception ex = null;

      if (xs == null)
         return runSync(callback, data);

      while (callback != null) {

         if (callback instanceof Callback.ProducesMultiple)  // TODO possibly this could be handled
            throw new IllegalStateException("Callbacks.runSync() cannot handle a Callback.ProducesMultiple");

         Callable callable = callableCallback(callback, ex, data, more);
         Future future = xs.submit(callable);
         try {
            data = future.get();
         } catch (ExecutionException e) {
            ex = getCause(e);
         }
         more = getMore(callback);
         callback = callback.getNextCallback();
      }

      if (ex != null)  // nobody handled it...
         throw ex;

      return data;
   }

   /**
    * By wrapping runASyncInLine() in a Callable, we can now run *everything* off the original thread.
    * However, see CallbackExecutor for a better alternative
    *
    * @param xs
    * @param first
    * @param inData
    * @return Callable
    * @see CallbackExecutor  for a better alternative
    */
   public static Callable callableRunASync(final ExecutorService xs, final Callback first,
                                           final Object inData, final Object...more) {
      return new Callable() {
         @Override
         public Object call() throws Exception {
            return runASyncInLine(xs, first, inData, more);
         }
      };
   }

   /**
    * Convert any Callback into a Callable
    * @param callback  if null this returns null
    * @param ex        input to the Callback
    * @param inData    input to the Callback
    * @return          a Callable, or null
    */
   public static <IN,OUT> Callable callableCallback(final Callback<IN, OUT> callback, final Exception ex,
                                                    final IN inData, final Object...more) {
      if (callback == null)
         return null;
      return new Callable() {
         public OUT call() throws Exception {
            return callback.callback(ex, inData, more);
         }
      } ;
   }

   /**
    * Utility to get the more results (or an empty []) from a callback
    *
    * @param  callback non-null
    * @return returns [] if callback is not a Callback.ProducesMore
    */
   public static Object[] getMore(Callback callback) {
      if (callback instanceof Callback.ProducesMore)
         return ((Callback.ProducesMore)callback).getMore();

      return EMPTY;
   }

   /**
    * Utility to get the cause from an ExecutionException as an Exception, not a Throwable
    * @param ee      may be null
    * @return        null if ee is null
    * @throws Error  if ee wrapped an Error
    */
   public static Exception getCause(ExecutionException ee) {
      if (ee == null)
         return null;
      Throwable t = ee.getCause();
      if (t instanceof Error)
         throw (Error)t;
      return (Exception)t;
   }
}


text:
import unittest
from .. import util as sutils
from .. import basic_transforms as bt
import pandas as pd
import json
import os.path
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
import logging

class Test_PipelineWrapper(unittest.TestCase):

    def _create_test_json(self,fname,as_list=False):
        f = open(fname,"w")
        if as_list:
            f.write("[")
        j = {}
        j["a"] = 1
        j["b"] = 2
        f.write(json.dumps(j,sort_keys=True))
        if as_list:
            f.write(",\n")
        else:
            f.write("\n")
        j = {}
        j["a"] = 3
        j["b"] = 4
        f.write(json.dumps(j,sort_keys=True))
        if as_list:
            f.write("]\n")
        else:
            f.write("\n")
        f.close()

    def test_load_json_folders(self):
        w = sutils.PipelineWrapper()
        data_folder = w.get_work_folder()+"/events"
        if not os.path.exists(data_folder):
            os.makedirs(data_folder)
        fname = data_folder+"/"+"test.json"
        self._create_test_json(fname)
        df = w.create_dataframe([data_folder])
        print df

    def test_load_json_file(self):
        w = sutils.PipelineWrapper()
        fname = w.get_work_folder()+"/"+"test.json"
        self._create_test_json(fname,as_list=True)
        df = w.create_dataframe(fname)
        print df

    def test_save_dataframe(self):
        w = sutils.PipelineWrapper()
        df = pd.DataFrame.from_dict([{"a":"a b","b":"c d","c":3},{"a":"word1","b":"word2"}])
        fname = w.get_work_folder()+"/"+"saved.json"
        w.save_dataframe(df,fname,"csv",csv_index=False)
        df2 = w.create_dataframe(fname,df_format="csv")
        from pandas.util.testing import assert_frame_equal
        assert_frame_equal(df.sort(axis=1), df2.sort(axis=1), check_names=True)

    def test_save_pipeline(self):
        w = sutils.PipelineWrapper()
        t = bt.IncludeFeaturesTransform(included=["a","b"])
        transformers = [("include_features",t)]
        p = Pipeline(transformers)
        df = pd.DataFrame.from_dict([{"a":1,"b":2,"c":3}])
        df2 = p.fit_transform(df)
        self.assertTrue(sorted(df2.columns) == sorted(["a","b"]))
        dest_folder = w.get_work_folder()+"/dest_pipeline"
        w.save_pipeline(p,dest_folder)
        p2 = w.load_pipeline(dest_folder)
        df3 = p2.transform(df)
        self.assertTrue(sorted(df3.columns) == sorted(["a","b"]))

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    unittest.main()


text:
-include $(TOPDIR)/.config
-include $(TOPDIR)/Make.defs
include $(APPDIR)/Make.defs

# kernel_sample built-in application info

APPNAME = kernel_sample
FUNCNAME = kernel_sample_main
THREADEXEC = TASH_EXECMD_ASYNC

# TinyAra OS Test

ASRCS =
CSRCS = dev_null.c restart.c
MAINSRC = kernel_sample_main.c

ifeq ($(CONFIG_EXAMPLES_KERNEL_SAMPLE_AIO),y)
CSRCS += aio.c
endif

ifeq ($(CONFIG_SCHED_WAITPID),y)
CSRCS += waitpid.c
endif

ifneq ($(CONFIG_DISABLE_PTHREAD),y)
CSRCS += cancel.c cond.c mutex.c sem.c semtimed.c barrier.c
ifeq ($(CONFIG_FS_NAMED_SEMAPHORES),y)
CSRCS += nsem.c
endif
ifneq ($(CONFIG_RR_INTERVAL),0)
CSRCS += roundrobin.c
endif # CONFIG_RR_INTERVAL
ifeq ($(CONFIG_PTHREAD_MUTEX_TYPES),y)
CSRCS += rmutex.c
endif # CONFIG_PTHREAD_MUTEX_TYPES
endif # CONFIG_DISABLE_PTHREAD

ifneq ($(CONFIG_DISABLE_SIGNALS),y)
CSRCS += sighand.c
ifneq ($(CONFIG_DISABLE_PTHREAD),y)
CSRCS += timedwait.c
endif # CONFIG_DISABLE_PTHREAD
endif # CONFIG_DISABLE_SIGNALS

ifneq ($(CONFIG_DISABLE_MQUEUE),y)
ifneq ($(CONFIG_DISABLE_PTHREAD),y)
CSRCS += mqueue.c timedmqueue.c
endif # CONFIG_DISABLE_PTHREAD
endif # CONFIG_DISABLE_MQUEUE

ifneq ($(CONFIG_DISABLE_POSIX_TIMERS),y)
CSRCS += posixtimer.c
endif

ifeq ($(CONFIG_ARCH_HAVE_VFORK),y)
ifeq ($(CONFIG_SCHED_WAITPID),y)
CSRCS += vfork.c
endif
endif

ifneq ($(CONFIG_DISABLE_SIGNALS),y)
ifneq ($(CONFIG_DISABLE_PTHREAD),y)
ifeq ($(CONFIG_PRIORITY_INHERITANCE),y)
CSRCS += prioinherit.c
endif # CONFIG_PRIORITY_INHERITANCE
endif # CONFIG_DISABLE_PTHREAD
endif # CONFIG_DISABLE_SIGNALS

AOBJS = $(ASRCS:.S=$(OBJEXT))
COBJS = $(CSRCS:.c=$(OBJEXT))
MAINOBJ = $(MAINSRC:.c=$(OBJEXT))

SRCS = $(ASRCS) $(CSRCS) $(MAINSRC)
OBJS = $(AOBJS) $(COBJS)

ifneq ($(CONFIG_BUILD_KERNEL),y)
  OBJS += $(MAINOBJ)
endif

ifeq ($(CONFIG_WINDOWS_NATIVE),y)
  BIN = ..\..\libapps$(LIBEXT)
else
ifeq ($(WINTOOL),y)
  BIN = ..\\..\\libapps$(LIBEXT)
else
  BIN = ../../libapps$(LIBEXT)
endif
endif

ifeq ($(WINTOOL),y)
  INSTALL_DIR = "${shell cygpath -w $(BIN_DIR)}"
else
  INSTALL_DIR = $(BIN_DIR)
endif

CONFIG_XYZ_PROGNAME ?= kernel_sample$(EXEEXT)
PROGNAME = $(CONFIG_XYZ_PROGNAME)

ROOTDEPPATH = --dep-path .

# Common build

VPATH =

all: .built
.PHONY: clean depend distclean

$(AOBJS): %$(OBJEXT): %.S
	$(call ASSEMBLE, $<, $@)

$(COBJS) $(MAINOBJ): %$(OBJEXT): %.c
	$(call COMPILE, $<, $@)

.built: $(OBJS)
	$(call ARCHIVE, $(BIN), $(OBJS))
	@touch .built

ifeq ($(CONFIG_BUILD_KERNEL),y)
$(BIN_DIR)$(DELIM)$(PROGNAME): $(OBJS) $(MAINOBJ)
	@echo "LD: $(PROGNAME)"
	$(Q) $(LD) $(LDELFFLAGS) $(LDLIBPATH) -o $(INSTALL_DIR)$(DELIM)$(PROGNAME) $(ARCHCRT0OBJ) $(MAINOBJ) $(LDLIBS)
	$(Q) $(NM) -u  $(INSTALL_DIR)$(DELIM)$(PROGNAME)

install: $(BIN_DIR)$(DELIM)$(PROGNAME)

else
install:

endif

ifeq ($(CONFIG_BUILTIN_APPS)$(CONFIG_EXAMPLES_KERNEL_SAMPLE),yy)
$(BUILTIN_REGISTRY)$(DELIM)$(FUNCNAME).bdat: $(DEPCONFIG) Makefile
	$(Q) $(call REGISTER,$(APPNAME),$(FUNCNAME),$(THREADEXEC),$(PRIORITY),$(STACKSIZE))

context: $(BUILTIN_REGISTRY)$(DELIM)$(FUNCNAME).bdat

else
context:

endif

.depend: Makefile $(SRCS)
	@$(MKDEP) $(ROOTDEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep
	@touch $@

depend: .depend

clean:
	$(call DELFILE, .built)
	$(call CLEAN)

distclean: clean
	$(call DELFILE, Make.dep)
	$(call DELFILE, .depend)

-include Make.dep
.PHONY: preconfig
preconfig:


text:
<?php

/**
 * Video
 *
 * @property integer $id
 * @property string $filename
 * @property string $type
 * @property integer $filesize
 * @property integer $width
 * @property integer $height
 * @property integer $duration
 * @property string $path
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @method static \Illuminate\Database\Query\Builder|\Video whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereFilename($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereType($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereFilesize($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereWidth($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereHeight($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereDuration($value)
 * @method static \Illuminate\Database\Query\Builder|\Video wherePath($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereUpdatedAt($value)
 * @property string $full_data
 * @method static \Illuminate\Database\Query\Builder|\Video whereFullData($value)
 * @property string $title
 * @property string $description
 * @property-read mixed $asset_type
 * @method static \Illuminate\Database\Query\Builder|\Video whereTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\Video whereDescription($value)
 */
class Video extends \Asset
{

    protected $table='assets_videos';

}


text:
World News Live add-on for XBMC
==========================================

This plugin provides streams of various news channels and allows you to watch them in XBMC.

Some contents are geo-restricted.

Installation
------------
This latest stable release of this add-on is available as part of the
[k3oni repository] [repository1] and the [xbmcplus repository] [repository2].

For the latest development version,
you can grab the [GitHub generated ZIP file] [githubzip].

Simply download the ZIP file to your XBMC device and install through the menu
via System -> Settings -> Add-ons -> Install from zip file

Issues
------
For any issues or bug reports, please file them on the [issues page] [issues].

Please include log output if possible, using [Github Gist] [gist] or
[xbmclogs.com] [xbmclogs].

The location of your XBMC log file will depend on your platform,
see the [XBMC Wiki page] [xbmc-wiki-log-file] for information.

Disclaimer
----------
This script is released freely without restrictions, but also without
warrenty as described in the file "COPYING.txt"

Credits
-------
 - andrepl
	Initial addon development.

[repository1]: https://github.com/k3oni/repository.k3oni.xbmc/archive/master.zip
[repository2]: https://github.com/moneymaker365/repository.xbmcplus.xbmc-plugins/releases
[githubzip]: https://github.com/k3oni/plugin.video.world.news.live/archive/master.zip
[issues]: https://github.com/k3oni/plugin.video.world.news.live/
[gist]: https://gist.github.com
[xbmclogs]: http://xbmclogs.com/
[xbmc-wiki-log-file]: http://wiki.xbmc.org/index.php?title=Log_file/Advanced#Log_files


text:
#include <ZLUnicodeUtil.h>

#include "HtmlMetainfoReader.h"

#include "../../library/Book.h"

HtmlMetainfoReader::HtmlMetainfoReader(Book &book, ReadType readType) :
	HtmlReader(book.encoding()), myBook(book), myReadType(readType) {
}

bool HtmlMetainfoReader::tagHandler(const HtmlReader::HtmlTag &tag) {
	if (tag.Name == "body") {
		return false;
	} else if ((myReadType & TAGS) == TAGS && tag.Name == "dc:subject") {
		myReadTags = tag.Start;
		if (!tag.Start && !myBuffer.empty()) {
			myBook.addTag(myBuffer);
			myBuffer.erase();
		}
	} else if ((myReadType & TITLE) == TITLE && tag.Name == "dc:title") {
		myReadTitle = tag.Start;
		if (!tag.Start && !myBuffer.empty()) {
			myBook.setTitle(myBuffer);
			myBuffer.erase();
		}
	} else if ((myReadType & AUTHOR) == AUTHOR && tag.Name == "dc:creator") {
		if (tag.Start) {
			const std::string *role = tag.find("role");
			if (role != 0 && ZLUnicodeUtil::toLower(*role) == "aut") {
				if (!myBuffer.empty()) {
					myBuffer += ", ";
				}
				myReadAuthor = true;
			}
		} else {
			myReadAuthor = false;
			if (!myBuffer.empty()) {
				myBook.addAuthor(myBuffer);
			}
			myBuffer.erase();
		}
	}
	return true;
}

void HtmlMetainfoReader::startDocumentHandler() {
	myReadAuthor = false;
	myReadTitle = false;
	myReadTags = false;
}

void HtmlMetainfoReader::endDocumentHandler() {
}

bool HtmlMetainfoReader::characterDataHandler(const char *text, size_t len, bool convert) {
	if (myReadTitle || myReadAuthor || myReadTags) {
		if (convert) {
			myConverter->convert(myBuffer, text, text + len);
		} else {
			myBuffer.append(text, len);
		}
	}
	return true;
}


text:
module Lang.LamIf
  ( module Lang.LamIf.Analyses
  , module Lang.LamIf.CPS
  , module Lang.LamIf.Monads
  , module Lang.LamIf.Parser
  , module Lang.LamIf.Passes
  , module Lang.LamIf.Semantics
  , module Lang.LamIf.StateSpace
  , module Lang.LamIf.Syntax
  , module Lang.LamIf.Val
  ) where

import Lang.LamIf.Analyses
import Lang.LamIf.CPS
import Lang.LamIf.Monads
import Lang.LamIf.Parser
import Lang.LamIf.Passes (stampM, stamp, cpsM, stampCPS, cps)
import Lang.LamIf.Pretty ()
import Lang.LamIf.Semantics
import Lang.LamIf.StateSpace
import Lang.LamIf.Syntax hiding (PreExp(..))
import Lang.LamIf.Val


text:
using System;
using System.Collections.Generic;
using Bundler.Infrastructure;

namespace Bundler {
    public class BundleResponse : IBundleResponse {
        public BundleResponse(string contentType, string contentHash, DateTimeOffset lastModification, string content, IReadOnlyDictionary<string, IBundleContentResponse> files, IReadOnlyDictionary<string, string> headers) {
            ContentType = contentType;
            ContentHash = contentHash;
            LastModification = lastModification;
            Content = content;
            Files = files;
            Headers = headers;
        }

        public string ContentType { get; }
        public DateTimeOffset LastModification { get; }
        public string Content { get; }
        public IReadOnlyDictionary<string, IBundleContentResponse> Files { get; }
        public string ContentHash { get; }
        public IReadOnlyDictionary<string, string> Headers { get; }
    }
}


text:
package files

import (
	"context"
	"io"
	"os"
	"path"
	"strings"
	"time"

	"github.com/mikolajb/servedir/internal/listing"
	"github.com/rs/zerolog"
)

const RootURLPath = "/files/"

type dirHandler struct {
	osPath  string
	urlPath string
}

func newDirHandler(osPath, urlPath string) targetHandler {
	return &dirHandler{
		osPath:  osPath,
		urlPath: urlPath,
	}
}

func (dh *dirHandler) Handle(ctx context.Context, w io.Writer) error {
	log := zerolog.Ctx(ctx)
	log.Info().
		Str("url1", dh.urlPath).
		Str("url2", pathOneUp(dh.urlPath)).
		Msg("listing a directory")
	listingPage := listing.New(dh.urlPath, pathOneUp(dh.urlPath))

	dirEntries, err := os.ReadDir(dh.osPath)
	if err != nil {
		log.Err(err).Msg("cannot read a directory")
		return err
	}

	for _, i := range dirEntries {
		fileInfo, err := i.Info()
		if err != nil {
			log.Err(err).Msg("error while reading file info while listing a directory")
			return err
		}

		newFileInfo := &listing.FileInfo{
			Name:      i.Name(),
			Path:      path.Join(dh.urlPath, i.Name()),
			Size:      listing.FileSize(0),
			Mod:       fileInfo.ModTime().Format(time.Stamp),
			Directory: true,
		}

		if !i.IsDir() {
			newFileInfo.Size = listing.FileSize(fileInfo.Size())
			newFileInfo.Directory = false
		}

		listingPage.AddFile(newFileInfo)
	}

	if err := listingPage.WritePage(w); err != nil {
		log.Err(err).Msg("error while rendering a listing page")
		return err
	}
	return nil
}

func pathOneUp(p string) string {
	splittedURLPath := strings.Split(p, "/")
	result := "/"
	skipped := false
	for i := len(splittedURLPath) - 1; i >= 0; i-- {
		if !skipped && len(splittedURLPath[i]) > 0 {
			skipped = true
			continue
		}

		if len(splittedURLPath[i]) == 0 {
			continue
		}

		result = "/" + splittedURLPath[i] + result
	}

	return result
}


text:
package com.twitter.finagle.util

import scala.annotation.tailrec

trait Drv extends (Rng => Int)

/**
 * Create discrete random variables representing arbitrary distributions.
 */
object Drv {
  private val ε = 0.01

  // We need the sum to be approximately equal to 1.0 +/- ε
  private[this] def isNormalized(sum: Double): Boolean = {
    1 - ε < sum && sum < 1 + ε
  }

  /**
   * A Drv using the Aliasing method [1]: a distribution is described
   * by a set of probabilities and aliases. In order to pick a value
   * j in distribution Pr(Y = j), j=1..n, we first pick a random
   * integer in the uniform distribution over 1..n. We then inspect
   * the probability table whose value represents a biased coin; the
   * random integer is returned with this probability, otherwise the
   * index in the alias table is chosen.
   *
   * "It is a peculiar way to throw dice, but the results are
   * indistinguishable from the real thing." -Knuth (TAOCP Vol. 2;
   * 3.4.1 p.121).
   *
   * [1] Alastair J. Walker. 1977. An Efficient Method for Generating
   * Discrete Random Variables with General Distributions. ACM Trans.
   * Math. Softw. 3, 3 (September 1977), 253-256.
   * DOI=10.1145/355744.355749
   * https://doi.acm.org/10.1145/355744.355749
   *
   * Package private for testing.
   */
  private[util] case class Aliased(alias: IndexedSeq[Int], prob: IndexedSeq[Double]) extends Drv {
    require(prob.size == alias.size)
    private[this] val N = alias.size

    def apply(rng: Rng): Int = {
      val i = rng.nextInt(N)
      val p = prob(i)
      if (p == 1 || rng.nextDouble() < p) i
      else alias(i)
    }
  }

  /**
   * Generate probability and alias tables in the manner of to Vose
   * [1]. This algorithm is simple, efficient, and intuitive. Vose's
   * algorithm is O(n) in the distribution size. The paper below
   * contains correctness and complexity proofs.
   *
   * [1] Michael D. Vose. 1991. A Linear Algorithm for Generating Random
   * Numbers with a Given Distribution. IEEE Trans. Softw. Eng. 17, 9
   * (September 1991), 972-975. DOI=10.1109/32.92917
   * https://dx.doi.org/10.1109/32.92917
   *
   * Package private for testing. Note that the provided array is mutated
   * but is not used after this method call in the generated `Drv`.
   */
  private[util] def newVose(p: Array[Double]): Drv = {
    val N = p.length

    val alias = new Array[Int](N)
    val prob = new Array[Double](N)
    val storage = new DrvSmallLargeSets(N)

    @tailrec
    def fillQueues(i: Int): Unit = if (i < N) {
      p(i) *= N
      if (p(i) < 1d) storage.smallPush(i)
      else storage.largePush(i)
      fillQueues(i + 1)
    }
    fillQueues(0)

    while (!storage.smallIsEmpty && !storage.largeIsEmpty) {
      val s = storage.smallPop()
      val l = storage.largePop()

      prob(s) = p(s)
      alias(s) = l

      p(l) = (p(s) + p(l)) - 1d // Same as p(l)-(1-p(s)), but more stable
      if (p(l) < 1) storage.smallPush(l)
      else storage.largePush(l)
    }

    while (!storage.largeIsEmpty) prob(storage.largePop()) = 1d

    while (!storage.smallIsEmpty) prob(storage.smallPop()) = 1d

    Aliased(alias, prob)
  }

  /**
   * Create a new Drv representing the passed in distribution of
   * probabilities. These must add up to 1, however we cannot
   * reliably test for this due to numerical stability issues: we're
   * operating on the honor's system.
   */
  def apply(dist: Seq[Double]): Drv = {
    require(dist.nonEmpty)
    val sum = dist.sum
    if (!isNormalized(sum))
      throw new AssertionError("Bad sum %.001f".format(sum))
    newVose(dist.toArray)
  }

  /**
   * Create a probability distribution based on a set of weights
   * (ratios).
   */
  def fromWeights(weights: Seq[Double]): Drv = {
    require(weights.nonEmpty)
    val sum = weights.sum

    newVose(
      if (sum == 0d) {
        val size = weights.size
        Array.fill(size) { 1d / size }
      } else {
        val arr = weights.toArray
        if (!isNormalized(sum)) {
          var i = 0
          while (i < arr.length) {
            arr(i) /= sum
            i += 1
          }
        }
        arr
      }
    )
  }
}


text:
package org.apache.bookkeeper.client;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.bookkeeper.bookie.Bookie;
import org.apache.bookkeeper.bookie.BookieShell.UpdateLedgerNotifier;
import org.apache.bookkeeper.client.AsyncCallback.AddCallback;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.proto.BookieServer;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.util.MathUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Test update operations on a ledger.
 */
public class UpdateLedgerOpTest extends BookKeeperClusterTestCase {
    private static final Logger LOG = LoggerFactory.getLogger(UpdateLedgerOpTest.class);
    private DigestType digestType = DigestType.CRC32;
    private static final String PASSWORD = "testPasswd";
    private static final int printprogress = 5;

    public UpdateLedgerOpTest() {
        super(3);
        baseConf.setGcWaitTime(100000);
    }

    UpdateLedgerNotifier progressable = new UpdateLedgerNotifier() {
        long lastReport = System.nanoTime();

        @Override
        public void progress(long updated, long issued) {
            if (TimeUnit.MILLISECONDS.toSeconds(MathUtils.elapsedMSec(lastReport)) >= printprogress) {
                LOG.info("Number of ledgers issued={}, updated={}", issued, updated);
                lastReport = MathUtils.nowInNano();
            }
        }
    };

    /**
     * Tests verifies update bookie id to FQDN hostname when there are many ledgers.
     */
    @Test
    public void testManyLedgersWithFQDNHostname() throws Exception {
        testManyLedgers(false);
    }

    /**
     * Tests verifies update bookie id to short hostname when there are many ledgers.
     */
    @Test(timeout = 120000)
    public void testManyLedgersWithShortHostname() throws Exception {
        testManyLedgers(true);
    }

    public void testManyLedgers(boolean useShortHostName) throws Exception {
        BookKeeper bk = new BookKeeper(baseClientConf, zkc);
        BookKeeperAdmin bkadmin = new BookKeeperAdmin(bk);

        LOG.info("Create ledger and add entries to it");
        List<LedgerHandle> ledgers = new ArrayList<LedgerHandle>();
        LedgerHandle lh1 = createLedgerWithEntries(bk, 0);
        ledgers.add(lh1);
        for (int i = 0; i < 99; i++) {
            ledgers.add(createLedgerWithEntries(bk, 0));
        }

        ArrayList<BookieSocketAddress> ensemble = lh1.getLedgerMetadata().getEnsemble(0);

        BookieSocketAddress curBookieAddr = ensemble.get(0);
        baseConf.setUseHostNameAsBookieID(true);
        baseConf.setUseShortHostName(useShortHostName);
        BookieSocketAddress curBookieId = Bookie.getBookieAddress(baseConf);
        BookieSocketAddress toBookieAddr = new BookieSocketAddress(curBookieId.getHostName() + ":"
                + curBookieAddr.getPort());
        UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, bkadmin);
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 5, Integer.MIN_VALUE, progressable);

        for (LedgerHandle lh : ledgers) {
            // ledger#close() would hit BadVersion exception as rename
            // increments cversion. But LedgerMetadata#isConflictWith()
            // gracefully handles this conflicts.
            lh.close();
            LedgerHandle openLedger = bk.openLedger(lh.getId(), digestType, PASSWORD.getBytes());
            ensemble = openLedger.getLedgerMetadata().getEnsemble(0);
            assertTrue("Failed to update the ledger metadata to use bookie host name",
                    ensemble.contains(toBookieAddr));
            assertFalse("Failed to update the ledger metadata to use bookie host name",
                    ensemble.contains(curBookieAddr));
        }
    }

    /**
     * Tests verifies with limit value lesser than the total number of ledgers.
     */
    @Test
    public void testLimitLessThanTotalLedgers() throws Exception {
        BookKeeper bk = new BookKeeper(baseClientConf, zkc);
        BookKeeperAdmin bkadmin = new BookKeeperAdmin(bk);

        LOG.info("Create ledger and add entries to it");
        List<LedgerHandle> ledgers = new ArrayList<LedgerHandle>();
        LedgerHandle lh1 = createLedgerWithEntries(bk, 0);
        ledgers.add(lh1);
        for (int i = 1; i < 10; i++) {
            ledgers.add(createLedgerWithEntries(bk, 0));
        }

        ArrayList<BookieSocketAddress> ensemble = lh1.getLedgerMetadata().getEnsemble(0);

        BookieSocketAddress curBookieAddr = ensemble.get(0);
        baseConf.setUseHostNameAsBookieID(true);
        BookieSocketAddress toBookieId = Bookie.getBookieAddress(baseConf);
        BookieSocketAddress toBookieAddr = new BookieSocketAddress(toBookieId.getHostName() + ":"
                + curBookieAddr.getPort());
        UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, bkadmin);
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 7, 4, progressable);
        int updatedLedgersCount = getUpdatedLedgersCount(bk, ledgers, toBookieAddr);
        assertEquals("Failed to update the ledger metadata to use bookie host name", 4, updatedLedgersCount);

        // next execution
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 2, 10, progressable);
        updatedLedgersCount = getUpdatedLedgersCount(bk, ledgers, toBookieAddr);
        assertEquals("Failed to update the ledger metadata to use bookie host name", 10, updatedLedgersCount);

        // no ledgers
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 3, 20, progressable);
        updatedLedgersCount = getUpdatedLedgersCount(bk, ledgers, toBookieAddr);
        assertEquals("Failed to update the ledger metadata to use bookie host name", 10, updatedLedgersCount);

        // no ledgers
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 3, Integer.MIN_VALUE, progressable);
        updatedLedgersCount = getUpdatedLedgersCount(bk, ledgers, toBookieAddr);
        assertEquals("Failed to update the ledger metadata to use bookie host name", 10, updatedLedgersCount);
    }

    /**
     * Tests verifies the ensemble reformation after updating the bookie id to
     * FQDN hostname in the existing ensemble.
     */
    @Test
    public void testChangeEnsembleAfterRenamingToFQDNHostname() throws Exception {
        testChangeEnsembleAfterRenaming(false);
    }

    /**
     * Tests verifies the ensemble reformation after updating the bookie id to
     * short hostname in the existing ensemble.
     */
    @Test(timeout = 120000)
    public void testChangeEnsembleAfterRenamingToShortHostname() throws Exception {
        testChangeEnsembleAfterRenaming(true);
    }

    public void testChangeEnsembleAfterRenaming(boolean useShortHostName) throws Exception {

        BookKeeper bk = new BookKeeper(baseClientConf, zkc);
        BookKeeperAdmin bkadmin = new BookKeeperAdmin(bk);

        LOG.info("Create ledger and add entries to it");
        LedgerHandle lh = createLedgerWithEntries(bk, 100);

        BookieServer bookieServer = bs.get(0);
        ArrayList<BookieSocketAddress> ensemble = lh.getLedgerMetadata().getEnsemble(0);
        BookieSocketAddress curBookieAddr = null;
        for (BookieSocketAddress bookieSocketAddress : ensemble) {
            if (bookieServer.getLocalAddress().equals(bookieSocketAddress)) {
                curBookieAddr = bookieSocketAddress;
            }
        }
        assertNotNull("Couldn't find the bookie in ledger metadata!", curBookieAddr);
        baseConf.setUseHostNameAsBookieID(true);
        baseConf.setUseShortHostName(useShortHostName);
        BookieSocketAddress toBookieId = Bookie.getBookieAddress(baseConf);
        BookieSocketAddress toBookieAddr = new BookieSocketAddress(toBookieId.getHostName() + ":"
                + curBookieAddr.getPort());
        UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, bkadmin);
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 5, 100, progressable);

        bookieServer.shutdown();

        ServerConfiguration serverConf1 = newServerConfiguration();
        bsConfs.add(serverConf1);
        bs.add(startBookie(serverConf1));

        // ledger#asyncAddEntry() would hit BadVersion exception as rename incr
        // cversion. But LedgerMetadata#isConflictWith() gracefully handles
        // this conflicts.
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicInteger rc = new AtomicInteger(BKException.Code.OK);
        lh.asyncAddEntry("foobar".getBytes(), new AddCallback() {
            @Override
            public void addComplete(int rccb, LedgerHandle lh, long entryId, Object ctx) {
                rc.compareAndSet(BKException.Code.OK, rccb);
                latch.countDown();
            }
        }, null);
        if (!latch.await(30, TimeUnit.SECONDS)) {
            throw new Exception("Entries took too long to add");
        }
        if (rc.get() != BKException.Code.OK) {
            throw BKException.create(rc.get());
        }
        lh.close();
        LedgerHandle openLedger = bk.openLedger(lh.getId(), digestType, PASSWORD.getBytes());
        final LedgerMetadata ledgerMetadata = openLedger.getLedgerMetadata();
        assertEquals("Failed to reform ensemble!", 2, ledgerMetadata.getEnsembles().size());
        ensemble = ledgerMetadata.getEnsemble(0);
        assertTrue("Failed to update the ledger metadata to use bookie host name",
                ensemble.contains(toBookieAddr));
    }

    /**
     * Tests verifies simultaneous flow between adding entries and rename of
     * bookie id.
     */
    @Test
    public void testRenameWhenAddEntryInProgress() throws Exception {
        final BookKeeper bk = new BookKeeper(baseClientConf, zkc);
        BookKeeperAdmin bkadmin = new BookKeeperAdmin(bk);

        LOG.info("Create ledger and add entries to it");
        final int numOfEntries = 5000;
        final CountDownLatch latch = new CountDownLatch(numOfEntries);
        final AtomicInteger rc = new AtomicInteger(BKException.Code.OK);
        final LedgerHandle lh = createLedgerWithEntries(bk, 1);
        latch.countDown();
        Thread th = new Thread() {
            public void run() {
                final AddCallback cb = new AddCallback() {
                    public void addComplete(int rccb, LedgerHandle lh, long entryId, Object ctx) {
                        rc.compareAndSet(BKException.Code.OK, rccb);
                        if (entryId % 100 == 0) {
                            LOG.info("Added entries till entryId:{}", entryId);
                        }
                        latch.countDown();
                    }
                };
                for (int i = 1; i < numOfEntries; i++) {
                    lh.asyncAddEntry(("foobar" + i).getBytes(), cb, null);
                }

            }
        };
        th.start();
        ArrayList<BookieSocketAddress> ensemble = lh.getLedgerMetadata().getEnsemble(0);
        BookieSocketAddress curBookieAddr = ensemble.get(0);
        BookieSocketAddress toBookieAddr = new BookieSocketAddress("localhost:" + curBookieAddr.getPort());
        UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, bkadmin);
        updateLedgerOp.updateBookieIdInLedgers(curBookieAddr, toBookieAddr, 5, 100, progressable);

        if (!latch.await(120, TimeUnit.SECONDS)) {
            throw new Exception("Entries took too long to add");
        }
        if (rc.get() != BKException.Code.OK) {
            throw BKException.create(rc.get());
        }
        lh.close();
        LedgerHandle openLedger = bk.openLedger(lh.getId(), digestType, PASSWORD.getBytes());
        ensemble = openLedger.getLedgerMetadata().getEnsemble(0);
        assertTrue("Failed to update the ledger metadata to use bookie host name",
                ensemble.contains(toBookieAddr));
    }

    private int getUpdatedLedgersCount(BookKeeper bk, List<LedgerHandle> ledgers, BookieSocketAddress toBookieAddr)
            throws InterruptedException, BKException {
        ArrayList<BookieSocketAddress> ensemble;
        int updatedLedgersCount = 0;
        for (LedgerHandle lh : ledgers) {
            // ledger#close() would hit BadVersion exception as rename
            // increments cversion. But LedgerMetadata#isConflictWith()
            // gracefully handles this conflicts.
            lh.close();
            LedgerHandle openLedger = bk.openLedger(lh.getId(), digestType, PASSWORD.getBytes());
            ensemble = openLedger.getLedgerMetadata().getEnsemble(0);
            if (ensemble.contains(toBookieAddr)) {
                updatedLedgersCount++;
            }
        }
        return updatedLedgersCount;
    }

    private LedgerHandle createLedgerWithEntries(BookKeeper bk, int numOfEntries) throws Exception {
        LedgerHandle lh = bk.createLedger(3, 3, digestType, PASSWORD.getBytes());
        final AtomicInteger rc = new AtomicInteger(BKException.Code.OK);
        final CountDownLatch latch = new CountDownLatch(numOfEntries);

        final AddCallback cb = new AddCallback() {
            public void addComplete(int rccb, LedgerHandle lh, long entryId, Object ctx) {
                rc.compareAndSet(BKException.Code.OK, rccb);
                latch.countDown();
            }
        };
        for (int i = 0; i < numOfEntries; i++) {
            lh.asyncAddEntry(("foobar" + i).getBytes(), cb, null);
        }
        if (!latch.await(30, TimeUnit.SECONDS)) {
            throw new Exception("Entries took too long to add");
        }
        if (rc.get() != BKException.Code.OK) {
            throw BKException.create(rc.get());
        }
        return lh;
    }
}


text:
(function () {

    var injectParams = ['$rootScope', '$http', '$state', '$cookies', 'SETTINGS'];

    var AuthService = function ($rootScope, $http, $state, $cookies, SETTINGS) {
        var userName;
        var auth;

        this.login = function (credentials) {
            var req = {
                method: 'POST',
                url: SETTINGS.LOGIN_URL,
                data: angular.element.param({user: credentials.user, pwd: credentials.pwd}),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            };
            userName = credentials.user;
            var p = $http(req);
            p.then(r => {
                auth = 'Basic ' + btoa(credentials.user + ":" + credentials.pwd);
                $cookies.put('authentication', auth);
            });
            return p;
        };

        this.currentUsername = function() {
            return userName;
        };

        this.getRestAuth = function() {
            auth = $cookies.get("authentication");
            return auth;
        };

        this.redirectToLogin = function () {
            $state.go('home');
        };

        this.isLoggedIn = function () {
            auth = $cookies.get("authentication")
            return auth != null;
        };

        this.logout = function () {
            $cookies.remove("authentication");
        };

    };

    AuthService.$inject = injectParams;

    angular.module('openmuc.auth').service('AuthService', AuthService);

})();


text:
@interface UIImage (ClipSubImage)

-(UIImage*)getSubImage:(CGRect)rect;

@end


text:
SYNONYM

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

#### Published in
Handbook of British Fungi 2: 900 (1871)

#### Original name
Sphaeria ulnospora Cooke, 1871

### Remarks
null


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */

/**
 * PHP version 5.3
 *
 * Copyright (c) 2011-2013 KUBO Atsuhiro <kubo@iteman.jp>,
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @package    Stagehand_TestRunner
 * @copyright  2011-2013 KUBO Atsuhiro <kubo@iteman.jp>
 * @license    http://www.opensource.org/licenses/bsd-license.php  New BSD License
 * @version    Release: @package_version@
 * @since      File available since Release 3.0.0
 */

namespace Stagehand\TestRunner\DependencyInjection\Extension;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

use Stagehand\TestRunner\Core\Plugin\CakePHPPlugin;

/**
 * @package    Stagehand_TestRunner
 * @copyright  2011-2013 KUBO Atsuhiro <kubo@iteman.jp>
 * @license    http://www.opensource.org/licenses/bsd-license.php  New BSD License
 * @version    Release: @package_version@
 * @since      Class available since Release 3.0.0
 */
class CakePHPExtension extends SimpleTestExtension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        parent::load($configs, $container);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../../Resources/config'));
        $loader->load(self::getAlias() . '.yml');
    }

    public function getAlias()
    {
        return strtolower(CakePHPPlugin::getPluginID());
    }
}

/*
 * Local Variables:
 * mode: php
 * coding: iso-8859-1
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * indent-tabs-mode: nil
 * End:
 */


text:
<%#
 Copyright 2013-2017 the original author or authors from the StackStack project.

 This file is part of the StackStack project, see http://www.jhipster.tech/
 for more information.

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

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

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

Error Page!

{{errorMessage}}


text:
require File.expand_path("spec_helper", File.dirname(__FILE__))

describe "session handling" do
  it "should give a warning if session variable is not available" do
    app do |r|
      begin
        session
      rescue Exception => e
        e.message
      end
    end

    body.must_match(/use Rack::Session::Cookie/)
  end

  it "should return session if available" do
    app(:bare) do
      use Rack::Session::Cookie, :secret=>'1'

      route do |r|
        r.on do
          (session[1] ||= 'a') << 'b'
          session[1]
        end
      end
    end

    _, h, b = req
    b.join.must_equal 'ab'
    _, h, b = req('HTTP_COOKIE'=>h['Set-Cookie'].sub("; path=/; HttpOnly", ''))
    b.join.must_equal 'abb'
    _, h, b = req('HTTP_COOKIE'=>h['Set-Cookie'].sub("; path=/; HttpOnly", ''))
    b.join.must_equal 'abbb'
  end
end


text:
<?php

use app\models\Attribute;
use app\models\Auto;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\Value */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'auto_id')->hiddenInput(['value'=>$_GET['auto_id']])?>

    <?= $form->field($model, 'attribute_id')->dropDownList(Attribute::find()->select(['name','id'])->indexBy('id')->column(), ['prompt' => '']) ?>

    <?= $form->field($model, 'value')->textInput(['maxlength' => true]) ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
<?php
/**
 * <textarea></textarea> with WYSIWYG editing
 * @author m.augustynowicz
 *
 * (params passed as local variables)
 * same as FString_area plus:
 *
 * @param bool $xinha_use_loader show splash screen (xinha specific)
 * @param string $user_content_css css file path to use for content
 * @param string $ck_uploader uri to file uploader (ckeditor specific)
 * @param string $ck_imageuploader uri to image file uploader (ckeditor specific)
 * @param string $ck_flashuploader uri to flash file uploader (ckeditor specific)
 */

extract(array_merge(
        array(
            'xinha_use_loader' => null,
            'user_content_css' => null,
            'ck_uploader'      => null,
            'ck_imageuploader' => null,
            'ck_flashuploader' => null,
        ),
        (array) $____local_variables
    ));

$wysiwyg_parmas = array();

if (null !== $xinha_use_loader)
    $wysiwyg_parmas['use_loader'] = $xinha_use_loader;

if (null !== $user_content_css)
    @$____local_variables['attrs']['data-user-content-css'] = $user_content_css;

if (null !== $ck_uploader)
    @$____local_variables['attrs']['data-ckeditor-uploader'] = $ck_uploader;
if (null !== $ck_imageuploader)
    @$____local_variables['attrs']['data-ckeditor-image-uploader'] = $ck_imageuploader;
if (null !== $ck_flashuploader)
    @$____local_variables['attrs']['data-ckeditor-flash-uploader'] = $ck_flashuploader;

$t->inc('wysiwyg/init', $wysiwyg_parmas);

if (!@$____local_variables['disabled'])
    @$____local_variables['class'] .= ' richedit';

$t->inc('Forms/FMultilineString', $____local_variables);


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

namespace Azure.ResourceManager.ProviderHub.Models
{
    /// <summary> The ResourceTypeRegistrationPropertiesManagement. </summary>
    public partial class ResourceTypeRegistrationPropertiesManagement : ResourceProviderManagement
    {
        /// <summary> Initializes a new instance of ResourceTypeRegistrationPropertiesManagement. </summary>
        public ResourceTypeRegistrationPropertiesManagement()
        {
        }

        /// <summary> Initializes a new instance of ResourceTypeRegistrationPropertiesManagement. </summary>
        /// <param name="schemaOwners"></param>
        /// <param name="manifestOwners"></param>
        /// <param name="incidentRoutingService"></param>
        /// <param name="incidentRoutingTeam"></param>
        /// <param name="incidentContactEmail"></param>
        /// <param name="serviceTreeInfos"></param>
        /// <param name="resourceAccessPolicy"></param>
        /// <param name="resourceAccessRoles"></param>
        internal ResourceTypeRegistrationPropertiesManagement(IList<string> schemaOwners, IList<string> manifestOwners, string incidentRoutingService, string incidentRoutingTeam, string incidentContactEmail, IList<ServiceTreeInfo> serviceTreeInfos, ResourceProviderManagementResourceAccessPolicy? resourceAccessPolicy, IList<BinaryData> resourceAccessRoles) : base(schemaOwners, manifestOwners, incidentRoutingService, incidentRoutingTeam, incidentContactEmail, serviceTreeInfos, resourceAccessPolicy, resourceAccessRoles)
        {
        }
    }
}


text:
import Link from 'next/link'
import { useRouter } from 'next/router'

export default function Post() {
  const router = useRouter()
  return (

Post #{router.query.id}

Lorem ipsum

      <Link href="/">
        Back to blog
      </Link>

  )
}


text:
import os
import sys

PROJECT_SRC_NAME = 'ehb_service'

# absolute path to the myproject directory
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
# absolute path to myproject/src
PROJECT_SRC_PATH = os.path.join(PROJECT_PATH, PROJECT_SRC_NAME)
# absolute path to the myproject/src/apps directory
PROJECT_APPS_PATH = os.path.join(PROJECT_SRC_PATH, 'apps')
# For now we're explicitly defining the Dockerized path

os.environ['DJANGO_SETTINGS_MODULE'] = '%s.conf.settings' % PROJECT_SRC_NAME
os.environ['PYTHON_EGG_CACHE'] = '/tmp'

# check that the project module can be imported.
try:
    __import__(PROJECT_SRC_NAME)
except ImportError:
    # couldn't import the project, place it on the python path and try again.
    sys.path.insert(0, PROJECT_PATH)

    try:
        __import__(PROJECT_SRC_NAME)
    except ImportError:
        sys.stderr.write("Error: Can't import the \"%s\" project module." %
                         PROJECT_SRC_NAME)

sys.path.insert(0, PROJECT_SRC_PATH)
sys.path.insert(0, PROJECT_APPS_PATH)

# finally.. define the WSGI handler as the entry point to the application
from django.core.wsgi import get_wsgi_application
application=get_wsgi_application()


text:
<?php

try
{
  /* connect to server, login and get TeamSpeak3_Node_Host object by URI */
  $ts3_ServerInstance = TeamSpeak3::factory("serverquery://" . $cfg["user"] . ":" . $cfg["pass"] . "@" . $cfg["host"] . ":" . $cfg["query"] . "/");

  /* access server instance address using __toString() */
  echo "
Client List Filter - " . $ts3_ServerInstance . "
\n";

  /* display server select form */
  $selected_sid = form_server_selector($ts3_ServerInstance->serverList());

  /* get TeamSpeak3_Node_Server object by ID */
  $ts3_VirtualServer = $ts3_ServerInstance->serverGetById($selected_sid);

  /* set some example filters */
  $filter = array(
    "client_nickname" => "[^[:alnum:]]",
    "client_type" => TeamSpeak3::CLIENT_TYPE_REGULAR,
  );

  /* display filter info */
  echo "Nickname Filter: [^[:alnum:]]

\n";

  /* walk through list of clients */
  echo "
\n";
  echo "
\n" .
       "  ID	\n" .
       "  Nickname	\n" .
       "  Unique Identifier	\n" .
       "  Status	\n" .
       "  Platform	\n" .
       "  Version	\n" .
       "
\n";
  foreach($ts3_VirtualServer->clientList($filter) as $client)
  {
    echo "
\n" .
         "  " . $client->getId() . "	\n" .
         "  " . htmlspecialchars($client) . "	\n" .
         "  " . $client["client_unique_identifier"] . "	\n" .
         "  getIcon() . ".png\" alt=\"\" />	\n" .
         "  " . $client["client_platform"] . "	\n" .
         "  " . $client["client_version"] . "	\n" .
         "
\n";
  }
  echo "
\n";

  /* display runtime from adapter profiler */
  echo "
Executed " . $ts3_ServerInstance->getAdapter()->getQueryCount() . " queries in " . $ts3_ServerInstance->getAdapter()->getQueryRuntime() . " seconds
\n";
}
catch(Exception $e)
{
  /* catch exceptions and display error message if anything went wrong */
  echo "Error " . $e->getCode() . ": " . $e->getMessage() . "\n";
}


text:
function _writeOnlyError(name) {
  throw new TypeError("\"" + name + "\" is write-only");
}

module.exports = _writeOnlyError, module.exports.__esModule = true, module.exports["default"] = module.exports;


text:
using System.ComponentModel;
using System.Diagnostics;
using CoreGraphics;
using Foundation;
using UIKit;

namespace XamarinPaintCode
{
    /// <summary>
    /// The actual view class which contains the icon.
    /// </summary>
    [Register("BaseballerIcon")]
    [DesignTimeVisible(true)]
    public class BaseballerIcon : UIView
    {
        private UIColor _iconColor = UIColor.Black;

        /// <summary>
        /// The time in ms took to draw the icon.
        /// </summary>
        public long DrawTime { get; set; }

        /// <summary>
        /// Indicates if need to redraw when the size changes.
        /// </summary>
        public bool Redraw { get; set; }

        /// <summary>
        /// Changes the new colot and automatically redraws the icon.
        /// </summary>
        public UIColor IconColor
        {
            get
            {
                return _iconColor;
            }

            set
            {
                _iconColor = value;
                SetNeedsDisplay();
            }
        }

        /// <summary>
        /// The icon frame. It can be changed without actually redrawing it.
        /// </summary>
        public override CGRect Frame
        {
            get
            {
                return base.Frame;
            }
            set
            {
                base.Frame = value;
                if (Redraw)
                    SetNeedsDisplay();
                else
                    DrawTime = 0;
            }
        }

        /// <summary>
        /// Constructor based on frame.
        /// </summary>
        /// <param name="frame"></param>
        public BaseballerIcon(CGRect frame) : base(frame)
        {
        }

        /// <summary>
        /// Overriding the draw method to manually draw this view.
        /// </summary>
        /// <param name="rect">The area that the view should be drawn in.</param>
        public override void Draw(CGRect rect)
        {
            // Timing the draw.
            var sw = new Stopwatch();
            sw.Start();

            // Drawing the icon.
            Icons.DrawBaseballer(rect, this, IconColor);
            sw.Stop();

            //Updating the time consumed.
            DrawTime = sw.ElapsedMilliseconds;
        }
    }
}


text:
**This page has moved to the
[leanprover-community website](https://leanprover-community.github.io/contribute/naming.html).**


text:
package skuber.apps

import skuber.ResourceSpecification.{Names, Scope}
import skuber._

import play.api.libs.functional.syntax._
import play.api.libs.json.{Format, JsPath, Json}
import skuber.json.format._ // reuse some core skuber json formatters

/**
  * Created by hollinwilkins on 4/5/17.
  * The api version of this StatefulSet type is v1beta2, which is for use with k8s 1.8+.
  * For earlier versions of k8s, use skuber.apps.v1beta1.StatefulSet
  */
case class StatefulSet(
  kind: String ="StatefulSet",
  apiVersion: String = "apps/v1beta2", // correct at k8s 1.8
  metadata: ObjectMeta,
  spec:  Option[StatefulSet.Spec] = None,
  status:  Option[StatefulSet.Status] = None)
    extends ObjectResource
{
  def withResourceVersion(version: String) = this.copy(metadata = metadata.copy(resourceVersion=version))

  lazy val copySpec = this.spec.getOrElse(StatefulSet.Spec(template = Pod.Template.Spec()))
  private val rollingUpdateStrategy = StatefulSet.UpdateStrategy(`type`=StatefulSet.UpdateStrategyType.RollingUpdate, None)
  private def rollingUpdateStrategy(partition: Int)=
    StatefulSet.UpdateStrategy(`type`=StatefulSet.UpdateStrategyType.RollingUpdate,Some(StatefulSet.RollingUpdateStrategy(partition)))

  def withReplicas(count: Int) = this.copy(spec=Some(copySpec.copy(replicas=Some(count))))
  def withServiceName(serviceName: String) = this.copy(spec=Some(copySpec.copy(serviceName=Some(serviceName))))
  def withTemplate(template: Pod.Template.Spec) = this.copy(spec=Some(copySpec.copy(template=template)))
  def withLabelSelector(sel: LabelSelector) = this.copy(spec=Some(copySpec.copy(selector=Some(sel))))
  def withRollingUpdateStrategyPartition(partition:Int) = this.copy(spec=Some(copySpec.copy(updateStrategy = Some(rollingUpdateStrategy(partition)))))
  def withVolumeClaimTemplate(claim: PersistentVolumeClaim) = {
    val spec = copySpec.withVolumeClaimTemplate(claim)
    this.copy(spec=Some(spec))
  }
}

object StatefulSet {

  val specification=NonCoreResourceSpecification (
    apiGroup="apps",
    version="v1beta2", // version as at k8s v1.8
    scope = Scope.Namespaced,
    names=Names(
      plural = "statefulsets",
      singular = "statefulset",
      kind = "StatefulSet",
      shortNames = List()
    )
  )
  implicit val stsDef = new ResourceDefinition[StatefulSet] { def spec=specification }
  implicit val stsListDef = new ResourceDefinition[StatefulSetList] { def spec=specification }
  implicit val scDef = new Scale.SubresourceSpec[StatefulSet] { override def apiVersion = "apps/v1beta2"}

  def apply(name: String): StatefulSet = StatefulSet(metadata=ObjectMeta(name=name))

  object PodManagementPolicyType extends Enumeration {
    type PodManagementPolicyType = Value
    val OrderedReady,Parallel = Value
  }

  object UpdateStrategyType extends Enumeration {
    type UpdateStrategyType = Value
    val OnDelete,RollingUpdate = Value
  }

  case class UpdateStrategy(`type`: UpdateStrategyType.UpdateStrategyType, rollingUpdate: Option[RollingUpdateStrategy]=None)
  case class RollingUpdateStrategy(partition: Int)

  case class Spec(replicas: Option[Int] = Some(1),
                  serviceName: Option[String] = None,
                  selector: Option[LabelSelector] = None,
                  template: Pod.Template.Spec,
                  volumeClaimTemplates: List[PersistentVolumeClaim] = Nil,
                  podManagmentPolicy: Option[PodManagementPolicyType.PodManagementPolicyType] = None,
                  updateStrategy: Option[UpdateStrategy] = None,
                  revisionHistoryLimit: Option[Int] = None)
  {
    def withVolumeClaimTemplate(claim: PersistentVolumeClaim) = copy(volumeClaimTemplates = claim :: volumeClaimTemplates)
  }

  case class Condition(`type`:String,status:String,lastTransitionTime:Option[Timestamp],reason:Option[String],message:Option[String])

  case class Status(observedGeneration: Option[Int],
                    replicas: Int,
                    readyReplicas: Option[Int],
                    updatedReplicas: Option[Int],
                    currentRevision: Option[String],
                    updateRevision: Option[String],
                    collisionCount: Option[Int],
                    conditions: Option[List[Condition]])

  // json formatters

  implicit val statefulSetPodPcyMgmtFmt: Format[StatefulSet.PodManagementPolicyType.PodManagementPolicyType] = Format(enumReads(StatefulSet.PodManagementPolicyType, StatefulSet.PodManagementPolicyType.OrderedReady), enumWrites)
  implicit val statefulSetRollUp: Format[StatefulSet.RollingUpdateStrategy] = Json.format[StatefulSet.RollingUpdateStrategy]
  implicit val statefulSetUpdStrFmt: Format[StatefulSet.UpdateStrategy] = (
    (JsPath \ "type").formatEnum(StatefulSet.UpdateStrategyType, Some(StatefulSet.UpdateStrategyType.RollingUpdate)) and
    (JsPath \ "rollingUpdate").formatNullable[StatefulSet.RollingUpdateStrategy]
  )(StatefulSet.UpdateStrategy.apply _,unlift(StatefulSet.UpdateStrategy.unapply))

  implicit val statefulSetSpecFmt: Format[StatefulSet.Spec] = (
    (JsPath \ "replicas").formatNullable[Int] and
    (JsPath \ "serviceName").formatNullable[String] and
    (JsPath \ "selector").formatNullableLabelSelector and
    (JsPath \ "template").format[Pod.Template.Spec] and
    (JsPath \ "volumeClaimTemplates").formatMaybeEmptyList[PersistentVolumeClaim] and
    (JsPath \ "podManagmentPolicy").formatNullableEnum(StatefulSet.PodManagementPolicyType) and
    (JsPath \ "updateStrategy").formatNullable[StatefulSet.UpdateStrategy] and
    (JsPath \ "revisionHistoryLimit").formatNullable[Int]
  )(StatefulSet.Spec.apply _, unlift(StatefulSet.Spec.unapply))

  implicit val statefulSetCondFmt: Format[StatefulSet.Condition] = Json.format[StatefulSet.Condition]
  implicit val statefulSetStatusFmt: Format[StatefulSet.Status] = Json.format[StatefulSet.Status]

  implicit lazy val statefulSetFormat: Format[StatefulSet] = (
    objFormat and
    (JsPath \ "spec").formatNullable[StatefulSet.Spec] and
    (JsPath \ "status").formatNullable[StatefulSet.Status]
  )(StatefulSet.apply _, unlift(StatefulSet.unapply))

  implicit val statefulSetListFormat: Format[StatefulSetList] = ListResourceFormat[StatefulSet]
}


text:
using System.Collections.Generic;
using System.Net;

namespace Amarillo.Network
{
    public class Response<TPayload>
    {
        public HttpStatusCode Status { get; set; }
        public TPayload Payload { get; set; }
        public KeyValuePair<string, IList<string>> Errors { get; set; }
    }
}


text:
<?php

require_once 'PHPUnit/Framework.php';

define('PHP_EXTENSION', '.php');
define('DB_NAME', 'demo');

require dirname(__FILE__) . '/../lib/DB.php';
require dirname(__FILE__) . '/../lib/Model.php';

class ModelTest extends PHPUnit_Framework_TestCase
{
    public function testLoadMongoInstance()
    {
        $demoObj = new DemoModel;
        $data = array('foo' => 'bar');
        $demoObj->insert($data);
        $results = $demoObj->findOne($data, array('foo'));
        $this->assertEquals('bar', $results['foo']);
        $demoObj->drop();
    }
}

class DemoModel extends Model
{
    protected $_collectionName = 'demo';
}


text:
  // Cannot do anything for ROOT5CINT / OpenCL1, so just disable
  #define GPUInfo(...)
  #define GPUImportant(...)
  #define GPUWarning(...)
  #define GPUError(...)
  #define GPUFatal(...)
#elif defined(GPUCA_STANDALONE) && !defined(GPUCA_GPUCODE_DEVICE) && !defined(GPUCA_NO_FMT)
  #include <fmt/printf.h>
  #define GPUInfo(string, ...)                 \
    {                                          \
      fmt::printf(string "\n", ##__VA_ARGS__); \
    }
  #define GPUImportant(...) GPUInfo(__VA_ARGS__)
  #define GPUWarning(string, ...)                       \
    {                                                   \
      fmt::fprintf(stderr, string "\n", ##__VA_ARGS__); \
    }
  #define GPUError(...) GPUWarning(__VA_ARGS__)
  #define GPUFatal(string, ...)                         \
    {                                                   \
      fmt::fprintf(stderr, string "\n", ##__VA_ARGS__); \
      throw std::exception();                           \
    }
#elif defined(GPUCA_STANDALONE) || defined(GPUCA_GPUCODE_DEVICE) || (defined(GPUCA_ALIROOT_LIB) && defined(GPUCA_GPUCODE) && defined(__cplusplus) && __cplusplus < 201703L)
  // For standalone / CUDA / HIP, we just use printf, which should be available
  // Temporarily, we also have to handle CUDA on AliRoot with O2 defaults due to ROOT / CUDA incompatibilities
  #define GPUInfo(string, ...)            \
    {                                     \
      printf(string "\n", ##__VA_ARGS__); \
    }
  #define GPUImportant(...) GPUInfo(__VA_ARGS__)
  #ifdef GPUCA_GPUCODE_DEVICE
    #define GPUWarning(...) GPUInfo(__VA_ARGS__)
    #define GPUError(...) GPUInfo(__VA_ARGS__)
    #define GPUFatal(...) GPUInfo(__VA_ARGS__)
  #else
    #define GPUWarning(string, ...)                  \
      {                                              \
        fprintf(stderr, string "\n", ##__VA_ARGS__); \
      }
    #define GPUError(...) GPUWarning(__VA_ARGS__)
    #ifdef GPUCA_NOCOMPAT
      #define GPUFatal(string, ...)                    \
        {                                              \
          fprintf(stderr, string "\n", ##__VA_ARGS__); \
          throw std::exception();                      \
        }
    #else
      #define GPUFatal(string, ...)                  \
        {                                            \
          fprintf(stderr, string "\n", __VA_ARGS__); \
          exit(1);                                   \
        }
    #endif
  #endif
#elif defined(GPUCA_ALIROOT_LIB)
  // Forward to HLT Logging functions for AliRoot
  #include "AliHLTLogging.h"
  #define GPUInfo(...) HLTInfo(__VA_ARGS__)
  #define GPUImportant(...) HLTImportant(__VA_ARGS__)
  #define GPUWarning(...) HLTWarning(__VA_ARGS__)
  #define GPUError(...) HLTError(__VA_ARGS__)
  #define GPUFatal(...) HLTFatal(__VA_ARGS__)
  // Workaround for static functions / classes not deriving from AliHLTLogging
  namespace AliGPU
  {
  namespace gpu
  {
  // We pollute the AliGPU::gpu namespace with some anonymous functions that catch the HLT...() magic
  namespace
  {
  AliHLTLogging gAliGPULog; // This creates a couple of bogus instances, but there are plenty anyway
  template <typename... Args>
  void LoggingVarargs(Args... args)
  {
    gAliGPULog.LoggingVarargs(args...);
  }
  template <typename... Args>
  bool CheckFilter(Args... args)
  {
    return gAliGPULog.CheckFilter(args...);
  }
  const char* Class_Name() { return "GPU"; };
  } // namespace
  } // namespace gpu
  } // namespace AliGPU
#elif defined(GPUCA_O2_LIB) || defined(GPUCA_O2_INTERFACE)
  // Forward to O2 LOGF logginf for O2
  #include "GPUCommonLogger.h"
  #define GPUInfo(...) LOGF(info, __VA_ARGS__)
  #define GPUImportant(...) LOGF(info, __VA_ARGS__)
  #define GPUWarning(...) LOGF(warning, __VA_ARGS__)
  #define GPUError(...) LOGF(error, __VA_ARGS__)
  #define GPUFatal(...) LOGF(fatal, __VA_ARGS__)
#endif

// clang-format on

#endif // GPULOGGING_H


text:
jQuery(function() {
	handle_side_menu();

	enable_search_ahead();

	add_browser_detection(jQuery);

	general_things();

	widget_boxes();

	//bootstrap v 2.3.1 prevents this event which firefox's middle mouse button "new tab link" action, so we off it!
	$(document).off('click.dropdown-menu');
});

function handle_side_menu() {
	$('#menu-toggler').on('click', function() {
		$('#sidebar').toggleClass('display');
		$(this).toggleClass('display');
		return false;
	});
	//mini
	var $minimized = false;
	$('#sidebar-collapse').on('click', function(){
		$('#sidebar').toggleClass('menu-min');
		$(this.firstChild).toggleClass('icon-double-angle-right');

		$minimized = $('#sidebar').hasClass('menu-min');
		if($minimized) {
			$('.open > .submenu').removeClass('open');
		}
	});

	//opening submenu
	$('.nav-list').on('click', function(e){
		if($minimized) return;

		//check to see if we have clicked on an element which is inside a .dropdown-toggle element?!
		//if so, it means we should toggle a submenu
		var link_element = $(e.target).closest('.dropdown-toggle');
		if(link_element && link_element.length > 0) {
		    var sub = link_element.next().get(0);

			//if we are opening this submenu, close all other submenus except the ".active" one
			if(! $(sub).is(':visible') ) {//ie, we are about to open it and make it visible
			  $('.open > .submenu').each(function(){
				if(this != sub && !$(this.parentNode).hasClass('active')) {
					$(this).slideUp(200).parent().removeClass('open');
				}
			  });
			}

			$(sub).slideToggle(200).parent().toggleClass('open');
			return false;
		 }
	 })
}

function enable_search_ahead() {
	$('#nav-search-input').typeahead({
		source: ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"],
		updater:function (item) {
			$('#nav-search-input').focus();
			return item;
		}
	});
}

function general_things() {
 $('.ace-nav [class*="icon-animated-"]').closest('a').on('click', function(){
	var icon = $(this).find('[class*="icon-animated-"]').eq(0);
	var $match = icon.attr('class').match(/icon\-animated\-([\d\w]+)/);
	icon.removeClass($match[0]);
	$(this).off('click');
 });

 //simple settings

 $('#ace-settings-btn').on('click', function(){
	$(this).toggleClass('open');
	$('#ace-settings-box').toggleClass('open');
 });

 $('#ace-settings-header').removeAttr('checked').on('click', function(){
	if(this.checked) {
		$('.navbar').addClass('navbar-fixed-top');
		$(document.body).addClass('navbar-fixed');
	}
	else {
		$('.navbar').removeClass('navbar-fixed-top');
		$(document.body).removeClass('navbar-fixed');

		if($('#ace-settings-sidebar').get(0).checked) $('#ace-settings-sidebar').click();
	}
 });

 $('#ace-settings-sidebar').removeAttr('checked').on('click', function(){
	if(this.checked) {
		$('#sidebar').addClass('fixed');
		if(! $('#ace-settings-header').get(0).checked) $('#ace-settings-header').click();
	}
	else {
		$('#sidebar').removeClass('fixed');
	}
 });

 $('#btn-scroll-up').on('click', function(){
	var duration = Math.max(100, parseInt($('html').scrollTop() / 3));
	$('html,body').animate({scrollTop: 0}, duration);
	return false;
 });

  $('#skin-colorpicker').ace_colorpicker().on('change', function(){
	var skin_class = $(this).find('option:selected').data('class');

	var body = $(document.body);

	body.attr('class', body.hasClass('navbar-fixed') ? 'navbar-fixed' : '');
	if(skin_class != 'default') body.addClass(skin_class);

	if(skin_class == 'skin-1') {
		//$('.ace-nav > li').addClass('no-border');
		$('.ace-nav > li.grey').addClass('dark');
	}
	else {
		//$('.ace-nav > li').removeClass('no-border');
		$('.ace-nav > li.grey').removeClass('dark');
	}

	if(skin_class == 'skin-2') {
		$('.ace-nav > li').addClass('no-border margin-1');
		$('.ace-nav > li:not(:last-child)').addClass('light-pink').find('> a > [class*="icon-"]').addClass('pink').end().eq(0).find('.badge').addClass('badge-warning');
	}
	else {
		$('.ace-nav > li').removeClass('no-border').removeClass('margin-1');
		$('.ace-nav > li:not(:last-child)').removeClass('light-pink').find('> a > [class*="icon-"]').removeClass('pink').end().eq(0).find('.badge').removeClass('badge-warning');
	}

	if(skin_class == 'skin-3') {
		$('.ace-nav > li.grey').addClass('red').find('.badge').addClass('badge-yellow');
	} else {
		$('.ace-nav > li.grey').removeClass('red').find('.badge').removeClass('badge-yellow');
	}
 });

}

function widget_boxes() {
	$('.widget-toolbar > a[data-action]').each(function() {
		var $this = $(this);
		var $action = $this.data('action');
		var $box = $this.closest('.widget-box');

		if($action == 'collapse') {
			var $body = $box.find('.widget-body');
			var $icon = $this.find('[class*=icon-]').eq(0);
			var $match = $icon.attr('class').match(/icon\-(.*)\-(up|down)/);
			var $icon_down = 'icon-'+$match[1]+'-down';
			var $icon_up = 'icon-'+$match[1]+'-up';

			$body = $body.wrapInner('

').find(':first-child').eq(0);
			$this.on('click', function(ev){
				if($box.hasClass('collapsed')) {
					if($icon) $icon.addClass($icon_up).removeClass($icon_down);
					$box.removeClass('collapsed');
					$body.slideDown(200);
				}
				else {
					if($icon) $icon.addClass($icon_down).removeClass($icon_up);
					$body.slideUp(300, function(){$box.addClass('collapsed')});
				}
				ev.preventDefault();
			});
			if($box.hasClass('collapsed') && $icon) $icon.addClass($icon_down).removeClass($icon_up);

		}
		else if($action == 'close') {
			$this.on('click', function(ev){
				$box.hide(300 , function(){$box.remove();});
				ev.preventDefault();
			});
		}
		else if($action == 'reload') {
			$this.on('click', function(ev){
				$this.blur();
				//var $body = $box.find('.widget-body');
				var $remove = false;
				if(!$box.hasClass('position-relative')) {$remove = true; $box.addClass('position-relative');}
				$box.append('

');
				setTimeout(function(){
					$box.find('> div:last-child').remove();
					if($remove) $box.removeClass('position-relative');
				}, parseInt(Math.random() * 1000 + 1000));
				ev.preventDefault();
			});
		}
		else if($action == 'settings') {
			$this.on('click', function(ev){
				ev.preventDefault();
			});
		}

	});
}

//code taken from http://code.jquery.com/jquery-1.8.3.js to provide simple browser detection for 1.9+ versions
function add_browser_detection($) {
	if(!$.browser) {
		var matched, browser;

		// Use of jQuery.browser is frowned upon.
		// More details: http://api.jquery.com/jQuery.browser
		// jQuery.uaMatch maintained for back-compat
		$.uaMatch = function( ua ) {
			ua = ua.toLowerCase();

			var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
				/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
				/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
				/(msie) ([\w.]+)/.exec( ua ) ||
				ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
				[];

			return {
				browser: match[ 1 ] || "",
				version: match[ 2 ] || "0"
			};
		};

		matched = $.uaMatch( navigator.userAgent );
		browser = {};

		if ( matched.browser ) {
			browser[ matched.browser ] = true;
			browser.version = matched.version;
		}

		// Chrome is Webkit, but Webkit is also Safari.
		if ( browser.chrome ) {
			browser.webkit = true;
		} else if ( browser.webkit ) {
			browser.safari = true;
		}

		$.browser = browser;

	}
}