text:
package com.ibm.uk.hursley.perfharness.amqp.utils;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

import com.ibm.mqlight.api.BytesDelivery;
import com.ibm.mqlight.api.Delivery;
import com.ibm.mqlight.api.StringDelivery;

 /**
 * @author ElliotGregory
 *
 * Embedded Action message for the test payloads.
 * Takes the form of
 * $EC$command=argument[,command=argument]$EC$
 */
public class EmbeddedAction {

	private final static String EYE_CATCHER = "$EC$";
	private final static int MAX_SEARCH = 200;
	private final Map<String,String> commands = new HashMap<String,String>();

	/**
	 * @param delivery
	 * @return
	 */
	public static EmbeddedAction createEmbeddedAction (final Delivery delivery) {
		EmbeddedAction rc = null;

		byte[] data;
		if (delivery != null) {
			if (delivery instanceof StringDelivery) {
				data = ((StringDelivery) delivery).getData().getBytes();
				rc = createEmbeddedAction(data);
			}
			else if (delivery instanceof BytesDelivery) {
				ByteBuffer buffer = ((BytesDelivery) delivery).getData();
				rc = createEmbeddedAction(buffer.array());
			}
		}
		return rc;
	}

	/**
	 * @param buffer
	 * @return
	 */
	public static EmbeddedAction createEmbeddedAction (final byte [] buffer) {

		if (isEyeCatcher(buffer, 0)) {
			int maxSearch = Math.min(MAX_SEARCH, buffer.length);
			for (int endOffset = EYE_CATCHER.length(); endOffset < maxSearch; endOffset++) {
				if (isEyeCatcher(buffer, endOffset)) {
					return new EmbeddedAction(new String(buffer,EYE_CATCHER.length(), endOffset - EYE_CATCHER.length()));
				}
			}
		}

		return null;
	}

	/**
	 * @param buffer
	 * @param offset
	 * @return
	 */
	private static boolean isEyeCatcher (final byte [] buffer, final int offset) {
		int os = offset;
		for (byte b : EYE_CATCHER.getBytes()) {
			if (buffer[os++] != b) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @throws EmbeddedActionException
	 * @throws ParserConfigurationException
	 *
	 */
	public EmbeddedAction () {

	}

	/**
	 *
	 */
	private EmbeddedAction (final String rawText) {
		String[] items = rawText.split(",");
		for (String item : items) {
			String[] elements = item.split("=");
			if (elements.length == 2) {
				commands.put(elements[0], elements[1]);
			}
		}
	}

	/**
	 * @param command
	 * @param argument
	 */
	public void putCommand (final String command, final String argument) {
		commands.put(command, argument);
	}

	/**
	 * @param command
	 * @return
	 */
	public String getCommand (final String command) {
		return commands.get(command);
	}

	/**
	 * @param command
	 * @param defaultValue
	 * @return
	 */
	public String getCommand (final String command, final String defaultValue) {
		return commands.containsKey(command) ? commands.get(command) : defaultValue;
	}

	/**
	 * @return
	 */
	public String generateMessage() {
		StringBuilder sb = new StringBuilder();
		sb.append(EYE_CATCHER);
		String separator = "";
		for (Map.Entry<String,String> entry : commands.entrySet()) {
			sb.append(separator);
			separator = ",";
			sb.append(entry.getKey());
			sb.append("=");
			sb.append(entry.getValue());
		}
		sb.append(EYE_CATCHER);
		return sb.toString();
	}

	private final static String EOL = System.getProperty("line.separator");

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("EmbeddedAction [commands="+ EOL);
		for (Map.Entry<String,String> entry : commands.entrySet()) {
			String value = entry.getValue();
			if (value == null) value = "NULL";
			sb.append(entry.getKey() + " = " + value + EOL);
		}
		sb.append("]" + EOL);
		return sb.toString();
	}
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var timer = require("timer");
var file = require("file");

exports.findAndRunTests = function findAndRunTests(options) {
  var finder = new TestFinder(options.dirs);
  var runner = new TestRunner();
  runner.startMany({tests: finder.findTests(),
                    onDone: options.onDone});
};

var TestFinder = exports.TestFinder = function TestFinder(dirs) {
  this.dirs = dirs;
};

TestFinder.prototype = {
  _makeTest: function _makeTest(suite, name, test) {
    function runTest(runner) {
      console.info("executing '" + suite + "." + name + "'");
      test(runner);
    }
    return runTest;
  },

  findTests: function findTests() {
    var self = this;
    var tests = [];

    this.dirs.forEach(
      function(dir) {
        var suites = [name.slice(0, -3)
                      for each (name in file.list(dir))
                      if (/^test-.*\.js$/.test(name))];

        suites.forEach(
          function(suite) {
            var module = require(suite);
            for (name in module)
              if (name.indexOf("test") == 0)
                tests.push(self._makeTest(suite, name, module[name]));
          });
      });
    return tests;
  }
};

var TestRunner = exports.TestRunner = function TestRunner(options) {
  this.passed = 0;
  this.failed = 0;
};

TestRunner.prototype = {
  DEFAULT_PAUSE_TIMEOUT: 10000,

  makeSandboxedLoader: function makeSandboxedLoader(options) {
    if (!options)
      options = {};
    var Cuddlefish = require("cuddlefish");

    options.fs = Cuddlefish.parentLoader.fs;
    return new Cuddlefish.Loader(options);
  },

  pass: function pass(message) {
    console.info("pass:", message);
    this.passed++;
  },

  fail: function fail(message) {
    console.error("fail:", message);
    this.failed++;
  },

  exception: function exception(e) {
    console.exception(e);
    this.failed++;
  },

  assertMatches: function assertMatches(string, regexp, message) {
    if (regexp.test(string)) {
      if (!message)
        message = uneval(string) + " matches " + uneval(regexp);
      this.pass(message);
    } else {
      var no = uneval(string) + " doesn't match " + uneval(regexp);
      if (!message)
        message = no;
      else
        message = message + " (" + no + ")";
      this.fail(message);
    }
  },

  assertRaises: function assertRaises(func, predicate, message) {
    try {
      func();
      if (message)
        this.fail(message + " (no exception thrown)");
      else
        this.fail("function failed to throw exception");
    } catch (e) {
      if (typeof(predicate) == "object")
        this.assertMatches(e.message, predicate, message);
      else
        this.assertEqual(e.message, predicate, message);
    }
  },

  assertNotEqual: function assertNotEqual(a, b, message) {
    if (a != b) {
      if (!message)
        message = "a != b != " + uneval(a);
      this.pass(message);
    } else {
      var equality = uneval(a) + " == " + uneval(b);
      if (!message)
        message = equality;
      else
        message += " (" + equality + ")";
      this.fail(message);
    }
  },

  assertEqual: function assertEqual(a, b, message) {
    if (a == b) {
      if (!message)
        message = "a == b == " + uneval(a);
      this.pass(message);
    } else {
      var inequality = uneval(a) + " != " + uneval(b);
      if (!message)
        message = inequality;
      else
        message += " (" + inequality + ")";
      this.fail(message);
    }
  },

  done: function done() {
    if (!this.isDone) {
      this.isDone = true;
      if (this.waitTimeout !== null) {
        timer.clearTimeout(this.waitTimeout);
        this.waitTimeout = null;
      }
      if (this.onDone !== null) {
        var onDone = this.onDone;
        this.onDone = null;
        onDone(this);
      }
    }
  },

  waitUntilDone: function waitUntilDone(ms) {
    if (ms === undefined)
      ms = this.DEFAULT_PAUSE_TIMEOUT;

    var self = this;

    function tiredOfWaiting() {
      self.failed++;
      self.done();
    }

    this.waitTimeout = timer.setTimeout(tiredOfWaiting, ms);
  },

  startMany: function startMany(options) {
    function scheduleNextTest(self) {
      function runNextTest() {
        var test = options.tests.pop();
        if (test)
          self.start({test: test, onDone: scheduleNextTest});
        else
          options.onDone(self);
      }
      timer.setTimeout(runNextTest, 0);
    }
    scheduleNextTest(this);
  },

  start: function start(options) {
    this.test = options.test;
    this.isDone = false;
    this.onDone = options.onDone;
    this.waitTimeout = null;

    try {
      this.test(this);
    } catch (e) {
      this.exception(e);
    }
    if (this.waitTimeout === null)
      this.done();
  }
};

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * Sushis controller.
 */

var fs    = require('fs'),
    route = require('koa-route'),
    parse = require('co-body'),
    formidable = require('koa-formidable'),
    mongo = require('../config/mongo'),
    createSushiInGraph  = require('../graph-entities/userCreateSushi'),
    createUser2SushiRel = require('../graph-entities/addUser2SushiRelation'),
    createSushi2UserRel = require('../graph-entities/addSushi2UserRelation'),
    createSushi2SushiRel  = require('../graph-entities/addSushi2SushiRelation'),
    removeUser2SushiRel = require('../graph-entities/delUser2SushiRelation'),
    getUserSushis       = require('../graph-entities/getUserSushis'),
    getRelatedChilds  = require('../graph-entities/getRelatedChildSushis'),
    getRelatedParents = require('../graph-entities/getRelatedParentSushis'),
    updateQi          = require('../graph-entities/updateQiOnSushi'),
    setType           = require('../graph-entities/setTypeOnSushi'),
    clearSushi          = require('../graph-entities/clearSushi'),
    packdata          = require('../sushi-entities/packdata'),
    xp                = require('../user-entities/xp'),
    indexer           = require('../indexer/addSushi'),
    unindexer         = require('../indexer/removeSushi'),
    search            = require('../indexer/searchSushi'),
    types             = require('../config/types'),
    emails            = require('../services/emails/index.js'),
    ws                = require('../config/ws'),
    foreach           = require('generator-foreach'),
    ObjectID          = mongo.ObjectID;

// register koa routes
exports.init = function (app) {
  app.use(route.get ('/api/sushis/search/:query', searchSushis));
  app.use(route.get ('/api/sushis', listSushis));
  app.use(route.get ('/api/sushis/:sushiId/view', viewSushi));
  app.use(route.get ('/api/sushis/:sushiId/child/:type', relatedChilds));
  app.use(route.get ('/api/sushis/:sushiId/parent/:type', relatedParent));
  app.use(route.put ('/api/sushis/:sushiId/update', updateSushi));
  app.use(route.put ('/api/sushis/:sushiId/share', shareSushi));
  app.use(route.put ('/api/sushis/:sushiId/follow', followSushi));
  app.use(route.put ('/api/sushis/:sushiId/unfollow', unfollowSushi));
  app.use(route.put ('/api/sushis/:sushiId/sponsor', sponsorSushi));
  app.use(route.put ('/api/sushis/:sushiId/unsponsor', unsponsorSushi));
  app.use(route.put ('/api/sushis/:sushiId/support', supportSushi));
  app.use(route.put ('/api/sushis/:sushiId/evolve/:type', evolveSushi));
  app.use(route.put ('/api/sushis/:sushiId/unsupport', unsupportSushi));
  app.use(route.post('/api/sushis', createSushi));
  app.use(route.post('/api/sushis/:parentSushiId', createSubSushi));
  app.use(route.post('/api/sushis/:sushiId/attachments', uploadFile));
  app.use(route.delete ('/api/sushis/:sushiId/attachments/:fileId', removeFile));
  app.use(route.post('/api/sushis/:sushiId/mailto/:to', sendSushiByMail));
  app.use(route.post('/api/sushis/:sushiId/packdata/:type', createPackData));
  app.use(route.get ('/api/sushis/:sushiId/packdata/:type', getPackData));
  app.use(route.put ('/api/sushis/:sushiId/packdata/:type', setPackData));
  app.use(route.put ('/api/sushis/:sushiId/packdata/:type/end', endPackData));
  app.use(route.delete ('/api/sushis/:sushiId', deleteSushi));
};

function *searchSushis(query)
{
  var results = yield search(query);
  this.body = results;
}

function *sendSushiByMail(sushiId, to)
{
  sushiId   = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  yield emails.sendSushi (this.user, to, sushi);
  this.status = 200;
  this.body   = 'ok';
}

/**
* Find related labeled sushis following neo4j CHILD relationships
*/
function *relatedChilds(sushiId, type)
{
  var relatedSushisIds = yield getRelatedChilds(sushiId,type);
  var sushis = yield mongo.sushis.find(
      {_id: { $in: relatedSushisIds }}).toArray();
  var scope = this;
  yield * foreach(sushis, function * (sushi) {
        sushi.id = sushi._id;
        delete sushi._id;
        sushi.dataCache = packdata.getPack (sushi, sushi.type);
        sushi.typeInfo = types[sushi.type];
        sushi.qi = yield updateQi(scope.user, sushi, 0);
      });
  this.body = sushis;
}

/**
* Find related labeled sushis following neo4j CHILD relationships
*/
function *relatedParent(sushiId, type)
{
  var relatedSushisIds = yield getRelatedParents(sushiId,type);
  var sushis = yield mongo.sushis.find(
  {_id: { $in: relatedSushisIds }}).toArray();
  var scope = this;
  yield * foreach(sushis, function * (sushi) {
    sushi.id = sushi._id;
    delete sushi._id;
    sushi.dataCache = packdata.getPack (sushi, sushi.type);
    sushi.typeInfo = types[sushi.type];
    sushi.qi = yield updateQi(scope.user, sushi, 0);
  });
  this.body = sushis;
}

/**
 * Lists all user sushis
 */
function *listSushis()
{
  var userSushisIds = yield getUserSushis(this.user);
  var sushis = yield mongo.sushis.find(
      {_id: { $in: userSushisIds }}).toArray();

  var scope = this;
  yield * foreach(sushis, function * (sushi) {
    sushi.id = sushi._id;
    delete sushi._id;
    sushi.dataCache = packdata.getPack (sushi, sushi.type);
    sushi.typeInfo = types[sushi.type];
    sushi.qi = yield updateQi(scope.user, sushi, 0);
  });

  this.body = sushis;
}

/**
 * Get one sushi by id
 */
function *viewSushi(sushiId)
{
  sushiId   = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});

