text:
<?php

namespace ErenMustafaOzdal\LaravelModulesBase\Controllers;

use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
use Illuminate\Http\Request;
use DB;
use Laracasts\Flash\Flash;
use Config;

use ErenMustafaOzdal\LaravelModulesBase\Repositories\FileRepository;
use ErenMustafaOzdal\LaravelModulesBase\Repositories\ImageRepository;
// exceptions
use ErenMustafaOzdal\LaravelModulesBase\Exceptions\StoreException;
use ErenMustafaOzdal\LaravelModulesBase\Exceptions\UpdateException;
use ErenMustafaOzdal\LaravelModulesBase\Exceptions\DestroyException;

trait OperationTrait
{
    /**
     * model
     *
     * @var \Illuminate\Database\Eloquent\Model
     */
    private $model;

    /**
     * model name
     *
     * @var string
     */
    private $modelName;

    /**
     * Related model id
     *
     * @var integer|null
     */
    private $relatedId = null;

    /**
     * model route regex
     *
     * @var string|null
     */
    private $routeRegex = null;

    /**
     * current request
     *
     * @var \Illuminate\Http\Request
     */
    protected $request;

    /**
     * files options
     *
     * @var array
     */
    protected $fileOptions = [];

    /**
     * operation events
     *
     * @var array
     */
    private $events = [];

    /**
     * model relations for create or edit
     *
     * @var array
     */
    private $opsRelation = [];

    /**
     * if is use image or file repository, image or file repository object
     *
     * @var ImageRepository|FileRepository
     */
    private $repo;

    /**
     * operation has photo
     *
     * @var boolean
     */
    private $hasPhoto = false;

    /**
     * operation has file
     *
     * @var boolean
     */
    private $hasFile = false;

    /**
     * trait constructor method
     *
     * @param Request|null $request
     */
    public function __construct(Request $request = null)
    {
        $this->request = $request;
    }

    /**
     * store data of the eloquent model
     *
     * @param $class
     * @param string|null $path
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function storeModel($class, $path = null)
    {
        DB::beginTransaction();
        try {
            $this->model = $class::create($this->getData());
            if ( ! isset($this->model->id) ) {
                throw new StoreException($this->request->all());
            }

            // eğer dosya varsa yükle
            if ($this->fileOptions) {
                $this->preUploadFile(StoreException::class);
            }

            // eğer başka ilişki varsa onları da ekle
            if ($this->opsRelation && ! $this->fillModel($this->opsRelation)) {
                throw new StoreException($this->request->all());
            }

            event(new $this->events['success']($this->model));
            DB::commit();

            if (is_null($path)) {
                return response()->json($this->returnData('success'));
            }
            Flash::success(trans('laravel-modules-base::admin.flash.store_success'));
            return $this->redirectRoute($path);
        } catch (StoreException $e) {
            DB::rollback();
            event(new $this->events['fail']($e->getDatas()));

            if (is_null($path)) {
                return response()->json($this->returnData('error'));
            }
            Flash::error(trans('laravel-modules-base::admin.flash.store_error'));
            return $this->redirectRoute($path);
        }
    }

    /**
     * update data of the eloquent model
     *
     * @param $model
     * @param string|null $path
     * @param boolean $updateRelation
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function updateModel($model, $path = null, $updateRelation = false)
    {
        $this->model = $model;
        DB::beginTransaction();
        try {
            $this->model->fill($this->getData());
            if ( ! $this->model->save()) {
                throw new UpdateException($this->model);
            }

            // eğer dosya varsa yükle
            if ($this->fileOptions) {
                $this->preUploadFile(UpdateException::class);
            }

            // eğer başka ilişki varsa onları da ekle
            if ($this->opsRelation && ! $this->fillModel($this->opsRelation)) {
                throw new UpdateException($this->request->all());
            }

            event(new $this->events['success']($this->model));
            DB::commit();

            if (is_null($path)) {
                return response()->json($this->returnData('success'));
            }

            Flash::success(trans('laravel-modules-base::admin.flash.update_success'));
            return $this->redirectRoute($path, $updateRelation); // yeni ilişkili kategoriye göre git
        } catch (UpdateException $e) {
            DB::rollback();
            event(new $this->events['fail']($e->getDatas()));

            if (is_null($path)) {
                return response()->json($this->returnData('error'));
            }
            Flash::error(trans('laravel-modules-base::admin.flash.update_error'));
            return $this->redirectRoute($path);
        }
    }

    /**
     * destroy data of the eloquent model or models
     *
     * @param \Illuminate\Database\Eloquent\Model|array $model [Model|ids]
     * @param string|null $path
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function destroyModel($model, $path = null)
    {
        $this->model = $model;
        try {
            if ( ! $this->model->delete()) {
                throw new DestroyException($this->model);
            }

            event(new $this->events['success']($this->model));

            if (is_null($path)) {
                return response()->json($this->returnData('success'));
            }
            Flash::success(trans('laravel-modules-base::admin.flash.destroy_success'));
            return $this->redirectRoute($path);
        } catch (DestroyException $e) {
            event(new $this->events['fail']($e->getDatas()));

            if (is_null($path)) {
                return response()->json($this->returnData('error'));
            }
            Flash::error(trans('laravel-modules-base::admin.flash.destroy_error'));
            return $this->redirectRoute($path);
        }
    }

    /**
     * publish group action
     *
     * @param $class
     * @return boolean
     */
    protected function publishGroupAction($class)
    {
        try {
            if ( ! $class::whereIn('id', $this->request->id)->update(['is_publish' => true])) {
                throw new UpdateException($this->request->id, 'group not published');
            }
            event(new $this->events['success']($this->request->id));
            return true;
        } catch (UpdateException $e) {
            event(new $this->events['fail']($e->getDatas()));
            return false;
        }
    }

    /**
     * destroy group action
     *
     * @param $class
     * @return boolean
     */
    protected function destroyGroupAction($class)
    {
        $result = $class::destroy($this->request->id);
        if ( is_integer($result) && $result > 0) {
            return true;
        }
        return false;
    }

    /**
     * not publish group action
     *
     * @param $class
     * @return boolean
     */
    protected function notPublishGroupAction($class)
    {
        try {
            if ( ! $class::whereIn('id', $this->request->id)->update(['is_publish' => false])) {
                throw new UpdateException($this->request->id, 'group not not published');
            }
            event(new $this->events['success']($this->request->id));
            return true;
        } catch (UpdateException $e) {
            event(new $this->events['fail']($e->getDatas()));
            return false;
        }
    }

    /**
     * fill model datas to database
     *
     * @param array $datas
     * @return boolean
     */
    protected function fillModel($datas)
    {
        $grouped = collect($datas)->groupBy('relation_type');
        foreach($grouped as $key => $groups) {

            // no relation
            if ($key === 'not') {
                foreach($groups as $group) {
                    $this->model->fill($group['datas'])->save();
                }
                continue;
            }

            // hasOne relation
            if ($key === 'hasOne') {
                foreach($groups as $group) {
                    $relation = $group['relation'];
                    if (is_null($this->model->$relation)) {
                        $this->model->$relation()->save(new $group['relation_model']($group['datas']));
                        continue;
                    }
                    $this->model->$relation->fill($group['datas'])->save();
                }
                continue;
            }

            // hasMany relation
            if ($key === 'hasMany') {
                foreach($groups as $group) {
                    $relation = $group['relation'];
                    $relation_models = [];
                    foreach ($group['datas'] as $data) {
                        $relation_models[] = new $group['relation_model']($data);
                    }

                    if (isset($group['is_reset']) && $group['is_reset']) {
                        $this->model->$relation()->delete();
                    }

                    // bu if image banner için eklenmiştir
                    if (isset($group['changeToHasOne']) && $group['changeToHasOne']) {
                        if (is_null($this->model->{$group['changeToHasOne']})) {
                            $this->model->{$group['changeToHasOne']}()->save(new $group['relation_model']($group['datas'][0]));
                            continue;
                        }
                        $this->model->{$group['changeToHasOne']}->fill($group['datas'][0])->save();
                        continue;
                    }
                    $this->model->$relation()->saveMany($relation_models);
                }
                continue;
            }
            return false;
        }
        return true;
    }

