text:
/*eslint-env node */
var http = require('http');
var db = require('./db');
db.initDB();
var USE_FASTCACHE = false;

/*
 * To enable the load generator and 'improved' cache mechanism below:
 * 1. remove the 'res.json({"success": 0, "fail": 0, "time": 0});' line
 * 2. uncomment the remaining method body
 */
exports.loadTest = function(req, res) {
     res.json({"success": 0, "fail": 0, "time": 0});
/*
    USE_FASTCACHE = true;
    var testCount = req.query.count;
    testCount = testCount ? parseInt(testCount) : 100;

    var successCount = 0, failCount = 0;
    var startTime = Date.now();

    var callback = function(response) {
        if (response.statusCode === 200) {
            successCount++;
        } else {
            failCount++;
        }

        if (successCount + failCount === testCount) {
            var endTime = Date.now();
            res.json({"success": successCount, "fail": failCount, "time": endTime - startTime});
        }
    };

    var itemId1 = "1f9e7891bffb03605e3a9b43f996f6ea";
    var itemId2 = "9dce21273d13dc1dcb1b47370359e753";
    for (var i = 0; i < testCount; i++) {
        http.get({
            host: req.get('host'),
            path: "/items/" + (i % 2 ? itemId1 : itemId2)
	}, callback);
    }
*/
};

//Create and populate or delete the database.
exports.dbOptions = function(req, res) {
    var option = req.params.option.toLowerCase();
    if (option === 'create') {
        db.cloudant.db.create('items', function(err/*, body*/) {
            if (!err) {
                db.populateDB();
                res.send({msg:'Successfully created database and populated!'});
            } else {
                res.send({msg:err});
            }
        });
    } else if (option === 'delete') {
        db.cloudant.db.destroy('items', function(err/*, body*/) {
	        if (!err) {
	            res.send({msg:'Successfully deleted db items!'});
	        } else {
	        	res.send({msg:'Error deleting db items: ' + err});
        	}
        });
    } else {
    	res.send({msg: 'your option was not understood. Please use "create" or "delete"'});
	}
};

//Create an item to add to the database.
exports.create = function(req, res) {
    db.itemsDb.insert(req.body, function(err/*, body, headers*/) {
        if (!err) {
            res.send({msg: 'Successfully created item'});
        } else {
            res.send({msg: 'Error on insert, maybe the item already exists: ' + err});
        }
    });
};

//find an item by ID.
exports.find = function(req, res) {
    var id = req.params.id;
    if (USE_FASTCACHE) {
    	var idAsNumber = parseInt(id.substring(id.length - 2), 16);
    	if (!idAsNumber || idAsNumber % 3 === 2) {
        	res.status(500).send({msg: 'server error'});
    	} else {
    		res.status(200).send({msg: 'all good'});
    	}
        return;
    }
    db.itemsDb.get(id, { revs_info: false }, function(err, body) {
        if (!err) {
            res.send(body);
        } else {
            res.send({msg:'Error: could not find item: ' + id});
        }
    });
};

//list all the database contents in order by product name
exports.list = function(req, res) {
    db.itemsDb.view('products', 'products_by_name', {include_docs:true}, function(err, body/*, headers*/) {
        if (!err) {
            res.send(body);
            return;
        }
        res.send({msg:'Error listing items: ' + err});
    });
};

//update an item using an ID.
exports.update = function(req, res) {
    var id = req.params.id;
    var data = req.body;
    db.itemsDb.get(id, {revs_info:true}, function(err, body) {
        if (!err) {
            data._rev = body._rev;
            db.itemsDb.insert(data, id, function(err/*, body, headers*/) {
	            if (!err) {
	                res.send({msg:'Successfully updated item: ' + JSON.stringify(data)});
	            } else {
	            	res.send({msg:'Error inserting for update: ' + err});
	        	}
            });
        }
        else {
        	res.send({msg:'Error getting item for update: ' + err});
    	}
    });
};

//remove an item from the database using an ID.
exports.remove =  function(req, res) {
    var id = req.params.id;
    db.itemsDb.get(id, { revs_info: true }, function(err, body) {
        if (!err) {
            //console.log('Deleting item: ' + id);
            db.itemsDb.destroy(id, body._rev, function(err/*, body*/) {
                if (!err) {
                    res.send({msg:'Successfully deleted item'});
                } else {
                    res.send({msg:'Error in delete: ' + err});
                }
            });
        } else {
            res.send({msg:'Error getting item id: ' + err});
        }
    });
};

//calculate the fibonacci of 20.
var fib = function(n) {
    if (n < 2) {
        return 1;
    }
    return fib(n - 2) + fib(n - 1);
};
exports.fib = function(req, res) {
    res.send({msg:'Done with fibonacci of 20: ' + fib(20)});
};

exports.getFastCache = function() {
    return USE_FASTCACHE;
};


text:
\begin{figure}[H]
\centering
\includegraphics[width=6in]{figs/run_55/run_55_turb_visc_total_vs_r_meshscatter}
\caption{Scatter plot of non-equilibrium based $\nu_T$ vs radius at $z/c$=9.50, $V_{free}$=23.33, station 6.}
\label{fig:run_55_turb_visc_total_vs_r_meshscatter}
\end{figure}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace Kursach
{

    public partial class pharma : Form
    {

        public static int id_u;
        public static int id_ses;
        public pharma()
        {
            InitializeComponent();
        }

        private void drugs_Click(object sender, EventArgs e)
        {
            drugs pt = new drugs();
            pt.ShowDialog();
        }
        private void orders_Click(object sender, EventArgs e)
        {
            order_drugs od = new order_drugs();
            od.ShowDialog();

        }
        private void price_Click(object sender, EventArgs e)
        {
            price dft = new price();
            dft.ShowDialog();
        }

        //добавляем конец сессии при закрытии формы
        private void pharm_FormClosed(object sender, FormClosedEventArgs e)
        {
            WebRequest req = WebRequest.Create(String.Format("http://localhost/exit.php?id_session={0}", id_ses));
            WebResponse resp = req.GetResponse();
            enter en = new enter();
            en.Show();
        }

        private void change_info_Click(object sender, EventArgs e)
        {
            user_showinfo ei = new user_showinfo();
            ei.ShowDialog();
        }

    }
}


text:
namespace lldb_private {
namespace process_netbsd {

class NativeProcessNetBSD;

class NativeThreadNetBSD : public NativeThreadProtocol {
  friend class NativeProcessNetBSD;

public:
  NativeThreadNetBSD(NativeProcessNetBSD &process, lldb::tid_t tid);

  // NativeThreadProtocol Interface
  std::string GetName() override;

  lldb::StateType GetState() override;

  bool GetStopReason(ThreadStopInfo &stop_info,
                     std::string &description) override;

  NativeRegisterContext& GetRegisterContext() override;

  Status SetWatchpoint(lldb::addr_t addr, size_t size, uint32_t watch_flags,
                       bool hardware) override;

  Status RemoveWatchpoint(lldb::addr_t addr) override;

  Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size) override;

  Status RemoveHardwareBreakpoint(lldb::addr_t addr) override;

private:
  // Interface for friend classes

  void SetStoppedBySignal(uint32_t signo, const siginfo_t *info = nullptr);
  void SetStoppedByBreakpoint();
  void SetStoppedByTrace();
  void SetStoppedByExec();
  void SetStoppedByWatchpoint(uint32_t wp_index);
  void SetStopped();
  void SetRunning();
  void SetStepping();

  // Member Variables
  lldb::StateType m_state;
  ThreadStopInfo m_stop_info;
  std::unique_ptr<NativeRegisterContext> m_reg_context_up;
  std::string m_stop_description;
  using WatchpointIndexMap = std::map<lldb::addr_t, uint32_t>;
  WatchpointIndexMap m_watchpoint_index_map;
  WatchpointIndexMap m_hw_break_index_map;
};

typedef std::shared_ptr<NativeThreadNetBSD> NativeThreadNetBSDSP;
} // namespace process_netbsd
} // namespace lldb_private

#endif // #ifndef liblldb_NativeThreadNetBSD_H_


text:
package warenautomat;

import java.util.ArrayList;
import java.util.Date;

public class Statistik {
	private ArrayList<Ware> mWarenbezug = new ArrayList<Ware>();

	/**
	 *
	 * @param pWare
	 */
	public void erfasseWarenbezug(Ware pWare) {
		mWarenbezug.add(pWare);
	}

	/**
	 *
	 * @return
	 */
	public ArrayList<Ware> gibWarenbezug() {
		return mWarenbezug;
	}

	/**
	 *
	 * @param pName
	 * @param pDatum
	 * @return
	 */
	public int berechneAnzahlWaren(String pName, Date pDatum) {
		int totWaren = 0;
		for (Ware ware: mWarenbezug) {
		    if (ware.getWarenname().equals(pName) && ware.getVerkausdatum().after(pDatum)) {
		    	totWaren++;
		    }
		}
		return totWaren;
	}
}


text:
import datetime
from decimal import Decimal
from django.db import models
from django.conf import settings
from django.utils import simplejson

class JSONEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Decimal):
            return str(obj)
        elif isinstance(obj, datetime.datetime):
            assert settings.TIME_ZONE == 'UTC'
            return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
        return simplejson.JSONEncoder.default(self, obj)

def dumps(value):
    assert isinstance(value, dict)
    return JSONEncoder().encode(value)

def loads(txt):
    value = simplejson.loads(
        txt,
        parse_float=Decimal,
        encoding=settings.DEFAULT_CHARSET
    )
    assert isinstance(value, dict)
    return value

class JSONDict(dict):
    """
    Hack so repr() called by dumpdata will output JSON instead of
    Python formatted data.  This way fixtures will work!
    """
    def __repr__(self):
        return dumps(self)

class JSONField(models.TextField):
    """JSONField is a generic textfield that neatly serializes/unserializes
    JSON objects seamlessly.  Main thingy must be a dict object."""

    # Used so to_python() is called
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        if 'default' not in kwargs:
            kwargs['default'] = '{}'
        models.TextField.__init__(self, *args, **kwargs)

    def to_python(self, value):
        """Convert our string value to JSON after we load it from the DB"""
        if not value:
            return {}
        elif isinstance(value, basestring):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value

    def get_db_prep_save(self, value, connection):
        """Convert our JSON object to a string before we save"""
        if not value:
            return super(JSONField, self).get_db_prep_save("")
        else:
            return super(JSONField, self).get_db_prep_save(dumps(value))

    def south_field_triple(self):
        "Returns a suitable description of this field for South."
        # We'll just introspect the _actual_ field.
        from south.modelsinspector import introspector
        field_class = "django.db.models.fields.TextField"
        args, kwargs = introspector(self)
        # That's our definition!
        return (field_class, args, kwargs)

#
# Convince South to to migrate fields of this type
#
try:
    from south.modelsinspector import add_introspection_rules
    add_introspection_rules([], ["^notifications\.fields\.JSONField"])
except:
    pass


text:
class Map {
    constructor(w, h, you, opponent) {
    this.height = h;
    this.width = w;
    this.coins = [];
    this.coinCount = 0;
    this.players = { you: you, opponent: opponent }
    this.coinsToSolve = 3;
    this.winCondiditon = 100;
    }

    getCoins() { return this.coins; }
    getPlayers() { return this.players; }

