text:
namespace EffekseerRendererDX9
{
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace Standard_VS
{
static
#include "Shader/EffekseerRenderer.Standard_VS.h"
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace Standard_PS
{
static
#include "Shader/EffekseerRenderer.Standard_PS.h"
}

//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace StandardNoTexture_PS
{
static
#include "Shader/EffekseerRenderer.StandardNoTexture_PS.h"
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
TrackRenderer::TrackRenderer( RendererImplemented* renderer, Shader* shader, Shader* shader_no_texture )
	: m_renderer	( renderer )
	, m_shader		( shader )
	, m_shader_no_texture		( shader_no_texture )
{
	shader->SetVertexConstantBufferSize(sizeof(Effekseer::Matrix44));
	shader->SetVertexRegisterCount(4);
	shader_no_texture->SetVertexConstantBufferSize(sizeof(Effekseer::Matrix44));
	shader_no_texture->SetVertexRegisterCount(4);
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
TrackRenderer::~TrackRenderer()
{
	ES_SAFE_DELETE( m_shader );
	ES_SAFE_DELETE( m_shader_no_texture );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
TrackRenderer* TrackRenderer::Create( RendererImplemented* renderer )
{
	assert( renderer != NULL );
	assert( renderer->GetDevice() != NULL );

	// À•W(3) F(1) UV(2)
	D3DVERTEXELEMENT9 decl[] =
	{
		{0,	0,	D3DDECLTYPE_FLOAT3,		D3DDECLMETHOD_DEFAULT,	D3DDECLUSAGE_POSITION,	0},
		{0,	12,	D3DDECLTYPE_D3DCOLOR,	D3DDECLMETHOD_DEFAULT,	D3DDECLUSAGE_NORMAL,	0},
		{0,	16,	D3DDECLTYPE_FLOAT2,		D3DDECLMETHOD_DEFAULT,	D3DDECLUSAGE_TEXCOORD,	0},
		D3DDECL_END()
	};

	Shader* shader = Shader::Create(
		renderer,
		Standard_VS::g_vs20_VS,
		sizeof(Standard_VS::g_vs20_VS),
		Standard_PS::g_ps20_PS,
		sizeof(Standard_PS::g_ps20_PS),
		"StandardRenderer", decl );
	if( shader == NULL ) return NULL;

	Shader* shader_no_texture = Shader::Create(
		renderer,
		Standard_VS::g_vs20_VS,
		sizeof(Standard_VS::g_vs20_VS),
		StandardNoTexture_PS::g_ps20_PS,
		sizeof(StandardNoTexture_PS::g_ps20_PS),
		"StandardRenderer No Texture",
		decl );

	return new TrackRenderer( renderer, shader, shader_no_texture );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void TrackRenderer::BeginRendering( const efkTrackNodeParam& parameter, int32_t count, void* userData )
{
	BeginRendering_<Vertex>( m_renderer, parameter, count, userData );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void TrackRenderer::Rendering( const efkTrackNodeParam& parameter, const efkTrackInstanceParam& instanceParameter, void* userData )
{
	Rendering_<Vertex>( parameter, instanceParameter, userData, m_renderer->GetCameraMatrix() );
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
void TrackRenderer::EndRendering( const efkTrackNodeParam& parameter, void* userData )
{
	if( m_ringBufferData == NULL ) return;

	m_renderer->GetVertexBuffer()->Unlock();

	if( m_ribbonCount <= 1 ) return;

	EndRendering_<RendererImplemented, Shader, IDirect3DTexture9*, Vertex>(m_renderer, m_shader, m_shader_no_texture, parameter);
}

//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------


text:
Matt
====

Basic version tracking for matthewswerdlin.com

redpajama_set_name: RedPajamaGithub


text:
[![NPM version][npm-image]][npm-url]
[![NPM downloads][downloads-image]][downloads-url]

Support for Chrome Extensions in Electron apps

## Usage

```js
var chromeExtensions = require('electron-chrome-extensions')

webview.addEventListener('dom-ready', () => {
  chromeExtensions.load(chromeExtensions.defaultPath, (err, extensions) => {
    extensions.forEach((extension) => {
      chromeExtensions.addToWebview(webview, extension, (err) => {
      })
    })
  })
})
```

## Installation

```sh
npm install electron-chrome-extensions --save
```

## License

MIT license

[npm-image]: https://img.shields.io/npm/v/electron-chrome-extensions.svg?style=flat
[npm-url]: https://npmjs.org/package/electron-chrome-extensions
[downloads-image]: https://img.shields.io/npm/dm/electron-chrome-extensions.svg?style=flat
[downloads-url]: https://npmjs.org/package/electron-chrome-extensions


text:
// ItemDB.Plugin
// ItemPublisher.cs
//
// Copyright @2015 Violet Cheng - 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.
//  * Neither the name of SyndicatedLife nor the names of its contributors may
//    be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// 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.

using System;
using System.IO;
using System.Collections.Generic;
using FFXIVAPP.Common.Core.Memory;
using FFXIVAPP.Common.Utilities;
using NLog;
using ItemDB.Plugin.Properties;
using ItemDB.Plugin.Views;
using ItemDB.Plugin.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;
using FFXIVAPP.Common.Core.Memory.Enums;
using FFXIVAPP.Common.Models;
namespace ItemDB.Plugin.Utilities
{
    public static class ItemPublisher
    {
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        public static List<ItemFullInfo> HireCatalog = new List<ItemFullInfo>();
        //TODO remove this when character name bug is fixed
        public static bool logout = false;
        private static int lastcount = -1;
        private static String lastName = "";
        private static void WriteCatalog(List<ItemFullInfo> list, int hire = 0, int company = 0)
        {
            if (Constants.CharacterName == "")
            {
                return;
            }
            var userPath = Path.Combine(NameDatabase.filepath, "Users");
            DirectoryInfo di = new DirectoryInfo(userPath);

            if (!di.Exists)
            {
                try
                {
                    di.Create();
                    Logging.Log(Logger, "ITEMDB Log: Created Users folder");
                }
                catch (Exception ex)
                {
                    Logging.Log(Logger, new LogItem("Exception on create Users folder", ex, LogLevel.Error));

                }
            }
            String suffix = "";
            String update = Constants.CharacterName + "的";
            if (hire == 0 && company == 0)
            {
                suffix= Constants.CharacterName + ".json";
                update += "物品更新成功";
            }
            else if (hire != 0){
                suffix= Constants.CharacterName + "-雇员"+hire.ToString()+".json";
                update += "雇员"+hire.ToString()+"物品更新成功";
            }
            else if (company != 0)
            {
                suffix = Constants.CharacterName + "-部队储物柜"+ ".json";
                update += "个人物品及部队储物柜更新成功";
            }
            var fileName = Path.Combine(userPath, suffix);
            try
            {
                var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                string xx = JsonConvert.SerializeObject(list);

                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xx);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Close();
                PluginViewModel.Instance.ResultAmount = "["+DateTime.Now.ToLongTimeString().ToString()+"]"+update;
                Logging.Log(Logger, "ITEMDB Log: Finished writing json file");
            }
            catch (Exception ex)
            {

                Logging.Log(Logger, new LogItem("Exception on create json file", ex, LogLevel.Error));
            }

        }
        public static void ProcessHire(int hire)
        {
            if (hire == 0)
            {
                return;
            }
            else
            {
                if (HireCatalog.Count > 0)
                {
                    WriteCatalog(HireCatalog, hire, 0);
                }
            }
        }
        private static uint GetAllItemAmount(List<InventoryEntity> inventoryEntry)
        {
            uint count = 0;
            foreach(var container in inventoryEntry)
            {
                count += container.Amount;
            }
            return count;
        }
        public static void Process(List<InventoryEntity> inventoryEntry)
        {
            try
            {

                uint allitemscount = GetAllItemAmount(inventoryEntry);
                if (allitemscount <= 5)
                {
                    Logging.Log(LogManager.GetCurrentClassLogger(), "ITEMDB Log: Less than 5 items, maybe a wrong inventory event");
                    logout = true;
                    return;
                }
                if (logout == true)
                {
                    //skip the first saving after logout
                    Logging.Log(LogManager.GetCurrentClassLogger(), "ITEMDB Log: Just Logout, skip this inventory");
                    logout = false;
                    return;
                }
                List<ItemFullInfo> allItems = new List<ItemFullInfo>();
                List<ItemFullInfo> companyItems = new List<ItemFullInfo>();
                HireCatalog.Clear();
                uint countnull = 0;
                foreach (var container in inventoryEntry)
                {
                    if (container.Amount > 0)
                    {
                        foreach (var item in container.Items)
                        {
                            //in case of memory overwritten

                            var lItem = new ItemFullInfo();
                            lItem.Info = item;
                            lItem.Desc = NameDatabase.GetDescFromInfo(item);
                            if (lItem.Desc == null)
                            {
                                countnull++;
                                continue;
                            }
                            lItem.Location = new Location();
                            lItem.Location.Type = container.Type;
                            lItem.Location.Character = Constants.CharacterName;

                            if (container.Type == Inventory.Container.COMPANY_1 || container.Type == Inventory.Container.COMPANY_2 || container.Type == Inventory.Container.COMPANY_3)
                            {
                                companyItems.Add(lItem);
                            }

                            else if (container.Type < Inventory.Container.HIRE_1 || container.Type > Inventory.Container.HIRE_7)
                            {
                                allItems.Add(lItem);
                            }
                            else
                            {
                                HireCatalog.Add(lItem);
                            }

                        }

                    }

                }
                if (countnull*2 > allitemscount)
                {
                    Logging.Log(LogManager.GetCurrentClassLogger(), "ITEMDB Log: Too many null items, maybe a wrong inventory event");
                    return;
                }

                if (lastcount == -1)
                {
                    lastcount = allItems.Count;
                    lastName = Constants.CharacterName;
                }
                else
                {

                    if (allItems.Count < lastcount/2 && Constants.CharacterName == lastName)
                    {
                        Logging.Log(LogManager.GetCurrentClassLogger(), "ITEMDB Log: items decreased too fast in the same character, maybe a wrong inventory event");
                        return;
                    }
                    if (Constants.CharacterName != lastName)
                    {
                        lastName = Constants.CharacterName;
                    }
                }

                WriteCatalog(allItems, 0, 0);
                if (companyItems.Count > 0)
                {
                    WriteCatalog(companyItems, 0, 1);
                }

                lastcount = allItems.Count;

            }
            catch (Exception ex)
            {
                Logging.Log(Logger, new LogItem("Exception on writeCatalog", ex, LogLevel.Error));
            }
        }
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="32dp"
        android:height="32dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFFFF"
        android:pathData="M6,19h4L10,5L6,5v14zM14,5v14h4L18,5h-4z"/>
</vector>


text:
namespace Incoding.Data
{
    #region << Using >>

    using System;

    #endregion

    public class AndFetchSpecification<TEntity> : FetchSpecification<TEntity>
    {
        #region Fields

        readonly FetchSpecification<TEntity> first;

        readonly FetchSpecification<TEntity> second;

        #endregion

        #region Constructors

        public AndFetchSpecification(FetchSpecification<TEntity> first, FetchSpecification<TEntity> second)
        {
            this.first = first;
            this.second = second;
        }

        #endregion

        public override Action<AdHocFetchSpecificationBase<TEntity>> FetchedBy()
        {
            return r =>
                       {
                           this.first.FetchedBy()(r);
                           this.second.FetchedBy()(r);
                       };
        }
    }
}


text:
package showclixscanner;

import java.io.*;

/**
 *
 * @author SunnyBat
 */
public class ProcessHandler {

  private static final String TASKLIST = "tasklist";
  private static final String KILL = "taskkill /T /IM ";
  private static final String FORCEKILL = "taskkill /T /F /IM ";

  public static boolean isProcessRunging(String serviceName) {
    try {
      Process p = Runtime.getRuntime().exec(TASKLIST);
      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        line = line.toLowerCase();
        if (line.contains(serviceName)) {
          ShowclixScanner.println(serviceName + " found.", ShowclixScanner.LOGTYPE.VERBOSE);
          return true;
        }
      }
    } catch (IOException e) {
      System.out.println("Error reading processes!");
      e.printStackTrace();
    }
    return false;

  }

  public static void killProcess(String serviceName) {
    try {
      Runtime.getRuntime().exec(KILL + serviceName);
    } catch (IOException e) {
      ShowclixScanner.println("Unable to kill process " + serviceName, ShowclixScanner.LOGTYPE.MINIMUM);
      e.printStackTrace();
    }
  }

  public static void forceKillProcess(String serviceName) {
    try {
      Runtime.getRuntime().exec(FORCEKILL + serviceName);
    } catch (IOException e) {
      ShowclixScanner.println("Unable to kill process " + serviceName, ShowclixScanner.LOGTYPE.MINIMUM);
      e.printStackTrace();
    }
  }

  public static void killFirefox() {
    String processName = "firefox.exe";
    if (isProcessRunging(processName)) {
      ShowclixScanner.println("Send close request to Firefox...", ShowclixScanner.LOGTYPE.DEBUG);
      killProcess(processName);
    } else {
      ShowclixScanner.println("Unable to find firefox.exe -- Please close Firefox manually if it is running (check Task Manager if necesssary).", ShowclixScanner.LOGTYPE.MINIMUM);
    }
  }

  public static void forceKillFirefox() {
    String processName = "firefox.exe";
    if (isProcessRunging(processName)) {
      ShowclixScanner.println("WARNING: Force killing Firefox...", ShowclixScanner.LOGTYPE.MINIMUM);
      forceKillProcess(processName);
    } else {
      ShowclixScanner.println("Unable to find firefox.exe -- Please close Firefox manually if it is running (check Task Manager if necesssary).", ShowclixScanner.LOGTYPE.MINIMUM);
    }
  }
}


text:
var log = require('./log')('query'),
  cache = require('./cache'),
  util = require('./util'),
  error = require('./error'),
  ModelInstance = require('./ModelInstance'),
  constructQuerySet = require('./QuerySet');

/**
 * @class [Query description]
 * @param {Model} model
 * @param {Object} query
 */
function Query(model, query) {
  var opts = {};
  for (var prop in query) {
    if (query.hasOwnProperty(prop)) {
      if (prop.slice(0, 2) == '__') {
        opts[prop.slice(2)] = query[prop];
        delete query[prop];
      }
    }
  }
  util.extend(this, {
    model: model,
    query: query,
    opts: opts
  });
  opts.order = opts.order || [];
  if (!util.isArray(opts.order)) opts.order = [opts.order];
}

function valueAsString(fieldValue) {
  var fieldAsString;
  if (fieldValue === null) fieldAsString = 'null';
  else if (fieldValue === undefined) fieldAsString = 'undefined';
  else if (fieldValue instanceof ModelInstance) fieldAsString = fieldValue.localId;
  else fieldAsString = fieldValue.toString();
  return fieldAsString;
}

function contains(opts) {
  if (!opts.invalid) {
    var obj = opts.object;
    if (util.isArray(obj)) {
      arr = util.pluck(obj, opts.field);
    }
    else
      var arr = obj[opts.field];
    if (util.isArray(arr) || util.isString(arr)) {
      return arr.indexOf(opts.value) > -1;
    }
  }
  return false;
}

var comparators = {
  e: function(opts) {
    var fieldValue = opts.object[opts.field];
    if (log.enabled) {
      log(opts.field + ': ' + valueAsString(fieldValue) + ' == ' + valueAsString(opts.value), {opts: opts});
    }
    return fieldValue == opts.value;
  },
  lt: function(opts) {
    if (!opts.invalid) return opts.object[opts.field] < opts.value;
    return false;
  },
  gt: function(opts) {
    if (!opts.invalid) return opts.object[opts.field] > opts.value;
    return false;
  },
  lte: function(opts) {
    if (!opts.invalid) return opts.object[opts.field] <= opts.value;
    return false;
  },
  gte: function(opts) {
    if (!opts.invalid) return opts.object[opts.field] >= opts.value;
    return false;
  },
  contains: contains,
  in: contains
};

util.extend(Query, {
  comparators: comparators,
  registerComparator: function(symbol, fn) {
    if (!comparators[symbol]) {
      comparators[symbol] = fn;
    }
  }
});

function cacheForModel(model) {
  var cacheByType = cache._localCacheByType;
  var modelName = model.name;
  var collectionName = model.collectionName;
  var cacheByModel = cacheByType[collectionName];
  var cacheByLocalId;
  if (cacheByModel) {
    cacheByLocalId = cacheByModel[modelName] || {};
  }
  return cacheByLocalId;
}

util.extend(Query.prototype, {
  execute: function(cb) {
    return util.promise(cb, function(cb) {
      this._executeInMemory(cb);
    }.bind(this));
  },
  _dump: function(asJson) {
    return asJson ? '{}' : {};
  },
  sortFunc: function(fields) {
    var sortFunc = function(ascending, field) {
      return function(v1, v2) {
        var d1 = v1[field],
          d2 = v2[field],
          res;
        if (typeof d1 == 'string' || d1 instanceof String &&
          typeof d2 == 'string' || d2 instanceof String) {
          res = ascending ? d1.localeCompare(d2) : d2.localeCompare(d1);
        }
        else {
          if (d1 instanceof Date) d1 = d1.getTime();
          if (d2 instanceof Date) d2 = d2.getTime();
          if (ascending) res = d1 - d2;
          else res = d2 - d1;
        }
        return res;
      }
    };
    var s = util;
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      s = s.thenBy(sortFunc(field.ascending, field.field));
    }
    return s == util ? null : s;
  },
  _sortResults: function(res) {
    var order = this.opts.order;
    if (res && order) {
      var fields = order.map(function(ordering) {
        var splt = ordering.split('-'),
          ascending = true,
          field = null;
        if (splt.length > 1) {
          field = splt[1];
          ascending = false;
        }
        else {
          field = splt[0];
        }
        return {field: field, ascending: ascending};
      }.bind(this));
      var sortFunc = this.sortFunc(fields);
      if (res.immutable) res = res.mutableCopy();
      if (sortFunc) res.sort(sortFunc);
    }
    return res;
  },
  /**
   * Return all model instances in the cache.
   * @private
   */
  _getCacheByLocalId: function() {
    return this.model.descendants.reduce(function(memo, childModel) {
      return util.extend(memo, cacheForModel(childModel));
    }, util.extend({}, cacheForModel(this.model)));
  },
  _executeInMemory: function(callback) {
    var _executeInMemory = function() {
      this.model
        ._indexIsInstalled
        .then(function() {
          var cacheByLocalId = this._getCacheByLocalId();
          var keys = Object.keys(cacheByLocalId);
          var self = this;
          var res = [];
          var err;
          for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var obj = cacheByLocalId[k];
            var matches = self.objectMatchesQuery(obj);
            if (typeof(matches) == 'string') {
              err = error(matches);
              break;
            } else {
              if (matches) res.push(obj);
            }
          }
          res = this._sortResults(res);
          if (err) log('Error executing query', err);
          callback(err, err ? null : constructQuerySet(res, this.model));
        }.bind(this))
        .catch(function(err) {
          var _err = 'Unable to execute query due to failed index installation on Model "' +
            this.model.name + '"';
          console.error(_err, err);
          callback(_err);
        }.bind(this));
    }.bind(this);
    if (this.opts.ignoreInstalled) {
      _executeInMemory();
    }
    else {
      siesta._afterInstall(_executeInMemory);
    }
  },
  clearOrdering: function() {
    this.opts.order = null;
  },
  objectMatchesOrQuery: function(obj, orQuery) {
    for (var idx in orQuery) {
      if (orQuery.hasOwnProperty(idx)) {
        var query = orQuery[idx];
        if (this.objectMatchesBaseQuery(obj, query)) {
          return true;
        }
      }
    }
    return false;
  },
  objectMatchesAndQuery: function(obj, andQuery) {
    for (var idx in andQuery) {
      if (andQuery.hasOwnProperty(idx)) {
        var query = andQuery[idx];
        if (!this.objectMatchesBaseQuery(obj, query)) {
          return false;
        }
      }
    }
    return true;
  },
  splitMatches: function(obj, unprocessedField, value) {
    var op = 'e';
    var fields = unprocessedField.split('.');
    var splt = fields[fields.length - 1].split('__');
    if (splt.length == 2) {
      var field = splt[0];
      op = splt[1];
    }
    else {
      field = splt[0];
    }
    fields[fields.length - 1] = field;
    fields.slice(0, fields.length - 1).forEach(function(f) {
      if (util.isArray(obj)) {
        obj = util.pluck(obj, f);
      }
      else {
        obj = obj[f];
      }
    });
    // If we get to the point where we're about to index null or undefined we stop - obviously this object does
    // not match the query.
    var notNullOrUndefined = obj != undefined;
    if (notNullOrUndefined) {
      if (util.isArray(obj)) {
      }
      else {
        var val = obj[field];
        var invalid = util.isArray(val) ? false : val === null || val === undefined;
      }
      var comparator = Query.comparators[op],
        opts = {object: obj, field: field, value: value, invalid: invalid};
      if (!comparator) {
        return 'No comparator registered for query operation "' + op + '"';
      }
      return comparator(opts);
    }
    return false;
  },
  objectMatches: function(obj, unprocessedField, value, query) {
    if (unprocessedField == '$or') {
      var $or = query['$or'];
      if (!util.isArray($or)) {
        $or = Object.keys($or).map(function(k) {
          var normalised = {};
          normalised[k] = $or[k];
          return normalised;
        });
      }
      if (!this.objectMatchesOrQuery(obj, $or)) return false;
    }
    else if (unprocessedField == '$and') {
      if (!this.objectMatchesAndQuery(obj, query['$and'])) return false;
    }
    else {
      var matches = this.splitMatches(obj, unprocessedField, value);
      if (typeof matches != 'boolean') return matches;
      if (!matches) return false;
    }
    return true;
  },
  objectMatchesBaseQuery: function(obj, query) {
    var fields = Object.keys(query);
    for (var i = 0; i < fields.length; i++) {
      var unprocessedField = fields[i],
        value = query[unprocessedField];
      var rt = this.objectMatches(obj, unprocessedField, value, query);
      if (typeof rt != 'boolean') return rt;
      if (!rt) return false;
    }
    return true;
  },
  objectMatchesQuery: function(obj) {
    return this.objectMatchesBaseQuery(obj, this.query);
  }
});

module.exports = Query;


text:
      <button id="showLayers">Show Layers</button>
      <button id="hideLayers">Hide Layers</button>

      <button id="queryLayers">Query Layers</button>

      <button id="getIntersectionObjects">Get Intersection Objects</button>

      <button id="getIntersectionArea">Get Intersection Area</button>

      <button id="showIntersectionArea">Show Intersection Area</button>
      <button id="clearIntersectionArea">Clear Intersection Area</button>

      <button id="createNewlayer">Create New Layer</button>

      <button id="showAllLayerObjects">Show All Layer Objects</button>

      <button id="isContainsObject">Is Contains Object</button>

      <button id="extendsAreaObject">Get Extended Area</button>

      <button id="deleteLayerObject">Delete Object</button>
      <button id="deleteLayerObjects">Delete Objects</button>

      <button id="nearestObject">Get Nearest Object</button>
      <button id="distanceObjects">Get Distance</button>

      <button id="showObjects">Show Objects</button>
      <button id="hideObjects">Hide Objects</button>

      <button id="moveObjectToLayer">Move Object To Layer</button>

      <button id="copyObject">Copy Object</button>

      <button id="creatObject">Create Object</button>

      <button id="getRhumb"> Get Rhumb</button>

      <button id="getLayerObjectOptions">Get Object Attributes</button>

      <button id="editLayerObject">Edit Layer Object</button>

      <button id="hideLeftPanel">Hide left panel</button>
      <button id="showLeftPanel">Show left panel</button>
      <input type="text" size="40" id="nameTools">

      <button id="hideRightPanel">Hide right panel</button>
      <button id="showRightPanel">Show right panel</button>

      <button id="startChangeMultyLayerObject">Change Multy Object</button>
      <button id="createPolygonObjectCoordinates">Create Object By Coordinates</button>
      <button id="createPolygonObjectRhumb">Create Object By Rhumb</button>

      <button id="groupLayers">Group Layers</button>


text:
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

	protected $redirectTo = '/';

	protected $subject = 'Password Reset Link for P-AWS Tutorial 04';

    /**
     * Create a new password controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

}


text:
	<meta charset="utf-8">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" type="text/css"/>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />
	<title>Jekyll+GitHub API+JS=Dynamic CMS :-)</title>

	<meta name="viewport" content="width=device-width, initial-scale=1">

Create new post at {{ site.title }}

  {% include_relative validation.html %}

	<form id="theform" method="get">

			<input type="text" class="form-control" placeholder="File Path <videos/sample.md>" id="p_filename" name="filename">

			<textarea class="form-control" rows="10" id="p_body" placeholder="Type your post here." name="body"></textarea>

				Username
				<input type="text" class="form-control" id="username" placeholder="GitHub username">

				password
				<input type="password" class="form-control" id="password" placeholder="GitHub password">

			<input type="button" class="btn btn-default" id="go" value="Post" />
			Remember username/password

Because of the way this form works (the form data is not sumbitted, as forms usually do), your browser may not ask you to remember the username/password.

If you'd like to save them to your password manager, fill them in and click this button.

This will not create a new post!

	    	<input type="submit" class="btn btn-default" value="Trick browser to save username/password">

	</form>

Drag this link to your bookmarks, to post from any webpage: <a href="javascript:(function(){
	var title = document.getElementsByTagName('title')[0].innerHTML;
	title = encodeURIComponent(title) ;
	var selection = '';
	if (window.getSelection) {
	    selection = window.getSelection().toString();
	} else if (document.selection && document.selection.type != 'Control') {
	    selection = document.selection.createRange().text;
	}
	selection = encodeURIComponent(selection);
	new_window=window.open('{{ "/boo" | prepend: site.baseurl | prepend: site.url }}?title='+title+'&selection='+selection+'&url='+encodeURIComponent(document.location.href),'BooPopup','resizable,scrollbars,status=0,toolbar=0,menubar=0,titlebar=0,width=640,height=600,location=0');
	})();"
	>post to {{ site.title }}


text:
@implementation UICollectionView (BDKKit)

- (NSIndexPath *)minimumIndexPath {
    return [NSIndexPath indexPathForItem:0 inSection:0];
}

- (NSIndexPath *)maximumIndexPath {
    NSInteger lastSection = self.numberOfSections - 1;
    NSInteger lastitem = [self numberOfItemsInSection:lastSection] - 1;
    return [NSIndexPath indexPathForItem:lastitem inSection:lastSection];
}

- (NSIndexPath *)incrementIndexPath:(NSIndexPath *)indexPath {
    return [self incrementIndexPath:indexPath wrap:YES];
}

- (NSIndexPath *)incrementIndexPath:(NSIndexPath *)indexPath wrap:(BOOL)wrap {
    if ([indexPath compare:self.maximumIndexPath] == NSOrderedSame) return wrap ? self.minimumIndexPath : nil;
    if (indexPath.item == [self numberOfItemsInSection:indexPath.section] - 1) {
        return [NSIndexPath indexPathForItem:0 inSection:(indexPath.section + 1)];
    } else return [NSIndexPath indexPathForItem:(indexPath.item + 1) inSection:indexPath.section];
}

- (NSIndexPath *)decrementIndexPath:(NSIndexPath *)indexPath {
    return [self decrementIndexPath:indexPath wrap:YES];
}

- (NSIndexPath *)decrementIndexPath:(NSIndexPath *)indexPath wrap:(BOOL)wrap {
    if ([indexPath compare:self.minimumIndexPath] == NSOrderedSame) return wrap ? self.maximumIndexPath : nil;
    if (indexPath.item == 0) {
        NSInteger lastItem = [self numberOfItemsInSection:(indexPath.section - 1)] - 1;
        return [NSIndexPath indexPathForItem:lastItem inSection:(indexPath.section - 1)];
    } else return [NSIndexPath indexPathForItem:(indexPath.item - 1) inSection:indexPath.section];
}

@end


text:
import { parse, ParseOptions } from '@messageformat/parser';
import * as PluralCategories from 'make-plural/pluralCategories';
import type {
  FunctionRef,
  Literal,
  MessageGroup,
  VariableRef
} from 'messageformat';
import { astToMessage } from './mf1-ast-to-message';

const isPluralId = (id: string): id is keyof typeof PluralCategories =>
  id in PluralCategories;

function normalize(locale: string) {
  if (typeof locale !== 'string' || locale.length < 2)
    throw new Error(`Invalid language tag: ${locale}`);

  // The only locale for which anything but the primary subtag matters is
  // Portuguese as spoken in Portugal.
  if (locale.startsWith('pt-PT')) return 'pt_PT';

  const m = locale.match(/.+?(?=[-_])/);
  return m ? m[0] : locale;
}

/**
 * A hierarchical structure of ICU MessageFormat strings
 *
 * @public
 * @remarks
 * Used in {@link compileMessageGroup} and {@link compileResource} arguments
 */
export interface StringStructure {
  [key: string]: StringStructure | string;
}

function compileMessageGroup(
  src: StringStructure,
  options: ParseOptions
): MessageGroup<Literal | VariableRef | FunctionRef> {
  const entries: MessageGroup<Literal | VariableRef | FunctionRef>['entries'] =
    {};
  for (const [key, value] of Object.entries(src)) {
    entries[key] =
      typeof value === 'string'
        ? astToMessage(parse(value, options))
        : compileMessageGroup(value, options);
  }
  return { type: 'group', entries };
}

export function compileMF1(
  src: StringStructure,
  { locale, strict }: { locale: string; strict?: boolean }
): MessageGroup<Literal | VariableRef | FunctionRef> {
  const lc = normalize(locale);
  if (!isPluralId(lc)) throw new Error(`Unsupported locale: ${locale}`);
  const { cardinal, ordinal } = PluralCategories[lc];
  const { entries } = compileMessageGroup(src, { cardinal, ordinal, strict });
  return { type: 'group', entries };
}


text:
"""
Created on July 2017

@author: JulienWuthrich
"""
import pandas as pd
import numpy as np

from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_absolute_error, accuracy_score, r2_score
from sklearn.model_selection import train_test_split

from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, GradientBoostingClassifier
from sklearn.ensemble import ExtraTreesRegressor, RandomForestRegressor, GradientBoostingRegressor, AdaBoostRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import ElasticNetCV, LassoLarsCV, RidgeCV
from sklearn.naive_bayes import BernoulliNB, GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neighbors import KNeighborsRegressor

from xgboost import XGBRegressor, XGBClassifier

from vecstack import stacking

# Read the csv file
data = pd.read_csv("toto2.csv")
regression = True
if regression:
    metric = r2_score
else:
    metric = accuracy_score

# Split dependants and independant variables
y = data[["predict"]]
X = data.drop("predict", axis=1)

# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)

# Apply Some Featuring
poly_reg = PolynomialFeatures(degree=1)

# Transform into numpy object
x_train = poly_reg.fit_transform(X_train)
x_test = poly_reg.fit_transform(X_test)
y_test = np.array(y_test.ix[:,0])
y_train = np.array(y_train.ix[:,0])

# define lmodels
lmodels = [LassoLarsCV(copy_X=True, cv=None, eps=2.2204460492503131e-16,
      fit_intercept=True, max_iter=500, max_n_alphas=1000, n_jobs=1,
      normalize=True, positive=False, precompute='auto', verbose=False), RidgeCV(alphas=(0.1, 1.0, 10.0), cv=None, fit_intercept=True, gcv_mode=None,
    normalize=False, scoring=None, store_cv_values=False), XGBRegressor(base_score=0.5, colsample_bylevel=1, colsample_bytree=1, gamma=0,
       learning_rate=0.1, max_delta_step=0, max_depth=8,
       min_child_weight=6, missing=None, n_estimators=75, nthread=-1,
       objective='reg:linear', reg_alpha=0, reg_lambda=1,
       scale_pos_weight=1, seed=0, silent=True, subsample=0.8)]

# build the stack level 1
S_train, S_test = stacking(
    lmodels, x_train, y_train, x_test,
    regression=regression, metric=metric,
    n_folds=3, shuffle=True, random_state=0, verbose=1
)

# build model lvel 2
model = DecisionTreeRegressor(criterion='mse', max_depth=10, max_features=None,
           max_leaf_nodes=None, min_impurity_split=1e-07,
           min_samples_leaf=4, min_samples_split=4,
           min_weight_fraction_leaf=0.0, presort=False, random_state=None,
           splitter='best')

# Fit the model
model.fit(S_train, y_train)

# Predict
y_pred = model.predict(S_test)

# Scoring
if regression:
    print('Score on test set:', mean_absolute_error(y_test, y_pred))
else:
    print('Score on test set:', accuracy_score(y_test, y_pred))
print(metric(y_test, y_pred))


text:
var GitHubStrategy = require('passport-github').Strategy;
var configuration = require('@webgap/configuration');

module.exports = function (passport) {

  var strategy = new GitHubStrategy({
      clientID: configuration.get('MODULE.AUTHENTICATION.GITHUB.CLIENT_ID'),
      clientSecret: configuration.get('MODULE.AUTHENTICATION.GITHUB.CLIENT_SECRET'),
      callbackURL: [configuration.get('SERVER.PROTOCOL'), configuration.get('SERVER.HOST'), ':',
        configuration.get('SERVER.APACHE_PORT'), '/auth/github/oauth2callback'].join(''),
      passReqToCallback: true
    }, function (req, accessToken, refreshToken, profile, done) {
      process.nextTick(function () {
        profile.accessToken = accessToken || null;
        profile.tokenType = null;
        profile.expiresIn = null;
        profile.refreshToken = refreshToken || null;
        profile.loggedUser = req.user || null;
        return done(null, profile);
      });
    }
  );

  passport.use(strategy);

  global.express.router.get('/auth/github', passport.authenticate('github'));

  global.express.router.get('/auth/github/oauth2callback', passport.authenticate('github', {failureRedirect: '/auth/login'}),
    function (req, res) {
      res.redirect('/account/profile');
    });

};


text:
module Lift where

data Session = Session { lift :: LiftName
                       , sets :: [Set]
                       } deriving (Show)

type LiftName = String

data Set = Set { weight :: Weight
               , reps   :: Reps
               } deriving (Show)

type Reps = Integer

sessionVolume :: Session -> Weight
sessionVolume = foldl1 (+) . map volume . sets

volume :: Set -> Weight
volume (Set wt reps) = fromInteger (reps) * wt

convert :: Weight -> Weight
convert (Wt x Lb) = Wt (x/2.2046) Kg
convert (Wt x Kg) = Wt (x*2.2046) Lb


text:
package wicket.in.action.chapter02.section_2_1_2.listing01;

import org.apache.wicket.Request;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.protocol.http.WebSession;

public class CheeseStoreSession extends WebSession {

  private Basket basket;

  public CheeseStoreSession(WebApplication application,
      Request request) {
    super(application, request);
  }

  public Basket getBasket() {
    return basket;
  }

  public void setBasket(Basket basket) {
    this.basket = basket;
  }
}


text:
package org.hibernate.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class JDBCExceptionReporter {

	public static final Log log = LogFactory.getLog(JDBCExceptionReporter.class);
	public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception";
	public static final String DEFAULT_WARNING_MSG = "SQL Warning";

	private JDBCExceptionReporter() {}

	public static void logAndClearWarnings(Connection connection) {
		if ( log.isWarnEnabled() ) {
			try {
				logWarnings( connection.getWarnings() );
				connection.clearWarnings();
			}
			catch (SQLException sqle) {
				//workaround for WebLogic
				log.debug("could not log warnings", sqle);
			}
		}
	}

	public static void logWarnings(SQLWarning warning) {
		logWarnings(warning, null);
	}

	public static void logWarnings(SQLWarning warning, String message) {
		if ( log.isWarnEnabled() ) {
			if ( log.isDebugEnabled() && warning != null ) {
				message = StringHelper.isNotEmpty(message) ? message : DEFAULT_WARNING_MSG;
				log.debug( message, warning );
			}
			while (warning != null) {
				StringBuffer buf = new StringBuffer(30)
				        .append( "SQL Warning: ")
						.append( warning.getErrorCode() )
						.append( ", SQLState: ")
						.append( warning.getSQLState() );
				log.warn( buf.toString() );
				log.warn( warning.getMessage() );
				warning = warning.getNextWarning();
			}
		}
	}

	public static void logExceptions(SQLException ex) {
		logExceptions(ex, null);
	}

	public static void logExceptions(SQLException ex, String message) {
		if ( log.isErrorEnabled() ) {
			if ( log.isDebugEnabled() ) {
				message = StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG;
				log.debug( message, ex );
			}
			while (ex != null) {
				StringBuffer buf = new StringBuffer(30)
						.append( "SQL Error: " )
				        .append( ex.getErrorCode() )
				        .append( ", SQLState: " )
				        .append( ex.getSQLState() );
				log.warn( buf.toString() );
				log.error( ex.getMessage() );
				ex = ex.getNextException();
			}
		}
	}

//	public static JDBCException newJDBCException(String string, SQLException root, String sql) {
//		string = string + " [" + sql + ']';
//		log.error(string, root);
//		logExceptions(root);
//		return new JDBCException(string, root, sql);
//	}
//
//	public static JDBCException newJDBCException(String string, SQLException root) {
//		log.error(string, root);
//		logExceptions(root);
//		return new JDBCException(string, root);
//	}

}


text:
- #### Installing Node

    mac usres:
    ```sh
    brew install node
    ```

    Linux/Ubuntu users:
    Go to [Node.js](https://nodejs.org/en/download/) and download and install the setup

- #### Check if npm is installed
    in console, try:
    ```sh
    npm -v
    ```
    you will see npm version if everything goes right.

- #### Clone Repo
    ```sh
    cd ~/Documents
    git clone https://github.com/iiison/React-Redux-Eslint-SASS-boilerplate.git
    cd React-Redux-Eslint-SASS-boilerplate
    ```

- #### Install Dependencies
    ````sh
    npm i
    ````

        First Time setup is completed 👍

## Running Server

- #### Dev server
    ```sh
    npm run start
    ```
    Front-End is using it's own server, it points to Staging(configurable).

- #### Production Build
    ```sh
    npm run production
    ```


text:
layout:     post
title:      illusion
date:       2019-07-05 00:43:09
summary:
categories: drawing
---
![illusion](/images/diary/illusion.png ".")


text:
'use strict';

var express = require('express');
var async = require('async');
var fs = require('fs');
var exec = require('child_process').exec;
var router = express.Router();

var Canvas = require('../data/models/canvas');

router.get('/', function (req, res, next) {
  Canvas
  .find({_owner: req.session.user._id})
  .select('_id title updateDate')
  .sort({updateDate: -1})
  .exec(function (err, data) {
    if (err) { return next(err); }
    res.status(200).json(data);
  });
});

router.get('/:id', function (req, res, next) {
  Canvas
  .findOne({
    _id: req.params.id,
    _owner: req.session.user._id
  })
  .exec(function (err, data) {
    if (err) { return next(err); }
    if (!data) {
      return res.status(404).end();
    }
    res.status(200).json(data);
  });
});

router.post('/', function (req, res, next) {
  if (req.body._id !== undefined) {
    delete req.body._id;
  }

  var canvas = new Canvas(req.body);
  canvas._owner = req.session.user._id;
  canvas.regDate = new Date();

  canvas.save(function (err) {
    if (err) { return next(err); }
    res.status(201).json(canvas);
  });
});

router.post('/upload', function (req, res) {
  var resData = req.body;
  var scriptFile = `${global.appRoot}/gdb-script.js`;
  var sourceFile = `${global.appRoot}/tmp/${req.cookies.id}.cpp`;
  var binaryFile = `${global.appRoot}/tmp/${req.cookies.id}.out`;
  var designFile = `${global.appRoot}/tmp/${req.cookies.id}.json`;
  var inputFile = `${global.appRoot}/tmp/${req.cookies.id}.txt`;

  async.waterfall([
    function (callback) {
      fs.writeFile(sourceFile, req.body.code, callback);
    },
    function (callback) {
      exec(`g++ -g ${sourceFile} -o ${binaryFile}`, callback);
    },
    function (stdout, stderr, callback) {
      fs.writeFile(designFile, JSON.stringify(req.body.design), callback);
    },
    function (callback) {
      if (!req.body.input) {
        return callback();
      }
      fs.writeFile(inputFile, req.body.input, callback);
    },
    function (callback) {
      exec(`node ${scriptFile} ${sourceFile} ${binaryFile} `
        + `${designFile} ${inputFile}`, callback);
    },
    function (stdout) {
      resData.result = JSON.parse(stdout);
      res.status(201).json(resData);
    }
  ], function (err) {
    throw err;
  });
});

router.post('/:id', function (req, res, next) {
  var canvas = new Canvas(req.body);
  canvas._id = req.params.id;
  canvas.updateDate = new Date();

  Canvas
  .findOneAndUpdate({
    _id: canvas._id,
    _owner: req.session.user._id
  },
  {$set: canvas},
  {'new': true})
  .exec(function (err, data) {
    if (err) { return next(err); }
    if (!data) {
      return res.status(404).end();
    }
    res.status(200).json(data);
  });
});

router.delete('/:id', function (req, res, next) {
  Canvas
  .findOneAndRemove({
    _id: req.params.id,
    _owner: req.session.user._id
  })
  .exec(function (err, data) {
    if (err) { return next(err); }
    if (!data) {
      return res.status(404).end();
    }
    res.status(204).end();
  });
});

module.exports = router;


text:
package org.knowm.sundial.jobs;

import org.knowm.sundial.Job;
import org.knowm.sundial.JobContext;
import org.knowm.sundial.exceptions.JobInterruptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SampleJob3 extends Job {

  private final Logger logger = LoggerFactory.getLogger(SampleJob3.class);

  @Override
  public void doRun() throws JobInterruptException {

    logger.info("Running SampleJob3.");

    JobContext context = getJobContext();

    context.put("MyValue", new Integer(123));

    new SampleJobAction().run();

  }
}


text:
package com.rbmhtechnology.eventuate

import java.util.{ List => JList, Optional => JOption }
import java.util.function.BiFunction

import scala.collection.JavaConverters._
import scala.compat.java8.OptionConverters._
import scala.util._

import VersionedAggregate._

/**
 * Manages concurrent versions of an event-sourced aggregate.
 *
 * @param id Aggregate id
 * @param cmdHandler Command handler
 * @param evtHandler Event handler
 * @param aggregate Aggregate.
 * @tparam S Aggregate type.
 * @tparam C Command type.
 * @tparam E Event type.
 */
case class VersionedAggregate[S, C: DomainCmd, E: DomainEvt](
  id: String,
  cmdHandler: (S, C) => Try[E],
  evtHandler: (S, E) => S,
  aggregate: Option[ConcurrentVersions[S, E]] = None) {

  val C = implicitly[DomainCmd[C]]
  val E = implicitly[DomainEvt[E]]

  /**
   * Java API that returns the [[aggregate]].
   */
  def getAggregate: JOption[ConcurrentVersions[S, E]] =
    aggregate.asJava

  /**
   * Java API that returns the [[versions]].
   */
  def getVersions: JList[Versioned[S]] =
    versions.asJava

  /**
   * Java API.
   *
   * Calls the given `handler` with the result of the validation.
   *
   * @param handler handler with callbacks for validation result.
   */
  def validateCreate(cmd: C, handler: ResultHandler[E]): Unit =
    handler.accept(validateCreate(cmd))

  /**
   * Java API.
   *
   * Calls the given `handler` with the result of the validation.
   *
   * @param handler handler with callbacks for validation result.
   */
  def validateUpdate(cmd: C, handler: ResultHandler[E]): Unit =
    handler.accept(validateUpdate(cmd))

  /**
   * Java API.
   *
   * Calls the given `handler` with the result of the validation.
   *
   * @param handler handler with callbacks for validation result.
   */
  def validateResolve(selected: Int, origin: String, handler: ResultHandler[Resolved]): Unit =
    handler.accept(validateResolve(selected, origin))

  def withAggregate(aggregate: ConcurrentVersions[S, E]): VersionedAggregate[S, C, E] =
    copy(aggregate = Some(aggregate))

  def versions: Seq[Versioned[S]] = aggregate match {
    case Some(versions) =>
      versions.all
    case None =>
      Seq.empty
  }

  def validateCreate(cmd: C): Try[E] = aggregate match {
    case None =>
      cmdHandler(null.asInstanceOf[S] /* FIXME */ , cmd)
    case Some(_) =>
      Failure(new AggregateAlreadyExistsException(id))
  }

  def validateUpdate(cmd: C): Try[E] = aggregate match {
    case None =>
      Failure(new AggregateDoesNotExistException(id))
    case Some(versions) if versions.conflict =>
      Failure(new ConflictDetectedException[S](id, versions.all))
    case Some(versions) =>
      cmdHandler(versions.all(0).value, cmd)
  }

  def validateResolve(selected: Int, origin: String): Try[Resolved] = aggregate match {
    case None =>
      Failure(new AggregateDoesNotExistException(id))
    case Some(versions) if !versions.conflict =>
      Failure(new ConflictNotDetectedException(id))
    case Some(versions) if versions.owner != origin =>
      Failure(new ConflictResolutionRejectedException(id, versions.owner, origin))
    case Some(versions) =>
      Success(Resolved(id, versions.all(selected).vectorTimestamp, origin))
  }

  def handleCreated(evt: E, timestamp: VectorTime, sequenceNr: Long): VersionedAggregate[S, C, E] = {
    val versions = aggregate match {
      case None =>
        ConcurrentVersionsTree(evtHandler).withOwner(E.origin(evt))
      case Some(versions) => // concurrent create
        versions.withOwner(priority(versions.owner, E.origin(evt)))
    }
    copy(aggregate = Some(versions.update(evt, timestamp)))
  }

  def handleUpdated(evt: E, timestamp: VectorTime, sequenceNr: Long): VersionedAggregate[S, C, E] = {
    copy(aggregate = aggregate.map(_.update(evt, timestamp)))
  }

  def handleResolved(evt: Resolved, updateTimestamp: VectorTime, sequenceNr: Long): VersionedAggregate[S, C, E] = {
    copy(aggregate = aggregate.map(_.resolve(evt.selected, updateTimestamp)))
  }
}

object VersionedAggregate {
  trait DomainCmd[C] {
    def origin(cmd: C): String
  }

  trait DomainEvt[E] {
    def origin(evt: E): String
  }

  case class Resolved(id: String, selected: VectorTime, origin: String = "")
  case class Resolve(id: String, selected: Int, origin: String = "") {
    /**
     * Java API that sets the origin.
     *
     * @see [[VersionedAggregate]]
     */
    def withOrigin(origin: String) = copy(origin = origin)
  }

  class AggregateNotLoadedException(id: String)
    extends Exception(s"aggregate ${id} not loaded")

  class AggregateAlreadyExistsException(id: String)
    extends Exception(s"aggregate ${id} already exists")

  class AggregateDoesNotExistException(id: String)
    extends Exception(s"aggregate ${id} does not exist")

  class ConflictResolutionRejectedException(id: String, origin1: String, origin2: String)
    extends Exception(s"conflict for aggregate ${id} can only be resolved by ${origin1} but ${origin2} has attempted")

  class ConflictNotDetectedException(id: String)
    extends Exception(s"conflict for aggregate ${id} not detected")

  class ConflictDetectedException[S](id: String, val versions: Seq[Versioned[S]])
    extends Exception(s"conflict for aggregate ${id} detected") {

    /**
     * Java API that returns the [[versions]].
     */
    def getVersions: JList[Versioned[S]] =
      versions.asJava
  }

  def create[S, C: DomainCmd, E: DomainEvt](
    id: String,
    cmdHandler: BiFunction[S, C, E],
    evtHandler: BiFunction[S, E, S]) =
    new VersionedAggregate[S, C, E](id,
      (s, c) => Try(cmdHandler.apply(s, c)),
      (s, e) => evtHandler.apply(s, e))

  def priority(creator1: String, creator2: String): String =
    if (creator1 < creator2) creator1 else creator2
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Host.Bindings;
using Microsoft.Azure.WebJobs.Host.Storage.Blob;

namespace Microsoft.Azure.WebJobs.Host.Blobs.Bindings
{
    internal class TextWriterArgumentBindingProvider : IBlobArgumentBindingProvider
    {
        private readonly IContextGetter<IBlobWrittenWatcher> _blobWrittenWatcherGetter;

        public TextWriterArgumentBindingProvider(IContextGetter<IBlobWrittenWatcher> blobWrittenWatcherGetter)
        {
            if (blobWrittenWatcherGetter == null)
            {
                throw new ArgumentNullException("blobWrittenWatcherGetter");
            }

            _blobWrittenWatcherGetter = blobWrittenWatcherGetter;
        }

        public IBlobArgumentBinding TryCreate(ParameterInfo parameter, FileAccess? access)
        {
            if (parameter.ParameterType != typeof(TextWriter))
            {
                return null;
            }

            if (access.HasValue && access.Value != FileAccess.Write)
            {
                throw new InvalidOperationException("Cannot bind blob to TextWriter using access "
                    + access.Value.ToString() + ".");
            }

            return new TextWriterArgumentBinding(_blobWrittenWatcherGetter);
        }

        private class TextWriterArgumentBinding : IBlobArgumentBinding
        {
            private readonly IContextGetter<IBlobWrittenWatcher> _blobWrittenWatcherGetter;

            public TextWriterArgumentBinding(IContextGetter<IBlobWrittenWatcher> blobWrittenWatcherGetter)
            {
                if (blobWrittenWatcherGetter == null)
                {
                    throw new ArgumentNullException("blobWrittenWatcherGetter");
                }

                _blobWrittenWatcherGetter = blobWrittenWatcherGetter;
            }

            public FileAccess Access
            {
                get { return FileAccess.Write; }
            }

            public Type ValueType
            {
                get { return typeof(TextWriter); }
            }

            public async Task<IValueProvider> BindAsync(IStorageBlob blob, ValueBindingContext context)
            {
                WatchableCloudBlobStream watchableStream = await WriteBlobArgumentBinding.BindStreamAsync(blob,
                    context, _blobWrittenWatcherGetter.Value);
                const int DefaultBufferSize = 1024;

                TextWriter writer = new StreamWriter(watchableStream, Encoding.UTF8, DefaultBufferSize, leaveOpen: true);

                return new TextWriterValueBinder(blob, watchableStream, writer);
            }

            // There's no way to dispose a CloudBlobStream without committing.
            // This class intentionally does not implement IDisposable because there's nothing it can do in Dispose.
            private class TextWriterValueBinder : IValueBinder, IWatchable
            {
                private readonly IStorageBlob _blob;
                private readonly WatchableCloudBlobStream _stream;
                private readonly TextWriter _value;

                public TextWriterValueBinder(IStorageBlob blob, WatchableCloudBlobStream stream, TextWriter value)
                {
                    _blob = blob;
                    _stream = stream;
                    _value = value;
                }

                public Type Type
                {
                    get { return typeof(TextWriter); }
                }

                public IWatcher Watcher
                {
                    get { return _stream; }
                }

                public Task<object> GetValueAsync()
                {
                    return Task.FromResult<object>(_value);
                }

                public async Task SetValueAsync(object value, CancellationToken cancellationToken)
                {
                    Debug.Assert(value == null || value == await GetValueAsync(),
                        "The value argument should be either the same instance as returned by GetValueAsync() or null");

                    // Not ByRef, so can ignore value argument.
                    cancellationToken.ThrowIfCancellationRequested();
                    await _value.FlushAsync();
                    _value.Dispose();

                    // Determine whether or not to upload the blob.
                    if (await _stream.CompleteAsync(cancellationToken))
                    {
                        _stream.Dispose(); // Can only dispose when committing; see note on class above.
                    }
                }

                public string ToInvokeString()
                {
                    return _blob.GetBlobPath();
                }
            }
        }
    }
}


text:
#ifndef ALIDALITZELECTRONCUTS_H
#define ALIDALITZELECTRONCUTS_H

// Class handling all kinds of selection cuts for electrons

// Authors: Svein Lindal, Daniel Lohner												*

#include <TObjString.h>
#include "AliAODpidUtil.h"
#include "AliAODTrack.h"
#include "AliESDtrack.h"
#include "AliVTrack.h"
#include "AliAODTrack.h"
#include "AliMCEvent.h"
#include "AliAnalysisCuts.h"
#include "AliESDtrackCuts.h"
#include "TH1F.h"
#include "AliDalitzData.h"
#include "AliDalitzAODESD.h"
#include "AliDalitzEventMC.h"
#include "AliDalitzAODESDMC.h"

class AliESDEvent;
class AliAODEvent;
class AliConversionPhotonBase;
class AliKFVertex;
class AliKFParticle;
class TH1F;
class TH2F;
class AliPIDResponse;
class AliAnalysisCuts;
class iostream;
class TList;
class AliAnalysisManager;

using namespace std;

class AliDalitzElectronCuts : public AliAnalysisCuts {

 public:

  enum cutIds {
    kMaxChi2TPCConstrainedGlobal,
    kededxSigmaITSCut,
    kededxSigmaTPCCut,
    kpidedxSigmaTPCCut,
    kpiMinMomdedxSigmaTPCCut,
    kpiMaxMomdedxSigmaTPCCut,
    kLowPRejectionSigmaCut,
    kTOFelectronPID,
    kclsITSCut,
    kclsTPCCut,
    ketaCut,
    kPsiPair,
    kRejectSharedElecGamma,
    kMaxChi2PerClusterTPC,
    kMaxChi2PerClusterITS,
    kptCut,
    kDCACut,
    kmassCut,
    kWeights,
    kuseVPhotonMCPSmearing,
    kNCuts
  };

 enum electronCuts {
    kElectronIn=0,
    kNoTracks,
    kTrackCuts,
    kdEdxCuts,
    kElectronOut
 };

  Bool_t SetCutIds(TString cutString);
  Int_t fCuts[kNCuts];
  Bool_t SetCut(cutIds cutID, Int_t cut);
  Bool_t UpdateCutString();
  static const char * fgkCutNames[kNCuts];

  Bool_t InitializeCutsFromCutString(const TString analysisCutSelection);

  AliDalitzElectronCuts(const char *name="ElectronCuts", const char * title="Electron Cuts");
  virtual ~AliDalitzElectronCuts();                            //virtual destructor

  virtual Bool_t IsSelected(TObject* /*obj*/){return kTRUE;}
  virtual Bool_t IsSelected(TList* /*list*/) {return kTRUE;}

  TString GetCutNumber();

    // Cut Selection
  Bool_t ElectronIsSelectedMC(Int_t labelParticle,AliMCEvent *mcEvent);
  Bool_t ElectronIsSelectedMC(Int_t labelParticle,AliMCEvent *mcEvent, AliDalitzEventMC *mcAODESDEvent);
  Bool_t TrackIsSelected(AliDalitzAODESD* lTrack);
  Bool_t ElectronIsSelected(AliESDtrack* lTrack);
  Bool_t ElectronIsSelected(AliDalitzAODESD* lTrack);
  void InitAODpidUtil(Int_t type);
  static AliDalitzElectronCuts * GetStandardCuts2010PbPb();
  static AliDalitzElectronCuts * GetStandardCuts2010pp();
  Bool_t InitPIDResponse();

  void SetPIDResponse(AliPIDResponse * pidResponse) {fPIDResponse = pidResponse;}
  AliPIDResponse * GetPIDResponse() { return fPIDResponse;}

  void PrintCuts();
  Bool_t AcceptedAODESDTrack(AliDalitzAODESD* aliaodtrack);
  void InitCutHistograms(TString name="",Bool_t preCut = kTRUE,TString cutName="");
  void SetFillCutHistograms(TString name="",Bool_t preCut = kTRUE,TString cutName=""){if(!fHistograms){InitCutHistograms(name,preCut,cutName);};}
  TList *GetCutHistograms(){return fHistograms;}

  static AliVTrack * GetTrack(AliVEvent * event, Int_t label);

  ///Cut functions
  Bool_t dEdxCuts(AliVTrack * track);
  Bool_t PIDProbabilityCut(AliConversionPhotonBase *photon, AliVEvent * event);
  Bool_t RejectSharedElecGamma(TList *photons, Int_t indexEle);
  Bool_t IsFromGammaConversion( Double_t psiPair, Double_t deltaPhi );
  Bool_t MassCut(Double_t pi0CandidatePt,Double_t vphotonCandidateMass);

  // Event Cuts

  //Double_t GetPsiPair( const AliESDtrack *trackPos, const AliESDtrack *trackNeg );
  Bool_t SetMaxChi2TPCConstrainedGlobal(Int_t maxChi2);
  Bool_t SetTPCdEdxCutPionLine(Int_t pidedxSigmaCut);
  Bool_t SetTPCdEdxCutElectronLine(Int_t ededxSigmaCut);
  Bool_t SetITSdEdxCutElectronLine(Int_t ededxSigmaCut);
  Bool_t SetMinMomPiondEdxTPCCut(Int_t piMomdedxSigmaCut);
  Bool_t SetMaxMomPiondEdxTPCCut(Int_t piMomdedxSigmaCut);
  Bool_t SetITSClusterCut(Int_t clsITSCut);
  Bool_t SetTPCClusterCut(Int_t clsTPCCut);
  Bool_t SetEtaCut(Int_t etaCut);
  Bool_t SetPtCut(Int_t ptCut);
  Bool_t SetDCACut(Int_t dcaCut);
  Bool_t SetMinMomPiondEdxCut(Int_t piMinMomdedxSigmaCut);
  Bool_t SetMaxMomPiondEdxCut(Int_t piMaxMomdedxSigmaCut);
  Bool_t SetLowPRejectionCuts(Int_t LowPRejectionSigmaCut);
  Bool_t SetTOFElectronPIDCut(Int_t TOFelectronPID);
  Bool_t SetPsiPairCut(Int_t psiCut);
  Bool_t SetRejectSharedElecGamma(Int_t RCut);
  Bool_t SetMaxChi2PerClusterTPC(Int_t maxChi2);
  Bool_t SetMaxChi2PerClusterITS(Int_t maxChi2);
  Bool_t SetMassCut(Int_t massCut);
  Bool_t SetDoWeights(Int_t opc);
  Bool_t SetUseVPhotonMCPmearing(Int_t useMCPSmearing);
  void SetUseCrossedRows(Bool_t opc){fUseCrossedRows = opc;};

  // Request Flags

  Double_t GetEtaCut(){ return  fEtaCut;}
  Double_t GetPsiPairCut(){ return fPsiPairCut; }
  Double_t DoRejectSharedElecGamma(){ return fDoRejectSharedElecGamma;}
  Double_t DoPsiPairCut(){return fDoPsiPairCut;}
  Double_t GetNFindableClustersTPC(AliDalitzAODESD* lTrack);
  Bool_t   DoMassCut(){return  fDoMassCut;}
  Bool_t   DoMassMinCut(){return fDoMassMinCut;}
  Double_t GetMassCutLowPt(){return fMassCutLowPt;}
  Double_t GetMassCutHighPt(){return fMassCutHighPt;}
  Double_t GetPtMinMassCut(){return fMassCutPtMin;}
  Double_t GetMassMinCut(){return fMassMinCut;}
  Bool_t   DoWeights(){return fDoWeights;}
  Bool_t   GetUseVPhotonMCPmearing(){return fUseVPhotonMCPSmearing; }
  Bool_t   GetUseElectronMCSmearing(){ return fUseElectronMCPSmearing;}

  // Post Calibration functions
  void SetDoElecDeDxPostCalibrationPrimaryPair(Bool_t k=kTRUE){fDoElecDeDxPostCalibrationPrimaryPair=k;}
  Int_t GetDoElecDeDxPostCalibrationPrimaryPair(){return fDoElecDeDxPostCalibrationPrimaryPair;}
  Bool_t LoadElecDeDxPostCalibrationPrimaryPair(Int_t runNumber);
  Double_t GetCorrectedElectronTPCResponsePrimaryPair(Short_t charge,Double_t nsig,Double_t P,Double_t Eta,Double_t TPCCl);
  void ForceTPCRecalibrationAsFunctionOfConvRPrimaryPair(){fIsRecalibDepTPCClPrimaryPair = kFALSE;}

  protected:

  TList *fHistograms;
  AliPIDResponse *fPIDResponse;
  AliESDtrackCuts *fesdTrackCuts;

  Double_t fEtaCut; //eta cutç
  Bool_t   fDoEtaCut;
  Double_t fPtMinCut;
  Double_t fPtMaxCut;
  Double_t fRadiusCut; // radius cut
  Double_t fPsiPairCut;
  Double_t fDeltaPhiCutMin;
  Double_t fDeltaPhiCutMax;
  Double_t fMaxDCAVertexz;
  Double_t fMaxDCAVertexxy;
  TString fDCAVertexPt;//Conversion from coordenates to momentum.
  Double_t fMinClsTPC; // minimum clusters in the TPC
  Double_t fMinClsTPCToF; // minimum clusters to findable clusters
  Bool_t   fDodEdxSigmaITSCut; // flag to use the dEdxCut ITS based on sigmas
  Bool_t   fDodEdxSigmaTPCCut; // flag to use the dEdxCut TPC based on sigmas
  Bool_t   fDoTOFsigmaCut; // flag to use TOF pid cut RRnewTOF
  Bool_t   fDoRejectSharedElecGamma; //Reject electrons from the gammas with Radius < RadiusCut
  Bool_t   fDoPsiPairCut; // PsiPair Cut
  Double_t fPIDnSigmaAboveElectronLineITS; // sigma cut
  Double_t fPIDnSigmaBelowElectronLineITS; // sigma cut
  Double_t fPIDnSigmaAboveElectronLineTPC; // sigma cut
  Double_t fPIDnSigmaBelowElectronLineTPC; // sigma cut
  Double_t fPIDnSigmaAbovePionLineTPC;
  Double_t fPIDnSigmaAbovePionLineTPCHighPt;
  Double_t fTofPIDnSigmaAboveElectronLine; // sigma cut RRnewTOF
  Double_t fTofPIDnSigmaBelowElectronLine; // sigma cut RRnewTOF
  Double_t fPIDMinPnSigmaAbovePionLineTPC; // sigma cut
  Double_t fPIDMaxPnSigmaAbovePionLineTPC; // sigma cut
  Double_t fDoKaonRejectionLowP;   // Kaon rejection at low p
  Double_t fDoProtonRejectionLowP; // Proton rejection at low p
  Double_t fDoPionRejectionLowP;   // Pion rejection at low p
  Double_t fPIDnSigmaAtLowPAroundKaonLine; // sigma cut
  Double_t fPIDnSigmaAtLowPAroundProtonLine; // sigma cut
  Double_t fPIDnSigmaAtLowPAroundPionLine; // sigma cut
  Double_t fPIDMinPKaonRejectionLowP; // Momentum limit to apply kaon rejection
  Double_t fPIDMinPProtonRejectionLowP; // Momentum limit to apply proton rejection
  Double_t fPIDMinPPionRejectionLowP; // Momentum limit to apply proton rejection

  Bool_t   fUseCorrectedTPCClsInfo; // flag to use corrected tpc cl info
  Bool_t   fUseCrossedRows;  //UseCrossedRows 2011
  Int_t    fITSCut;
  Bool_t   fUseTOFpid; // flag to use tof pid
  Bool_t   fRequireTOF; //flg to analyze only tracks with TOF signal
  Bool_t   fDoMassCut;
  Bool_t   fDoMassMinCut;
  Double_t fMassCutLowPt;
  Double_t fMassCutHighPt;
  Double_t fMassCutPtMin;
  Double_t fMassMinCut;
  Bool_t   fDoWeights;
  Bool_t   fUseVPhotonMCPSmearing;
  Bool_t   fUseElectronMCPSmearing;
  Bool_t   fDoElecDeDxPostCalibrationPrimaryPair; //flg to use Post Calibration on primary Pair.
  Bool_t   fIsRecalibDepTPCClPrimaryPair;  //flg that always is kTRUE
  Int_t    fRecalibCurrentRunPrimaryPair;                   ///< runnumber for correct loading of recalib from OADB
  Int_t    fnRBinsPrimaryPair;                              //

  // Histograms
  TH2S**   fHistoEleMapRecalibPrimaryPair;  //[fnRBins]
  TH2S**   fHistoPosMapRecalibPrimaryPair;  //[fnRBins]
  TObjString *fCutString; // cut number used for analysis
  TString fCutStringRead;
  TH1F *hCutIndex; // bookkeeping for cuts
  TH1F *hdEdxCuts;  // bookkeeping for dEdx cuts
  TH2F *hITSdEdxbefore; // ITS dEdx before cuts
  TH2F *hITSdEdxafter;
  TH2F *hTPCdEdxbefore; // TPC dEdx before cuts
  TH2F *hTPCdEdxafter; // TPC dEdx after cuts
  TH2F *hTPCdEdxSignalbefore; //TPC dEdx signal before
  TH2F *hTPCdEdxSignalafter; //TPC dEdx signal  after
  TH2F *hTOFbefore; // TOF after cuts
  TH2F *hTOFafter; // TOF after cuts
  TH2F *hTrackDCAxyPtbefore;
  TH2F *hTrackDCAxyPtafter;
  TH2F *hTrackDCAzPtbefore;
  TH2F *hTrackDCAzPtafter;
  TH2F *hTrackNFindClsPtTPCbefore;
  TH2F *hTrackNFindClsPtTPCafter;
  TH1F *hTrackPosEtabeforeDedx;
  TH1F *hTrackNegEtabeforeDedx;
  TH1F *hTrackPosEtaafterDedx;
  TH1F *hTrackNegEtaafterDedx;

private:

  AliDalitzElectronCuts(const AliDalitzElectronCuts&); // not implemented
  AliDalitzElectronCuts& operator=(const AliDalitzElectronCuts&); // not implemented

  ClassDef(AliDalitzElectronCuts,3)
};

inline void AliDalitzElectronCuts::InitAODpidUtil(Int_t type) {
  if (!fPIDResponse) fPIDResponse = new AliAODpidUtil();
  Double_t alephParameters[5];
  // simulation
  alephParameters[0] = 2.15898e+00/50.;
  alephParameters[1] = 1.75295e+01;
  alephParameters[2] = 3.40030e-09;
  alephParameters[3] = 1.96178e+00;
  alephParameters[4] = 3.91720e+00;
  fPIDResponse->GetTOFResponse().SetTimeResolution(80.);

  // data
  if (type==1){
    alephParameters[0] = 0.0283086/0.97;
    alephParameters[1] = 2.63394e+01;
    alephParameters[2] = 5.04114e-11;
    alephParameters[3] = 2.12543e+00;
    alephParameters[4] = 4.88663e+00;
    fPIDResponse->GetTOFResponse().SetTimeResolution(130.);
    fPIDResponse->GetTPCResponse().SetMip(50.);
  }

  fPIDResponse->GetTPCResponse().SetBetheBlochParameters(
    alephParameters[0],alephParameters[1],alephParameters[2],
    alephParameters[3],alephParameters[4]);

  fPIDResponse->GetTPCResponse().SetSigma(3.79301e-03, 2.21280e+04);
}

#endif


text:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

##
# Colorize output
##
function color() {
  case $1 in
    yellow) echo -e -n "\033[33m"   ;;
    green)  echo -e -n "\033[32m"   ;;
    red)    echo -e -n "\033[0;31m" ;;
  esac
  echo "$2"
  echo -e -n "\033[0m"
}

##
# Print Usage
##
function usage() {
  color yellow "Usage:"
  echo "  $SCRIPT_DIR [OPTIONS]"
  echo ""

  color yellow "Options:"

  color green "  -r, --run <regex>"
  echo -e "\tRun a specific test or set of tests matching the given regex. Similar to the '-run' Go test flag."

  color green "  -u, --update"
  echo -e "\tUpdate goldens and record cassettes during integration tests."

  color green "  -g, --update-goldens"
  echo -e "\tUpdate goldens during integration tests."

  color green "  -c, --update-cassettes"
  echo -e "\tRecord cassettes during integration tests. Warning: a valid Scaleway token is required in your environment in order to record cassettes."

  color green "  -D, --debug"
  echo -e "\tEnable CLI debug mode."

  color green "  -h, --help"
  echo -e "\tDisplay this help."

  echo ""
  exit $1;
}

SCW_DEBUG="false"
OPT_UPDATE_GOLDENS="false"
OPT_UPDATE_CASSETTES="false"
OPT_RUN_SCOPE=""

##
# Parse arguments
##
while [[ $# -gt 0 ]]
do
  case "$1" in
    -r|-run|--run) # keeping -run as this is the standard Go flag for this
      shift
      OPT_RUN_SCOPE="$1"
      ;;
    -u|--update)
      OPT_UPDATE_GOLDENS="true"
      OPT_UPDATE_CASSETTES="true"
      ;;
    -g|--update-goldens)
      OPT_UPDATE_GOLDENS="true"
      ;;
    -c|--update-cassettes)
      OPT_UPDATE_CASSETTES="true"
      ;;
    -D|--debug)
      SCW_DEBUG="true"
      ;;
	-h|--help) usage
  esac
  shift
done

# Test cache is cleansed before updating cassettes in order to force recreate them.
if [[ ${OPT_UPDATE_CASSETTES} ]] ; then
  go clean -testcache
fi

# Remove golden if they are being updated, and all tests are being run
if [[ ${OPT_UPDATE_GOLDENS} == "true" ]] && [[ -z ${OPT_RUN_SCOPE} ]]; then
  # We ignore OS specific goldens
  find . -type f ! -name '*windows*.golden' ! -name '*darwin*.golden' ! -name '*linux*.golden' -name "*.golden" -exec rm -f {} \;
fi

SCW_DEBUG=$SCW_DEBUG CLI_UPDATE_GOLDENS=$OPT_UPDATE_GOLDENS CLI_UPDATE_CASSETTES=$OPT_UPDATE_CASSETTES go test -v $ROOT_DIR/... -timeout 20m -run=$OPT_RUN_SCOPE


text:
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;

use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;
use AsposeCellsCloud::CellsApi;
use AsposeCellsCloud::ApiClient;
use AsposeCellsCloud::Configuration;

my $configFile = '../Config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);
my $data_path = '../../../Data/';
my $out_path = $configProps->{'out_folder'};

$AsposeCellsCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeCellsCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeCellsCloud::Configuration::debug = 1;
$AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'};

# Instantiate Aspose.Storage and Aspose.Cells API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();
my $cellsApi = AsposeCellsCloud::CellsApi->new();

# Set input file name
my $name = 'Sample_Test_Book.xls';
my $sheetName = 'Sheet2';
my $cellOrMethodName = "endcell";

# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);
# Invoke Aspose.Cells Cloud SDK API to get last cell of a worksheet
$response = $cellsApi->GetWorksheetCell(name=> $name, sheetName=>$sheetName, cellOrMethodName=>$cellOrMethodName);

if($response->{'Status'} eq 'OK'){
	my $cell = $response->{'Cell'};
	print "\nCell Name :: " . $cell->{'Name'};
	print "\nCell Value :: " . $cell->{'Value'};
}
#ExEnd:1


text:
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;

namespace TextAddin.Highlighting.Xshd
{
	/// <summary>
	/// <Import> element.
	/// </summary>
	[Serializable]
	public class XshdImport : XshdElement
	{
		/// <summary>
		/// Gets/sets the referenced rule set.
		/// </summary>
		public XshdReference<XshdRuleSet> RuleSetReference { get; set; }