    /**
     * get data, if image column passed, except it
     */
    protected function getData()
    {
        if ( ! $this->fileOptions) {
            return $this->request->all();
        }

        $excepts = collect($this->fileOptions)->keyBy(function ($item) {
            $columns = explode('.', $item['column']);
            return count($columns) === 1 ? $columns[0] : $columns[1];
        })->keys()->all();
        return $this->request->except($excepts);
    }

    /**
     * pre upload file control function
     *
     * @param $exception
     */
    private function preUploadFile($exception)
    {
        $datas = [];
        foreach($this->fileOptions as $options) {
            $result = $this->uploadFile($options);
            if ($result !== false) {
                $datas[] = $result;
            }
        }

        if ( ! empty($datas) && ! $this->fillModel($datas)) {
            throw new $exception($this->request->all());
        }
    }

    /**
     * upload file or files
     *
     * @param array $options
     * @return array|boolean
     */
    protected function uploadFile($options)
    {
        if ( $options['type'] === 'file' ) {
            $this->repo = new FileRepository($options);
            $this->hasFile = true;
        } else {
            $this->repo = new ImageRepository($options);
            $this->hasPhoto = true;
        }

        if ( ! $this->repo->upload($this->model, $this->request) ) {
            return false;
        }

        return $this->repo->getDatas($this->request);
    }

    /**
     * return data for api
     *
     * @param string $type
     * @return array
     */
    protected function returnData($type)
    {
        $data = ['result' => $type];
        if ( $this->hasPhoto ){
            $data['photos'] = $this->repo->files;
        }
        if ( $this->hasFile ) {
            $data['files'] = $this->repo->files;
        }
        return $data;
    }

    /**
     * return redirect url path
     *
     * @param string $path
     * @param boolean $isUpdate
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function redirectRoute($path, $isUpdate = false)
    {
        $indexPos = strpos($path,'index');
        $dotPos = strpos($path,'.');
        $slug = getModelSlug($this->model);

        // İlişkisiz yalın sayfalardan index hariç
        if ( $indexPos === false && $dotPos === false ) {
            return redirect( lmbRoute("admin.{$slug}.{$path}", ['id' => $this->model->id]) );
        }

        // İlişkili sayfalardan index hariç
        if( $indexPos === false ) {
            $id = $isUpdate && ! is_null($this->model->category_id) && is_null($this->relatedId) ? $this->model->category_id : ( $isUpdate && is_null($this->relatedId) ? $this->model->categories->first()->id : $this->relatedId);
            return redirect( lmbRoute("admin.{$path}", [
                'id'                => $id,
                $this->routeRegex   => $this->model->id
            ]) );
        }

        // İlişkisiz sayfalardan index
        if ($dotPos === false) {
            return redirect( lmbRoute("admin.{$slug}.{$path}") );
        }

        // İlişkili sayfalardan index
        return redirect( lmbRoute("admin.{$path}", ['id' => $this->relatedId]) );
    }

    /**
     * set the file options
     *
     * @param array $options
     */
    protected function setFileOptions(array $options)
    {
        $this->fileOptions = $options;
    }

    /**
     * set to file options is file from elfinder
     *
     * @param string|array $column
     */
    protected function setElfinderToOptions($column)
    {
        $this->fileOptions = collect($this->fileOptions)->map(function($item, $key) use($column)
        {
            if (
                (is_array($column) && $key === $column['index'] && $item['column'] === $column['column'])
                || $item['column'] === $column
            ) {
                $item['isElfinder'] = true;
            }
            return $item;
        })->all();
    }

    /**
     * set the events
     *
     * @param array $events
     */
    protected function setEvents(array $events)
    {
        $this->events = $events;
    }

    /**
     * set the operation relation data
     *
     * @param array $relationData
     */
    protected function setOperationRelation(array $relationData)
    {
        $this->opsRelation = $relationData;
    }

    /**
     * set the relation route data
     *
     * @param integer $id
     * @param string $routeRegex
     */
    protected function setRelationRouteParam($id, $routeRegex)
    {
        $this->relatedId = $id;
        $this->routeRegex = $routeRegex;
    }

    /**
     * set the model
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     */
    protected function setModel($model)
    {
        $this->model = $model;
    }

    /**
     * get the model
     *
     * @return \Illuminate\Database\Eloquent\Model $model
     */
    protected function getModel()
    {
        return $this->model;
    }

    /**
     * update alias method
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     * @param array $events
     * @param string|null $path
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    protected function updateAlias($model, $events = [], $path = null)
    {
        $namespace = getBaseName($model, 'Events');

        $events = $events ? $events : [
            'success'   => "{$namespace}\\UpdateSuccess",
            'fail'      => "{$namespace}\\UpdateFail",
        ];
        $this->setEvents($events);
        return $this->updateModel($model, $path);
    }

    /**
     * group operation alias method
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     * @param string $subBase
     * @return boolean
     */
    protected function groupAlias($model, $subBase = 'Events')
    {
        $namespace = getBaseName($model, $subBase);
        $events = [];
        switch($this->request->action) {
            case 'activate':
                $events['activationSuccess'] = \ErenMustafaOzdal\LaravelUserModule\Events\Auth\ActivateSuccess::class;
                $events['activationFail'] = \ErenMustafaOzdal\LaravelUserModule\Events\Auth\ActivateFail::class;
                break;
            case 'not_activate':
                $events['activationRemove'] = \ErenMustafaOzdal\LaravelUserModule\Events\Auth\ActivateRemove::class;
                $events['activationFail'] = \ErenMustafaOzdal\LaravelUserModule\Events\Auth\ActivateFail::class;
                break;
            case 'publish':
                $events['success'] = "{$namespace}\\PublishSuccess";
                $events['fail'] = "{$namespace}\\PublishFail";
                break;
            case 'not_publish':
                $events['success'] = "{$namespace}\\NotPublishSuccess";
                $events['fail'] = "{$namespace}\\NotPublishFail";
                break;
            case 'destroy':
                if ($model == 'App\User' && in_array(Sentinel::getUser()->id,$this->request->get('id'))) {
                    abort(403);
                }
                break;
        }
        $this->setEvents($events);
        $action = camel_case($this->request->action) . 'GroupAction';
        return $this->$action($model);
    }