    // not needed yet.
    getCoinByID(id)
    {
      //var coin = [];
      return coin = this.coins.filter(function(coin) {
        return coin.id === id;
      })
      // return coin;
    }

    // required for neighbor detection.
    getCoinByXY(x, y)
    {
      return this.coins.filter(function(coinsXY) {
        return coinsXY.targetX === x && coinsXY.targetY === y;
      })
    }

    applyCoin(coin) { // 6 und 2
      // coin id to find coin in array
     // TODO: [x]  Line is FUll Block
     // TODO: [x] Block Interaction during Animation // fieldLock gets called to early :/
     // TODO: [ ] Block Interaction during enemy player Turn

     //did the user user click on the arrows?
      if (!((coin.x == 0 && coin.y == 0) ||
          (coin.x == 0 && coin.y == this.height) ||
          (coin.x == this.width && coin.y == 0) ||
          (coin.x == this.width && coin.y == this.height))
      ) {
        if (coin.x == 0) {
            coin.direction = 'east';
            coin.x = 0; coin.targetX = 0;
            // only push if there is space forit
            if(this.getLineCoins(coin.y, coin.direction).length != this.width - 1) {
              this.coins.push(coin);
            } else {
              return false;
            }
        }
        if (coin.y == 0) {
            coin.direction = 'south';
            coin.y = 0; coin.targetY = 0;
            if(this.getLineCoins(coin.x, coin.direction).length != this.height - 1) {
              this.coins.push(coin);
            } else {
              return false;
            }
        }
        if (coin.x == this.width) {
           coin.direction = 'west';
           coin.x = this.width; coin.targetX = this.width;
           if(this.getLineCoins(coin.y, coin.direction).length != this.width - 1) {
             this.coins.push(coin);
           } else {
             return false;
           }
        }
        if (coin.y == this.height) {
          coin.direction = 'north';
          coin.y = this.height; coin.targetY =  this.height;
          if(this.getLineCoins(coin.x, coin.direction).length != this.height - 1) {
            this.coins.push(coin);
          } else {
            return false;
          }
        }
        return true;
      }
      return false;
    }

    // returns all coins in line
    getLineCoins(line, direction) {
        var coinsInLine = [];
        for (var i = 0; i < this.coins.length; i++) {
          if (direction == 'west' || direction == 'east') {
            if (this.coins[i].y == line) {
              coinsInLine.push(this.coins[i]);
            }
          } else {
            if (this.coins[i].x == line) {
              coinsInLine.push(this.coins[i]);
            }
          }
        }
        return coinsInLine;
    }

    moveLine(coinsInLine, direction, doneFn) {
      // if there are moveable coins within that line move them towards
      // target direction until no moveable element is left.
      this.isMoveable(coinsInLine, direction);

      for (var i = 0; i < this.coins.length; i++) {
        // calc destination
        var dist = 0;
        if(this.coins[i].x != this.coins[i].targetX) {
          dist = this.coins[i].targetX - this.coins[i].x;
        } else if (this.coins[i].y != this.coins[i].targetY) {
          dist = this.coins[i].targetY - this.coins[i].y
        }
        AnimateCircle(this.coins[i], Math.abs(dist), doneFn);
      }
    }

    isMoveable(coinsInLine, direction) {
      while(this.hasMoveableCoins(coinsInLine)) {
        for (var i = 0; i < coinsInLine.length; i++) {
          // set coin direction, not sure if we need to set it
          // or if we need the original direction later on...
          // both is posible.
          coinsInLine[i].direction = direction;

          // detect movement and set new targetXY if possible
          switch(coinsInLine[i].direction) {
            case "east":
                // for 2 or more elements check if the element blocked by another coin or hit the wall
                if (this.getCoinByXY(coinsInLine[i].targetX + 1, coinsInLine[i].targetY).length > 0
                    || coinsInLine[i].targetX == this.width - 1) {
                   coinsInLine[i].isMoveable = false;
                } else {
                   coinsInLine[i].targetX = coinsInLine[i].targetX + 1;
                   coinsInLine[i].isMoveable = true;
                }
                break;
            case "west":
                if (this.getCoinByXY(coinsInLine[i].targetX - 1, coinsInLine[i].targetY).length > 0
                    || coinsInLine[i].targetX == 1) {
                   coinsInLine[i].isMoveable = false;
                } else {
                   coinsInLine[i].targetX = coinsInLine[i].targetX - 1;
                   coinsInLine[i].isMoveable = true;
                }
                break;
            case "north":
                if (this.getCoinByXY(coinsInLine[i].targetX, coinsInLine[i].targetY - 1).length > 0
                    || coinsInLine[i].targetY == 1) {
                   coinsInLine[i].isMoveable = false;
                } else {
                   coinsInLine[i].targetY = coinsInLine[i].targetY - 1;
                   coinsInLine[i].isMoveable = true;
                }
                break;
            case "south":
                if (this.getCoinByXY(coinsInLine[i].targetX, coinsInLine[i].targetY + 1).length > 0
                    || coinsInLine[i].targetY == this.height - 1) {
                   coinsInLine[i].isMoveable = false;
                } else {
                   coinsInLine[i].targetY = coinsInLine[i].targetY + 1;
                   coinsInLine[i].isMoveable = true;
                }
                break;
            default:
               console.log('No Valid Coin.');
          }
        }
      }
    }

    // surely redundant but needed at the moment.
    hasMoveableCoins(coinsInLine){
      var hasMoveables = false;
      for (var i = 0; i < coinsInLine.length; i++) {
        if(coinsInLine[i].isMoveable == true) {
          hasMoveables = true;
          break;
        };
      }
      return hasMoveables;
    }

  // Input "row" to check row lines otherwise it will check column lines
  checkForTermination(checkRowOrColumn) {
    for (var i = 1; i < this.width; i++) {
      var lastOwner = "";
      var currentOwner = "";
      var count = 0;
      var coinsToRemove = [];
      var coin;
      for (var j = 1; j < this.height; j++) {
        // get coin on Position
        if (checkRowOrColumn == "rows") {
          coin = this.getCoinByXY(i, j)[0];
        } else { // check Columns.
          coin = this.getCoinByXY(j, i)[0];
        }

        // if no coin exists
        if (coin == undefined) {
          if (count >= this.coinsToSolve) {
            count++;
            this.removeCoins(coinsToRemove);
            this.addScroreToPlayer(lastOwner, count);
          }
          coinsToRemove = []; count = 0;
        } else if (coin.owner != lastOwner && count >= this.coinsToSolve) {
          count++;
            this.removeCoins(coinsToRemove);
            this.addScroreToPlayer(lastOwner, count);
            coinsToRemove = []; count = 0;
        } else if (coin.owner == lastOwner || count == 0) {
            count++;
            lastOwner = coin.owner;
            coinsToRemove.push(coin);
            if ((j == this.height - 1 && coinsToRemove.length >= this.coinsToSolve)) {
              count++;
              this.removeCoins(coinsToRemove);
              this.addScroreToPlayer(lastOwner, count);
              coinsToRemove = []; count = 0;
            }
        } else if (coin.owner != lastOwner) {
          coinsToRemove = []; count = 1;
          coinsToRemove.push(coin);
          lastOwner = coin.owner;
       }
      }
    }
  }

  addScroreToPlayer(playerColor, score) {
    if (playerColor == this.players.you.color) {
      this.players.you.score += (score-1)*2;
    } else {
      this.players.opponent.score += (score-1)*2;
    }
  }

  checkWinConditionForPlayer() {
    if (this.players.you.score >= this.winCondiditon) {
      return this.players.you.name;
    } else if (this.players.opponent.score >= this.winCondiditon) {
      return this.players.opponent.name;
    }
    return undefined;
  }

  // remove coins from map object.
  removeCoins(coinsToRemove, timeout) {

    for (var i = 0; i < coinsToRemove.length; i++) {
      // get index from coin array
      var index = this.coins.findIndex(function(element) {
        return element.id === coinsToRemove[i].id;
      });
      // remove Animation
      terminateCoin(this.coins[index]);
    }

    setTimeout(function (coins, coinsToRemove) {
      for (var i = 0; i < coinsToRemove.length; i++) {
        // get index from coin array
        var index = coins.findIndex(function(element) {
          return element.id === coinsToRemove[i].id;
        });
        // remove Animation
        coins.splice(index, 1);
      }
    }, 1000, this.coins, coinsToRemove);

  }

  // start the coin animation --- called from GameController on ngRepeatFinishedEvent
	animate(unlockField, doneFn){
    // get last inserted coin
    var lastCoin = this.coins[this.coins.length -1];
    var line;

    // get movement
    switch(lastCoin.direction) {
      case "east":
         line = lastCoin.y;
         break;
      case "west":
         line = lastCoin.y;
         break;
      case "north":
         line = lastCoin.x;
         break;
      case "south":
         line = lastCoin.x;
         break;
      default:
         console.log('No Valid Coin.');
    }

    // Move Coins in Line
    var line = this.getLineCoins(line, lastCoin.direction);
    this.moveLine(line, lastCoin.direction, doneFn);

    //check for termination
    // this.checkAllRowsForTermination();
    // undlock gamefield and force Readraw // Triggers to early
    unlockField();
	}
}


text:
package com.google.refine.clustering.binning;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.refine.browsing.Engine;
import com.google.refine.browsing.FilteredRows;
import com.google.refine.browsing.RowVisitor;
import com.google.refine.clustering.Clusterer;
import com.google.refine.model.Cell;
import com.google.refine.model.Project;
import com.google.refine.model.Row;

public class BinningClusterer extends Clusterer {

    private Keyer _keyer;

    static final protected Map<String, Keyer> _keyers = new HashMap<String, Keyer>();

    final static Logger logger = LoggerFactory.getLogger("binning_clusterer");

    List<Map<String,Integer>> _clusters;

    static {
        _keyers.put("fingerprint", new FingerprintKeyer());
        _keyers.put("ngram-fingerprint", new NGramFingerprintKeyer());
        _keyers.put("metaphone", new MetaphoneKeyer());
        _keyers.put("double-metaphone", new DoubleMetaphoneKeyer());
        _keyers.put("metaphone3", new Metaphone3Keyer());
        _keyers.put("soundex", new SoundexKeyer());
        _keyers.put("cologne-phonetic", new ColognePhoneticKeyer());
    }

    class BinningRowVisitor implements RowVisitor {

        Keyer _keyer;
        Object[] _params;
        JSONObject _config;

        Map<String,Map<String,Integer>> _map = new HashMap<String,Map<String,Integer>>();

        public BinningRowVisitor(Keyer k, JSONObject o) {
            _keyer = k;
            _config = o;
            if (k instanceof NGramFingerprintKeyer) {
                try {
                    int size = _config.getJSONObject("params").getInt("ngram-size");
                    logger.debug("Using ngram size: {}", size);
                    _params = new Object[1];
                    _params[0] = size;
                } catch (JSONException e) {
                    //Refine.warn("No params specified, using default");
                }
            }
        }

        @Override
        public void start(Project project) {
            // nothing to do
        }

        @Override
        public void end(Project project) {
            // nothing to do
        }