  if(sushi)
  {
    sushi.id = sushi._id;
    delete sushi._id;
    sushi.dataCache = packdata.getPack (sushi, sushi.type);
    sushi.typeInfo  = types[sushi.type];
    this.body = sushi;

    sushi.qi  = yield updateQi(this.user, sushi, 0);
    var result = yield mongo.sushis.update(
        {_id: sushiId},
        {$set: {qi: sushi.qi}}
    );
  }
  else
  {
    this.throw(404, 'Sushi not found');
  }

}

/**
 * Saves a new sushi in the database after proper validations.
 */
function *createSushi()
{
  // it is best to validate sushi body with something like node-validator here, before saving it in the database..
  var sushi  = yield parse(this);
  sushi.creator = this.user;
  sushi.createdTime = new Date();
  sushi.qi = 0;

  var results = yield mongo.sushis.insert(sushi);

  sushi.id = sushi._id;
  delete sushi._id;

  //add sushi in graph
  yield createSushiInGraph (this.user, sushi);
  yield createUser2SushiRel (this.user, sushi, 'CREATED');
  sushi.qi = yield updateQi(this.user, sushi, 0);
  this.status = 201;
  this.body = results[0].id.toString(); // we need .toString() here to return text/plain response
  yield indexer(sushi);

  // now notify everyone about this new sushi
  ws.notify('qi.updated', sushi);
  ws.notify('sushis.created', sushi);
  if(sushi.type) {
    var packData = {
      type : sushi.type,
      data : {}
    };

    var result = yield mongo.sushis.update(
        {_id: sushi.id},
        {$push: {types: sushi.type, sushiPacksData: packData}}
    );

    yield setType(this.user, sushi, sushi.type);

    ws.notify('sushis.evolved', sushi);
  }

  yield xp.gainMainXP (this.user, 50);
  ws.notify('userupdate', this.user);
}

/**
 * Saves a new sushi linked to a parent sushi
 */
function *createSubSushi(parentSushiId)
{
  //get parent
  parentSushiId = new ObjectID(parentSushiId);
  var parentSushi = yield mongo.sushis.findOne({_id : parentSushiId});
  if(parentSushi === null)
  {
    this.throw(404, 'Unable to find parent sushi from id');
  }

  parentSushi.id = parentSushi._id;
  delete parentSushi._id;

  //create sushi
  var sushi  = yield parse(this);
  sushi.creator = this.user;
  sushi.createdTime = new Date();
  sushi.qi = 0;
  sushi.parentSushi = parentSushi;

  var results = yield mongo.sushis.insert(sushi);

  //embbed sub sushi in document
  yield mongo.sushis.update(
      {_id: parentSushiId},
      {$push: {subSushis: {id: sushi._id, title: sushi.title} } }
  );

  sushi.id = sushi._id;
  delete sushi._id;
  this.status = 201;
  this.body = sushi.id; // we need .toString() here to return text/plain response
  yield indexer(sushi);

  //add sushi in graph
  yield createSushiInGraph  (this.user, sushi);
  yield createUser2SushiRel (this.user, sushi, 'CREATED');
  yield createSushi2SushiRel  (sushi, parentSushi, 'PARENT');
  yield createSushi2SushiRel  (parentSushi, sushi, 'CHILD');
  //update parentqi
  parentSushi.qi = yield updateQi (this.user, parentSushi, 1);
  var result = yield mongo.sushis.update(
      {_id: parentSushi.id},
      {$set: {qi: parentSushi.qi}}
  );

  // now notify everyone about this new sushi
  ws.notify('qi.updated', sushi);
  ws.notify('qi.updated', parentSushi);
  ws.notify('sushis.created', sushi);
  ws.notify('sushis.updated', parentSushi);
  if(sushi.type) {
    var packData = {
      type : sushi.type,
      data : {}
    };

    var result = yield mongo.sushis.update(
        {_id: sushi.id},
        {$push: {types: sushi.type, sushiPacksData: packData}}
    );

    yield setType(this.user, sushi, sushi.type);

    ws.notify('sushis.evolved', sushi);

  }

  yield xp.gainMainXP (this.user, 50);
  ws.notify('userupdate', this.user);
}

/**
 * Update a sushi in the database after proper validations.
 */
function *updateSushi()
{
  var sushi  = yield parse(this);
  if(sushi.creator.id !== this.user.id)
  {
    this.throw(403, 'You are not the creator of this sushi');
  }

  sushi.lastUpdate = new Date();
  if(sushi.revision)
  {
    sushi.revision++;
  }
  else
  {
    sushi.revision = 1
  }

  sushi._id = new ObjectID(sushi.id);
  var results = yield mongo.sushis.update(
    {_id: sushi._id},
    {$set: {
      title: sushi.title,
      content: sushi.content,
      privacy: sushi.privacy,
      type: sushi.type,
      revision: sushi.revision,
      lastUpdate: sushi.lastUpdate
    }});

  if(sushi.parentSushi)
  {
    var parentSushiId = new ObjectID(sushi.parentSushi.id);
    var r=yield mongo.sushis.update(
        {_id: parentSushiId, 'subSushis.id' : sushi._id},
        {$set: {'subSushis.$.title': sushi.title } }
    );
  }

  if(sushi.subSushis)
  {
    yield * foreach(sushi.subSushis, function * (sSushi) {
      var sSushiId = new ObjectID(sSushi.id);
      var r=yield mongo.sushis.update(
          {_id: sSushiId},
          {$set: {'parentSushi.title': sushi.title } });
    });
  }

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response
  yield indexer(sushi);

  ws.notify('sushis.updated', sushi);
}

/**
 * Add Type to sushi
 */
function *evolveSushi(sushiId, type)
{
  if(!type)
  {
    this.throw(403, 'type is not valid');
  }

  var sushiId = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  sushi.id = sushi._id;
  delete sushi._id;

  if(sushi.creator.id !== this.user.id)
  {
    this.throw(403, 'You are not the creator of this sushi');
  }

  var evolveNeeded = true;
  if(sushi.types)
  {
    if(sushi.types.indexOf(type) !== -1)
    {
      var result = yield mongo.sushis.update(
          {_id: sushiId},
          {$set: {type: type}});
      console.log('restored in '+ type);
      evolveNeeded = false;
    }
  }

  if(evolveNeeded)
  {
    var packData = {
      type : type,
      data : {}
    };

    var result = yield mongo.sushis.update(
        {_id: sushiId},
        {$push: {types: type, sushiPacksData: packData}}
    );

    result = yield mongo.sushis.update(
        {_id: sushiId},
        {$set: {type: type}});
    console.log('evolved in '+ type);
    yield setType(this.user, sushi, type);

    yield indexer(sushi);

    if (types[type].hasOwnProperty('skills')) {
      yield xp.gainSkillXP (this.user,types[type].skills.creator, 20);
      ws.notify('userupdate', this.user);
    }

  }

  sushi.qi       = yield updateQi (this.user, sushi, 0);

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('sushis.evolved', {id: sushiId, type: type});

}

/**
 * Share a sushi
 */
function *shareSushi(sushiId)
{
  var users   = yield parse(this);
  sushiId      = new ObjectID(sushiId);

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$push: {shares: users}}
  );

  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  sushi.id = sushi._id;
  delete sushi._id;

  yield * foreach(users, function * (user) {
    yield createSushi2UserRel(user, sushi, 'SHARED_TO');

  });

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('qi.updated', sushi);
  ws.notify('sushis.sharesChanged', sushi);
}

/**
 * Sponsor a sushi
 */
function *sponsorSushi()
{
  var sushi   = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(sushi.creator.id === this.user.id)
  {
    this.throw(403, 'You are the creator of this sushi');
  }

  if(sushi.sponsors && sushi.sponsors.indexOf(this.user.id) !== -1)
  {
    this.throw(403, 'You already sponsor this sushi');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$push: {sponsors: this.user.id}}
  );

  yield createUser2SushiRel(this.user, sushi, 'SPONSOR');
  sushi.qi = yield updateQi(this.user, sushi, 0);

  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('qi.updated', sushi);
  ws.notify('sushis.sponsorsChanged', sushi);
}