    /**
     * clone model and relation
     *
     * @param $model
     * @param $lastCopy
     * @param array $changeColumns
     * @param array $relations
     * @return \Illuminate\Database\Eloquent\Model|boolean
     */
    protected function cloneModel($model, $lastCopy, $changeColumns = [], $relations = [])
    {
        // model copy
        $clone = $model->replicate();
        $clone->copied_id = $model->id;
        if ( is_null($lastCopy) ) {
            foreach($changeColumns as $column) {
                $clone->$column = "{$model->$column}-2";
            }
        } else {
            foreach($changeColumns as $column) {
                $explodeColumn = explode('-',$lastCopy->$column);
                $explodeColumn = last($explodeColumn) + 1;
                $clone->$column = "{$model->$column}-{$explodeColumn}";
            }
        }
        if ( ! is_null($model->parent_id)) {
            $clone->lft = null;
            $clone->rgt = null;
            $clone->parent_id = null;
            $clone->depth = 0;
        }
        if ( ! $clone->push() ) {
            return false;
        }

        foreach($relations as $relation) {
            if ($relation['type'] === 'hasOne' && ! is_null($model->$relation['relation'])) {
                $cloneOption = $this->cloneRelation($model->$relation['relation']);
                if ( ! $clone->$relation['relation']()->save($cloneOption)) {
                    return false;
                }
            }
            if ($relation['type'] === 'hasMany') {
                foreach($model->$relation['relation'] as $option) {
                    $cloneOption = $this->cloneRelation($option);
                    if ( ! $clone->$relation['relation']()->save($cloneOption) ) {
                        return false;
                    }
                }
            }
        }
        return $clone;
    }

    /**
     * relation clone
     *
     * @param $model
     * @return \Illuminate\Database\Eloquent\Model
     */
    private function cloneRelation($model)
    {
        $clone = $model->replicate();
        $clone->push();
        return $clone;
    }

    /**
     * set the module config
     *
     * @param $category
     * @param string $model
     * @param string $uploadType
     * @return void
     */
    protected function setModuleThumbnails($category, $model, $uploadType)
    {
        $module = getModule(get_called_class());
        if (is_null($category->thumbnails)) {
            return;
        }
        Config::set("{$module}.{$model}.uploads.{$uploadType}.thumbnails",$category->thumbnails->map(function($item)
        {
            return [
                'width' => $item->photo_width,
                'height'=> $item->photo_height,
                'slug'  => $item->slug
            ];
        })->keyBy('slug')->toArray());
    }
}


text:
import * as p from 'path';
import expect from 'expect';
import {sync as globSync} from 'glob';