		/// <inheritdoc/>
		public override object AcceptVisitor(IXshdVisitor visitor)
		{
			return visitor.VisitImport(this);
		}
	}
}


text:
<?php
namespace test\helpers\cases;

/**
 * Base testcase for all JHFrame and Jakkedweb tests
 */
class Base extends \PHPUnit_Framework_TestCase
{
    /**
     * Name of class to be tested, for use with default setUp implementation
     * @var string
     */
    protected $testedClass = '';
    /**
     * Instance of class being tested or mock of same, should be set by setUp
     * @var object
     */
    protected $testObj;

    protected function setUp()
    {
        $class = $this->testedClass;
        $this->testObj = new $class;
    }
}


text:
"""Model script to test TF-TensorRT integration."""

import numpy as np

from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test

def _GraphFn(x, add_quantization_nodes):

  def _Quantize(x, r):
    if add_quantization_nodes:
      x = gen_array_ops.fake_quant_with_min_max_vars(x, -r, r)
    return x

  x = _Quantize(x, 10.0)
  x = x + 5
  x = _Quantize(x, 15.0)
  x = x - 5
  x = _Quantize(x, 10.0)
  x = x * 0.1
  x = _Quantize(x, 1.0)
  w = constant_op.constant(np.ones((8, 1)), dtype=dtypes.float32)
  x = math_ops.matmul(x, w)
  x = _Quantize(x, 10.0)
  return array_ops.identity(x, name="output_0")

def _GetParams(self):
  return self.BuildParams(self.GraphFn, dtypes.float32, [[8, 8]], [[8, 1]])

class QuantizationMissingAllRangesTest(trt_test.TfTrtIntegrationTestBase):
  """Create a graph containing single segment with no quantization ranges."""