/**
 * Unsponsor a sushi
 */
function *unsponsorSushi()
{
  var sushi  = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(!sushi.sponsors || sushi.sponsors.indexOf(this.user.id) === -1)
  {
    this.throw(403, 'You are not sponsorer');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$pull: {sponsors: this.user.id}}
  );

  yield removeUser2SushiRel(this.user, sushi, 'SPONSOR');
  sushi.qi = yield updateQi(this.user, sushi, 0);

  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('qi.updated', sushi);
  ws.notify('sushis.sponsorsChanged', sushi);
}

/**
 * Add Support a sushi
 */
function *supportSushi(sushiId)
{
  var sushi   = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(sushi.creator.id === this.user.id)
  {
    this.throw(403, 'You are the creator of this sushi');
  }

  if(sushi.supporters && sushi.supporters.indexOf(this.user.id) !== -1)
  {
    this.throw(403, 'You have already supported this sushi');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$push: {supporters: this.user.id}}
  );

  yield createUser2SushiRel(this.user, sushi, 'SUPPORT');
  sushi.qi = yield updateQi(this.user, sushi, this.user.lvl);

  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('qi.updated', sushi);
  ws.notify('sushis.supportersChanged', sushi);
}

/**
 * Unsupport a sushi
 */
function *unsupportSushi()
{
  var sushi  = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(!sushi.supporters || sushi.supporters.indexOf(this.user.id) === -1)
  {
    this.throw(403, 'You are not supporter');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$pull: {supporters: this.user.id}}
  );

  yield removeUser2SushiRel(this.user, sushi, 'SUPPORT');
  sushi.qi = yield updateQi(this.user, sushi, 0);
  ws.notify('qi.updated', sushi);

  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('sushis.supportersChanged', sushi);
}

/**
 * Follow a sushi
 */
function *followSushi()
{
  var sushi   = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(sushi.creator.id === this.user.id)
  {
    this.throw(403, 'You are the creator of this sushi');
  }

  if(sushi.followers && sushi.followers.indexOf(this.user.id) !== -1)
  {
    this.throw(403, 'You already follow this sushi');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$push: {followers: this.user.id}}
  );

  yield createUser2SushiRel(this.user, sushi, 'FOLLOW');
  sushi.qi = yield updateQi(this.user, sushi, 1);
  ws.notify('qi.updated', sushi);
  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('sushis.followersChanged', sushi);
}

/**
 * Unfollow a sushi
 */
function *unfollowSushi()
{
  var sushi  = yield parse(this);
  var sushiId = new ObjectID(sushi.id);

  if(!sushi.followers || sushi.followers.indexOf(this.user.id) === -1)
  {
    this.throw(403, 'You are not follower');
  }

  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$pull: {followers: this.user.id}}
  );

  yield removeUser2SushiRel(this.user, sushi, 'FOLLOW');
  sushi.qi = yield updateQi(this.user, sushi, 0);
  ws.notify('qi.updated', sushi);
  sushi = yield mongo.sushis.findOne({_id : sushiId});

  sushi.id = sushi._id;
  delete sushi._id;

  this.status = 201;
  this.body = sushi.id.toString(); // we need .toString() here to return text/plain response

  ws.notify('sushis.followersChanged', sushi);
}

/**
 * Appends a new comment to a given sushi.
 * @param sushiId - Sushi ID.
 */
function *createComment(sushiId)
{
  sushiId         = new ObjectID(sushiId);
  var comment   = yield parse(this);
  var commentId = new ObjectID();

  // update sushi document with the new comment
  comment = {_id: commentId, from: this.user, createdTime: new Date(), message: comment.message};
  var result = yield mongo.sushis.update(
      {_id: sushiId},
      {$push: {comments: comment}}
  );

  this.status = 201;
  this.body = commentId.toString(); // we need .toString() here to return text/plain response

  var sushi = {
    id : sushiId
  };
  // now notify everyone about this new comment
  comment.id = comment._id;
  comment.sushiId = sushiId;
  delete comment._id;
  ws.notify('qi.updated', sushi);
  ws.notify('sushis.comments.created', comment);
  yield xp.gainMainXP (this.user, 2);
  ws.notify('userupdate', this.user);
}

/**
* Add files to sushi
* @param sushiId - Sushi ID.
*/
function *uploadFile(sushiId)
{
  var path = require('path');
  sushiId = new ObjectID(sushiId);
  // multipart upload
  var uploads = [];
  var form = yield formidable.parse({uploadDir: '/tmp/sushi/'},this);
  console.log (JSON.stringify(form));
  var fileData = {
    path: form.files.file.path,
    type: form.files.file.type,
    name: form.files.file.name,
    size: form.files.file.size
  };
  var result = yield mongo.sushis.update(
    {_id: sushiId},
    {$push: {files: fileData}}
  );
  var sushi = sushi = yield mongo.sushis.findOne({_id : sushiId});
  sushi.id = sushi._id;
  delete sushi._id;
  this.status = 201;
  ws.notify('sushis.updated', sushi);
}

/**
*
*/
function *getFile(sushiId, fileId)
{
  var path = require ('path');
  var os = require ('os');
  sushiId = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  var targetFile = null;
  var targetType = null
  sushi.files.forEach (function (file) {
    if(file.name === fileId)
    {
      targetFile = file.path;
      targetType = file.type;
      return;
    }
  });
  if(targetFile !== null) {
    yield send(this, targetFile);
  }
}

/**
*
*/
function *removeFile(sushiId, fileId)
{
  sushiId = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  var targetFile = null;
  sushi.files.forEach (function (file) {
    if(file.name === fileId)
    {
      fs.unlinkSync(file.path);
      targetFile = file;
      return;
    }
  });
  var result = yield mongo.sushis.update(
    {_id: sushiId},
    {$pull: {files: targetFile}}
  );
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  sushi.id = sushi._id;
  delete sushi._id;
  this.status = 201;
  ws.notify('sushis.updated', sushi);
}

/**
 * Create a new packData for a given typed sushi.
 * @param sushiId - Sushi ID.
 */
function *createPackData(sushiId, type)
{
  sushiId      = new ObjectID(sushiId);

  var result = yield mongo.sushis.findOne({_id : sushiId,'sushiPacksData.type' : type});
  if(result) {
    // update sushi document with the new packData
    var data = yield parse(this);
    result = yield mongo.sushis.update(
    {_id: sushiId,'sushiPacksData.type' : type},
        {$set: {'sushiPacksData.$.data': data}}
    );

    this.status = 201;
    this.body = result;
    ws.notify('sushis.sushiPacksData.updated', sushiId);
  }
  else
  {
    var packData   = {
      type: type,
      data: yield parse(this)
    };
    console.log('create packdata');
    // update sushi document with the new packData
    var result = yield mongo.sushis.update(
        {_id: sushiId},
        {$push: {sushiPacksData: packData}}
    );

    this.status = 201;
    ws.notify('sushis.sushiPacksData.created');
  }

}

/**
 * Set packData for a given typed sushi.
 * @param sushiId - Sushi ID.
 */
function *setPackData(sushiId, type)
{
  sushiId         = new ObjectID(sushiId);
  var packData   = yield parse(this);

  // update sushi document with the new packData
  var result = yield mongo.sushis.update(
      {_id: sushiId,'sushiPacksData.type' : type},
      {$set: {'sushiPacksData.$.data': packData}}
  );

  this.status = 201;
  this.body = result;
  ws.notify('sushis.sushiPacksData.updated', sushiId);
}

/**
* End packData lifecycle
* @param sushiId - Sushi ID.
*/
function *endPackData(sushiId, type)
{
  sushiId             = new ObjectID(sushiId);
  var packData      = yield parse(this);

  // update sushi document with the new packData and lockit
  var result = yield mongo.sushis.update(
  {_id: sushiId,'sushiPacksData.type' : type},
  {$set: {
    'sushiPacksData.$.data': packData,
    'sushiPacksData.$.readonly': true
    }
  });

  if (types[type].hasOwnProperty('skills')) {
    if (types[type].skills.hasOwnProperty('actor')) {
      if (packData.actor) {
        yield xp.gainSkillXP (packData.actor,types[type].skills.actor, 20);
        ws.notify('userupdate', packData.actor);
      }
    }
  }

  this.status = 201;
  this.body = result;
  ws.notify('sushis.sushiPacksData.ended', sushiId);
}

/**
* Get packData for a given typed sushi.
* @param sushiId - Sushi ID.
 */
function *getPackData(sushiId, type)
{
  sushiId        = new ObjectID(sushiId);
  var sushi      = yield mongo.sushis.findOne({_id : sushiId,'sushiPacksData.type' : type});

  var packData = packdata.getPack (sushi, type);
  this.status = 200;
  this.body = packData;
}

/**
 * Delete sushi by id
 */