describe('locale data', () => {
    it('has generated locale data modules with correct shape', () => {
        const localeDataFiles = globSync('./locale-data/*.js');

        expect(localeDataFiles.length).toBeGreaterThan(0);
        localeDataFiles.forEach((filename) => {
            const localeData = require(p.resolve(filename));

            expect(localeData).toBeAn('array');
            localeData.forEach((locale) => {
                expect(locale).toBeAn('object');
                expect(locale.locale).toExist();
            });
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Retrinko\Ini\IniFile;

use Retrinko\Ini\Exceptions\FileException;
use Retrinko\Ini\Exceptions\InvalidDataException;
use Retrinko\Ini\IniFile;
use Retrinko\Ini\IniParser;
use Retrinko\Ini\IniSection;

class Factory
{
    /**
     * @param array $data
     *
     * @return IniFile
     * @throws InvalidDataException
     * @throws FileException
     */
    public static function fromArray(array $data)
    {
        $iniSections = IniParser::i()->parseArray($data);

        return self::fromIniSections($iniSections);
    }

    /**
     * @param IniSection[] $iniSections
     *
     * @return IniFile
     * @throws InvalidDataException
     * @throws FileException
     */
    public static function fromIniSections(array $iniSections)
    {
        $iniFile = new IniFile();
        foreach ($iniSections as $iniSection)
        {
            if (false === $iniSection instanceof IniSection)
            {
                throw new InvalidDataException('Invalid data! ');
            }
            $iniFile->addSection($iniSection);
        }

        return $iniFile;
    }

    /**
     * @param string $file File path
     *
     * @return IniFile
     * @throws FileException
     * @throws InvalidDataException
     */
    public static function fromFile($file)
    {
        return new IniFile($file);
    }

}


text:
"use strict";

var world_blue = document.getElementById("world_blue");

var WaveCircle = function(x, y) {
    this.x = x;
    this.y = y;
    this.radius = 0;
    this.lifeTime = WaveCircle.avgLifeTime * (Math.random() + 0.5);
    this.life = this.lifeTime;
    this.circleCount = Math.round(3 * Math.random()) + 1;
};

WaveCircle.avgLifeTime = 4; // (unit: s)
WaveCircle.growSpeed = world_blue.width / 10; // radius px / s

WaveCircle.prototype.update = function(dt) {
    this.radius += WaveCircle.growSpeed * dt / 1000;
    this.life -= dt / 1000;
};

WaveCircle.prototype.draw = function(ctx) {
    // assume 0,0 to be circles' origin
    ctx.save();
    var saveAlpha = ctx.globalAlpha;

    for (var i = this.circleCount; i > 0; i--) {
        var ratio = this.circleCount / i;
        ctx.globalAlpha = Math.max(0, (this.life / this.lifeTime) / ratio);
        ctx.strokeStyle = "white";
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.arc(0, 0, this.radius / ratio, 0, Math.PI * 2);
        ctx.stroke();
    }

    ctx.restore();
    ctx.globalAlpha = saveAlpha;
}

var Fish = function() {

};

world_blue.init = function(inputs) {

    world_blue.tW = world_blue.width / inputs[0].length;
    world_blue.tH = world_blue.height / inputs.length;

    world_blue.inputs = [];
    for (var h = 0; h < inputs.length; h++) {
        world_blue.inputs.push([]);
        for (var w = 0; w < inputs[h].length; w++) {
            world_blue.inputs[h].push(inputs[h][w].checked);
        }
    }

    this.waveCircles = [];

};

world_blue.update = function(dt, inputs) {
    for (var h = 0; h < inputs.length; h++) {
        for (var w = 0; w < inputs[h].length; w++) {
            if (inputs[h][w].checked !== world_blue.inputs[h][w]) {
                world_blue.inputs[h][w] = inputs[h][w].checked;
                this.waveCircles.push(new WaveCircle(
                    (w + 0.5) * world_blue.tW,
                    (h + 0.5) * world_blue.tH
                ));
            }
        }
    }

    for (var wc = 0; wc < this.waveCircles.length; wc++) {
        var waveCircle = this.waveCircles[wc];
        if (waveCircle.life < 0) {
            this.waveCircles.splice(wc, 1);
            wc--;
        } else {
            waveCircle.update(dt);
        }
    }
};

world_blue.draw = function() {
    var ctx = world_blue.getContext("2d");

    ctx.save();
    ctx.beginPath();
    ctx.fillStyle = "RoyalBlue";
    ctx.rect(0, 0, world_blue.width, world_blue.height);
    ctx.fill();
    ctx.restore();

    for (var wc = 0; wc < this.waveCircles.length; wc++) {
        var waveCircle = this.waveCircles[wc];
        ctx.save();
        ctx.translate(waveCircle.x, waveCircle.y);
        ctx.rotate(Math.PI/4);
        // ctx.scale(0, 2);
        waveCircle.draw(ctx);
        ctx.restore();
    }
};


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../prettify/prettify.css" type="text/css" rel="stylesheet" />

/**
 * @class Ext.LoadMask
 * A simple utility class for generically masking elements while loading data.  If the {@link #store}
 * config option is specified, the masking will be automatically synchronized with the store's loading
 * process and the mask element will be cached for reuse.
 * <p>Example usage:</p>
 * <pre><code>
// Basic mask:
var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
myMask.show();
</code></pre>

 */

Ext.define('Ext.LoadMask', {

    /* Begin Definitions */

    mixins: {
        observable: 'Ext.util.Observable'
    },

    requires: ['Ext.data.StoreManager'],

    /* End Definitions */

    /**
     * @cfg {Ext.data.Store} store
     * Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and
     * hidden on either load success, or load fail.
     */

    /**
     * @cfg {String} msg
     * The text to display in a centered loading message box (defaults to 'Loading...')
     */
    msg : 'Loading...',
    /**
     * @cfg {String} msgCls
     * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
     */
    msgCls : Ext.baseCSSPrefix + 'mask-loading',

    /**
     * @cfg {Boolean} useMsg
     * Whether or not to use a loading message class or simply mask the bound element.
     */
    useMsg: true,

    /**
     * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
     * @type Boolean
     */
    disabled: false,

    /**
     * Creates new LoadMask.
     * @param {Mixed} el The element, element ID, or DOM node you wish to mask.
     * Also, may be a Component who's element you wish to mask.
     * @param {Object} config (optional) The config object
     */
    constructor : function(el, config) {
        var me = this;

        if (el.isComponent) {
            me.bindComponent(el);
        } else {
            me.el = Ext.get(el);
        }
        Ext.apply(me, config);

        me.addEvents('beforeshow', 'show', 'hide');
        if (me.store) {
            me.bindStore(me.store, true);
        }
        me.mixins.observable.constructor.call(me, config);
    },

    bindComponent: function(comp) {
        var me = this,
            listeners = {
                resize: me.onComponentResize,
                scope: me
            };

        if (comp.el) {
            me.onComponentRender(comp);
        } else {
            listeners.render = {
                fn: me.onComponentRender,
                scope: me,
                single: true
            };
        }
        me.mon(comp, listeners);
    },

    /**
     * @private
     * Called if we were configured with a Component, and that Component was not yet rendered. Collects the element to mask.
     */
    onComponentRender: function(comp) {
        this.el = comp.getContentTarget();
    },

    /**
     * @private
     * Called when this LoadMask's Component is resized. The isMasked method also re-centers any displayed message.
     */
    onComponentResize: function(comp, w, h) {
        this.el.isMasked();
    },

    /**
     * Changes the data store bound to this LoadMask.
     * @param {Store} store The store to bind to this LoadMask
     */
    bindStore : function(store, initial) {
        var me = this;

        if (!initial && me.store) {
            me.mun(me.store, {
                scope: me,
                beforeload: me.onBeforeLoad,
                load: me.onLoad,
                exception: me.onLoad
            });
            if(!store) {
                me.store = null;
            }
        }
        if (store) {
            store = Ext.data.StoreManager.lookup(store);
            me.mon(store, {
                scope: me,
                beforeload: me.onBeforeLoad,
                load: me.onLoad,
                exception: me.onLoad
            });

        }
        me.store = store;
        if (store && store.isLoading()) {
            me.onBeforeLoad();
        }
    },

    /**
     * Disables the mask to prevent it from being displayed
     */
    disable : function() {
        var me = this;

       me.disabled = true;
       if (me.loading) {
           me.onLoad();
       }
    },

    /**
     * Enables the mask so that it can be displayed
     */
    enable : function() {
        this.disabled = false;
    },

    /**
     * Method to determine whether this LoadMask is currently disabled.
     * @return {Boolean} the disabled state of this LoadMask.
     */
    isDisabled : function() {
        return this.disabled;
    },

    // private
    onLoad : function() {
        var me = this;

        me.loading = false;
        me.el.unmask();
        me.fireEvent('hide', me, me.el, me.store);
    },

    // private
    onBeforeLoad : function() {
        var me = this;

        if (!me.disabled && !me.loading && me.fireEvent('beforeshow', me, me.el, me.store) !== false) {
            if (me.useMsg) {
                me.el.mask(me.msg, me.msgCls, false);
            } else {
                me.el.mask();
            }

            me.fireEvent('show', me, me.el, me.store);
            me.loading = true;
        }
    },

    /**
     * Show this LoadMask over the configured Element.
     */
    show: function() {
        this.onBeforeLoad();
    },

    /**
     * Hide this LoadMask.
     */
    hide: function() {
        this.onLoad();
    },

    // private
    destroy : function() {
        this.hide();
        this.clearListeners();
    }
});


text:
<chapter id="Cache_NoCache_CacheControl">
   <title>Resteasy Caching Features</title>
   <para>
     Resteasy provides numerous annotations and facilities to support HTTP caching semantics.  Annotations to make setting Cache-Control
     headers easier and both server-side and client-side in-memory caches are available.
   </para>
  <sect1 id="Cache_Annotation">
  <title>@Cache and @NoCache Annotations</title>
   <para>
      Resteasy provides an extension to JAX-RS that allows you to automatically set Cache-Control headers on a successful
      GET request.  It can only be used on @GET annotated methods.  A successful @GET request is any request
      that returns 200 OK response.
   </para>
   <programlisting>
package org.jboss.resteasy.annotations.cache;

public @interface Cache
{
   int maxAge() default -1;
   int sMaxAge() default -1;
   boolean noStore() default false;
   boolean noTransform() default false;
   boolean mustRevalidate() default false;
   boolean proxyRevalidate() default false;
   boolean isPrivate() default false;
}

public @interface NoCache
{
   String[] fields() default {};
}

   </programlisting>
   <para>
      While @Cache builds a complex Cache-Control header, @NoCache is a simplified notation to say that you don't
      want anything cached i.e. Cache-Control: nocache.
   </para>
   <para>
      These annotations can be put on the resource class or interface and specifies a default cache value for each
      @GET resource method.  Or they can be put individually on each @GET resource method.
   </para>
   </sect1>
   <sect1 id="client_cache">
     <title>Client "Browser" Cache</title>
     <para>
        Resteasy has the ability to set up a client-side, browser-like, cache.  You can use it with the Client Proxy Framework, or with raw
        ClientRequests.  This cache looks for Cache-Control headers sent back with a server response.  If the Cache-Control headers specify
       that the client is allowed to cache the response, Resteasy caches it within local memory.  The cache obeys max-age requirements
       and will also automatically do HTTP 1.1 cache revalidation if either or both the Last-Modified and/or ETag headers are sent back with the
       original response.  See the HTTP 1.1 specification for details on how Cache-Control or cache revalidation works.
     </para>
     <para>It is very simple to enable caching.  Here's an example of using the client cache with the Client Proxy Framework</para>
<programlisting>
@Path("/orders")
public interface OrderServiceClient {

   @Path("{id}")
   @GET
   @Produces("application/xml")
   public Order getOrder(@PathParam("id") String id);
}
</programlisting>
    <para>To create a proxy for this interface and enable caching for that proxy requires only a few simple steps:</para>
<programlisting>
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.cache.CacheFactory;
import org.jboss.resteasy.client.cache.LightweightBrowserCache;

public static void main(String[] args) throws Exception
{
      RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
      OrderServiceClient proxy = ProxyFactory.create(OrderServiceClient.class, generateBaseUrl());

      // This line enables caching
      LightweightBrowserCache cache = CacheFactory.makeCacheable(proxy);
}
</programlisting>
   <para>If you are using the ClientRequest class to make invocations rather than the proxy framework, it is just as easy</para>
<programlisting>
import org.jboss.resteasy.client.ProxyFactory;
import org.jboss.resteasy.client.cache.CacheFactory;
import org.jboss.resteasy.client.cache.LightweightBrowserCache;

public static void main(String[] args) throws Exception
{
      RegisterBuiltin.register(ResteasyProviderFactory.getInstance());

      // This line enables caching
      LightweightBrowserCache cache = new LightweightBrowserCache();

      ClientRequest request = new ClientRequest("http://example.com/orders/333");
      CacheFactory.makeCacheable(request, cache);
}
</programlisting>
   <para>The LightweightBrowserCache, by default, has a maximum 2 megabytes of caching space.  You can change this programmatically by callings
         its setMaxBytes() method.   If the cache gets full, the cache completely wipes itself of all cached data.  This may seem
         a bit draconian, but the cache was written to avoid unnecessary synchronizations in a concurrent environment where the cache is
         shared between multiple threads.  If you desire a more complex caching solution or if you want to plug in a thirdparty cache
         please contact our resteasy-developers list and discuss it with the community.
   </para>
   </sect1>
   <sect1 id="server_cache">
      <title>Local Server-Side Response Cache</title>
      <para>Resteasy has a server-side, local, in-memory cache that can sit in front of your JAX-RS services.
          It automatically caches marshalled responses from HTTP GET JAX-RS invocations if, and only if your
          JAX-RS resource method sets a Cache-Control header.  When a GET comes in, the Resteasy Server Cache checks
          to see if the URI is stored in the cache.  If it does, it returns the already marshalled response without
          invoking your JAX-RS method.  Each cache entry has a max age to whatever is specified in the Cache-Control
          header of the initial request.  The cache also will automatically generate an ETag using an MD5 hash on the
          response body.  This allows the client to do HTTP 1.1 cache revalidation with the IF-NONE-MATCH header.
          The cache is also smart enough to perform revalidation if there is no initial cache hit, but the jax-rs
          method still returns a body that has the same ETag.
      </para>
       <para>
          Starting in Resteasy 2.3, the cache is also automatically invalidated for a particular URI that has
           PUT, POST, or DELETE invoked on it.  You can also obtain a reference to the cache by injecting a
           org.jboss.resteasy.plugins.cache.ServerCache
           via the @Context annotation
       </para>
<programlisting>

    @Context
    ServerCache cache;

    @GET
    public String get(@Context ServerCache cache) {...}

</programlisting>
      <para>To set up the server-side cache, there are a few simple steps you have to perform.  If you are using Maven you must depend on the resteasy-cache-core artifact:</para>
<programlisting>
<![CDATA[
<dependency>
   <groupId>org.jboss.resteasy</groupId>
   <artifactId>resteasy-cache-core</artifactId>
   <version>2.3.7.Final</version>
</dependency>
]]>
</programlisting>
      <para>The next thing you have to do is to add a ServletContextListener, org.jboss.resteasy.plugins.cache.server.ServletServerCache.
            This must be specified after the ResteasyBootstrap listener in your web.xml file.</para>
<programlisting>
<![CDATA[
<web-app>
    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <context-param>
        <param-name>resteasy.server.cache.maxsize</param-name>
        <param-value>1000</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.server.cache.eviction.wakeup.interval</param-name>
        <param-value>5000</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.cache.server.ServletServerCache
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>Resteasy</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Resteasy</servlet-name>
        <url-pattern>/rest-services/*</url-pattern>
    </servlet-mapping>

</web-app>
]]>
</programlisting>
   <para>The cache implementation is based on the JBoss Cache project: http://jboss.org/jbosscache.  There are two context-param configuration variables
         that you can set.  resteasy.server.cache.maxsize sets the number of elements that can be cached.  The resteasy.server.cache.eviction.wakeup.interval sets the rate at which the background eviction thread runs to purge the cache of stale entries.
   </para>
   </sect1>
</chapter>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/empty_bookmark"
        android:visibility="gone"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" >

        <ImageView
            android:src="@drawable/empty_bookmark"
            android:layout_width="wrap_content"
            android:layout_height="300dp" />
    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/talk_recycler_view"
        android:paddingTop="8dp"
        android:clipToPadding="false"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>


text:
package li.barter.data;

import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.text.TextUtils;

import java.util.Locale;

import li.barter.utils.Logger;

/**
 * View representation for users, combined with their locations
 *
 * @author Vinay S Shenoy
 */
public class ViewUsersWithLocations {

    private static final String TAG             = "ViewUsersLocations";

    //Aliases for the tables
    private static final String ALIAS_USERS     = "A";
    private static final String ALIAS_LOCATIONS = "B";

    public static final String  NAME            = "USERS_WITH_LOCATIONS";

    public static void create(final SQLiteDatabase db) {

        final String columnDef = TextUtils
                        .join(",", new String[] {
                                String.format(Locale.US, SQLConstants.ALIAS_COLUMN, ALIAS_USERS, BaseColumns._ID),
                                DatabaseColumns.FIRST_NAME,
                                DatabaseColumns.LAST_NAME,
                                DatabaseColumns.PROFILE_PICTURE,
                                DatabaseColumns.DESCRIPTION,
                                DatabaseColumns.USER_ID,
                                String.format(Locale.US, SQLConstants.ALIAS_COLUMN, ALIAS_USERS, DatabaseColumns.LOCATION_ID),
                                DatabaseColumns.NAME, DatabaseColumns.ADDRESS

                        });
        Logger.d(TAG, "View Column Def: %s", columnDef);

        final String fromDef = TextUtils
                        .join(",", new String[] {
                                String.format(Locale.US, SQLConstants.TABLE_ALIAS, TableUsers.NAME, ALIAS_USERS),
                                String.format(Locale.US, SQLConstants.TABLE_ALIAS, TableLocations.NAME, ALIAS_LOCATIONS)
                        });
        Logger.d(TAG, "From Def: %s", fromDef);

        final String whereDef = String
                        .format(Locale.US, SQLConstants.ALIAS_COLUMN, ALIAS_USERS, DatabaseColumns.LOCATION_ID)
                        + SQLConstants.EQUALS
                        + String.format(Locale.US, SQLConstants.ALIAS_COLUMN, ALIAS_LOCATIONS, DatabaseColumns.LOCATION_ID);
        Logger.d(TAG, "Where Def: %s", whereDef);

        final String selectDef = String
                        .format(Locale.US, SQLConstants.SELECT_FROM_WHERE, columnDef, fromDef, whereDef);

        Logger.d(TAG, "Select Def: %s", selectDef);
        db.execSQL(String
                        .format(Locale.US, SQLConstants.CREATE_VIEW, NAME, selectDef));

    }

    public static void upgrade(final SQLiteDatabase db, final int oldVersion,
                    final int newVersion) {

      //Add any data migration code here. Default is to drop and rebuild the table

        if (oldVersion == 1) {

            /* Drop & recreate the view if upgrading from DB version 1(alpha version) */
            db.execSQL(String
                            .format(Locale.US, SQLConstants.DROP_VIEW_IF_EXISTS, NAME));
            create(db);

        }
    }
}


text:
<template id="ast-node-break-statement" >

  break
  <slot id="label" name="label"></slot>
</template>


text:
package net.plusmid.mensaberlin.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import net.plusmid.mensaberlin.R;
import net.plusmid.mensaberlin.mensa.Dish;

public class DishView extends GridLayout {
    private Dish mDish;
    private View mRootView;

    public DishView(Context context) {
        super(context);
        init(context);
    }

    public DishView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DishView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        mRootView = inflate(context, R.layout.view_dish, this);
        updateDish(mRootView, mDish);
    }

    public void setDish(Dish dish) {
        mDish = dish;
        updateDish(mRootView, dish);
    }

    private void updateDish(View rootView, Dish dish) {
        if (rootView == null || dish == null)
            return;

        TextView textName = (TextView) rootView.findViewById(R.id.text_name);
        TextView textDesc = (TextView) rootView.findViewById(R.id.text_desc);
        TextView textPrice = (TextView) rootView.findViewById(R.id.text_price);
//        LinearLayout layoutProps = (LinearLayout) rootView.findViewById(R.id.layout_props);

        textName.setText(dish.name);

        if (dish.desc == null || dish.desc.equals("")) {
            textDesc.setVisibility(View.GONE);
        } else {
            textDesc.setText(dish.desc);
        }
        textPrice.setText(String.format("%2.2f €", dish.price[0]));
    }

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Motivation</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Chrono 2.0.5">
<link rel="up" href="../overview.html" title="Overview">
<link rel="prev" href="../overview.html" title="Overview">
<link rel="next" href="description.html" title="Description">

Home
Libraries
People
FAQ
More

Motivation

        Time

        We all deal with time every day of our lives. We've intuitively known it
        since birth. Thus we are all very familiar with it and believe it to be a
        simple matter. The modeling of time in computer programs should be similarly
        simple. The unfortunate truth is that this perceived simplicity is only skin
        deep. Fortunately, we do not need a terribly complicated solution to meet
        the bulk of our needs. However, overly simplistic solutions can be dangerous
        and inefficient, and won't adapt as the computer industry evolves.

        Boost.Chrono implements the new time facilities
        in C++11, as proposed in N2661 - A Foundation to Sleep On. That document
        provides background and motivation for key design decisions and is the source
        of a good deal of information in this documentation.

        In addition to the clocks provided by the standard proposal, Boost.Chrono
        provides specific process and thread clocks.

        Wall
        clock versus system and user time

        To make the timing facilities of Boost.Chrono more generally useful, the
        library provides a number of clocks that are thin wrappers around the operating
        system's process time API, thereby allowing the extraction of wall clock
        time, user CPU time, and system CPU time of the process. Wall clock time
        is the sum of CPU time and system CPU time. (On POSIX-like systems, this
        relies on times().
        On Windows, it relies on GetProcessTimes().)

Copyright © 2008 Howard Hinnant
Copyright © 2006, 2008 Beman Dawes
Copyright © 2009-2013 Vicente J. Botet Escriba

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using UIKit;

namespace ArcGISRuntime.Samples.ChangeStretchRenderer
{
    [Register("ChangeStretchRenderer")]
    [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("95392f99970d4a71bd25951beb34a508")]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        name: "Stretch renderer",
        category: "Layers",
        description: "Use a stretch renderer to enhance the visual contrast of raster data for analysis.",
        instructions: "Choose one of the stretch parameter types:",
        tags: new[] { "analysis", "deviation", "histogram", "imagery", "interpretation", "min-max", "percent clip", "pixel", "raster", "stretch", "symbology", "visualization" })]
    public class ChangeStretchRenderer : UIViewController
    {
        // Hold references to UI controls.
        private MapView _myMapView;
        private UISegmentedControl _rendererTypes;
        private UILabel _labelParameter1;
        private UITextField _inputParameter1;
        private UILabel _labelParameter2;
        private UITextField _inputParameter2;
        private UIButton _updateRendererButton;

        public ChangeStretchRenderer()
        {
            Title = "Stretch renderer";
        }

        private async void Initialize()
        {
            // Add an imagery basemap.
            _myMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);

            // Get the file name.
            string filepath = DataManager.GetDataFolder("95392f99970d4a71bd25951beb34a508", "shasta", "ShastaBW.tif");

            // Load the raster file.
            Raster rasterFile = new Raster(filepath);

            // Create the layer.
            RasterLayer rasterLayer = new RasterLayer(rasterFile);

            // Add the layer to the map.
            _myMapView.Map.OperationalLayers.Add(rasterLayer);

            try
            {
                // Wait for the layer to load.
                await rasterLayer.LoadAsync();

                // Set the viewpoint
                await _myMapView.SetViewpointGeometryAsync(rasterLayer.FullExtent);
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }

        private void rendererTypes_ValueChanged(object sender, EventArgs e)
        {
            // This function modifies the UI parameter controls depending on which stretch
            // renderer is chosen by the user.
            switch (_rendererTypes.SelectedSegment)
            {
                case 0: // Min Max.
                    // Make sure all the GUI items are visible.
                    _labelParameter1.Hidden = false;
                    _labelParameter2.Hidden = false;
                    _inputParameter1.Hidden = false;
                    _inputParameter2.Hidden = false;

                    // Define what values/options the user sees.
                    _labelParameter1.Text = "Minimum value (0 - 255):";
                    _labelParameter2.Text = "Maximum value (0 - 255):";
                    _inputParameter1.Text = "10";
                    _inputParameter2.Text = "150";

                    break;

                case 1: // Percent Clip.
                    // Make sure all the GUI items are visible.
                    _labelParameter1.Hidden = false;
                    _labelParameter2.Hidden = false;
                    _inputParameter1.Hidden = false;
                    _inputParameter2.Hidden = false;

                    // Define what values/options the user sees.
                    _labelParameter1.Text = "Minimum (0 - 100):";
                    _labelParameter2.Text = "Maximum (0 - 100):";
                    _inputParameter1.Text = "0";
                    _inputParameter2.Text = "50";

                    break;

                case 2: // Standard Deviation.
                    // Make sure that only the necessary GUI items are visible.
                    _labelParameter1.Hidden = false;
                    _labelParameter2.Hidden = true;
                    _inputParameter1.Hidden = false;
                    _inputParameter2.Hidden = true;

                    // Define what values/options the user sees.
                    _labelParameter1.Text = "Factor (.25 to 4):";
                    _inputParameter1.Text = "0.5";

                    break;
            }
        }

        private void UpdateRendererButton_Clicked(object sender, EventArgs e)
        {
            // This function acquires the user selection of the stretch renderer from the table view
            // along with the parameters specified, then a stretch renderer is created and applied to
            // the raster layer.

            // Convert the input text to doubles and return if they're invalid.
            double input1;
            double input2;
            try
            {
                input1 = Convert.ToDouble(_inputParameter1.Text);
                input2 = Convert.ToDouble(_inputParameter2.Text);
            }
            catch (Exception ex)
            {
                new UIAlertView("alert", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
                return;
            }

            // Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render.
            IEnumerable<double> gammaValues = new List<double>();

            // Create a color ramp for the stretch renderer.
            ColorRamp colorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000);

            // Create the place holder for the stretch renderer.
            StretchRenderer stretchRenderer = null;

            switch (_rendererTypes.SelectedSegment)
            {
                case 0:

                    // This section creates a stretch renderer based on a MinMaxStretchParameters.
                    // TODO: Add you own logic to ensure that accurate min/max stretch values are used.

                    try
                    {
                        // Create an IEnumerable from a list of double min stretch value doubles.
                        IEnumerable<double> minValues = new List<double> { input1 };

                        // Create an IEnumerable from a list of double max stretch value doubles.
                        IEnumerable<double> maxValues = new List<double> { input2 };

                        // Create a new MinMaxStretchParameters based on the user choice for min and max stretch values.
                        MinMaxStretchParameters minMaxStretchParameters = new MinMaxStretchParameters(minValues, maxValues);

                        // Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp.
                        stretchRenderer = new StretchRenderer(minMaxStretchParameters, gammaValues, true, colorRamp);
                    }
                    catch (ArgumentException)
                    {
                        ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
                        return;
                    }

                    break;

                case 1:

                    // This section creates a stretch renderer based on a PercentClipStretchParameters.
                    // TODO: Add you own logic to ensure that accurate min/max percent clip values are used.

                    try
                    {
                        // Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values.
                        PercentClipStretchParameters percentClipStretchParameters = new PercentClipStretchParameters(input1, input2);

                        // Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp.
                        stretchRenderer = new StretchRenderer(percentClipStretchParameters, gammaValues, true, colorRamp);
                    }
                    catch (Exception)
                    {
                        ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
                        return;
                    }

                    break;

                case 2:

                    // This section creates a stretch renderer based on a StandardDeviationStretchParameters.
                    // TODO: Add you own logic to ensure that an accurate standard deviation value is used

                    try
                    {
                        // Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value.
                        StandardDeviationStretchParameters standardDeviationStretchParameters = new StandardDeviationStretchParameters(input1);
                        // Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp.
                        stretchRenderer = new StretchRenderer(standardDeviationStretchParameters, gammaValues, true, colorRamp);
                    }
                    catch (Exception)
                    {
                        ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
                        return;
                    }

                    break;
            }

            // Get the existing raster layer in the map.
            RasterLayer rasterLayer = (RasterLayer)_myMapView.Map.OperationalLayers[0];

            // Apply the stretch renderer to the raster layer.
            rasterLayer.Renderer = stretchRenderer;
        }

        private void ShowMessage(string title, string message)
        {
            new UIAlertView(title, message, (IUIAlertViewDelegate)null, "OK", null).Show();
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            Initialize();
        }

        public override void LoadView()
        {
            // Create the views.
            View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };

            UIView formContainer = new UIView();
            formContainer.TranslatesAutoresizingMaskIntoConstraints = false;
            formContainer.BackgroundColor = ApplicationTheme.BackgroundColor;

            _myMapView = new MapView();
            _myMapView.TranslatesAutoresizingMaskIntoConstraints = false;

            _inputParameter1 = new UITextField();
            _inputParameter1.TranslatesAutoresizingMaskIntoConstraints = false;
            _inputParameter1.BorderStyle = UITextBorderStyle.RoundedRect;

            _inputParameter2 = new UITextField();
            _inputParameter2.TranslatesAutoresizingMaskIntoConstraints = false;
            _inputParameter2.BorderStyle = UITextBorderStyle.RoundedRect;

            _labelParameter1 = new UILabel();
            _labelParameter1.TextAlignment = UITextAlignment.Right;
            _labelParameter1.TranslatesAutoresizingMaskIntoConstraints = false;

            _labelParameter2 = new UILabel();
            _labelParameter2.TextAlignment = UITextAlignment.Right;
            _labelParameter2.TranslatesAutoresizingMaskIntoConstraints = false;

            _updateRendererButton = new UIButton();
            _updateRendererButton.SetTitle("Update renderer", UIControlState.Normal);
            _updateRendererButton.SetTitleColor(View.TintColor, UIControlState.Normal);
            _updateRendererButton.TranslatesAutoresizingMaskIntoConstraints = false;

            _rendererTypes = new UISegmentedControl("Min/Max", "% Clip", "Std. Deviation");
            _rendererTypes.SelectedSegment = 0;
            _rendererTypes.TintColor = View.TintColor;
            _rendererTypes.TranslatesAutoresizingMaskIntoConstraints = false;

            // Call a function to configure the labels appropriately
            rendererTypes_ValueChanged(_rendererTypes, null);

            // Add the views.
            View.AddSubviews(_myMapView, formContainer, _rendererTypes, _inputParameter1,
                _inputParameter2, _labelParameter1, _labelParameter2, _updateRendererButton);

            // Lay out the views.
            NSLayoutConstraint.ActivateConstraints(new[]
            {
                _rendererTypes.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor, 8),
                _rendererTypes.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor, 8),
                _rendererTypes.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor, -8),

                _inputParameter1.TopAnchor.ConstraintEqualTo(_rendererTypes.BottomAnchor, 8),
                _inputParameter1.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor, -8),
                _inputParameter1.WidthAnchor.ConstraintEqualTo(72),

                _inputParameter2.TopAnchor.ConstraintEqualTo(_inputParameter1.BottomAnchor, 8),
                _inputParameter2.TrailingAnchor.ConstraintEqualTo(_inputParameter1.TrailingAnchor),
                _inputParameter2.WidthAnchor.ConstraintEqualTo(_inputParameter1.WidthAnchor),

                _updateRendererButton.TopAnchor.ConstraintEqualTo(_inputParameter2.BottomAnchor, 8),
                _updateRendererButton.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor),
                _updateRendererButton.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor),

                _labelParameter1.TopAnchor.ConstraintEqualTo(_inputParameter1.TopAnchor),
                _labelParameter1.LeadingAnchor.ConstraintEqualTo(_rendererTypes.LeadingAnchor),
                _labelParameter1.TrailingAnchor.ConstraintEqualTo(_inputParameter1.LeadingAnchor, -8),
                _labelParameter1.BottomAnchor.ConstraintEqualTo(_inputParameter1.BottomAnchor),

                _labelParameter2.TopAnchor.ConstraintEqualTo(_inputParameter2.TopAnchor),
                _labelParameter2.BottomAnchor.ConstraintEqualTo(_inputParameter2.BottomAnchor),
                _labelParameter2.LeadingAnchor.ConstraintEqualTo(_labelParameter1.LeadingAnchor),
                _labelParameter2.TrailingAnchor.ConstraintEqualTo(_labelParameter1.TrailingAnchor),

                formContainer.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
                formContainer.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                formContainer.BottomAnchor.ConstraintEqualTo(_updateRendererButton.BottomAnchor, 8),
                formContainer.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),

                _myMapView.TopAnchor.ConstraintEqualTo(formContainer.BottomAnchor),
                _myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
                _myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
                _myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
            });
        }

        private bool HandleTextField(UITextField textField)
        {
            // This method allows pressing 'return' to dismiss the software keyboard.
            textField.ResignFirstResponder();
            return true;
        }

        public override void ViewWillAppear(bool animated)
        {
            base.ViewWillAppear(animated);

            // Subscribe to events.
            _inputParameter1.ShouldReturn += HandleTextField;
            _inputParameter2.ShouldReturn += HandleTextField;
            _updateRendererButton.TouchUpInside += UpdateRendererButton_Clicked;
            _rendererTypes.ValueChanged += rendererTypes_ValueChanged;
        }

        public override void ViewDidDisappear(bool animated)
        {
            base.ViewDidDisappear(animated);

            // Unsubscribe from events, per best practice.
            _inputParameter1.ShouldReturn -= HandleTextField;
            _inputParameter2.ShouldReturn -= HandleTextField;
            _updateRendererButton.TouchUpInside -= UpdateRendererButton_Clicked;
            _rendererTypes.ValueChanged -= rendererTypes_ValueChanged;
        }
    }
}