        @Override
        public boolean visit(Project project, int rowIndex, Row row) {
            Cell cell = row.getCell(_colindex);
            if (cell != null && cell.value != null) {
                Object v = cell.value;
                String s = (v instanceof String) ? ((String) v) : v.toString();
                String key = _keyer.key(s,_params);
                if (_map.containsKey(key)) {
                    Map<String,Integer> m = _map.get(key);
                    if (m.containsKey(s)) {
                        m.put(s, m.get(s) + 1);
                    } else {
                        m.put(s,1);
                    }
                } else {
                    Map<String,Integer> m = new TreeMap<String,Integer>();
                    m.put(s,1);
                    _map.put(key, m);
                }
            }
            return false;
        }

        public Map<String,Map<String,Integer>> getMap() {
            return _map;
        }
    }

    public static class SizeComparator implements Comparator<Map<String,Integer>>, Serializable {
        private static final long serialVersionUID = -1390696157208674054L;
        @Override
        public int compare(Map<String,Integer> o1, Map<String,Integer> o2) {
            int s1 = o1.size();
            int s2 = o2.size();
            if (o1 == o2) {
                int total1 = 0;
                for (int i : o1.values()) {
                    total1 += i;
                }
                int total2 = 0;
                for (int i : o2.values()) {
                    total2 += i;
                }
                return total2 - total1;
            } else {
                return s2 - s1;
            }
        }
    }

    public static class EntriesComparator implements Comparator<Entry<String,Integer>>, Serializable {
        private static final long serialVersionUID = 2763378036791777964L;
        @Override
        public int compare(Entry<String,Integer> o1, Entry<String,Integer> o2) {
            return o2.getValue() - o1.getValue();
        }
    }

    @Override
    public void initializeFromJSON(Project project, JSONObject o) throws Exception {
        super.initializeFromJSON(project, o);
        _keyer = _keyers.get(o.getString("function").toLowerCase());
    }

    @Override
    public void computeClusters(Engine engine) {
        BinningRowVisitor visitor = new BinningRowVisitor(_keyer,_config);
        FilteredRows filteredRows = engine.getAllFilteredRows();
        filteredRows.accept(_project, visitor);

        Map<String,Map<String,Integer>> map = visitor.getMap();
        _clusters = new ArrayList<Map<String,Integer>>(map.values());
        Collections.sort(_clusters, new SizeComparator());
    }

    @Override
    public void write(JSONWriter writer, Properties options) throws JSONException {
        EntriesComparator c = new EntriesComparator();

        writer.array();
        for (Map<String,Integer> m : _clusters) {
            if (m.size() > 1) {
                writer.array();
                List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(m.entrySet());
                Collections.sort(entries,c);
                for (Entry<String,Integer> e : entries) {
                    writer.object();
                    writer.key("v"); writer.value(e.getKey());
                    writer.key("c"); writer.value(e.getValue());
                    writer.endObject();
                }
                writer.endArray();
            }
        }
        writer.endArray();
    }
}


text:
package org.apache.druid.guice;

import com.fasterxml.jackson.databind.Module;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.multibindings.Multibinder;
import org.apache.druid.initialization.DruidModule;
import org.apache.druid.math.expr.ExprMacroTable;
import org.apache.druid.query.expression.GuiceExprMacroTable;
import org.apache.druid.query.expression.IPv4AddressMatchExprMacro;
import org.apache.druid.query.expression.IPv4AddressParseExprMacro;
import org.apache.druid.query.expression.IPv4AddressStringifyExprMacro;
import org.apache.druid.query.expression.LikeExprMacro;
import org.apache.druid.query.expression.RegexpExtractExprMacro;
import org.apache.druid.query.expression.RegexpLikeExprMacro;
import org.apache.druid.query.expression.TimestampCeilExprMacro;
import org.apache.druid.query.expression.TimestampExtractExprMacro;
import org.apache.druid.query.expression.TimestampFloorExprMacro;
import org.apache.druid.query.expression.TimestampFormatExprMacro;
import org.apache.druid.query.expression.TimestampParseExprMacro;
import org.apache.druid.query.expression.TimestampShiftExprMacro;
import org.apache.druid.query.expression.TrimExprMacro;

import java.util.List;

public class ExpressionModule implements DruidModule
{
  public static final List<Class<? extends ExprMacroTable.ExprMacro>> EXPR_MACROS =
      ImmutableList.<Class<? extends ExprMacroTable.ExprMacro>>builder()
          .add(IPv4AddressMatchExprMacro.class)
          .add(IPv4AddressParseExprMacro.class)
          .add(IPv4AddressStringifyExprMacro.class)
          .add(LikeExprMacro.class)
          .add(RegexpExtractExprMacro.class)
          .add(RegexpLikeExprMacro.class)
          .add(TimestampCeilExprMacro.class)
          .add(TimestampExtractExprMacro.class)
          .add(TimestampFloorExprMacro.class)
          .add(TimestampFormatExprMacro.class)
          .add(TimestampParseExprMacro.class)
          .add(TimestampShiftExprMacro.class)
          .add(TrimExprMacro.BothTrimExprMacro.class)
          .add(TrimExprMacro.LeftTrimExprMacro.class)
          .add(TrimExprMacro.RightTrimExprMacro.class)
          .build();

  @Override
  public void configure(Binder binder)
  {
    binder.bind(ExprMacroTable.class).to(GuiceExprMacroTable.class).in(LazySingleton.class);
    for (Class<? extends ExprMacroTable.ExprMacro> exprMacroClass : EXPR_MACROS) {
      addExprMacro(binder, exprMacroClass);
    }
  }

  @Override
  public List<? extends Module> getJacksonModules()
  {
    return ImmutableList.of();
  }

  public static void addExprMacro(final Binder binder, final Class<? extends ExprMacroTable.ExprMacro> clazz)
  {
    Multibinder.newSetBinder(binder, ExprMacroTable.ExprMacro.class)
               .addBinding()
               .to(clazz);
  }
}


text:
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}

module Main where

import qualified Data.Map as Map

import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.RWS.Strict
import Control.Monad.ST
import Data.Array.Repa
import Data.Array.Repa.Repr.ForeignPtr
import Data.Array.Repa.IO.DevIL
import Data.Array.ST
import Data.Map (Map)
import Data.Word
import Foreign (pokeElemOff, withForeignPtr)
import System.Directory
import System.Environment
import System.Exit

import Config
import Types

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

main = do
  -- Args: map image, conf file, output path
  argv <- getArgs
  when (length argv /= 4) $ do
    putStrLn "Usage: dom3conquestmaptool mapimage-file borderimage-file conf-file output-file"
    exitFailure

  let [imagePath, borderPath, confPath, outPath] = argv

  -- Load images
  img <- runIL $ readImage imagePath
  bImg <- runIL $ readImage borderPath

  -- Load conf
  conf <- loadConfig confPath

  -- Create the new image
  work img bImg conf outPath

  -- exit(1)
  exitSuccess

work img bImg conf outPath = do
  -- Parse provinces out of the image
  provs <- findProvinces img

  -- Do floodfill on the pixel data, based on province ownerships from conf
  floodfill conf provs bImg img

  -- DevIL refuses to overwrite files, so delete the target file first if it exists
  whenM (doesFileExist outPath) $
    removeFile outPath

  -- Save modified image to file
  runIL $ writeImage outPath img

-- | Finds the province dot coordinates from the image.
findProvinces :: Image -> IO [(Int, (Int, Int))]
findProvinces img =
  case img of
    RGB  pixs -> findProvinces' pixs
    RGBA pixs -> findProvinces' pixs
    BGR  pixs -> findProvinces' pixs
    BGRA pixs -> findProvinces' pixs
  where
    findProvinces' pixs =
      let Z :. maxY :. maxX :. _ = extent pixs
          whites = do
            y <- [0 .. maxY - 1]
            x <- [0 .. maxX - 1]
            guard (pixs `unsafeIndex` (ix3 y x 0) == 0xff &&
                   pixs `unsafeIndex` (ix3 y x 1) == 0xff &&
                   pixs `unsafeIndex` (ix3 y x 2) == 0xff)
            return (y, x)
      in return $ zip [1 ..] whites

-- | Floodfill depth-first from each of the province dots. Handle wraparound in the
--   neighbor selection.
floodfill :: Config -> [(Int, (Int, Int))] -> Image -> Image -> IO ()
floodfill conf provs bordersImg img =
  let (pixs, rc, gc, bc) = case img of
        RGB  pixs -> (pixs, 0, 1, 2)
        RGBA pixs -> (pixs, 0, 1, 2)
        BGR  pixs -> (pixs, 2, 1, 0)
        BGRA pixs -> (pixs, 2, 1, 0)
      (bPixs, bRc, bGc, bBc) = case bordersImg of
        RGB  pixs -> (pixs, 0, 1, 2)
        RGBA pixs -> (pixs, 0, 1, 2)
        BGR  pixs -> (pixs, 2, 1, 0)
        BGRA pixs -> (pixs, 2, 1, 0)
  in floodfill' pixs rc gc bc bPixs bRc bGc bBc

  where
    floodfill' pixs rc gc bc bPixs bRc bGc bBc =
      withForeignPtr (toForeignPtr pixs) $ \ptr -> do
        let Z :. maxY :. maxX :. chans = extent pixs

        forM_ provs $ \(pnum, (y0, x0)) ->
          when (pnum `Map.member` provinces conf) $ do
            -- What's our colour for this province?
            let owner = provinces conf Map.! pnum
                Colour { red = r, green = g, blue = b } = nations conf Map.! owner

            -- Find colourable pixels
            let toFill = seek conf bPixs bRc bGc bBc y0 x0

            -- Paint them
            forM_ toFill $ \(y, x) -> do
              pokeElemOff ptr (y * maxX * chans + x * chans + rc) r
              pokeElemOff ptr (y * maxX * chans + x * chans + gc) g
              pokeElemOff ptr (y * maxX * chans + x * chans + bc) b

seek :: Config -> Array F DIM3 Word8 ->
        Int -> Int -> Int ->
        Int -> Int ->
        [(Int, Int)]