function *deleteSushi(sushiId)
{
  sushiId   = new ObjectID(sushiId);
  var sushi = yield mongo.sushis.findOne({_id : sushiId});
  sushi.id = sushi._id;
  delete sushi._id;
  if(!sushi)
  {
    this.throw(403, 'Unable to find sushi');
  }
  if(sushi.creator.id !== this.user.id)
  {
    this.throw(403, 'You are not the creator of this sushi');
  }
  if(sushi.parentSushi) {
    var parentSushiId = sushi.parentSushi.id;
    yield mongo.sushis.update(
        {_id: parentSushiId},
        {$pull: {subSushis: {id: sushi.id, title: sushi.title} } }
    );
  }
  yield unindexer(sushi);
  yield clearSushi  (sushi);
  yield mongo.sushis.remove({_id : sushiId});
  this.status = 201;
  this.body = "deleted";
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

import {BrowserRouter, HashRouter} from 'react-router-dom'
ReactDOM.render(
  <HashRouter>
    <App />
  </HashRouter>,
  document.getElementById('root')
);


text:
package com.mvp4g.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Default Mvp4g entry point. Add the start view of the Root Module to the RootPanel.
 */
public class Mvp4gEntryPoint
  implements EntryPoint {

  /*
   * (non-Javadoc)
   *
   * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
   */
  public void onModuleLoad() {
    Mvp4gModule module = (Mvp4gModule) GWT.create(Mvp4gModule.class);
    module.createAndStartModule();
    RootPanel.get()
             .add((IsWidget) module.getStartView());
  }
}


text:
public class UglyNumbers {
	/*
	 * Ugly numbers are positive integers whose prime factors are 2, 3, or 5. The first ugly number is 1.
	 * This means that no other prime numbers are part of the ugly numbers. What we could do is iterate
	 * through the set of real numbers starting from 1 and incrementing up. We keep a counter of our current
	 * ugly number count and cache it for future use. We can then check each number as to whether or not
	 * the number is divisible by 2, 3, or 5, and if it is, then it is an ugly number.
	 *
	 * However, maybe there is another way that does only one computation based on what's already cached to
	 * find the next ugly number. But how? If we simply do bottom up computations such as 2 * 2 * 2 = 8, what if
	 * we did 5 * 5 * 5, which is 125? There is definitely several more ugly numbers in between than to reach
	 * three computations of three times a prime factor. Doing it that way produces very random numbers that will
	 * need to be sorted, and what if there is an ugly number that we missed? I think I will implement the algorithm
	 * I described in the first paragraph and then see if I can improve it later.
	 *
	 * Okay, thinking about it more, if you take the minimum between the three multiples of 2, 3, and 5, and keep
	 * track of each multiple you are on, then you can compute the next ugly number in one computation. Also,
	 * there seems to be a flaw in the algorithm of my first paragraph. 14 is not an ugly number since it has
	 * a prime factor of 7. This holds true for other prime factors as well that are multiplied by 2, 3, or 5.
	 */

	int current, currentIdx, first, second, third;
	int[] cache;

	public UglyNumbers() {
		current = 1;
		currentIdx = 0;
		cache = new int[500];
		cache[currentIdx] = current;
		first = 0;
		second = 0;
		third = 0;

	}

	public int findUglyNum(int K) throws Exception {

		if (K > cache.length) {
			expandCache();
		}

		if (cache[K-1] != 0) {
			//System.out.println("Pulled from cache");
			return cache[K-1];
		}

		while (currentIdx < K - 1) {
			int two = cache[first] * 2;
			int three = cache[second] * 3;
			int five = cache[third] * 5;

			current = min (two, three, five);

			if (current == two) {
				first++;
			}
			else if (current == three) {
				second++;
			}
			else if (current == five) {
				third++;
			}

			//Prevent duplicates.
			if (current != cache[currentIdx]) {
				currentIdx++;
				cache[currentIdx] = current;
			}

		}

		/*
		for (int i = 0; i < currentIdx; i++) {
			System.out.println("Debug: " + cache[i]);
		}
		*/

		return cache[currentIdx];
	}

	private void expandCache() throws Exception {
		if (cache.length * 2 > Integer.MAX_VALUE) {
			throw new Exception("Number too large");
		}

		int[] oldCache = cache;
		cache = new int[oldCache.length * 2];

		for (int i = 0; i < oldCache.length; i++) {
			cache[i] = oldCache[i];
		}
	}

	public int min(int two, int three, int five) {
		if (two < three && two < five) {
			return two;
		}
		if (three < five) {
			return three;
		}
		return five;

	}

}


text:
package de.fau.cs.mad.rpgpack.toolbox;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import de.fau.cs.mad.rpgpack.R;
import de.fau.cs.mad.rpgpack.toolbox.Timer;
import de.fau.cs.mad.rpgpack.toolbox.TimerDialog;
import android.os.CountDownTimer;

public class TimerActivity extends Activity {

	private TextView mTVTime;
	private Boolean mTimerIsRunning;
	private CountDownTimer mTimer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_game_toolbox_timer);
		init();
	}

	private void init() {
		mTimerIsRunning = false;
		mTVTime = (TextView) findViewById(R.id.textViewTime);
		mTVTime.setText("00:00:00");

		mTVTime.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setTimer(findViewById(android.R.id.content));
			}
		});
	}

	@Override
	public void onSaveInstanceState(Bundle icicle) {
		super.onSaveInstanceState(icicle);
		icicle.putString("time", ((TextView) findViewById(R.id.textViewTime))
				.getText().toString());
		icicle.putBoolean("status", mTimerIsRunning);
	}

	@Override
	public void onRestoreInstanceState(Bundle icicle) {
		mTVTime.setText(icicle.getString("time"));
		if (icicle.getBoolean("status"))
			startTimer(findViewById(android.R.id.content));
	}

	public void setTimer(View v) {
		TimerDialog mTimer = new TimerDialog(this,
				new TimerDialog.OnTimeSetListener() {

					@Override
					public void onTimeSet(Timer view, int hour, int minute,
							int seconds) {
						mTVTime.setText(String.format("%02d:%02d:%02d", hour,
								minute, seconds));
					}
				}, getTimeInt(mTVTime)[0], getTimeInt(mTVTime)[1],
				getTimeInt(mTVTime)[2]);
		mTimer.show();
	}

	public void addSec(View v) {
		int[] time = getTimeInt(mTVTime);
		time[2] = time[2] + 15;
		if (time[2] > 59) {
			time[2] = time[2] - 60;
			int tmp = time[2];
			addMin(findViewById(android.R.id.content));
			time = getTimeInt(mTVTime);
			time[2] = tmp;

		}
		setTime(time);
		if (mTimerIsRunning) {
			startTimer(findViewById(android.R.id.content));
		}
	}

	public void addMin(View v) {
		int[] time = getTimeInt(mTVTime);
		time[1] = time[1] + 1;
		if (time[1] > 59) {
			time[1] = time[1] - 60;
			int tmp = time[1];
			addHour(findViewById(android.R.id.content));
			time = getTimeInt(mTVTime);
			time[1] = tmp;
		}
		setTime(time);
		if (mTimerIsRunning) {
			startTimer(findViewById(android.R.id.content));
		}
	}

	public void addHour(View v) {
		int[] time = getTimeInt(mTVTime);

		if (time[0] < 99) {
			time[0] = time[0] + 1;
			setTime(time);
		}

		if (mTimerIsRunning) {
			startTimer(findViewById(android.R.id.content));
		}
	}

	public void removeSec(View v) {
		int[] time = getTimeInt(mTVTime);

		if (time[0] > 0 || time[1] > 0) {
			time[2] = time[2] - 15;
			if (time[2] < 0) {
				time[2] = time[2] + 60;
				int tmp = time[2];
				removeMin(findViewById(android.R.id.content));
				time = getTimeInt(mTVTime);
				time[2] = tmp;

			}
		} else if (time[2] > 0) {
			time[2] = time[2] - 15;
			if (time[2] < 0) {
				time[2] = 0;
			}
		}
		setTime(time);

		if (mTimerIsRunning) {
			startTimer(findViewById(android.R.id.content));
		}
	}

	public void removeMin(View v) {
		int[] time = getTimeInt(mTVTime);

		if (time[0] > 0) {
			time[1] = time[1] - 1;
			if (time[1] < 0) {
				time[1] = time[1] + 60;
				int tmp = time[1];
				removeHour(findViewById(android.R.id.content));
				time = getTimeInt(mTVTime);
				time[1] = tmp;
			}
		} else if (time[1] > 0)
			time[1] = time[1] - 1;

		setTime(time);
		if (mTimerIsRunning) {
			startTimer(findViewById(android.R.id.content));
		}

	}

	public void removeHour(View v) {
		int[] time = getTimeInt(mTVTime);
		if (time[0] > 0)
			time[0] = time[0] - 1;
		setTime(time);
		if (mTimerIsRunning)
			startTimer(findViewById(android.R.id.content));
	}

	public void setTime(int[] time) {
		String tmp = String.format(Locale.getDefault(), "%02d:%02d:%02d",
				time[0], time[1], time[2]);
		mTVTime.setText(tmp);
	}

	public void startTimer(View v) {
		long time = getTimems();
		if (mTimerIsRunning) {
			mTimer.cancel();
		}

		mTimer = createTimer(time);
		mTimer.start();
		mTimerIsRunning = true;
	}

	public void stopTimer(View v) {
		if (mTimerIsRunning)
			mTimer.cancel();
		mTimerIsRunning = false;
	}

	public long getTimems() {
		// returns setted time in ms
		int[] time = getTimeInt(mTVTime);
		long timems = ((((60 * time[0]) + time[1]) * 60) + time[2]) * 1000;
		return timems;
	}

	public CountDownTimer createTimer(long time) {
		mTimer = new CountDownTimer(time, 1000) {
			public void onFinish() {
				// add some sound
				Uri defaultRingtoneUri = RingtoneManager
						.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

				MediaPlayer mediaPlayer = new MediaPlayer();

				mTVTime.setText("00:00:00");
				mTimerIsRunning = false;
				try {
					mediaPlayer.setDataSource(getApplicationContext(),
							defaultRingtoneUri);
					mediaPlayer
							.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
					mediaPlayer.prepare();

					mediaPlayer
							.setOnCompletionListener(new OnCompletionListener() {

								@Override
								public void onCompletion(MediaPlayer mp) {
									mp.release();
								}
							});

					mediaPlayer.start();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SecurityException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			public void onTick(long millisUntilFinished) {
				long millis = millisUntilFinished;
				String h = String.format(Locale.getDefault(), "%02d",
						TimeUnit.MILLISECONDS.toHours(millis));
				String m = String.format(
						Locale.getDefault(),
						"%02d",
						TimeUnit.MILLISECONDS.toMinutes(millis)
								- TimeUnit.HOURS
										.toMinutes(TimeUnit.MILLISECONDS
												.toHours(millis)));
				String s = String.format(
						Locale.getDefault(),
						"%02d",
						TimeUnit.MILLISECONDS.toSeconds(millis)
								- TimeUnit.MINUTES
										.toSeconds(TimeUnit.MILLISECONDS
												.toMinutes(millis)));

				mTVTime.setText(h + ":" + m + ":" + s);
			}
		};
		return mTimer;
	}

	public int[] getTimeInt(TextView time) {
		int[] time_array = new int[3];
		String time_string = mTVTime.getText().toString();
		String[] tmp = time_string.split(":");
		for (int i = 0; i < 3; i++)
			time_array[i] = Integer.parseInt(tmp[i]);
		return time_array;
	}

}


text:
#include "abstracttwitter4qmltest.h"

#include <friendshipsdestroy.h>

class FriendshipsDestroyTest : public AbstractTwitter4QMLTest
{
    Q_OBJECT

private Q_SLOTS:
    void screen_name();
};

void FriendshipsDestroyTest::screen_name()
{
    FriendshipsDestroy test;
    test.screen_name("kenya888");
    QVERIFY2(exec(&test), "FriendshipsDestroy::exec()");
}

QTEST_MAIN(FriendshipsDestroyTest)

#include "tst_friendships_destroy.moc"


text:
layout: posts
title: Api - IModelPathCallback Interface
---

Callback signature for model.walkPaths().

Hierarchy

			IModelPathCallback

Callable

__call(modelContext: IModel, pathId: string, pathContext: IPath): void

Defined in src/maker.js/packages/maker.js/src/core/maker.ts:622

Callback signature for model.walkPaths().

Parameters

modelContext: IModel

pathId: string

pathContext: IPath

Returns void

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package bar

import (
	"fmt"
)

// Done says it has done something
func Done() {
	fmt.Println("Bye from bar")
}


text:
from ..entry import Entry
from ..writer import Writer
import yaml

content_type = 'application/yaml'

def load(self, text):
    """Entry from YAML representation."""
    self.__dict__ = yaml.load(text)

def dump(self):
    """Entry in YAML representation."""
    return yaml.dump(self.primitive, default_flow_style=False)

class Writer(Writer):
    """Write YAML array."""
    def __init__(self, stream, sep="\n"):
        self.stream = stream
        self.sep = sep
        self.sol = ""

    def write(self, entry):
        self.stream.write(
            self.sol
            + yaml.dump([entry.primitive], default_flow_style=False))
        self.sol = self.sep

Entry.yaml = property(dump, load)


text:
package com.navercorp.pinpoint.profiler.sender.grpc;

public interface StreamTask<M, ReqT> {

    void start();

    void stop();
}


text:
@implementation BMArchive

- (void)archiveFromPath:(NSString *)inPath toPath:(NSString *)outPath
{
    // we archive it so when expanding, it includes the directory itself

    ZKFileArchive *archive = [ZKFileArchive archiveWithArchivePath:outPath];

    [archive deflateDirectory:inPath relativeToPath:[inPath stringByDeletingLastPathComponent] usingResourceFork:NO];

    if ([[NSFileManager defaultManager] fileExistsAtPath:outPath])
    {
        NSLog(@"archived succeeded!");
    }
    else
    {
        NSLog(@"archiving failed!");
    }
}

- (void)unarchiveFromPath:(NSString *)inPath toPath:(NSString *)outPath
{
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:@"/tmp/PyBitmessage" error:&error];

    if (error)
    {
        NSLog(@"removing old tmp file failed");
        return;
    }

    ZKFileArchive *archive = [ZKFileArchive archiveWithArchivePath:inPath];
    [archive inflateToDirectory:@"/tmp" usingResourceFork:NO];

    if (error)
    {
        NSLog(@"unarchiving failed");
        return;
    }

    [[NSFileManager defaultManager] removeItemAtPath:outPath error:&error];

    if (error)
    {
        NSLog(@"removing old mailbox failed");
        return;
    }

    [[NSFileManager defaultManager] moveItemAtPath:@"/tmp/PyBitmessage" toPath:outPath error:&error];

    if (error)
    {
        NSLog(@"moving in new mailbox failed");
        return;
    }

}