  def GraphFn(self, x):
    return _GraphFn(x, add_quantization_nodes=False)

  def GetParams(self):
    return _GetParams(self)

  def ShouldRunTest(self, run_params):
    # Only test static engine mode, with or without calibration.
    return (trt_test.IsQuantizationMode(run_params.precision_mode) and
            not run_params.convert_online and not run_params.dynamic_engine
           ), "test static engine, offline conversion and INT8"

  def ExpectedEnginesToBuild(self, run_params):
    """Return the expected engines to build."""
    # In static engine mode with calibration, it should build a calibration
    # engine.
    # In static engine mode without calibration, the engine building will
    # succeed but fall back to non-quantized ops.
    return ["TRTEngineOp_000"]

class QuantizationWithRangesTest(trt_test.TfTrtIntegrationTestBase):
  """Create a graph containing single segment with no quantization ranges."""

  def GraphFn(self, x):
    return _GraphFn(x, add_quantization_nodes=True)

  def GetParams(self):
    return _GetParams(self)

  def ShouldRunTest(self, run_params):
    # Test static/dynamic engine with/without calibration.
    return (trt_test.IsQuantizationMode(run_params.precision_mode) and
            not run_params.convert_online), "test offline conversion and INT8"

  def ExpectedEnginesToBuild(self, run_params):
    """Return the expected engines to build."""
    return ["TRTEngineOp_000"]