seek conf pixs rc gc bc y0 x0 = runST $ do
  visited0 <- newArray ((0,0), (maxY, maxX)) False

  execRWST (seek' y0 x0) visited0 [] >>= return . fst

  where
    Z :. maxY :. maxX :. chans = extent pixs

    visit y x = do
      arr <- ask
      lift $ writeArray arr (y, x) True
    isVisited y x =  do
      arr <- ask
      lift $ readArray arr (y, x)

    found y x = modify $ ((y,x):)

    isBorder y x =
      let r = pixs `unsafeIndex` ix3 y x rc
          g = pixs `unsafeIndex` ix3 y x gc
          b = pixs `unsafeIndex` ix3 y x bc
      in return $
         r == red   (borderColour conf) &&
         g == green (borderColour conf) &&
         b == blue  (borderColour conf)

    inBounds y x = y >= 0 && y < maxY && x >= 0 && x < maxX

    wrap y x =
      if wraparound conf
      then ((y + maxY) `mod` maxY, (x + maxX) `mod` maxX)
      else (y, x)

    seek' :: Int -> Int -> RWST (STUArray s (Int, Int) Bool) () [(Int, Int)] (ST s) ()
    seek' y x = do
      -- Do nothing if we've already visited
      beenHere <- isVisited y x
      when (inBounds y x && not beenHere) $ do
        -- Mark this pixel visited
        visit y x

        -- Is it border? If it is, we're done
        border <- isBorder y x
        when (not border) $ do
          -- Add this pixel to the ones we need to colour
          found y x

          -- Walk to the neighbouring pixels
          --- Up
          uncurry seek' $ wrap (y + 1) x
          --- Down
          uncurry seek' $ wrap (y - 1) x
          --- Right
          uncurry seek' $ wrap y (x + 1)
          --- Left
          uncurry seek' $ wrap y (x - 1)

whenM :: Monad m => m Bool -> m () -> m ()
whenM pred act = pred >>= flip when act


text:
from selenium import webdriver
from fixture.session import SessionHelper
from fixture.group import GroupHelper
from fixture.user import UserHelper

class Application:

    def __init__(self, browser, base_url):
        if browser == "firefox":
            self.wd = webdriver.Firefox()
        elif browser == "chrome":
            self.wd = webdriver.Chrome()
        elif browser == "ie":
            self.wd = webdriver.Ie()
        else:
            raise ValueError("Unrecognized browser %s" % browser)
        self.session = SessionHelper(self)
        self.group = GroupHelper(self)
        self.user = UserHelper(self)
        self.base_url = base_url

    def is_valid(self):
        try:
            self.wd.current_url
            return True
        except:
            return False

    def open_home_page(self):
        wd = self.wd
        wd.get(self.base_url)

    def destroy(self):
        self.wd.quit()


text:
var argscheck = require('cordova/argscheck'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

var PLUGIN_NAME = "CameraPreview";

var CameraPreview = function() {};

function isFunction(obj) {
    return !!(obj && obj.constructor && obj.call && obj.apply);
};

CameraPreview.startCamera = function(options, onSuccess, onError) {
    options = options || {};
    options.x = options.x || 0;
    options.y = options.y || 0;
    options.width = options.width || window.screen.width;
    options.height = options.height || window.screen.height;
    options.camera = options.camera || CameraPreview.CAMERA_DIRECTION.FRONT;
    if (typeof(options.tapPhoto) === 'undefined') {
        options.tapPhoto = true;
    }

    if (typeof (options.tapFocus) == 'undefined') {
      options.tapFocus = false;
    }

    options.previewDrag = options.previewDrag || false;
    options.toBack = options.toBack || false;
    if (typeof(options.alpha) === 'undefined') {
        options.alpha = 1;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "startCamera", [options.x, options.y, options.width, options.height, options.camera, options.tapPhoto, options.previewDrag, options.toBack, options.alpha, options.tapFocus]);
};

CameraPreview.stopCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "stopCamera", []);
};

CameraPreview.switchCamera = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "switchCamera", []);
};

CameraPreview.hide = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "hideCamera", []);
};

CameraPreview.show = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "showCamera", []);
};

CameraPreview.takePicture = function(opts, onSuccess, onError) {
    if (!opts) {
        opts = {};
    } else if (isFunction(opts)) {
        onSuccess = opts;
        opts = {};
    }

    if (!isFunction(onSuccess)) {
        return false;
    }

    opts.width = opts.width || 0;
    opts.height = opts.height || 0;

    if (!opts.quality || opts.quality > 100 || opts.quality < 0) {
        opts.quality = 85;
    }

    exec(onSuccess, onError, PLUGIN_NAME, "takePicture", [opts.width, opts.height, opts.quality]);
};

CameraPreview.setColorEffect = function(effect, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setColorEffect", [effect]);
};

CameraPreview.setZoom = function(zoom, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setZoom", [zoom]);
};

CameraPreview.getMaxZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getMaxZoom", []);
};

CameraPreview.getZoom = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getZoom", []);
};

CameraPreview.setPreviewSize = function(dimensions, onSuccess, onError) {
    dimensions = dimensions || {};
    dimensions.width = dimensions.width || window.screen.width;
    dimensions.height = dimensions.height || window.screen.height;

    return exec(onSuccess, onError, PLUGIN_NAME, "setPreviewSize", [dimensions.width, dimensions.height]);
};

CameraPreview.getSupportedPictureSizes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedPictureSizes", []);
};

CameraPreview.getSupportedFlashModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedFlashModes", []);
};

CameraPreview.setFlashMode = function(flashMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setFlashMode", [flashMode]);
};

CameraPreview.getFlashMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getFlashMode", []);
};

CameraPreview.getSupportedFocusModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedFocusModes", []);
};

CameraPreview.getFocusMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getFocusMode", []);
};

CameraPreview.setFocusMode = function(focusMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setFocusMode", [focusMode]);
};

CameraPreview.tapToFocus = function(xPoint, yPoint, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "tapToFocus", [xPoint, yPoint]);
};

CameraPreview.getExposureModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureModes", []);
};

CameraPreview.getExposureMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureMode", []);
};

CameraPreview.setExposureMode = function(exposureMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureMode", [exposureMode]);
};

CameraPreview.getExposureCompensation = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensation", []);
};

CameraPreview.setExposureCompensation = function(exposureCompensation, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setExposureCompensation", [exposureCompensation]);
};

CameraPreview.getExposureCompensationRange = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getExposureCompensationRange", []);
};

CameraPreview.getSupportedWhiteBalanceModes = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getSupportedWhiteBalanceModes", []);
};

CameraPreview.getWhiteBalanceMode = function(onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "getWhiteBalanceMode", []);
};

CameraPreview.setWhiteBalanceMode = function(whiteBalanceMode, onSuccess, onError) {
    exec(onSuccess, onError, PLUGIN_NAME, "setWhiteBalanceMode", [whiteBalanceMode]);
};

CameraPreview.FOCUS_MODE = {
    FIXED: 'fixed',
    AUTO: 'auto',
    CONTINUOUS: 'continuous', // IOS Only
    CONTINUOUS_PICTURE: 'continuous-picture', // Android Only
    CONTINUOUS_VIDEO: 'continuous-video', // Android Only
    EDOF: 'edof', // Android Only
    INFINITY: 'infinity', // Android Only
    MACRO: 'macro' // Android Only
};

CameraPreview.EXPOSURE_MODE = {
    LOCK: 'lock',
    AUTO: 'auto', // IOS Only
    CONTINUOUS: 'continuous', // IOS Only
    CUSTOM: 'custom' // IOS Only
};

CameraPreview.WHITE_BALANCE_MODE = {
    LOCK: 'lock',
    AUTO: 'auto',
    CONTINUOUS: 'continuous',
    INCANDESCENT: 'incandescent',
    CLOUDY_DAYLIGHT: 'cloudy-daylight',
    DAYLIGHT: 'daylight',
    FLUORESCENT: 'fluorescent',
    SHADE: 'shade',
    TWILIGHT: 'twilight',
    WARM_FLUORESCENT: 'warm-fluorescent'
};

CameraPreview.FLASH_MODE = {
    OFF: 'off',
    ON: 'on',
    AUTO: 'auto',
    RED_EYE: 'red-eye', // Android Only
    TORCH: 'torch'
};

CameraPreview.COLOR_EFFECT = {
    AQUA: 'aqua', // Android Only
    BLACKBOARD: 'blackboard', // Android Only
    MONO: 'mono',
    NEGATIVE: 'negative',
    NONE: 'none',
    POSTERIZE: 'posterize',
    SEPIA: 'sepia',
    SOLARIZE: 'solarize', // Android Only
    WHITEBOARD: 'whiteboard' // Android Only
};

CameraPreview.CAMERA_DIRECTION = {
    BACK: 'back',
    FRONT: 'front'
};

module.exports = CameraPreview;


text:
from __future__ import absolute_import

import sys
import os
import threading
import collections
import weakref
import errno

from . import Pipe
from ._ext import _billiard
from .compat import get_errno
from .five import monotonic
from .synchronize import Lock, BoundedSemaphore, Semaphore, Condition
from .util import debug, error, info, Finalize, register_after_fork
from .five import Empty, Full
from .forking import assert_spawning

__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']

class Queue(object):
    '''
    Queue type using a pipe, buffer and thread
    '''
    def __init__(self, maxsize=0):
        if maxsize <= 0:
            maxsize = _billiard.SemLock.SEM_VALUE_MAX
        self._maxsize = maxsize
        self._reader, self._writer = Pipe(duplex=False)
        self._rlock = Lock()
        self._opid = os.getpid()
        if sys.platform == 'win32':
            self._wlock = None
        else:
            self._wlock = Lock()
        self._sem = BoundedSemaphore(maxsize)
        # For use by concurrent.futures
        self._ignore_epipe = False

        self._after_fork()

        if sys.platform != 'win32':
            register_after_fork(self, Queue._after_fork)

    def __getstate__(self):
        assert_spawning(self)
        return (self._ignore_epipe, self._maxsize, self._reader, self._writer,
                self._rlock, self._wlock, self._sem, self._opid)

    def __setstate__(self, state):
        (self._ignore_epipe, self._maxsize, self._reader, self._writer,
         self._rlock, self._wlock, self._sem, self._opid) = state
        self._after_fork()

    def _after_fork(self):
        debug('Queue._after_fork()')
        self._notempty = threading.Condition(threading.Lock())
        self._buffer = collections.deque()
        self._thread = None
        self._jointhread = None
        self._joincancelled = False
        self._closed = False
        self._close = None
        self._send = self._writer.send
        self._recv = self._reader.recv
        self._poll = self._reader.poll

    def put(self, obj, block=True, timeout=None):
        assert not self._closed
        if not self._sem.acquire(block, timeout):
            raise Full

        with self._notempty:
            if self._thread is None:
                self._start_thread()
            self._buffer.append(obj)
            self._notempty.notify()

    def get(self, block=True, timeout=None):
        if block and timeout is None:
            with self._rlock:
                res = self._recv()
                self._sem.release()
                return res

        else:
            if block:
                deadline = monotonic() + timeout
            if not self._rlock.acquire(block, timeout):
                raise Empty
            try:
                if block:
                    timeout = deadline - monotonic()
                    if timeout < 0 or not self._poll(timeout):
                        raise Empty
                elif not self._poll():
                    raise Empty
                res = self._recv()
                self._sem.release()
                return res
            finally:
                self._rlock.release()

    def qsize(self):
        # Raises NotImplementedError on Mac OSX because
        # of broken sem_getvalue()
        return self._maxsize - self._sem._semlock._get_value()

    def empty(self):
        return not self._poll()

    def full(self):
        return self._sem._semlock._is_zero()

    def get_nowait(self):
        return self.get(False)

    def put_nowait(self, obj):
        return self.put(obj, False)

    def close(self):
        self._closed = True
        self._reader.close()
        if self._close:
            self._close()

    def join_thread(self):
        debug('Queue.join_thread()')
        assert self._closed
        if self._jointhread:
            self._jointhread()

    def cancel_join_thread(self):
        debug('Queue.cancel_join_thread()')
        self._joincancelled = True
        try:
            self._jointhread.cancel()
        except AttributeError:
            pass

    def _start_thread(self):
        debug('Queue._start_thread()')

        # Start thread which transfers data from buffer to pipe
        self._buffer.clear()
        self._thread = threading.Thread(
            target=Queue._feed,
            args=(self._buffer, self._notempty, self._send,
                  self._wlock, self._writer.close, self._ignore_epipe),
            name='QueueFeederThread'
        )
        self._thread.daemon = True

        debug('doing self._thread.start()')
        self._thread.start()
        debug('... done self._thread.start()')

        # On process exit we will wait for data to be flushed to pipe.
        #
        # However, if this process created the queue then all
        # processes which use the queue will be descendants of this
        # process.  Therefore waiting for the queue to be flushed
        # is pointless once all the child processes have been joined.
        created_by_this_process = (self._opid == os.getpid())
        if not self._joincancelled and not created_by_this_process:
            self._jointhread = Finalize(
                self._thread, Queue._finalize_join,
                [weakref.ref(self._thread)],
                exitpriority=-5
            )

        # Send sentinel to the thread queue object when garbage collected
        self._close = Finalize(
            self, Queue._finalize_close,
            [self._buffer, self._notempty],
            exitpriority=10
        )

    @staticmethod
    def _finalize_join(twr):
        debug('joining queue thread')
        thread = twr()
        if thread is not None:
            thread.join()
            debug('... queue thread joined')
        else:
            debug('... queue thread already dead')

    @staticmethod
    def _finalize_close(buffer, notempty):
        debug('telling queue thread to quit')
        with notempty:
            buffer.append(_sentinel)
            notempty.notify()

    @staticmethod
    def _feed(buffer, notempty, send, writelock, close, ignore_epipe):
        debug('starting thread to feed data to pipe')
        from .util import is_exiting

        ncond = notempty
        nwait = notempty.wait
        bpopleft = buffer.popleft
        sentinel = _sentinel
        if sys.platform != 'win32':
            wlock = writelock
        else:
            wlock = None

        try:
            while 1:
                with ncond:
                    if not buffer:
                        nwait()
                try:
                    while 1:
                        obj = bpopleft()
                        if obj is sentinel:
                            debug('feeder thread got sentinel -- exiting')
                            close()
                            return

                        if wlock is None:
                            send(obj)
                        else:
                            with wlock:
                                send(obj)
                except IndexError:
                    pass
        except Exception as exc:
            if ignore_epipe and get_errno(exc) == errno.EPIPE:
                return
            # Since this runs in a daemon thread the resources it uses
            # may be become unusable while the process is cleaning up.
            # We ignore errors which happen after the process has
            # started to cleanup.
            try:
                if is_exiting():
                    info('error in queue thread: %r', exc, exc_info=True)
                else:
                    if not error('error in queue thread: %r', exc,
                                 exc_info=True):
                        import traceback
                        traceback.print_exc()
            except Exception:
                pass