@end


text:
/*
 * NaCl Server Runtime time abstraction layer.
 * This is the host-OS-dependent implementation.
 */

#include <sys/time.h>
#include <time.h>

#include "native_client/src/include/nacl_macros.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/shared/platform/nacl_time.h"
#include "native_client/src/shared/platform/posix/nacl_time_types.h"

#include "native_client/src/trusted/service_runtime/linux/nacl_syscall_inl.h"

#define NANOS_PER_UNIT  (1000*1000*1000)

static struct NaClTimeState gNaClTimeState;

void NaClAllowLowResolutionTimeOfDay(void) {
/* Always use high resolution timer. */
}

void NaClTimeInternalInit(struct NaClTimeState *ntsp) {
  ntsp->time_resolution_ns = NACL_NANOS_PER_MICRO;
}

void NaClTimeInternalFini(struct NaClTimeState *ntsp) {
  UNREFERENCED_PARAMETER(ntsp);
}

uint64_t NaClTimerResolutionNsInternal(struct NaClTimeState *ntsp) {
  return ntsp->time_resolution_ns;
}

void NaClTimeInit(void) {
  NaClTimeInternalInit(&gNaClTimeState);
}

void NaClTimeFini(void) {
  NaClTimeInternalFini(&gNaClTimeState);
}

uint64_t NaClTimerResolutionNanoseconds(void) {
  return NaClTimerResolutionNsInternal(&gNaClTimeState);
}

int NaClGetTimeOfDay(struct nacl_abi_timeval *tv) {
  struct timeval  sys_tv;
  int             retval;

  retval = gettimeofday(&sys_tv, NULL);
  if (0 == retval) {
    tv->nacl_abi_tv_sec = sys_tv.tv_sec;
    tv->nacl_abi_tv_usec = sys_tv.tv_usec;
  }

  retval = NaClXlateSysRet(retval);
  return retval;
}

int NaClNanosleep(struct nacl_abi_timespec const  *req,
                  struct nacl_abi_timespec        *rem) {
  struct timespec host_req;
  struct timespec host_rem;
  struct timespec *host_remptr;
  int             retval;

  host_req.tv_sec = req->tv_sec;
  host_req.tv_nsec = req->tv_nsec;
  if (NULL == rem) {
    host_remptr = NULL;
  } else {
    host_remptr = &host_rem;
  }
  NaClLog(4,
          "nanosleep(%"NACL_PRIxPTR", %"NACL_PRIxPTR")\n",
          (uintptr_t) &host_req,
          (uintptr_t) host_remptr);
  NaClLog(4, "nanosleep(time = %"NACL_PRId64".%09"NACL_PRId64" S)\n",
          (int64_t) host_req.tv_sec, (int64_t) host_req.tv_nsec);
  if (host_req.tv_nsec > NANOS_PER_UNIT) {
    NaClLog(4, "tv_nsec too large %"NACL_PRId64"\n",
            (int64_t) host_req.tv_nsec);
  }
  retval = nanosleep(&host_req, host_remptr);
  NaClLog(4, " returned %d\n", retval);

  if (0 != retval && EINTR == errno && NULL != rem) {
    rem->tv_sec = host_rem.tv_sec;
    rem->tv_nsec = host_rem.tv_nsec;
  }
  retval = NaClXlateSysRet(retval);
  return retval;
}


text:
A push reaction is what happens when a piston tries to push a block.

# 导入相关包

It might be required for you to import the package if you encounter any issues, so better be safe than sorry and add the import.
`import mods.contenttweaker.PushReaction;`

## Comparing two reactions

You can see if two reactions are equal by using the `==` operator.

```zenscript
if(a == b){}
```

## Static methods

You can use these methods to get PushReaction Objects:

```zenscript
mods.contenttweaker.PushReaction.normal();
mods.contenttweaker.PushReaction.destroy();
mods.contenttweaker.PushReaction.block();
mods.contenttweaker.PushReaction.ignore();
mods.contenttweaker.PushReaction.pushOnly();
```


text:
package com.google.appengine.api.taskqueue;

import java.util.Timer;

public class QueueFactory {

	private static volatile Timer timer = new Timer();

	public static Queue getDefaultQueue() {
		Queue q = new Queue();
		q.setTimer(QueueFactory.getTimer());
		return q;
	}

	private static Timer getTimer() {
		return QueueFactory.timer;
	}

}


text:
package org.uberfire.ext.wires.core.grids.client.widget.layer.impl;

import java.util.Set;

import com.ait.lienzo.client.core.mediator.Mediators;
import com.ait.lienzo.client.core.shape.IPrimitive;
import com.ait.lienzo.client.core.shape.Layer;
import com.ait.lienzo.client.core.shape.Viewport;
import com.ait.lienzo.client.core.types.Transform;
import com.ait.lienzo.client.widget.LienzoPanel;
import com.ait.lienzo.test.LienzoMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.ext.wires.core.grids.client.model.GridColumn;
import org.uberfire.ext.wires.core.grids.client.model.GridData;
import org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridData;
import org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.grid.impl.BaseGridWidget;
import org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.GridRenderer;
import org.uberfire.ext.wires.core.grids.client.widget.layer.GridLayer;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

@RunWith(LienzoMockitoTestRunner.class)
public class DefaultGridLayerTest {

    @Mock
    private Viewport viewport;

    @Mock
    private GridRenderer renderer;

    @Mock
    private Mediators mediators;

    private GridLayer gridLayer;

    private Transform transform;

    @Before
    public void setup() {
        this.transform = new Transform();

        final LienzoPanel panel = new LienzoPanel(500,
                                                  500);
        final DefaultGridLayer wrapped = new DefaultGridLayer() {

            @Override
            public Layer batch() {
                //Don't render Layer for tests
                return this;
            }

            @Override
            public Layer batch(final GridLayerRedrawManager.PrioritizedCommand command) {
                //Don't render Layer for tests
                return this;
            }
        };
        panel.add(wrapped);
        this.gridLayer = spy(wrapped);

        when(gridLayer.getViewport()).thenReturn(viewport);
        when(viewport.getTransform()).thenReturn(transform);
        when(viewport.getMediators()).thenReturn(mediators);
    }

    private GridWidget makeGridWidget() {
        final GridData uiModel = new BaseGridData();
        return new BaseGridWidget(uiModel,
                                  gridLayer,
                                  gridLayer,
                                  renderer) {
            @Override
            public void select() {
                //Don't render Selector for tests
            }
        };
    }

    @Test
    public void checkFlipToGridWidgetWhenPinned() {
        final GridWidget gridWidget = makeGridWidget();
        this.gridLayer.add(gridWidget);

        gridLayer.enterPinnedMode(gridWidget,
                                  new GridLayerRedrawManager.PrioritizedCommand(0) {
                                      @Override
                                      public void execute() {

                                      }
                                  });

        gridLayer.flipToGridWidget(gridWidget);

        verify(gridLayer,
               times(1)).updatePinnedContext(eq(gridWidget));
        verify(gridLayer,
               times(1)).batch(any(GridLayerRedrawManager.PrioritizedCommand.class));
    }

    @Test
    public void checkFlipToGridWidgetWhenNotPinned() {
        final GridWidget gridWidget = makeGridWidget();
        this.gridLayer.add(gridWidget);

        gridLayer.flipToGridWidget(gridWidget);

        verify(gridLayer,
               never()).updatePinnedContext(eq(gridWidget));
        verify(gridLayer,
               never()).batch(any(GridLayerRedrawManager.PrioritizedCommand.class));
    }

    @Test
    public void checkScrollToGridWidgetWhenPinned() {
        final GridWidget gridWidget = makeGridWidget();
        this.gridLayer.add(gridWidget);

        gridLayer.enterPinnedMode(gridWidget,
                                  new GridLayerRedrawManager.PrioritizedCommand(0) {
                                      @Override
                                      public void execute() {
                                          //Do nothing
                                      }
                                  });

        gridLayer.scrollToGridWidget(gridWidget);

        verify(gridLayer,
               never()).select(eq(gridWidget));
    }

    @Test
    public void checkScrollToGridWidgetWhenNotPinned() {
        final GridWidget gridWidget = makeGridWidget();
        this.gridLayer.add(gridWidget);

        gridLayer.scrollToGridWidget(gridWidget);

        verify(gridLayer,
               times(1)).select(eq(gridWidget));
    }

    @Test
    public void checkRemoveAllClearsCachedReferences() {
        final GridWidget gridWidget1 = makeGridWidget();
        final GridColumn column1 = mock(GridColumn.class);
        when(column1.isVisible()).thenReturn(true);
        gridWidget1.getModel().appendColumn(column1);

        final GridWidget gridWidget2 = makeGridWidget();
        final GridColumn column2 = mock(GridColumn.class);
        when(column2.isVisible()).thenReturn(true);
        when(column2.isLinked()).thenReturn(true);
        when(column2.getLink()).thenReturn(column1);
        gridWidget2.getModel().appendColumn(column2);

        this.gridLayer.add(gridWidget1);
        this.gridLayer.add(gridWidget2);

        assertEquals(2,
                     gridLayer.getGridWidgets().size());
        assertEquals(1,
                     gridLayer.getGridWidgetConnectors().size());

        gridLayer.removeAll();

        assertEquals(0,
                     gridLayer.getGridWidgets().size());
        assertEquals(0,
                     gridLayer.getGridWidgetConnectors().size());
    }