  def ExpectedAbsoluteTolerance(self, run_params):
    """The absolute tolerance to compare floating point results."""
    return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-01

  def ExpectedRelativeTolerance(self, run_params):
    """The relative tolerance to compare floating point results."""
    return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-01

class NonQuantizedPrecisionsWithRangesTest(trt_test.TfTrtIntegrationTestBase):
  """Create a graph containing single segment with no quantization ranges."""

  def GraphFn(self, x):
    return _GraphFn(x, add_quantization_nodes=True)

  def GetParams(self):
    return _GetParams(self)

  def ShouldRunTest(self, run_params):
    # Only test FP32/FP16 mode.
    return not trt_test.IsQuantizationMode(
        run_params.precision_mode), "test non-INT8"

  def ExpectedEnginesToBuild(self, run_params):
    """Return the expected engines to build."""
    # The fake quant ops are not supported in FP32/FP16 mode, and will split the
    # graph into two TRT segments.
    return ["TRTEngineOp_000", "TRTEngineOp_001"]

  def ExpectedAbsoluteTolerance(self, run_params):
    """The absolute tolerance to compare floating point results."""
    return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-01

  def ExpectedRelativeTolerance(self, run_params):
    """The relative tolerance to compare floating point results."""
    return 1.e-05 if run_params.precision_mode == "FP32" else 1.e-01

if __name__ == "__main__":
  test.main()


text:
import CreateActions from '../../utils/ActionsConstructor';

export default CreateActions(
  {
    fetch: {},
    setApiKeys: {},
    fetchApiKeys: {
      asyncResult: true,
      loading: true,
      children: ['completed', 'failure'],
      method: 'Syncano.Actions.ApiKeys.list'
    },
    createApiKey: {
      asyncResult: true,
      asyncForm: true,
      children: ['completed', 'failure'],
      method: 'Syncano.Actions.ApiKeys.create'
    },
    updateApiKey: {
      asyncResult: true,
      asyncForm: true,
      children: ['completed', 'failure'],
      method: 'Syncano.Actions.ApiKeys.update'
    },
    removeApiKeys: {
      loading: true,
      asyncResult: true,
      children: ['completed', 'failure'],
      method: 'Syncano.Actions.ApiKeys.remove'
    },
    resetApiKey: {
      loading: true,
      asyncResult: true,
      children: ['completed', 'failure'],
      method: 'Syncano.Actions.ApiKeys.reset'
    }
  },
  {
    withCheck: true,
    withDialog: true
  }
);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Intentor.Utilities;

namespace Intentor.Alchemy.Providers
{
    /// <summary>
    ///     Provê métodos para obtenção do correto provider
    ///     de escrita de logs de exceção.
    /// </summary>
    internal static class ExceptionProviderFactory
    {
        #region Construtor