text:
package osl

import (
	"os"
	"runtime"
	"testing"

	"github.com/docker/docker/pkg/reexec"
	"github.com/docker/libnetwork/ns"
	"github.com/docker/libnetwork/testutils"
)

func TestMain(m *testing.M) {
	if reexec.Init() {
		return
	}
	os.Exit(m.Run())
}

func TestSandboxCreate(t *testing.T) {
	defer testutils.SetupTestOSContext(t)()

	key, err := newKey(t)
	if err != nil {
		t.Fatalf("Failed to obtain a key: %v", err)
	}

	s, err := NewSandbox(key, true, false)
	if err != nil {
		t.Fatalf("Failed to create a new sandbox: %v", err)
	}

	if s.Key() != key {
		t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
	}

	tbox, err := newInfo(ns.NlHandle(), t)
	if err != nil {
		t.Fatalf("Failed to generate new sandbox info: %v", err)
	}

	for _, i := range tbox.Info().Interfaces() {
		err = s.AddInterface(i.SrcName(), i.DstName(),
			tbox.InterfaceOptions().Bridge(i.Bridge()),
			tbox.InterfaceOptions().Address(i.Address()),
			tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
		if err != nil {
			t.Fatalf("Failed to add interfaces to sandbox: %v", err)
		}
	}

	err = s.SetGateway(tbox.Info().Gateway())
	if err != nil {
		t.Fatalf("Failed to set gateway to sandbox: %v", err)
	}

	err = s.SetGatewayIPv6(tbox.Info().GatewayIPv6())
	if err != nil {
		t.Fatalf("Failed to set ipv6 gateway to sandbox: %v", err)
	}

	verifySandbox(t, s, []string{"0", "1", "2"})

	err = s.Destroy()
	if err != nil {
		t.Fatal(err)
	}
	verifyCleanup(t, s, true)
}

func TestSandboxCreateTwice(t *testing.T) {
	defer testutils.SetupTestOSContext(t)()

	key, err := newKey(t)
	if err != nil {
		t.Fatalf("Failed to obtain a key: %v", err)
	}

	_, err = NewSandbox(key, true, false)
	if err != nil {
		t.Fatalf("Failed to create a new sandbox: %v", err)
	}
	runtime.LockOSThread()

	// Create another sandbox with the same key to see if we handle it
	// gracefully.
	s, err := NewSandbox(key, true, false)
	if err != nil {
		t.Fatalf("Failed to create a new sandbox: %v", err)
	}
	runtime.LockOSThread()

	err = s.Destroy()
	if err != nil {
		t.Fatal(err)
	}
	GC()
	verifyCleanup(t, s, false)
}

func TestSandboxGC(t *testing.T) {
	key, err := newKey(t)
	if err != nil {
		t.Fatalf("Failed to obtain a key: %v", err)
	}

	s, err := NewSandbox(key, true, false)
	if err != nil {
		t.Fatalf("Failed to create a new sandbox: %v", err)
	}

	err = s.Destroy()
	if err != nil {
		t.Fatal(err)
	}

	GC()
	verifyCleanup(t, s, false)
}

func TestAddRemoveInterface(t *testing.T) {
	defer testutils.SetupTestOSContext(t)()

	key, err := newKey(t)
	if err != nil {
		t.Fatalf("Failed to obtain a key: %v", err)
	}

	s, err := NewSandbox(key, true, false)
	if err != nil {
		t.Fatalf("Failed to create a new sandbox: %v", err)
	}
	runtime.LockOSThread()

	if s.Key() != key {
		t.Fatalf("s.Key() returned %s. Expected %s", s.Key(), key)
	}

	tbox, err := newInfo(ns.NlHandle(), t)
	if err != nil {
		t.Fatalf("Failed to generate new sandbox info: %v", err)
	}

	for _, i := range tbox.Info().Interfaces() {
		err = s.AddInterface(i.SrcName(), i.DstName(),
			tbox.InterfaceOptions().Bridge(i.Bridge()),
			tbox.InterfaceOptions().Address(i.Address()),
			tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6()))
		if err != nil {
			t.Fatalf("Failed to add interfaces to sandbox: %v", err)
		}
	}

	verifySandbox(t, s, []string{"0", "1", "2"})

	interfaces := s.Info().Interfaces()
	if err := interfaces[0].Remove(); err != nil {
		t.Fatalf("Failed to remove interfaces from sandbox: %v", err)
	}

	verifySandbox(t, s, []string{"1", "2"})

	i := tbox.Info().Interfaces()[0]
	if err := s.AddInterface(i.SrcName(), i.DstName(),
		tbox.InterfaceOptions().Bridge(i.Bridge()),
		tbox.InterfaceOptions().Address(i.Address()),
		tbox.InterfaceOptions().AddressIPv6(i.AddressIPv6())); err != nil {
		t.Fatalf("Failed to add interfaces to sandbox: %v", err)
	}

	verifySandbox(t, s, []string{"1", "2", "3"})

	err = s.Destroy()
	if err != nil {
		t.Fatal(err)
	}

	GC()
	verifyCleanup(t, s, false)
}