    @Test
    public void checkConnectorsVisibilityFollowPinnedModeStatus() {
        final GridWidget gridWidget1 = makeGridWidget();
        final GridColumn column1 = mock(GridColumn.class);
        when(column1.isVisible()).thenReturn(true);
        gridWidget1.getModel().appendColumn(column1);

        final GridWidget gridWidget2 = makeGridWidget();
        final GridColumn column2 = mock(GridColumn.class);
        when(column2.isVisible()).thenReturn(true);
        when(column2.isLinked()).thenReturn(true);
        when(column2.getLink()).thenReturn(column1);
        gridWidget2.getModel().appendColumn(column2);

        this.gridLayer.add(gridWidget1);
        this.gridLayer.add(gridWidget2);

        gridLayer.refreshGridWidgetConnectors();

        checkConnectorsVisibility(true);

        gridLayer.enterPinnedMode(gridWidget1,
                                  new GridLayerRedrawManager.PrioritizedCommand(0) {
                                      @Override
                                      public void execute() {
                                          //Do nothing
                                      }
                                  });

        gridLayer.refreshGridWidgetConnectors();

        checkConnectorsVisibility(false);
    }

    private void checkConnectorsVisibility(final boolean isVisible) {
        final Set<IPrimitive<?>> connectors = gridLayer.getGridWidgetConnectors();
        assertEquals(1,
                     connectors.size());
        assertEquals(isVisible,
                     connectors.iterator().next().isVisible());
    }
}


text:
<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script for making ticket ID signed to allow
 * negative IDs for temp directories.
 **/
class Migration20140627091431ComSupport extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableHasField('#__support_attachments', 'ticket'))
		{
			$query = "ALTER TABLE `#__support_attachments` CHANGE `ticket` `ticket` INT(11)  NOT NULL  DEFAULT '0';";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableHasField('#__support_attachments', 'ticket'))
		{
			$query = "ALTER TABLE `#__support_attachments` CHANGE `ticket` `ticket` INT(11) unsigned NOT NULL  DEFAULT '0';";
			$this->db->setQuery($query);
			$this->db->query();
		}
	}
}


text:
<?php

namespace Mellivora\View\Compilers\Concerns;

trait CompilesIncludes
{
    /**
     * Compile the each statements into valid PHP.
     *
     * @param string $expression
     *
     * @return string
     */
    protected function compileEach($expression)
    {
        return "<?php echo \$__env->renderEach{$expression}; ?>";
    }

    /**
     * Compile the include statements into valid PHP.
     *
     * @param string $expression
     *
     * @return string
     */
    protected function compileInclude($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->make({$expression}, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
    }

    /**
     * Compile the include-if statements into valid PHP.
     *
     * @param string $expression
     *
     * @return string
     */
    protected function compileIncludeIf($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php if (\$__env->exists({$expression})) echo \$__env->make({$expression}, array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>";
    }

    /**
     * Compile the include-when statements into valid PHP.
     *
     * @param string $expression
     *
     * @return string
     */
    protected function compileIncludeWhen($expression)
    {
        $expression = $this->stripParentheses($expression);

        return "<?php echo \$__env->renderWhen($expression, array_except(get_defined_vars(), array('__data', '__path'))); ?>";
    }
}


text:
\section{Fehlerrechnung}
Dieses Kapitel listet kurz und bündig die benötigten und aus den Methoden der Statistik bekannten Formeln für die Fehlerrechnung auf.
Die Schätzung der Standardabweichung ist
\begin{equation}
  \label{eq:std}
  \Delta X = \sqrt{\frac{1}{n-1}\sum_{i=1}^n(X_i-\overline{X})^2}     \; .
\end{equation}
Der Mittelwert ist
\begin{equation}
  \overline{X} = \frac{1}{n} \sum_{i=1}^nX_i
\end{equation}
Der Fehler des Mittelwertes ist
\begin{equation}
  \label{eq:std_mean}
  \Delta \overline{X} = \sqrt{\frac{1}{n(n-1)}\sum_{i=1}^n(X_i-\overline{X})^2}   \; .
\end{equation}
Für fehlerbehaftete Größen, die auch in folgenden Formeln verwendet werden, muss die Fehlerfortpflanzung nach Gauß berücksichtigt werden.
\begin{equation}
  \label{eq:GFFP}
  \Delta f = \sqrt{\sum_{i=1}^n \left(\frac{\partial f}{\partial X_i}\right)^2 \cdot (\Delta X_i)^2}
\end{equation}


text:
int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([CFAppDelegate class]));
    }
}


text:
Website for Book of Business

Recieved Charlotte Start up Weekend 2015 - Audience Favorite award


text:
export const BattleFormats: {[k: string]: ModdedFormatsData} = {
	allowavs: {
		effectType: 'ValidatorRule',
		name: 'Allow AVs',
		desc: "Tells formats with the 'letsgo' mod to take Awakening Values into consideration when calculating stats",
		// implemented in TeamValidator#validateStats
	},
};


text:
import logging
LOG = logging.getLogger(__name__)

from re import compile as regex_compile
from time import time as time_now
from os.path import exists as path_exists, join as join_path

from threading import Lock

# pylint: disable=F0401
from pylons import config
import yaml
from paste.deploy.converters import asbool
# pylint: enable=F0401

from turbulenz_local.tools import get_absolute_path, create_dir
from turbulenz_local.lib.validation import ValidationException
from turbulenz_local.lib.tools import create_id
from turbulenz_local.lib.money import Money, get_currency

STORE_PRICING_TYPES = ['own', 'consume']

# TODO allow other currencies
DEFAULT_CURRENCY_TYPE = 'USD'
DEFAULT_CURRENCY = get_currency(DEFAULT_CURRENCY_TYPE)

class StoreError(Exception):
    def __init__(self, value, response_code=400):
        super(StoreError, self).__init__()
        self.value = value
        self.response_code = response_code

    def __str__(self):
        return self.value

class StoreUnsupported(StoreError):
    def __init__(self):
        super(StoreUnsupported, self).__init__('This game does not support a store', 404)

class StoreInvalidTransactionId(StoreError):
    def __init__(self):
        super(StoreInvalidTransactionId, self).__init__('Transaction id not found', 404)

class StoreItem(object):

    validate_key = regex_compile('^[A-Za-z0-9]+([\-\.][A-Za-z0-9]+)*$')

    def __init__(self, game, meta_data, existing_keys):
        self.errors = []
        self.warnings = []
        self.path = None

        self.game = game
        self.index = None

        if not isinstance(meta_data, dict):
            raise StoreError('YAML file item must be a dictionary')

        try:
            key = meta_data['key']
        except KeyError:
            raise StoreError('YAML file item missing key property')

        if not self.validate_key.match(key):
            self.error('invalid key format')
        self.key = key

        if key in existing_keys:
            self.error('duplicate key "%s"' % key)
        existing_keys.add(key)

        if 'title' not in meta_data or meta_data['title'] is None:
            self.error('title property missing for store item "%s"' % key)
            self.title = ''
        else:
            self.title = meta_data['title']

        if 'description' not in meta_data or meta_data['description'] is None:
            self.error('description property missing for store item "%s"' % key)
            self.description = ''
        else:
            self.description = meta_data['description']

        if 'icon' in meta_data:
            self.warning('"icon" yaml property has been deprecated please use '
                         '"icon256", "icon48" or "icon32" for store key "%s"' % key)

        self.images = {
            'img256': meta_data.get('icon256', ''),
            'img48': meta_data.get('icon48', ''),
            'img32': meta_data.get('icon32', '')
        }

    def error(self, msg):
        self.errors.append(msg)

    def warning(self, msg):
        self.warnings.append(msg)

class StoreOffering(StoreItem):

    def __init__(self, game, meta_data, offering_keys, resource_keys):
        super(StoreOffering, self).__init__(game, meta_data, offering_keys)

        prices = meta_data.get('price', meta_data.get('prices'))
        if prices is None:
            self.error('price property missing for store offering "%s"' % self.key)
            prices = {DEFAULT_CURRENCY_TYPE: 1}

        self.prices = {}
        for currency, currency_price in prices.items():
            if currency_price <= 0:
                self.error('price %s must be greater than zero for store offering "%s"' % (currency, self.key))
            try:
                self.prices[currency] = Money(get_currency(currency), currency_price)
            except TypeError:
                self.error('price %s invalid precision for store offering "%s" using default 1 %s'
                           % (currency, self.key, currency))
                self.prices[currency] = Money(get_currency(currency), 1)

        output = meta_data.get('output')
        if output is None:
            self.error('output property missing for store offering "%s"' % self.key)
            output = {}

        if not isinstance(output, dict):
            self.error('output property should be a dictionary for store offering "%s"' % self.key)
            output = {}

        self.output = {}
        for output_key, output_amount in output.items():
            if output_key not in resource_keys:
                self.error('no resource with key "%s".' % output_key)
            elif not isinstance(output_amount, int):
                self.error('output key "%s" amount must be an integer.' % output_key)
            elif output_amount <= 0:
                self.error('output key "%s" amount must be greater than zero.' % output_key)
            else:
                self.output[output_key] = output_amount

        try:
            self.available = asbool(meta_data.get('available', True))
        except ValueError:
            self.error('available property must be a boolean value.')

    def to_dict(self):
        return {'index': self.index,
                'title': self.title,
                'description': self.description,
                'images': self.images,
                'output': self.output,
                'prices': dict((k, v.get_minor_amount()) for k, v in self.prices.items()),
                'available': self.available}

    def get_price(self):
        return self.prices[DEFAULT_CURRENCY_TYPE]

class StoreResource(StoreItem):

    def __init__(self, game, meta_data, resource_keys):
        super(StoreResource, self).__init__(game, meta_data, resource_keys)

        self.type = meta_data.get('type')
        if self.type not in STORE_PRICING_TYPES:
            self.error('type property must be one of %s for store resource "%s"' % (str(STORE_PRICING_TYPES), self.key))
            self.type = 'own'

    def to_dict(self):
        return {'index': self.index,
                'title': self.title,
                'description': self.description,
                'images': self.images,
                'type': self.type}