_sentinel = object()

class JoinableQueue(Queue):
    '''
    A queue type which also supports join() and task_done() methods

    Note that if you do not call task_done() for each finished task then
    eventually the counter's semaphore may overflow causing Bad Things
    to happen.
    '''

    def __init__(self, maxsize=0):
        Queue.__init__(self, maxsize)
        self._unfinished_tasks = Semaphore(0)
        self._cond = Condition()

    def __getstate__(self):
        return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)

    def __setstate__(self, state):
        Queue.__setstate__(self, state[:-2])
        self._cond, self._unfinished_tasks = state[-2:]

    def put(self, obj, block=True, timeout=None):
        assert not self._closed
        if not self._sem.acquire(block, timeout):
            raise Full

        with self._notempty:
            with self._cond:
                if self._thread is None:
                    self._start_thread()
                self._buffer.append(obj)
                self._unfinished_tasks.release()
                self._notempty.notify()

    def task_done(self):
        with self._cond:
            if not self._unfinished_tasks.acquire(False):
                raise ValueError('task_done() called too many times')
            if self._unfinished_tasks._semlock._is_zero():
                self._cond.notify_all()

    def join(self):
        with self._cond:
            if not self._unfinished_tasks._semlock._is_zero():
                self._cond.wait()

class _SimpleQueue(object):
    '''
    Simplified Queue type -- really just a locked pipe
    '''

    def __init__(self, rnonblock=False, wnonblock=False):
        self._reader, self._writer = Pipe(
            duplex=False, rnonblock=rnonblock, wnonblock=wnonblock,
        )
        self._poll = self._reader.poll
        self._rlock = self._wlock = None
        self._make_methods()

    def empty(self):
        return not self._poll()

    def __getstate__(self):
        assert_spawning(self)
        return (self._reader, self._writer, self._rlock, self._wlock)

    def __setstate__(self, state):
        (self._reader, self._writer, self._rlock, self._wlock) = state
        self._make_methods()

    def _make_methods(self):
        recv = self._reader.recv
        try:
            recv_payload = self._reader.recv_payload
        except AttributeError:
            recv_payload = self._reader.recv_bytes
        rlock = self._rlock

        if rlock is not None:
            def get():
                with rlock:
                    return recv()
            self.get = get

            def get_payload():
                with rlock:
                    return recv_payload()
            self.get_payload = get_payload
        else:
            self.get = recv
            self.get_payload = recv_payload

        if self._wlock is None:
            # writes to a message oriented win32 pipe are atomic
            self.put = self._writer.send
        else:
            send = self._writer.send
            wlock = self._wlock

            def put(obj):
                with wlock:
                    return send(obj)
            self.put = put

class SimpleQueue(_SimpleQueue):

    def __init__(self):
        self._reader, self._writer = Pipe(duplex=False)
        self._rlock = Lock()
        self._wlock = Lock() if sys.platform != 'win32' else None
        self._make_methods()


text:
namespace GRAPH
{
    Event::Event(Type type)
        : type_(type)
        , isStopped_(false)
        , currentTarget_(nullptr) {
    }

    Event::~Event() {
    }

    EventCustom::EventCustom(const std::string& eventName)
        : Event(Type::CUSTOM)
        , userData_(nullptr)
        , eventName_(eventName) {
    }

    EventAcceleration::EventAcceleration(const Acceleration& acc)
        : Event(Type::ACCELERATION)
        , aaceleration_(acc) {
    }

    EventKeyboard::EventKeyboard(KeyCode keyCode, bool isPressed)
        : Event(Type::KEYBOARD)
        , keyCode_(keyCode)
        , isPressed_(isPressed) {

    }

    EventMouse::EventMouse(MouseEventType mouseEventCode)
        : Event(Type::MOUSE)
        , mouseEventType_(mouseEventCode)
        , mouseButton_(-1)
        , xPosition_(0.0f)
        , yPosition_(0.0f)
        , scrollX_(0.0f)
        , scrollY_(0.0f)
        , startPointCaptured_(false) {

    }

    MATH::Vector2f EventMouse::getLocationInView() const {
        return point_;
    }

    MATH::Vector2f EventMouse::getPreviousLocationInView() const {
        return prevPoint_;
    }

    MATH::Vector2f EventMouse::getStartLocationInView() const {
        return startPoint_;
    }

    MATH::Vector2f EventMouse::getLocation() const {
        return Director::getInstance().convertToGL(point_);
    }

    MATH::Vector2f EventMouse::getPreviousLocation() const {
        return Director::getInstance().convertToGL(prevPoint_);
    }

    MATH::Vector2f EventMouse::getStartLocation() const {
        return Director::getInstance().convertToGL(startPoint_);
    }

    MATH::Vector2f EventMouse::getDelta() const {
        return getLocation() - getPreviousLocation();
    }

    EventFocus::EventFocus(HObject *widgetLoseFocus, HObject* widgetGetFocus)
        :Event(Type::FOCUS),
        widgetGetFocus_(widgetGetFocus),
        widgetLoseFocus_(widgetLoseFocus) {

    }

    MATH::Vector2f Touch::getLocationInView() const {
        return point_;
    }

    MATH::Vector2f Touch::getPreviousLocationInView() const {
        return prevPoint_;
    }

    MATH::Vector2f Touch::getStartLocationInView() const {
        return startPoint_;
    }

    MATH::Vector2f Touch::getLocation() const {
        return Director::getInstance().convertToGL(point_);
    }

    MATH::Vector2f Touch::getPreviousLocation() const {
        return Director::getInstance().convertToGL(prevPoint_);
    }

    MATH::Vector2f Touch::getStartLocation() const {
        return Director::getInstance().convertToGL(startPoint_);
    }

    MATH::Vector2f Touch::getDelta() const {
        return getLocation() - getPreviousLocation();
    }

    EventTouch::EventTouch()
        : Event(Type::TOUCH) {
        touches_.reserve(MAXtouches_);
    }
}


text:
package com.seleniumtests.core.runner;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Listeners;

import com.seleniumtests.connectors.extools.Uft;
import com.seleniumtests.core.SeleniumTestsContext;
import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.core.TestStepManager;
import com.seleniumtests.core.TestTasks;
import com.seleniumtests.core.utils.TestNGResultUtils;
import com.seleniumtests.customexception.ScenarioException;
import com.seleniumtests.driver.WebUIDriver;
import com.seleniumtests.reporter.info.Info;
import com.seleniumtests.reporter.info.MultipleInfo;
import com.seleniumtests.reporter.info.VideoLinkInfo;
import com.seleniumtests.reporter.logger.TestStep;
import com.seleniumtests.util.logging.ScenarioLogger;
import com.seleniumtests.util.video.VideoCaptureMode;
import com.seleniumtests.util.video.VideoUtils;

@Listeners({com.seleniumtests.reporter.reporters.ReporterControler.class,
	com.seleniumtests.core.runner.SeleniumRobotTestListener.class//,
	//ReportPortalTestListener.class
	})
public class SeleniumRobotTestPlan {

	private static Map<Thread, Boolean> cucumberTest = Collections.synchronizedMap(new HashMap<>());
	protected static final Logger logger = ScenarioLogger.getScenarioLogger(SeleniumRobotTestPlan.class);

	public SeleniumRobotTestPlan() {
		System.setProperty( "file.encoding", "UTF-8" );
	}

	public static void setCucumberTest(boolean cucumberTestIn) {
		SeleniumRobotTestPlan.cucumberTest.put(Thread.currentThread(), cucumberTestIn);
	}

	public static boolean isCucumberTest() {
		Boolean isCucumberT = SeleniumRobotTestPlan.cucumberTest.get(Thread.currentThread());
		if (isCucumberT == null) {
			return false;
		}
		return isCucumberT;
	}

	@BeforeSuite(alwaysRun=true)
	public void doBeforeSuite() {
		// do nothing but be in the same state as most of the integration tests which call a Beforesuite method
		// this lead to the creation of a thread context for the main thread
	}

	/**
	 * issue #150: set driver to null in case it was not cleaned before
	 * This method will be called before any other before method
	 * @param method
	 */
	@BeforeMethod(alwaysRun=true)
	public void startTestMethod(Method method) {
		WebUIDriver.setWebDriver(null);

		// issue #297: be sure we reset the driver name before the test starts
		WebUIDriver.resetCurrentWebUiDriverName();
	}