text:
<?php

namespace Shop\ProductBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Shop\ProductBundle\Entity\Product;

class LoadProductsData extends AbstractFixture implements OrderedFixtureInterface
{
    public function getOrder()
    {
        return 2;
    }

    public function load(ObjectManager $manager)
    {
        $product1 = new Product();
        $product1->setName('HDD 1T Seagate');
        $product1->setDescription('Jakiś opis dysku');
        $product1->setPrice(200);
        $product1->setAmount(10);
        $product1->setCategory($manager->merge($this->getReference('category1')));
        $manager->persist($product1);

        $product2 = new Product();
        $product2->setName('Klawiatura Logitech');
        $product2->setDescription('Jakiś opis klawiatury');
        $product2->setPrice(50);
        $product2->setAmount(10);
        $product2->setCategory($manager->merge($this->getReference('category2')));
        $manager->persist($product2);

        $product3 = new Product();
        $product3->setName('Drukarka HP');
        $product3->setDescription('Jakiś opis drukarki');
        $product3->setPrice(250);
        $product3->setAmount(10);
        $product3->setCategory($manager->merge($this->getReference('category3')));
        $manager->persist($product3);

        $manager->flush();
    }
}


text:
#ifndef MidiMapping_h
#define MidiMapping_h

//package com.odbol.sensorizer.server;