class StoreUserGameItems(object):

    def __init__(self, user, game, game_store_items):
        self.user = user
        self.game = game
        self.game_store_items = game_store_items
        self.user_items = {}

        try:
            path = config['storeitems_db']
        except KeyError:
            LOG.error('storeitems_db path config variable not set')
            return

        # Create store items folder and user folder on the game path
        path = join_path(path, self.game.slug)
        if not create_dir(path):
            raise StoreError('User store items path \"%s\" could not be created.' % path)
        self.path = get_absolute_path(path)
        self.lock = Lock()
        self._read()

    def _read(self):
        with self.lock:
            unicode_path = unicode('%s/%s.yaml' % (self.path, self.user.username))
            if path_exists(unicode_path):
                try:
                    with open(unicode_path, 'r') as f:
                        file_store_items = yaml.load(f)

                        self.user_items = {}
                        if file_store_items:
                            for item in file_store_items:
                                item_amount = file_store_items[item]['amount']
                                self.user_items[str(item)] = {
                                    'amount': item_amount
                                }
                except (IOError, KeyError, yaml.YAMLError) as e:
                    LOG.error('Failed loading store items file "%s": %s', self.path, str(e))
                    raise StoreError('Failed loading store items file "%s": %s' % (self.path, str(e)))

            else:
                self.user_items = {}

    def _write(self):
        with self.lock:
            try:
                with open(unicode('%s/%s.yaml' % (self.path, self.user.username)), 'w') as f:
                    yaml.dump(self.user_items, f, default_flow_style=False)
            except IOError as e:
                LOG.error('Failed writing store items file "%s": %s', self.path, str(e))
                raise StoreError('Failed writing store items file %s' % self.path)

    def get_items(self):
        return dict((key, self.get_item(key)) for key in self.user_items.keys())

    def get_item(self, key):
        try:
            if self.game_store_items.get_resource(key).type == 'own':
                user_item = self.user_items.get(key)
                if user_item and user_item['amount'] > 1:
                    return {'amount': 1}
        except StoreError:
            pass
        return self.user_items[key]

    def remove_items(self):
        self.user_items = {}
        self._write()

    def transfer_items(self, transaction):
        for item_key, item in transaction.items.items():
            for resource_key, output_amount in self.game_store_items.get_offering(item_key).output.items():
                amount = item['amount'] * output_amount

                user_item = self.user_items.get(resource_key)
                if user_item:
                    user_item['amount'] += amount
                else:
                    self.user_items[str(resource_key)] = {
                        'amount': amount
                    }
        self._write()

    def consume_items(self, consume_transaction):
        item_key = consume_transaction.key
        try:
            user_item_amount = self.user_items[item_key]['amount']
            if user_item_amount < consume_transaction.consume_amount:
                # current values must match in order to apply the transaction
                return False
        except KeyError:
            return False

        new = user_item_amount - consume_transaction.consume_amount
        if new == 0:
            del self.user_items[item_key]
        else:
            self.user_items[item_key]['amount'] = new

        self._write()
        return True

    def reset_all_transactions(self):
        self.user_items = {}

class StoreUserList(object):

    def __init__(self, game, game_store_items):
        self.users = {}
        self.game = game
        self.game_store_items = game_store_items

    def get(self, user):
        try:
            return self.users[user.username]
        except KeyError:
            store_user = StoreUserGameItems(user, self.game, self.game_store_items)
            self.users[user.username] = store_user
            return store_user

class GameStoreItems(object):

    def __init__(self, game):
        self.offerings = {}
        self.resources = {}
        self.issues = []

        total_yaml_errors = 0
        def add_infos(key, item):
            num_errors = len(item.errors)
            if num_errors > 0 or len(item.warnings) > 0:
                self.issues.append((key, {
                    'errors': item.errors,
                    'warnings': item.warnings
                }))
            return num_errors

        yaml_path = unicode(get_absolute_path(join_path(game.path, 'storeitems.yaml')))
        if path_exists(yaml_path):
            try:
                with open(yaml_path, 'r') as f:
                    items_meta = yaml.load(f)

                    resource_keys = set()
                    offering_keys = set()
                    if isinstance(items_meta, list):
                        for index, m in enumerate(items_meta):
                            resource = StoreResource(game, m, resource_keys)
                            resource.index = index

                            total_yaml_errors += add_infos(resource.key, resource)
                            self.resources[resource.key] = resource

                        index = 0
                        items_meta_end = len(items_meta) - 1
                        for m in items_meta:
                            try:
                                m['output'] = {m['key']: 1}
                            except KeyError:
                                raise StoreError('Store item YAML item missing key')

                            offering = StoreOffering(game, m, offering_keys, resource_keys)
                            # put unavailable items at the end
                            if offering.available:
                                offering.index = index
                                index += 1
                            else:
                                offering.index = items_meta_end
                                items_meta_end -= 1

                            total_yaml_errors += add_infos(offering.key, offering)
                            self.offerings[offering.key] = offering

                    elif isinstance(items_meta, dict):
                        resource_meta = items_meta.get('resources')
                        if not isinstance(resource_meta, list):
                            raise StoreError('Store items YAML file must contain "resources"')

                        for index, m in enumerate(resource_meta):
                            resource = StoreResource(game, m, resource_keys)
                            resource.index = index

                            total_yaml_errors += add_infos(resource.key, resource)
                            self.resources[resource.key] = resource

                        offerings_meta = items_meta.get('offerings')
                        if not isinstance(offerings_meta, list):
                            raise StoreError('Store items YAML file must contain "offerings"')

                        index = 0
                        items_meta_end = len(offerings_meta) - 1
                        for m in offerings_meta:
                            offering = StoreOffering(game, m, offering_keys, resource_keys)
                            # put unavailable items at the end
                            if offering.available:
                                offering.index = index
                                index += 1
                            else:
                                offering.index = items_meta_end
                                items_meta_end -= 1

                            total_yaml_errors += add_infos(offering.key, offering)
                            self.offerings[offering.key] = offering

                    else:
                        raise StoreError('Store items YAML file must be a dictionary or list')
            except (IOError, yaml.YAMLError) as e:
                LOG.error('Failed loading store items: %s', str(e))
                raise StoreError('Failed loading storeitems.yaml file: %s' % str(e))
        else:
            raise StoreUnsupported()

        if total_yaml_errors > 0:
            raise ValidationException(self.issues)

        self.store_users = StoreUserList(game, self)

    def get_offering(self, key):
        try:
            return self.offerings[key]
        except KeyError:
            raise StoreError('No store offering with key %s' % key, 400)

    def get_resource(self, key):
        try:
            return self.resources[key]
        except KeyError:
            raise StoreError('No store resource with key %s' % key, 400)

    def get_store_user(self, user):
        return self.store_users.get(user)

    def read_meta(self):
        return dict((offering.key, offering.to_dict()) for offering in self.offerings.values())

    def read_resources(self):
        return dict((resource.key, resource.to_dict()) for resource in self.resources.values())

class ConsumeTransaction(object):

    def __init__(self, user, game, resource_key,
                 consume_amount, gamesession_id, token):

        self.user = user
        self.game = game
        self.id = create_id()
        self.key = resource_key
        self.gamesession_id = gamesession_id
        self.token = token
        self.consumed = False

        # validation step
        try:
            consume_amount = int(consume_amount)
        except ValueError:
            raise StoreError('Item "%s" consume amount parameters must be an integer' % resource_key)

        self.consume_amount = consume_amount

        if consume_amount <= 0:
            raise StoreError('Item "%s" consume amount parameter must be non-negative' % resource_key)

        game_store_items = StoreList.get(game)
        try:
            resource_meta = game_store_items.get_resource(resource_key)
            if resource_meta.type != 'consume':
                raise StoreError('Item "%s" is not a consumable' % resource_key)
        except KeyError:
            raise StoreError('No item with key "%s"' % resource_key)

    def check_match(self, other):
        return (self.user.username == other.user.username and
                self.game.slug == other.game.slug and
                self.key == other.key and
                self.gamesession_id == other.gamesession_id and
                self.token == other.token and
                self.consume_amount == other.consume_amount)

    def consume(self):
        game_store_items = StoreList.get(self.game)
        store_user = game_store_items.get_store_user(self.user)
        self.consumed = store_user.consume_items(self)
        UserTransactionsList.get(self.user).add_consume_transaction(self.gamesession_id, self.token, self)

class Transaction(object):

    def __init__(self, user, game, transaction_items):
        self.user = user
        self.game = game
        self.id = create_id()
        self.items = transaction_items

        total = 0

        game_store_items = StoreList.get(game)

        resource_keys = set()

        if len(transaction_items) == 0:
            raise StoreError('Basket is empty')

        for item_key, item in transaction_items.items():
            try:
                # convert string amounts to integers
                basket_amount = int(item['amount'])
                basket_price = int(item['price'])
            except (ValueError, KeyError, TypeError):
                raise StoreError('Item "%s" amount and price must be integers' % item_key)

            if basket_amount == 0:
                continue
            elif basket_amount < 0:
                raise StoreError('Item "%s" amount must be non-negative' % item_key)

            game_offering = game_store_items.get_offering(item_key)

            minor_price = game_offering.get_price().get_minor_amount()

            if basket_price != minor_price:
                raise StoreError('Item "%s" price does not match' % item_key)

            offering_output = game_offering.output
            try:
                basket_item_output = item['output']
                if not isinstance(basket_item_output, dict):
                    raise ValueError()
                if len(offering_output) != len(basket_item_output):
                    raise ValueError()

                for resource_key, amount in offering_output.items():
                    if amount != basket_item_output[resource_key]:
                        raise ValueError()
                    resource_keys.add(resource_key)
            except (KeyError, ValueError):
                raise StoreError('Offering "%s" output resources do not match' % item_key)

            self.items[item_key] = {
                'price': basket_price,
                'amount': basket_amount
            }

            total += minor_price * basket_amount

        for key in resource_keys:
            resource = game_store_items.get_resource(key)
            if resource is not None and resource.type == 'own':
                user_store_items = game_store_items.get_store_user(user)
                if user_store_items is not None:
                    try:
                        user_item = user_store_items.get_item(key)
                        if user_item['amount'] > 0:
                            raise StoreError('Basket contains an ownable item you already own')
                    except KeyError:
                        pass

        self.total = total

        self.completed = False
        self.completed_time = None

        UserTransactionsList.get(user).add_transaction(self.id, self)

    def pay(self):
        if self.completed:
            return
        game_store_items = StoreList.get(self.game)
        store_user = game_store_items.get_store_user(self.user)
        store_user.transfer_items(self)

        self.completed_time = time_now()
        self.completed = True

    def status(self):
        if self.completed:
            return {'status': 'completed'}
        else:
            return {'status': 'checkout'}

class TransactionsList(object):

    def __init__(self, user):
        self.transactions = {}
        self.consume_transactions = {}
        self.user = user

    def add_transaction(self, transaction_id, transaction):
        self.transactions[transaction_id] = transaction

    def add_consume_transaction(self, gamesession_id, token, consume_transaction):
        if gamesession_id in self.consume_transactions:
            self.consume_transactions[gamesession_id][token] = consume_transaction
        else:
            self.consume_transactions[gamesession_id] = {
                token: consume_transaction
            }

    def get_transaction(self, transaction_id):
        try:
            return self.transactions[transaction_id]
        except KeyError:
            raise StoreInvalidTransactionId()

    def get_consume_transaction(self, gamesession_id, token):
        try:
            return self.consume_transactions[gamesession_id][token]
        except (KeyError, TypeError):
            return None