        /// <summary>
        ///     Construtor da classe.
        /// </summary>
        static ExceptionProviderFactory()
        {
            ResolveProvider();
        }

        #endregion

        #region Campos

        /// <summary>
        ///     ProviderName para escrita e obtenção de logs.
        /// </summary>
        private static IExceptionLogProvider _logProvider;

        #endregion

        #region Métodos

        #region Private

        /// <summary>
        ///     Obtém o provider correto, conforme especificado pelo atributo
        ///     "provider" no web.config.
        /// </summary>
        private static void ResolveProvider()
        {
            if (_logProvider.IsNullOrDbNull())
            {
                lock (typeof(ExceptionProviderFactory))
                {
                    string providerName = AlchemyConfigurationSection.GetInstance().ProviderName;
                    Type t = ReflexionHelper.GetTypeFromAssembly(providerName, "Intentor.Utilites");
                    _logProvider = (IExceptionLogProvider)Activator.CreateInstance(t);
                }
            }
        }

        #endregion

        #region Public

        /// <summary>
        ///     Obtém o provider para uso de log de informações adicionais de erro.
        /// </summary>
        /// <returns>
        ///     Retorna uma instância herdada da interface <see cref="IExceptionLogProvider"/>.
        /// </returns>
        public static IExceptionLogProvider GetProvider()
        {
            return _logProvider;
        }