//import com.google.gson.annotations.Expose;
//import com.odbol.sensorizer.devices.MidiDevice;

//# include "SensorizerServer.h"

#include "MidiDevice.h"
#include "OutputMapping.h"
#include "PendingNoteQueue.h"
#include "Metro.h"

#define VALUES_HISTORY_LENGTH 2

// the num of milliseconds between sending CC notes, so we don't overload the pipes.
#define CC_MESSAGE_THROTTLE_INTERVAL 20

class MidiMapping : public OutputMapping {
	//types for msgType
	public: static const int NOTE;
	public: static const int CONTROL_CHANGE;
	public: static const int NOTE_ONE_ONLY;
	public: static const int PITCH_BEND;

	// keeps track of when the last CC was sent so we don't overload things
	private: Metro metro;

	// holds every note we sent so we can send a note off later.
	private: PendingNoteQueue* pendingNoteOffs;

	////@Expose
	public: int msgType;

	public: int getMsgType();

	public: void setMsgType(int msgType);

	//these are strings so you can do fancy things like "${0}" for variable substitution
	////@Expose
	public: int channel;

	////@Expose
	public: int note;

	////@Expose
	public: int duration;

	////@Expose
	//public: string midiDeviceName;

	private: bool isNoteOn;

	//valuesHistory.length is the threshold for detecting changes from null to not null
	//TODO: add adjustable threshold
	private: double valuesHistory[VALUES_HISTORY_LENGTH][1];

	public: MidiDevice* midiDevice;

	public: MidiMapping(MidiDevice* midiDevice);

	~MidiMapping();

	//@Override
	public: void init();

	void tick();

	/***
	 * adds the given values to the OSC path and sends an OSC message
	 */
	//@Override
	public: void send(double values[]);

};

#endif