	/**
	 * According to TestNG doc, this method will be executed after the \@AfterMethod inside test classes
	 * #issue 136: This will close any remaining browser for this thread and forbid user to create a new driver in other \@AfterXXX
	 */
	@AfterMethod(alwaysRun=true)
	public void finishTestMethod(Method method, ITestResult testResult) {

		// stop video capture and log file
		File videoFile = WebUIDriver.stopVideoCapture();

		if (videoFile != null) {
			VideoUtils.extractReferenceForSteps(videoFile, TestStepManager.getInstance().getTestSteps(), Paths.get(SeleniumTestsContextManager.getThreadContext().getOutputDirectory()));

	        if (SeleniumTestsContextManager.getThreadContext().getVideoCapture() == VideoCaptureMode.TRUE
	        		|| (SeleniumTestsContextManager.getThreadContext().getVideoCapture() == VideoCaptureMode.ON_SUCCESS && testResult.isSuccess())
	        		|| (SeleniumTestsContextManager.getThreadContext().getVideoCapture() == VideoCaptureMode.ON_ERROR && !testResult.isSuccess())) {

	        	((ScenarioLogger)logger).logFileToTestEnd(videoFile.getAbsoluteFile(), "Video capture");

	        	Info lastStateInfo = TestNGResultUtils.getTestInfo(testResult).get(TestStepManager.LAST_STATE_NAME);
	        	if (lastStateInfo != null) {
	        		((MultipleInfo)lastStateInfo).addInfo(new VideoLinkInfo(TestNGResultUtils.getUniqueTestName(testResult) + "/videoCapture.avi"));
	        	}

	        	logger.info("Video file copied to " + videoFile.getAbsolutePath());

			} else {
				try {
					Files.delete(Paths.get(videoFile.getAbsolutePath()));
				} catch (IOException e) {
					logger.warn(String.format("Video file %s not deleted: %s", videoFile.getAbsoluteFile(), e.getMessage()));
				}
			}
		}

		WebUIDriver.cleanUp();
		SeleniumTestsContextManager.getThreadContext().setDriverCreationBlocked(true);

		SeleniumRobotTestListener.getCurrentListener().onTestFullyFinished(testResult);
	}

	/**
     * Get parameter from configuration
     *
     * @param key
     *
     * @return String
     */
    public static String param(String key) {
    	return TestTasks.param(key);
    }

    /**
     * Get parameter from configuration using pattern
     * If multiple variables match the pattern, only one is returned
     * @param keyPattern	Pattern for searching key. If null, no filtering will be done on key
     * @return
     */
    public static String param(Pattern keyPattern) {
    	return TestTasks.param(keyPattern);
    }

    /**
     * Get parameter from configuration using pattern
     * If multiple variables match the pattern, only one is returned
     * @param keyPattern	Pattern for searching key. If null, no filtering will be done on key
     * @param valuePattern	Pattern for searching value. If null, no filtering will be done on value
     * @return
     */
    public static String param(Pattern keyPattern, Pattern valuePattern) {
    	return TestTasks.param(keyPattern, valuePattern);
    }

    /**
	 * Method for creating or updating a variable on the seleniumRobot server (or locally if server is not used)
     * Moreover, created custom variable is specific to tuple (application, version, test environment)
     * Variable will be stored as a variable of the current tested application
     * @param key				name of the param
     * @param value				value of the parameter (or new value if we update it)
     */
    public void createOrUpdateParam(String key, String value) {
    	TestTasks.createOrUpdateParam(key, value);
    }

    /**
	 * Method for creating or updating a variable locally. If selenium server is not used, there is no difference with 'createOrUpdateParam'.
	 * If seleniumRobot server is used, then, this method will only change variable value locally, not updating the remote one
	 * @param key
	 * @param newValue
	 */
	public void createOrUpdateLocalParam(String key, String newValue) {
		TestTasks.createOrUpdateLocalParam(key, newValue);
	}

    /**
     * Method for creating or updating a variable on the seleniumRobot server ONLY. This will raise a ScenarioException if variables are get from
     * env.ini file
     * Moreover, created custom variable is specific to tuple (application, version, test environment)
     * @param key					name of the param
     * @param specificToVersion		if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a
     * 								current variable.
     */
    public void createOrUpdateParam(String key, String value, boolean specificToVersion) {
    	TestTasks.createOrUpdateParam(key, value, specificToVersion);
    }

    /**
     * Method for creating or updating a variable. If variables are get from seleniumRobot server, this method will update the value on the server
     * Moreover, created custom variable is specific to tuple (application, version, test environment)
     * @param key					name of the param
     * @param specificToVersion		if true, this param will be stored on server with a reference to the application version. This will have no effect if changing a
     * 								current variable.
     * @param timeToLive			if > 0, this variable will be destroyed after some days (defined by variable). A positive value is mandatory if reservable is set to true
     * 								because multiple variable can be created
     * @param reservable			if true, this variable will be set as reservable in variable server. This means it can be used by only one test at the same time
     * 								True value also means that multiple variables of the same name can be created and a timeToLive > 0 MUST be provided so that server database is regularly purged
     */
    public void createOrUpdateParam(String key, String value, boolean specificToVersion, int timeToLive, boolean reservable) {
    	TestTasks.createOrUpdateParam(key, value, specificToVersion, timeToLive, reservable);
    }

    /**
     * In case the scenario uses several drivers, switch to one or another using this method, so that any new calls will go through this driver
     * @param driverName
     */
    public WebDriver switchToDriver(String driverName) {
    	return TestTasks.switchToDriver(driverName);
    }

    /**
     * Kills the named process, locally or remotely
     * @param processName		name of the process (do not provide .exe extension on windows)
     */
    public void killProcess(String processName) {
    	TestTasks.killProcess(processName);
    }

    /**
     * get list of the named process, locally or remotely
     * @param processName
     */
    public List<Integer> getProcessList(String processName) {
    	return TestTasks.getProcessList(processName);
    }

    /**
     * Add step to current test
     * @param stepName
     */
    public void addStep(String stepName, String ... passwordToMask) {
    	TestTasks.addStep(stepName, passwordToMask);
    }

    /**
     * execute command
     * @param program			name of the program
     * @param args				array of arguments to give to program
     */
    public String executeCommand(String program, String ... args) {
    	return TestTasks.executeCommand(program, args);
    }

    /**
     * Execute a UFT script locally or remotely via a VBS script called through csscript.exe
     * @param args			parameters to give to UFT script
     * @param timeout		timeout in seconds. Max time the script will run
     */
    public void executeUftScript(Uft uft, int timeout, Map<String, String> args) {
    	TestTasks.terminateCurrentStep();

		List<TestStep> uftSteps = uft.executeScript(timeout, args);
		for (TestStep uftStep: uftSteps) {
			TestStepManager.setCurrentRootTestStep(uftStep);
			TestStepManager.logTestStep(TestStepManager.getCurrentRootTestStep());

			if (Boolean.TRUE.equals(uftStep.getFailed())) {
				throw new ScenarioException(String.format("UFT execution failed on script %s", uft.getScriptPath()));

			}
		}
    }
    /**
     * Load a UFT script locally or remotely via a VBS script called through csscript.exe
     * @param almServer		ALM server address
     * @param almUser
     * @param almPassword
     * @param almDomain
     * @param almProject
     * @param scriptPath	path to ALM script. e.g: '[QualityCenter]Subject\TOOLS\TestsFoo\foo'
     * @param killUftOnStartup	if true, UFT will be killed before starting the UFT test
     */
    public Uft loadUftScript(String almServer, String almUser, String almPassword, String almDomain, String almProject, String scriptPath, boolean killUftOnStartup) {

    	Uft uft = new Uft(almServer, almUser, almPassword, almDomain, almProject, scriptPath);
    	uft.loadScript(killUftOnStartup);

    	return uft;
    }

    /**
     * returns the robot configuration
     * @return
     */
    public SeleniumTestsContext robotConfig() {
    	return SeleniumTestsContextManager.getThreadContext();
    }

    /**
     * Allow to increment the maxRetry in case an event occurs
     * Increment will be allowed up to 2 times the total defined by configuration (default is 2)
     */
    public void increaseMaxRetry() {
    	SeleniumRobotTestListener.increaseMaxRetry();
    }

    /**
     * Add a information to the test, that will be available in report files at test level
     * @param key	name of the information to display
     * @param value	A StringInfo or HyperlinkInfo instance to display the value
     */
    public void addTestInfo(String key, Info value) {
    	((ScenarioLogger)logger).logTestInfo(key, value);
    }
}


text:
#include "ArticulatedFigure.h"
#include <Physics/World.h>
#include <Physics/RBUtils.h>
#include <Utils/Utils.h>
/**
	Default constructor
*/
ArticulatedFigure::ArticulatedFigure(void){
	root = NULL;
	name[0] = '\0';
	mass = 0;
}

ArticulatedFigure::~ArticulatedFigure(void){
	//delete all the joints
	if (root != NULL)
		delete root;
	for (uint i=0;i<arbs.size();i++)
		delete arbs[i];
	for (uint i=0;i<joints.size();i++)
		delete joints[i];
	arbs.clear();
	joints.clear();
}

void ArticulatedFigure::loadIntoWorld() {
	World& world = World::instance();

	if( root == NULL )
		throwError( "Articulated figure needs a root before it can be loaded into the world!" );
	world.addRigidBody(root);
	for (uint i=0;i<arbs.size();i++)
		world.addRigidBody(arbs[i]);
}

/**
	Sets the root
*/
void ArticulatedFigure::setRoot( ArticulatedRigidBody* root ) {
	if (this->root != NULL)
		throwError("This articulated figure already has a root");
    root->setAFParent( this );
	this->root = root;
}

/**
	Sets the root
*/
void ArticulatedFigure::addArticulatedRigidBody( ArticulatedRigidBody* arb ) {
    arb->setAFParent( this );
	arbs.push_back( arb );
}

/**
	This method is used to automatically fix the errors in the joints (i.e. drift errors caused by numercial integration). At some future
	point it can be changed into a proper stabilization technique.
*/
void ArticulatedFigure::fixJointConstraints(bool fixOrientations, bool fixVelocities){
	if (!root)
		return;

	for (uint i=0;i<root->cJoints.size();i++)
		root->cJoints[i]->fixJointConstraints(fixOrientations, fixVelocities, true);
}

/**
	This method is used to compute the total mass of the articulated figure.
*/
void ArticulatedFigure::computeMass(){
	double curMass = root->getMass();
	double totalMass = curMass;

	for (uint i=0; i < joints.size(); i++){
		curMass = joints[i]->child->getMass();
		totalMass += curMass;
	}

	mass = totalMass;
}

/**
	This method is used to get the total mass of the articulated figure.
*/
double ArticulatedFigure::getMass(){
	return mass;
}