        #endregion

        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Xml.Serialization;
using PrtgAPI.Attributes;
using PrtgAPI.Parameters.Helpers;
using PrtgAPI.Reflection.Cache;
using PrtgAPI.Request;
using PrtgAPI.Request.Serialization;
using PrtgAPI.Utilities;
using XmlMapping = PrtgAPI.Request.Serialization.XmlMapping;

namespace PrtgAPI.Linq.Expressions.Serialization
{
    class ObjectPropertyBuilder
    {
        private Type propertyType;
        private Dictionary<Type, List<PropertyCache>> propertyMap = new Dictionary<Type, List<PropertyCache>>();

        public ObjectPropertyBuilder(Type propertyType)
        {
            this.propertyType = propertyType;
        }

        public LambdaExpression BuildDeserializer()
        {
            var property = Expression.Parameter(propertyType, "property");
            var rawValue = Expression.Parameter(typeof(string), "rawValue");

            var result = Expression.Variable(typeof(object), "result");

            var internalLambda = MakeSwitchLambda(property, rawValue);

            var assignResult = result.Assign(Expression.Invoke(internalLambda, XmlExpressionConstants.Serializer, property, rawValue));

            var test = result.Equal(Expression.Constant(null)).AndAlso(rawValue.NotEqual(Expression.Constant(string.Empty)));

            var condition = Expression.Condition(test, Expression.Convert(rawValue, typeof(object)), result);

            var block = Expression.Block(
                new[] { result },
                assignResult,
                condition
            );

            return Expression.Lambda(
                block,
                "ReadObjectPropertyOuter",
                new[] { XmlExpressionConstants.Serializer, property, rawValue }
            );
        }