# A dictionary of username to transaction list objects
class UserTransactionsList(object):
    user_transactions = {}

    @classmethod
    def load(cls, user):
        user_transactions_list = TransactionsList(user.username)
        cls.user_transactions[user.username] = user_transactions_list
        return user_transactions_list

    @classmethod
    def get(cls, user):
        try:
            return cls.user_transactions[user.username]
        except KeyError:
            return cls.load(user)

# A dictionary of game slug to store items objects
class StoreList(object):
    game_stores = {}

    @classmethod
    def load(cls, game):
        game_store = GameStoreItems(game)
        cls.game_stores[game.slug] = game_store
        return game_store

    @classmethod
    def get(cls, game):
        try:
            return cls.game_stores[game.slug]
        except KeyError:
            return cls.load(game)

    @classmethod
    def reset(cls):
        cls.game_stores = {}


text:
<?php

namespace m\Foundation;

/**
 * The core class for m framework.  This is where the meat of the
 * library is stored.
 *
 * @package m\Foundation
 */
class Core extends Collection
{

    /**
     * @var array Stored hooks
     */
    protected $_hooks = array();

    /**
     * @var array Container
     */
    protected $_ioc = array();

    /**
     * Constructor.
     */
    public function __construct()
    {

        $defaults = array(
            'database'  => array(
                'type'  => 'mysql',
                'host'  => 'localhost',
                'name'  => 'dbname',
                'user'  => 'root',
                'pass'  => ''
            )
        );

    }

    /**
     * Registers a new object container.
     *
     * @param string $name
     * @param \Closure $callable
     * @param bool $singleton
     * @return \m\Foundation\Core
     */
    public function bind($name, \Closure $callable, $singleton = false)
    {
        $this->_ioc[$name] = array(
            'closure'   => $callable,
            'singleton' => (bool) $singleton,
            'instance'  => null
        );

        return $this;
    }

    /**
     * Registers a singleton object container.
     *
     * @param string $name
     * @param \Closure $callable
     * @return \m\Foundation\Core
     */
    public function singleton($name, \Closure $callable)
    {
        return $this->bind($name, $callable, true);
    }

    /**
     * Resolves a set container and returns the result.
     *
     * @param string $name
     * @param array $params
     * @param bool $force
     * @return object|null
     */
    public function make($name, array $params = array(), $force = false)
    {
        if (isset($this->_ioc[$name])) {

            // If a singleton instance exists, return it
            if ($this->_ioc[$name]['instance'] && !$force)
                return $this->_ioc[$name]['instance'];

            // Include an instance of this object as the final argument
            $params[] = $this;

            // Call the stored container
            $result = call_user_func_array($this->_ioc[$name]['closure'], $params);

            // If this is supposed to be a singleton, store it
            if ($this->_ioc[$name]['singleton'])
                $this->_ioc[$name]['instance'] = $result;

            return $result;
        }

        return null;
    }

    /**
     * Force resolves a container and returns the new object.
     *
     * @param string $name
     * @param array $params
     * @return object|null
     */
    public function remake($name, array $params = array())
    {
        return $this->make($name, $params, true);
    }

    /**
     * Calls the hooks stored at the given event name (if any exist) and
     * passes them the given parameters.
     *
     * @param string $event
     * @param array $params
     * @return \m\Foundation\Core
     */
    public function call($event, array $params = array())
    {

        // Include an instance of this object as the final argument
        $params[] = $this;

        if (isset($this->_hooks[$event])) {
            foreach($this->_hooks[$event] as $hook) {
                call_user_func_array($hook, $params);
            }
        }

        return $this;
    }

    /**
     * Binds a new callable action to a hook event.
     *
     * @param string $event
     * @param \Closure|callable $callable
     * @return \m\Foundation\Core
     * @throws \InvalidArgumentException
     */
    public function on($event, $callable)
    {
        if (!is_callable($callable) && !$callable instanceof \Closure)
            throw new \InvalidArgumentException();

        if (!isset($this->_hooks[$event]))
            $this->_hooks[$event] = array();

        $this->_hooks[$event][] = $callable;

        return $this;
    }

}


text:
using System;
using System.Diagnostics.CodeAnalysis;

namespace starshipxac.Shell.Interop.KnownFolder
{
    /// <summary>
    ///     Flags that specify the current redirection capabilities of a known folder.
    ///     Used by <see cref="IKnownFolder.GetRedirectionCapabilities" />.
    /// </summary>
    /// <remarks>
    ///     http://msdn.microsoft.com/en-us/library/windows/desktop/bb762514(v=vs.85).aspx
    /// </remarks>
    [SuppressMessage("ReSharper", "InconsistentNaming")]
    internal enum KF_REDIRECTION_CAPABILITIES : uint
    {
        /// <summary>
        ///     The folder can be redirected if any of the bits in the lower byte of the value are set but no DENY flag is set.
        ///     DENY flags are found in the upper byte of the value.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_ALLOW_ALL = 0xff,

        /// <summary>
        ///     The folder can be redirected. Currently, redirection exists for only common and user folders;
        ///     fixed and virtual folders cannot be redirected.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_REDIRECTABLE = 0x1,

        /// <summary>
        ///     Redirection is not allowed.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_DENY_ALL = 0xfff00,

        /// <summary>
        ///     The folder cannot be redirected because it is already redirected by group policy.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_DENY_POLICY_REDIRECTED = 0x100,

        /// <summary>
        ///     The folder cannot be redirected because the policy prohibits redirecting this folder.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_DENY_POLICY = 0x200,

        /// <summary>
        ///     The folder cannot be redirected because the calling application does not have sufficient permissions.
        /// </summary>
        KF_REDIRECTION_CAPABILITIES_DENY_PERMISSIONS = 0x400
    }
}


text:
package gnu.xml.dom.html2;

import gnu.javax.swing.text.html.parser.support.Parser;

import java.io.IOException;
import java.io.Reader;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.text.AttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.parser.DTD;
import javax.swing.text.html.parser.TagElement;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.html2.HTMLDocument;

/**
 * This parser reads HTML from the given stream and stores into
 * {@link HTMLDocument}. The HTML tag becomes the {@link Node}.
 * The tag attributes become the node attributes. The text inside
 * HTML tag is inserted as one or several text nodes. The nested
 * HTML tags are inserted as child nodes.
 *
 * If the strict tree structure, closing the tag means closing all
 * nested tags. To work around this, this parser closes the nested
 * tags and immediately reopens them after the closed tag.
 * In this way, <b><i>c</b>d
 * is parsed as <b><i>c</i></b><i>d .
 *
 * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
 */
public class DomHTMLParser
  extends gnu.javax.swing.text.html.parser.support.Parser
{
  /**
   * The target where HTML document will be inserted.
   */
  protected DomHTMLDocument document;

  /**
   * The subsequently created new nodes will be inserted as the
   * childs of this cursor.
   */
  protected Node cursor;

  /**
   * Create parser using the given DTD.
   *
   * @param dtd the DTD (for example,
   * {@link gnu.javax.swing.text.html.parser.HTML_401F}).
   */
  public DomHTMLParser(DTD dtd)
  {
    super(dtd);
  }

  /**
   * Parse SGML insertion ( <! ... > ).
   * Currently just treats it as comment.
   */
  public boolean parseMarkupDeclarations(StringBuffer strBuff)
                                  throws java.io.IOException
  {
    Node c = document.createComment(strBuff.toString());
    cursor.appendChild(c);
    return false;
  }

  /**
   * Read the document, present in the given stream, and
   * return the corresponding {@link HTMLDocument}.
   *
   * @param input a stream to read from.
   * @return a document, reflecting the structure of the provided HTML
   * text.
   *
   * @throws IOException if the reader throws one.
   */
  public HTMLDocument parseDocument(Reader input)
                    throws IOException
  {
    try
      {
        document = new DomHTMLDocument();
        document.setCheckWellformedness(false);
        document.setCheckingCharacters(false);

        cursor = document;

        parse(input);

        DomHTMLDocument h = document;
        document = null;
        return h;
      }
    catch (Exception ex)
      {
        ex.printStackTrace();
        throw new IOException("Exception: " + ex.getMessage());
      }
  }

  /**
   * Create a new node.
   * @param name the name of node, case insensitive.
   * @return the created node.
   */
  protected Node createNode(String name)
  {
    Node new_node = document.createElement(name.toLowerCase());
    AttributeSet hatts = getAttributes();
    NamedNodeMap natts = new_node.getAttributes();

    Enumeration enumeration = hatts.getAttributeNames();
    Object key;
    Node attribute;

    while (hatts != null)
      {
        while (enumeration.hasMoreElements())
          {
            key = enumeration.nextElement();
            attribute = document.createAttribute(key.toString());
            attribute.setNodeValue(hatts.getAttribute(key).toString());
            natts.setNamedItem(attribute);
          }

        // The default values are stored in a parent node.
        hatts = hatts.getResolveParent();
      }

    return new_node;
  }

  /**
   * Handle comment by inserting the comment node.
   * @param text the comment text.
   */
  protected void handleComment(char[] text)
  {
    Node c = document.createComment(new String(text));
    cursor.appendChild(c);
  }

  /**
   * Handle the tag with no content.
   * @param tag the tag to handle.
   */
  protected void handleEmptyTag(TagElement tag)
  {
    String name = tag.getHTMLTag().toString();

    if (name.equalsIgnoreCase("#pcdata"))
      return;

    Node c = createNode(name);
    cursor.appendChild(c);
  }

  /**
   * Close the given tag. Close and reopen all nested tags.
   * @param tag the tag to close.
   */
  protected void handleEndTag(TagElement tag)
  {
    String name = tag.getHTMLTag().toString();
    String nname = cursor.getNodeName();

    // Closing the current tag.
    if (nname != null && nname.equalsIgnoreCase(name))
      {
        cursor = cursor.getParentNode();
      }
    else
      {
        Node nCursor = cursor.getParentNode();

        // Remember the opened nodes.
        LinkedList open = new LinkedList();
        Node close = cursor;
        while (close != null && !close.getNodeName().equalsIgnoreCase(name))
          {
            if (close != document)
              open.addFirst(close);
            close = close.getParentNode();
          }
        if (close == null)
          cursor = document;
        else
          cursor = close.getParentNode();

        // Insert the copies of the opened nodes.
        Iterator iter = open.iterator();
        while (iter.hasNext())
          {
            Node item = (Node) iter.next();
            cursor.appendChild(item);
            cursor = item;
          }
      }
  }

  /**
   * Handle the start tag by inserting the HTML element.
   * @param tag the tag to handle.
   */
  protected void handleStartTag(TagElement tag)
  {
    HTML.Tag h = tag.getHTMLTag();
    Node c = createNode(h.toString());
    cursor.appendChild(c);
    cursor = c;
  }

  /**
   * Handle text by inserting the text node.
   * @param text the text to insert.
   */
  protected void handleText(char[] text)
  {
    Node c = document.createTextNode(text, 0, text.length);
    cursor.appendChild(c);
  }
}