/**
	This method is used to load the details of an articulated figure from file. The PhysicalWorld parameter points to the world in which the objects
	that need to be linked live in.
*/
void ArticulatedFigure::loadFromFile(FILE* f, World* world){
	if (f == NULL)
		throwError("Invalid file pointer.");
	if (world == NULL)
		throwError("A valid physical world must be passed in as a parameter");
	//have a temporary buffer used to read the file line by line...
	char buffer[200];
	char tempName[100];
	Joint* tempJoint;

	//this is where it happens.
	while (!feof(f)){
		//get a line from the file...
		fgets(buffer, 200, f);
		if (strlen(buffer)>195)
			throwError("The input file contains a line that is longer than ~200 characters - not allowed");
		char *line = lTrim(buffer);
		int lineType = getRBLineType(line);
		switch (lineType) {
			case RB_ROOT:
				sscanf(line, "%s", tempName);
				if (root != NULL)
					throwError("This articulated figure already has a root");
				root = world->getARBByName(tempName);
				if (root == NULL)
					throwError("The articulated rigid body \'%s\' cannot be found!", tempName);
				break;
			case RB_JOINT_TYPE_UNIVERSAL:
				tempJoint = new UniversalJoint();
				tempJoint->readAxes( line );
				tempJoint->loadFromFile(f, world);
				tempJoint->child->AFParent = this;
				tempJoint->parent->AFParent = this;
				break;
			case RB_JOINT_TYPE_HINGE:
				tempJoint = new HingeJoint();
				tempJoint->readAxes( line );
				tempJoint->loadFromFile(f, world);
				tempJoint->child->AFParent = this;
				tempJoint->parent->AFParent = this;
				break;
			case RB_JOINT_TYPE_BALL_IN_SOCKET:
				tempJoint = new BallInSocketJoint();
				tempJoint->readAxes( line );
				tempJoint->loadFromFile(f, world);
				tempJoint->child->AFParent = this;
				tempJoint->parent->AFParent = this;
				break;
			case RB_END_ARTICULATED_FIGURE:
				//make sure that the root does not have a parent, otherwise we'll end up with loops in the articulated figure]
				if (root->pJoint != NULL)
					throwError("The root of the articulated figure is not allowed to have a parent!");
				return;//and... done
				break;
			case RB_NOT_IMPORTANT:
				if (strlen(line)!=0 && line[0] != '#')
					tprintf("Ignoring input line: \'%s\'\n", line);
				break;
			default:
				throwError("Incorrect articulated body input file: \'%s\' - unexpected line.", buffer);
		}
	}
	throwError("Incorrect articulated body input file! No /ArticulatedFigure found");
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.8.0/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/EaselJS_16x16.png">

	<title>EaselJS v0.7.0 API Documentation : ColorMatrixFilter</title>

            API Documentation for: 0.7.0

APIs

Classes

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

AlphaMapFilter

AlphaMaskFilter

Bitmap

BitmapAnimation

BitmapText

BlurFilter

ButtonHelper

ColorFilter

ColorMatrix

ColorMatrixFilter

Command

Container

DisplayObject

DOMElement

EaselJS

Event

EventDispatcher

Filter

Graphics

Matrix2D

MouseEvent

MovieClip

MovieClipPlugin

Point

Rectangle

Shadow

Shape

Sprite

SpriteSheet

SpriteSheetBuilder

SpriteSheetUtils

Stage

Text

Ticker

Touch

UID

Utility Methods

CreateJS

EaselJS

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

ColorMatrixFilter Class

            Extends Filter

            Defined in: ColorMatrixFilter:39

            Module: EaselJS

Allows you to carry out complex color operations such as modifying saturation, brightness, or inverting. See the
ColorMatrix for more information on changing colors. For an easier color transform,
consider the ColorFilter.

Example

This example creates a red circle, inverts its hue, and then saturates it to brighten it up.

 var shape = new createjs.Shape().set({x:100,y:100});
 shape.graphics.beginFill("#ff0000").drawCircle(0,0,50);

 var matrix = new createjs.ColorMatrix().adjustHue(180).adjustSaturation(100);
 shape.filters = [
     new createjs.ColorMatrixFilter(matrix)
 ];

 shape.cache(-50, -50, 100, 100);

See Filter for an more information on applying filters.

Constructor

ColorMatrixFilter

            (

                        matrix

)

                Defined in

        ColorMatrixFilter:39

Parameters:

                        matrix
                        Array

A 4x5 matrix describing the color operation to perform. See also the ColorMatrix
class.

Index

Methods

Item Index

Methods

                                applyFilter

                                clone

                                getBounds

                                initialize

                                toString

Methods

applyFilter

            (

                        ctx

                        x

                        y

                        width

                        height

                        [targetCtx]

                        [targetX]

                        [targetY]

)

            Boolean

Inherited from
                Filter:

        applyFilter:93

Applies the filter to the specified context.

Parameters:

                        ctx
                        CanvasRenderingContext2D

The 2D context to use as the source.

                        x
                        Number

The x position to use for the source rect.

                        y
                        Number

The y position to use for the source rect.

                        width
                        Number

The width to use for the source rect.

                        height
                        Number

The height to use for the source rect.

                        [targetCtx]
                        CanvasRenderingContext2D
                        optional

The 2D context to draw the result to. Defaults to the context passed to ctx.

                        [targetX]
                        Number
                        optional

The x position to draw the result to. Defaults to the value passed to x.

                        [targetY]
                        Number
                        optional

The y position to draw the result to. Defaults to the value passed to y.

Returns:

                        Boolean:

If the filter was applied successfully.

clone

        ()

            ColorMatrixFilter

Inherited from

                Filter

            but overwritten in

        clone:121

Returns a clone of this ColorMatrixFilter instance.

Returns:

                        ColorMatrixFilter:

A clone of the current ColorMatrixFilter instance.

getBounds

        ()

            Rectangle

Inherited from
                Filter:

        getBounds:82

Returns a rectangle with values indicating the margins required to draw the filter or null.
For example, a filter that will extend the drawing area 4 pixels to the left, and 7 pixels to the right
(but no pixels up or down) would return a rectangle with (x=-4, y=0, width=11, height=0).

Returns:

                        Rectangle:

a rectangle object indicating the margins required to draw the filter or null if the filter does not effect bounds.

initialize

            (

                        matrix

)

        protected

Inherited from

                Filter

            but overwritten in

        initialize:74

Parameters:

                        matrix
                        Array

A 4x5 matrix describing the color operation to perform.

toString

        ()

            String

Inherited from
                Filter:

        toString:108

Returns a string representation of this object.

Returns:

                        String:

a string representation of the instance.


text:
module Shared::GuideModule
  GUIDE_PARTIALS = %w(guide_taxa identotron_taxa)

  def show_guide
    filter_param_keys = [:colors, :taxon, :q, :establishment_means,
      :conservation_status, :threatened, :introduced, :native]
    @filter_params = Hash[params.select{|k,v|
      is_filter_param = filter_param_keys.include?(k.to_sym)
      is_blank = if v.is_a?(Array) && v.size == 1
        v[0].blank?
      else
        v.blank?
      end
      is_filter_param && !is_blank
    }].symbolize_keys
    @scope = Taxon.active.of_rank_equiv(10)

    if block_given?
      @scope = yield(@scope)
    end

    if @q = @filter_params[:q]
      @search_taxon_ids = Taxon.elastic_search(
        where: { "names.name": @q }, fields: :id).per_page(1000).map(&:id)
      if @search_taxon_ids.size == 1
        @taxon = Taxon.find_by_id(@search_taxon_ids.first)
      elsif Taxon.where(id: @search_taxon_ids).where("name LIKE ?", "#{@q.capitalize}%").count == 1
        @taxon = Taxon.where(name: @q.capitalize).first
      else
        @scope = @scope.among(@search_taxon_ids)
      end
    end

    if @filter_params[:taxon]
      @taxon = Taxon.find_by_id(@filter_params[:taxon].to_i) if @filter_params[:taxon].to_i > 0
      @taxon ||= TaxonName.where("lower(name) = ?", @filter_params[:taxon].to_s.strip.gsub(/[\s_]+/, ' ').downcase).
        first.try(:taxon)
    end
    if @taxon
      @scope = if @taxon.species_or_lower?
        @scope.self_and_descendants_of(@taxon)
      else
        @scope.descendants_of(@taxon)
      end
      @order = "taxa.ancestry, taxa.id, taxa.name" if params[:order] == 'taxonomy'
      @order ||= "listed_taxa.observations_count DESC, taxa.observations_count DESC"
    end

    if @colors = @filter_params[:colors]
      @scope = @scope.colored(@colors)
    end

    if @threatened = (params[:threatened] == "1")
      @scope = if @place
        @scope.threatened_in_place(@place)
      else
        @scope.threatened
      end
    elsif @conservation_status = @filter_params[:conservation_status]
      @scope = if @place
        @scope.has_conservation_status_in_place(@conservation_status, @place)
      else
        @scope.has_conservation_status(@conservation_status)
      end
    end

    page = (params[:page] || 1).to_i
    per_page = 50
    offset = (page - 1) * per_page
    total_entries = @scope.count
    @scope = @scope.select("taxa.*, listed_taxa.id as listed_taxon_id, listed_taxa.observations_count").distinct("taxa.id")
    @paged_scope = @scope.order(@order).limit(per_page).offset(offset)
    @paged_scope = @paged_scope.has_photos if @filter_params.blank?
    Taxon.preload_associations(@paged_scope, [
      { taxon_photos: :photo },
      { taxon_names: :place_taxon_names},
      :conservation_statuses,
      :taxon_descriptions,
      {taxon_scheme_taxa: :taxon_scheme}
    ])
    @taxa = WillPaginate::Collection.create(page, per_page, total_entries) do |pager|
      pager.replace(@paged_scope.to_a)
    end
    @taxa_by_taxon_id = @taxa.index_by{|t| t.id}

    @partial = params[:partial]
    @partial = "guide_taxa" unless GUIDE_PARTIALS.include?(@partial)
    @partial = "guides/#{@partial}"
  end

  def show_guide_widget
    @headless = @footless = true
    browsing_taxon_ids = Taxon::ICONIC_TAXA.map{|it| it.ancestor_ids + [it.id]}.flatten.uniq
    browsing_taxa = Taxon.where(id: browsing_taxon_ids).where("name != 'Life'").
      order(:ancestry).includes(:taxon_names)
    @arranged_taxa = Taxon.arrange_nodes(browsing_taxa)
    @grid = params[:grid]
    @grid = "grid" unless %w(grid fluid).include?(@grid)
    @size = params[:size]
    @size = "medium" unless %w(small medium).include?(@size)
    @labeled = params[:labeled]
    @labeld = nil unless params[:labeled] == 'unlabeled'
  end
end


text:
namespace lox {

class Value : private Copyable {
  using VariantType = std::variant<
    std::nullptr_t,
    bool,
    std::int64_t,
    double,
    std::string>;

  VariantType v_{};

  template <typename T> std::int64_t integer_cast(T x) noexcept {
    return static_cast<std::int64_t>(x);
  }

  template <typename T> Value& set_integer(T x) noexcept {
    return v_ = static_cast<std::int64_t>(x), *this;
  }

  Value& set_string(const std::string& s) noexcept {
    return v_ = s, *this;
  }

  Value add_operation(const Value& r) const {
    if (is_string() && r.is_string())
      return to_string() + r.to_string();
    else if (is_numeric() && r.is_numeric())
      return binary_numeric(add(), r);
    return nullptr;
  }

  Value add_string(const std::string& s) const {
    return to_string() + s;
  }

  struct add {
    template <typename X, typename Y>
    Value operator()(X x, Y y) const { return x + y; }
  };

  struct sub {
    template <typename X, typename Y>
    Value operator()(X x, Y y) const { return x - y; }
  };

  struct mul {
    template <typename X, typename Y>
    Value operator()(X x, Y y) const { return x * y; }
  };

  struct div {
    template <typename X, typename Y>
    Value operator()(X x, Y y) const { return x / y; }
  };

  template <typename BinaryFun>
  Value binary_numeric(BinaryFun&& fn, const Value& r) const {
    if (is_integer() && r.is_integer())
      return fn(to_integer(), r.to_integer());
    else if (is_integer() && r.is_decimal())
      return fn(to_integer(), r.to_decimal());
    else if (is_decimal() && r.is_integer())
      return fn(to_decimal(), r.to_integer());
    else
      return fn(to_decimal(), r.to_decimal());
  }

  Value mod_numeric(const Value& r) const {
    return to_integer() % r.to_integer();
  }
public:
  Value(void) noexcept : v_(nullptr) {}
  Value(std::nullptr_t) noexcept : v_(nullptr) {}
  Value(bool b) noexcept : v_(b) {}
  Value(std::int8_t i8) noexcept : v_(integer_cast(i8)) {}
  Value(std::uint8_t u8) noexcept : v_(integer_cast(u8)) {}
  Value(std::int16_t i16) noexcept : v_(integer_cast(i16)) {}
  Value(std::uint16_t u16) noexcept : v_(integer_cast(u16)) {}
  Value(std::int32_t i32) noexcept : v_(integer_cast(i32)) {}
  Value(std::uint32_t u32) noexcept : v_(integer_cast(u32)) {}
  Value(std::int64_t i64) noexcept : v_(i64) {}
  Value(std::uint64_t u64) noexcept : v_(integer_cast(u64)) {}
#if defined(__GNUC__)
  Value(long long ll) noexcept : v_(integer_cast(ll)) {}
  Value(unsigned long long ull) noexcept : v_(integer_cast(ull)) {}
#endif
  Value(double d) noexcept : v_(d) {}
  Value(const char* s) noexcept : v_(std::string(s)) {}
  Value(const std::string& s) noexcept : v_(s) {}
  Value(const Value& r) noexcept : v_(r.v_) {}
  Value(Value&& r) noexcept : v_(std::move(r.v_)) {}

  bool is_nil(void) const { return std::holds_alternative<std::nullptr_t>(v_); }
  bool is_boolean(void) const { return std::holds_alternative<bool>(v_); }
  bool is_integer(void) const { return std::holds_alternative<std::int64_t>(v_); }
  bool is_decimal(void) const { return std::holds_alternative<double>(v_); }
  bool is_string(void) const { return std::holds_alternative<std::string>(v_); }

  bool is_numeric(void) const { return is_integer() || is_decimal(); }

  bool to_boolean(void) const { return std::get<bool>(v_); }
  std::int64_t to_integer(void) const { return std::get<std::int64_t>(v_); }
  double to_decimal(void) const { return std::get<double>(v_); }
  std::string to_string(void) const { return std::get<std::string>(v_); }

  operator bool(void) const { return to_boolean(); }
  operator std::int64_t(void) const { return to_integer(); }
  operator double(void) const { return to_decimal(); }
  operator std::string(void) const { return to_string(); }

  bool operator==(const Value& r) const { return v_ == r.v_; }
  bool operator!=(const Value& r) const { return v_ != r.v_; }
  bool operator<(const Value& r) const { return v_ < r.v_; }
  bool operator<=(const Value& r) const { return v_ <= r.v_; }
  bool operator>(const Value& r) const { return v_ > r.v_; }
  bool operator>=(const Value& r) const { return v_ >= r.v_; }

  Value operator+(const Value& r) const { return add_operation(r); }
  Value operator-(const Value& r) const { return binary_numeric(sub(), r); }
  Value operator*(const Value& r) const { return binary_numeric(mul(), r); }
  Value operator/(const Value& r) const { return binary_numeric(div(), r); }
  Value operator%(const Value& r) const { return mod_numeric(r); }
  Value& operator+=(const Value& r) { return *this = *this + r, *this; }
  Value& operator-=(const Value& r) { return *this = *this - r, *this; }
  Value& operator*=(const Value& r) { return *this = *this * r, *this; }
  Value& operator/=(const Value& r) { return *this = *this / r, *this; }
  Value& operator%=(const Value& r) { return *this = *this % r, *this; }

  Value& operator=(const Value& r) noexcept { return v_ = r.v_, *this; }
  Value& operator=(Value&& r) noexcept { return v_ = std::move(r.v_), *this; }
  Value& operator=(std::nullptr_t) noexcept { return v_ = nullptr, *this; }
  Value& operator=(bool b) noexcept { return v_ = b, *this; }
  Value& operator=(std::int8_t i8) noexcept { return set_integer(i8); }
  Value& operator=(std::uint8_t u8) noexcept { return set_integer(u8); }
  Value& operator=(std::int16_t i16) noexcept { return set_integer(i16); }
  Value& operator=(std::uint16_t u16) noexcept { return set_integer(u16); }
  Value& operator=(std::int32_t i32) noexcept { return set_integer(i32); }
  Value& operator=(std::uint32_t u32) noexcept { return set_integer(u32); }
  Value& operator=(std::int64_t i64) noexcept { return set_integer(i64); }
  Value& operator=(std::uint64_t u64) noexcept { return set_integer(u64); }
#if defined(__GNUC__)
  Value& operator=(long long ll) noexcept { return set_integer(ll); }
  Value& operator=(unsigned long long ull) noexcept { return set_integer(ull); }
#endif
  Value& operator=(double d) noexcept { return v_ = d, *this; }
  Value& operator=(const char* s) noexcept { return set_string(s); }
  Value& operator=(const std::string& s) noexcept { return set_string(s); }

  bool is_truthy(void) const;
  std::string stringify(void) const;
  std::string type(void) const;
};

std::ostream& operator<<(std::ostream& out, const Value& r);

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <artifactId>spark-parent_2.10</artifactId>
    <groupId>org.apache.spark</groupId>
    <version>1.6.1</version>
    <relativePath>../../pom.xml</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.apache.spark</groupId>
  <artifactId>spark-streaming-kafka_2.10</artifactId>
  <name>Spark Project External Kafka</name>
  <url>http://spark.apache.org/</url>
  <build>
    <outputDirectory>target/scala-${scala.binary.version}/classes</outputDirectory>
    <testOutputDirectory>target/scala-${scala.binary.version}/test-classes</testOutputDirectory>
  </build>
  <dependencies>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-streaming_2.10</artifactId>
      <version>1.6.1</version>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <artifactId>spark-core_2.10</artifactId>
          <groupId>org.apache.spark</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.10</artifactId>
      <version>1.6.1</version>
      <type>test-jar</type>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>chill_2.10</artifactId>
          <groupId>com.twitter</groupId>
        </exclusion>
        <exclusion>
          <artifactId>chill-java</artifactId>
          <groupId>com.twitter</groupId>
        </exclusion>
        <exclusion>
          <artifactId>xbean-asm5-shaded</artifactId>
          <groupId>org.apache.xbean</groupId>
        </exclusion>
        <exclusion>
          <artifactId>spark-launcher_2.10</artifactId>
          <groupId>org.apache.spark</groupId>
        </exclusion>
        <exclusion>
          <artifactId>spark-network-common_2.10</artifactId>
          <groupId>org.apache.spark</groupId>
        </exclusion>
        <exclusion>
          <artifactId>spark-network-shuffle_2.10</artifactId>
          <groupId>org.apache.spark</groupId>
        </exclusion>
        <exclusion>
          <artifactId>spark-unsafe_2.10</artifactId>
          <groupId>org.apache.spark</groupId>
        </exclusion>
        <exclusion>
          <artifactId>commons-lang3</artifactId>
          <groupId>org.apache.commons</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jul-to-slf4j</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jcl-over-slf4j</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
        <exclusion>
          <artifactId>compress-lzf</artifactId>
          <groupId>com.ning</groupId>
        </exclusion>
        <exclusion>
          <artifactId>RoaringBitmap</artifactId>
          <groupId>org.roaringbitmap</groupId>
        </exclusion>
        <exclusion>
          <artifactId>akka-remote_2.10</artifactId>
          <groupId>com.typesafe.akka</groupId>
        </exclusion>
        <exclusion>
          <artifactId>akka-slf4j_2.10</artifactId>
          <groupId>com.typesafe.akka</groupId>
        </exclusion>
        <exclusion>
          <artifactId>json4s-jackson_2.10</artifactId>
          <groupId>org.json4s</groupId>
        </exclusion>
        <exclusion>
          <artifactId>mesos</artifactId>
          <groupId>org.apache.mesos</groupId>
        </exclusion>
        <exclusion>
          <artifactId>netty-all</artifactId>
          <groupId>io.netty</groupId>
        </exclusion>
        <exclusion>
          <artifactId>stream</artifactId>
          <groupId>com.clearspring.analytics</groupId>
        </exclusion>
        <exclusion>
          <artifactId>metrics-core</artifactId>
          <groupId>io.dropwizard.metrics</groupId>
        </exclusion>
        <exclusion>
          <artifactId>metrics-jvm</artifactId>
          <groupId>io.dropwizard.metrics</groupId>
        </exclusion>
        <exclusion>
          <artifactId>metrics-json</artifactId>
          <groupId>io.dropwizard.metrics</groupId>
        </exclusion>
        <exclusion>
          <artifactId>metrics-graphite</artifactId>
          <groupId>io.dropwizard.metrics</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jackson-databind</artifactId>
          <groupId>com.fasterxml.jackson.core</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jackson-module-scala_2.10</artifactId>
          <groupId>com.fasterxml.jackson.module</groupId>
        </exclusion>
        <exclusion>
          <artifactId>ivy</artifactId>
          <groupId>org.apache.ivy</groupId>
        </exclusion>
        <exclusion>
          <artifactId>oro</artifactId>
          <groupId>oro</groupId>
        </exclusion>
        <exclusion>
          <artifactId>tachyon-client</artifactId>
          <groupId>org.tachyonproject</groupId>
        </exclusion>
        <exclusion>
          <artifactId>pyrolite</artifactId>
          <groupId>net.razorvine</groupId>
        </exclusion>
        <exclusion>
          <artifactId>py4j</artifactId>
          <groupId>net.sf.py4j</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.10</artifactId>
      <version>0.8.2.1</version>
      <scope>compile</scope>
      <exclusions>
        <exclusion>
          <artifactId>jmxri</artifactId>
          <groupId>com.sun.jmx</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jmxtools</artifactId>
          <groupId>com.sun.jdmk</groupId>
        </exclusion>
        <exclusion>
          <artifactId>jopt-simple</artifactId>
          <groupId>net.sf.jopt-simple</groupId>
        </exclusion>
        <exclusion>
          <artifactId>slf4j-simple</artifactId>
          <groupId>org.slf4j</groupId>
        </exclusion>
        <exclusion>
          <artifactId>zookeeper</artifactId>
          <groupId>org.apache.zookeeper</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>net.sf.jopt-simple</groupId>
      <artifactId>jopt-simple</artifactId>
      <version>3.2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.scalacheck</groupId>
      <artifactId>scalacheck_2.10</artifactId>
      <version>1.11.3</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>test-interface</artifactId>
          <groupId>org.scala-sbt</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-test-tags_2.10</artifactId>
      <version>1.6.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.scalatest</groupId>
      <artifactId>scalatest_2.10</artifactId>
      <version>2.2.1</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>scala-reflect</artifactId>
          <groupId>org.scala-lang</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>hamcrest-core</artifactId>
          <groupId>org.hamcrest</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>com.novocode</groupId>
      <artifactId>junit-interface</artifactId>
      <version>0.11</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <artifactId>test-interface</artifactId>
          <groupId>org.scala-sbt</groupId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>
  <properties>
    <sbt.project.name>streaming-kafka</sbt.project.name>
  </properties>
</project>