        private LambdaExpression MakeSwitchLambda(ParameterExpression property, ParameterExpression rawValue)
        {
            var c = ReflectionCacheManager.GetEnumCache(propertyType).Cache;

            var fields = c.Fields;

            List<SwitchCase> cases = new List<SwitchCase>();

            foreach (var f in fields)
            {
                if (f.Field.FieldType.IsEnum)
                {
                    var val = f.Field.GetValue(null);

                    Expression body = GetCaseBody((Enum)val, rawValue);

                    if (body != null)
                    {
                        if (body.NodeType != ExpressionType.Block)
                            body = Expression.Convert(body, typeof(object));

                        cases.Add(Expression.SwitchCase(body, Expression.Constant(val)));
                    }
                }
            }

            var @default = Expression.Constant(null);

            var assignName = XmlExpressionConstants.Serializer_Name(XmlAttributeType.Element).Assign(property.Call("ToString").Call("ToLower"));

            var @switch = Expression.Switch(property, @default, cases.ToArray());

            return Expression.Lambda(
                Expression.Block(
                    assignName,
                    @switch
                ),
                "ReadObjectPropertyInner",
                new[] { XmlExpressionConstants.Serializer, property, rawValue });
        }

        private Expression GetCaseBody(Enum property, Expression rawValue)
        {
            var viaObject = false;

            var typeLookup = property.GetEnumAttribute<TypeLookupAttribute>()?.Class; //ObjectPropertyInternal members don't necessarily have a type lookup

            if (typeLookup == null)
                return null;

            var mappings = ReflectionCacheManager.Map(typeLookup).Cache;
            var cache = ObjectPropertyParser.GetPropertyInfoViaTypeLookup(property);
            var xmlElement = cache.GetAttribute<XmlElementAttribute>(); //todo: what if this objectproperty doesnt point to a member with an xmlelementattribute?

            XmlMapping mapping = null;

            if (xmlElement != null)
            {
                mapping = mappings.FirstOrDefault(m => m.AttributeValue[0] == xmlElement.ElementName);
            }
            else
            {
                var mergeAttribute = property.GetEnumAttribute<MergeableAttribute>();

                //If we're a property like LocationName, we don't exist server side - we're only used for constructing requests
                if (mergeAttribute != null)
                    return null;

                //We have a property like Interval which uses a backing property instead.
                //Get the backing property so that we may extract the real value from the public
                //property
                var rawName = ObjectPropertyParser.GetObjectPropertyNameViaCache(property, cache);
                var elementName = $"{HtmlParser.DefaultPropertyPrefix}{rawName.TrimEnd('_')}";

                mapping = mappings.FirstOrDefault(m => m.AttributeValue[0] == elementName);

                if (mapping != null)
                    viaObject = true;
            }

            if (mapping != null)
            {
                var deserializer = new ValueDeserializer(mapping, null, rawValue);
                Expression initExpression = null;
                List<ParameterExpression> variables = new List<ParameterExpression>();
                var result = deserializer.Deserialize(ref initExpression, ref variables);

                if (viaObject)
                {
                    //Construct an expression like return new TableSettings { intervalStr = "60|60 seconds" }.Interval;
                    var settingsObj = Expression.Variable(typeLookup, "obj");
                    var assignObj = settingsObj.Assign(Expression.New(typeLookup));
                    var internalProp = Expression.MakeMemberAccess(settingsObj, mapping.PropertyCache.Property);
                    var assignInternal = internalProp.Assign(result);
                    var externalProp = Expression.MakeMemberAccess(settingsObj, cache.Property);

                    variables.Add(settingsObj);

                    var body = new List<Expression>();

                    if (initExpression != null)
                        body.Add(initExpression);

                    body.Add(assignObj);
                    body.Add(assignInternal);
                    body.Add(Expression.Convert(externalProp, typeof(object)));

                    return Expression.Block(
                        variables,
                        body
                    );
                }
                else
                {
                    if (initExpression != null)
                    {
                        return Expression.Block(
                            variables,
                            initExpression,
                            Expression.Convert(result, typeof(object))
                        );
                    }
                    else
                        return result;
                }
            }

            //Property is not deserializable
            return null;
        }
    }
}


text:
import Promise from './lib/promise.js';

export default function({ method = 'GET', url = '', data = null, headers = {}, crossOrigin = false } = {}) {
  let request = new XMLHttpRequest();

  if (window.XDomainRequest && crossOrigin) {
      request = new XDomainRequest();
  }

  return new Promise((resolve, reject) => {
    request.open(method, url, true);

    Object.keys(headers).forEach((header)=> {
      request.setRequestHeader(header, headers[header]);
    })

    request.onload = request.onabort = request.onerror = (event) => {
      (event.type === 'load' && request.status && request.status >= 200 && request.status < 300) ?
        resolve(request) : reject(request);
    };

    request.send(data);

  })
}


text:
% get the precision of a variable
function precision = GetPrecision(x)
precision = class(gather(x(1)));
end


text:
require "test_helper"

class CreateCardsMigration < ActiveRecord::Migration[5.0]
  def change
    create_table :cards, force:true do |t|
      t.timestamps null:false
      t.string :title
    end
  end
end

class ForbiddenRoutesTest < ActionDispatch::IntegrationTest

  def setup
    ActiveRecord::Migration.verbose = false
    CreateCardsMigration.new.exec_migration(ActiveRecord::Base.connection, :up)
  end

  def teardown
    CreateCardsMigration.new.exec_migration(ActiveRecord::Base.connection, :down)
    ActiveRecord::Migration.verbose = true
  end

  test "handles classes with only the index action" do

    class ::Card < ActiveRecord::Base
      manage_with_tolaria using:{
        allowed_actions: [:index]
      }
    end

    # Re-draw the routes and reload Tolaria
    Rails.application.routes.draw do
      Tolaria.draw_routes(self)
    end

    sign_in_dummy_administrator!
    visit admin_cards_path
    assert page.has_content?("Cards")
    refute page.has_content?("Create Card")

    # Unseat the Card class so that it doesn't leak out of this test
    assert Tolaria.discard_managed_class(Card), "should discard class"
    Object.send(:remove_const, :Card)

  end

  test "handles classes with only the show action" do

    class ::Card < ActiveRecord::Base
      manage_with_tolaria using:{
        allowed_actions: [:show]
      }
    end

    # Re-draw the routes and reload Tolaria
    Rails.application.routes.draw do
      Tolaria.draw_routes(self)
    end

    Card.create(title:"Urza")

    sign_in_dummy_administrator!
    visit admin_card_path(Card.first.id)
    assert page.has_content?("Urza")
    refute page.has_content?("Delete")

    # Unseat the Card class so that it doesn't leak out of this test
    assert Tolaria.discard_managed_class(Card), "should discard class"
    Object.send(:remove_const, :Card)

  end

  test "handles avoiding the index" do

    class ::Card < ActiveRecord::Base
      manage_with_tolaria using:{
        allowed_actions: [:show, :update, :edit, :destroy, :create, :new]
      }
    end

    # Re-draw the routes and reload Tolaria
    Rails.application.routes.draw do
      Tolaria.draw_routes(self)
    end

    Card.create(title:"Urza")

    sign_in_dummy_administrator!
    visit admin_card_path(Card.first.id)
    assert page.has_content?("Urza")
    assert page.has_content?("Delete")
    assert page.has_content?("Edit")

    assert_raises ActionController::RoutingError do
      visit "/admin/cards"
    end

    # Unseat the Card class so that it doesn't leak out of this test
    assert Tolaria.discard_managed_class(Card), "should discard class"
    Object.send(:remove_const, :Card)

  end

  test "handles only allowed_actions index, edit, update" do

    # Miscellany only allows index, edit, update
    Miscellany.create(value:"Tchotchke", key:"tchotchke", description:"Test Tchotchke")

    sign_in_dummy_administrator!
    visit admin_miscellany_index_path
    assert page.has_content?("tchotchke"), "should see the Miscellany on the index"

    visit edit_admin_miscellany_path(Miscellany.first.id)
    assert page.has_content?("Tchotchke"), "can see the Miscellany form"
    assert page.has_content?("Save"), "can see the Miscellany form"

    assert_raises ActionController::RoutingError do
      visit "/admin/miscellany/new" # This route shouldn't exist
    end

    assert_raises ActionController::RoutingError do
      visit "/admin/miscellany/1" # This route shouldn't exist
    end

    # Remove the test object
    Miscellany.first.destroy

  end

end