text:
angular.module(PKG.name + '.feature.adapters')
  .controller('LeftPanelController', function(myAdapterApi, MyAppDAGService, MyDAGFactory, mySettings, $state, MySidebarService, $scope, rVersion, $stateParams, GLOBALS) {
    this.pluginTypes = [
      {
        name: 'source'
      },
      {
        name: 'transform'
      },
      {
        name: 'sink'
      }
    ];

    this.plugins= {
      items: []
    };

    this.panelstatus = {};
    this.panelstatus.isExpanded = true;

    $scope.$watch(function() {
      return this.panelstatus.isExpanded;
    }.bind(this), function() {
      MySidebarService.setIsExpanded(this.panelstatus.isExpanded);
    }.bind(this));

    this.onLeftSideGroupItemClicked = function(group) {
      var prom;
      var templateType = MyAppDAGService.metadata.template.type;
      var params = {
        namespace: $stateParams.namespace,
        adapterType: templateType,
        version: rVersion.version
      };
      switch(group.name) {
        case 'source':
          params.extensionType = GLOBALS.pluginTypes[templateType].source;
          prom = myAdapterApi.fetchSources(params).$promise;
          break;
        case 'transform':
          params.extensionType = GLOBALS.pluginTypes[templateType].transform;
          prom = myAdapterApi.fetchTransforms(params).$promise;
          break;
        case 'sink':
          params.extensionType = GLOBALS.pluginTypes[templateType].sink;
          prom = myAdapterApi.fetchSinks(params).$promise;
          break;

      }
      prom
        .then(function(res) {
          this.plugins.items = [];
          res.forEach(function(plugin) {
            this.plugins.items.push(
              angular.extend(
                {
                  type: group.name,
                  icon: MyDAGFactory.getIcon(plugin.name)
                },
                plugin
              )
            );
          }.bind(this));
          // This request is made only first time. Subsequent requests are fetched from
          // cache and not actual backend calls are made unless we force it.
          return mySettings.get('pluginTemplates');
        }.bind(this))
        .then(
          function success(res) {
            if (!angular.isObject(res)) {
              return;
            }
            if (!res || !res[$state.params.namespace]) {
              return;
            }
            var templates = res[$state.params.namespace][MyAppDAGService.metadata.template.type];
            if (!templates) {
              return;
            }

            this.plugins.items = this.plugins.items.concat(
              objectToArray(templates[GLOBALS.pluginTypes[templateType][group.name]])
            );
          }.bind(this),
          function error() {
            console.log('ERROR: fetching plugin templates');
          }
        );

    };

    this.onLeftSidePanelItemClicked = function(event, item) {
      if (item.type === 'source' && this.pluginTypes[0].error) {
        delete this.pluginTypes[0].error;
      } else if (item.type === 'sink' && this.pluginTypes[2].error) {
        delete this.pluginTypes[2].error;
      }

      // TODO: Better UUID?
      var id = item.name + '-' + item.type + '-' + Date.now();
      event.stopPropagation();

      var config;

      if (item.pluginTemplate) {
        config = {
          id: id,
          name: item.pluginName,
          icon: MyDAGFactory.getIcon(item.pluginName),
          type: item.pluginType,
          properties: item.properties,
          outputSchema: item.outputSchema,
          pluginTemplate: item.pluginTemplate,
          lock: item.lock
        };
      } else {
        config = {
          id: id,
          name: item.name,
          icon: item.icon,
          description: item.description,
          type: item.type
        };
      }

      MyAppDAGService.addNodes(config, config.type, true);
    };

    function objectToArray(obj) {
      var arr = [];

      angular.forEach(obj, function (val) {
        if (val.templateType === MyAppDAGService.metadata.template.type) {
          val.icon = MyDAGFactory.getIcon(val.pluginName);
          val.name = val.pluginTemplate;

          arr.push(val);
        }
      });

      return arr;
    }
  });


text:
@implementation BMFNotificationEvent

- (instancetype) initWithName:(NSString *)name block:(BMFActionBlock) eventBlock {
	return [self initWithName:name object:nil block:eventBlock];
}

- (instancetype) initWithName:(NSString *)name object:(id)object block:(BMFActionBlock) eventBlock {
	BMFAssertReturnNil(name);

	self = [super init];
	if (self) {
		@weakify(self);
		[[[NSNotificationCenter defaultCenter] rac_addObserverForName:name object:object] subscribeNext:^(id x) {
			@strongify(self);
			if (self.eventBlock) self.eventBlock(self);
		}];
	}
	return self;

}

@end

redpajama_set_name: RedPajamaGithub


text:
/**
 *
 */
package edu.ucdenver.ccp.datasource.fileparsers.ebi.uniprot;

/*
 * #%L
 * Colorado Computational Pharmacology's common module
 * %%
 * Copyright (C) 2012 - 2015 Regents of the University of Colorado
 * %%
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
 *    may be used to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

import java.util.ArrayList;
import java.util.List;

import lombok.Getter;

import org.apache.log4j.Logger;
import org.uniprot.DbReferenceType;
import org.uniprot.Entry;
import org.uniprot.OrganismType;

import edu.ucdenver.ccp.datasource.fileparsers.FileRecord;
import edu.ucdenver.ccp.datasource.fileparsers.Record;
import edu.ucdenver.ccp.datasource.fileparsers.RecordField;
import edu.ucdenver.ccp.datasource.fileparsers.ebi.uniprot.UniProtFileRecord.DbReference;
import edu.ucdenver.ccp.datasource.fileparsers.ebi.uniprot.UniProtFileRecord.Organism;
import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.ebi.uniprot.UniProtID;

/**
 * Useful for parsing trembl and ignoring most of it
 * ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/docs/dbxref.
 * txt
 *
 * @author Colorado Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
 *
 */
@Getter
@Record(dataSource = DataSource.UNIPROT, label = "uniprot record")
public class SparseUniProtFileRecord extends FileRecord {

	private static final Logger logger = Logger.getLogger(SparseUniProtFileRecord.class);

	@RecordField(isKeyField = true)
	private final UniProtID primaryAccession;
	@RecordField
	private final List<UniProtID> accession;
	@RecordField
	private final List<String> name;
	// @RecordField
	// private final Protein protein;
	// @RecordField
	// private final List<Gene> gene;
	@RecordField
	private final Organism organism;
	@RecordField
	private final List<Organism> organismHost;
	// @RecordField
	// private final List<GeneLocation> geneLocation;
	// @RecordField
	// private final List<Reference> reference;
	// @RecordField
	// private final List<Comment> comment;
	@RecordField
	private final List<DbReference> dbReference;

	// @RecordField
	// private final ProteinExistence proteinExistence;
	// @RecordField
	// private final List<Keyword> keyword;
	// @RecordField
	// private final List<Feature> feature;
	// @RecordField
	// private final List<Evidence> evidence;
	// @RecordField
	// private final Sequence sequence;
	// @RecordField
	// private final String dataset;
	// @RecordField
	// private final XMLGregorianCalendar created;
	// @RecordField
	// private final XMLGregorianCalendar modified;
	// @RecordField
	// private final int version;

	/**
	 * @param byteOffset
	 */
	public SparseUniProtFileRecord(Entry xmlType) {
		super(-1); // b/c this data is coming from XML there's no easy way to track the byte offset
		this.accession = new ArrayList<UniProtID>();
		for (String idStr : xmlType.getAccession()) {
			this.accession.add(new UniProtID(idStr));
		}
		this.primaryAccession = this.accession.get(0);
		this.name = new ArrayList<String>(xmlType.getName());

		this.organism = new Organism(xmlType.getOrganism());
		this.organismHost = new ArrayList<Organism>();
		if (xmlType.getOrganismHost() != null) {
			for (OrganismType org : xmlType.getOrganismHost()) {
				this.organismHost.add(new Organism(org));
			}
		}

		this.dbReference = new ArrayList<DbReference>();
		if (xmlType.getDbReference() != null) {
			for (DbReferenceType ref : xmlType.getDbReference()) {
				this.dbReference.add(new DbReference(ref));
			}
		}
	}

	/**
	 * @param byteOffset
	 * @param primaryAccession
	 * @param accession
	 * @param name
	 * @param organism
	 * @param organismHost
	 * @param dbReference
	 */
	public SparseUniProtFileRecord(UniProtID primaryAccession, List<UniProtID> accession, List<String> name,
			Organism organism, List<Organism> organismHost, List<DbReference> dbReference, long byteOffset) {
		super(byteOffset);
		this.primaryAccession = primaryAccession;
		this.accession = accession;
		this.name = name;
		this.organism = organism;
		this.organismHost = organismHost;
		this.dbReference = dbReference;
	}

}


text:
export default class XPathBoolean {
  private value: boolean;

  constructor(value: boolean) {
    this.value = value;
  }

  asString() {
    return "" + this.value;
  }

  asNumber() {
    return this.value ? 1 : 0;
  }

  asBoolean() {
    return this.value;
  }
}


text:
function [acc, ncorrect] = MIL_Bag_Evaluate(bags, labels)
nbag = length(bags);

if (nbag ~= length(labels)) || (nbag == 0)
    acc = -1;
    return;     %return -1 if the number of bags dismatch the number of labels
end

ncorrect = 0;
for i=1:nbag
    if bags(i).label == labels(i)
        ncorrect = ncorrect + 1;
    end
end
acc = ncorrect / nbag;


text:
=begin
Pseudocode:

imput: students names as individual strings
output: groups of students, preferably in groups of 4-5
steps:

create an array that contains all of the students names
count total number of students
divide total by five: this will be the number of groups
sort by permutation or combination by this number - cannot remember which is which
OR divide array by 5s, if possible
OR find a method that will divide the array into the total of groups found earlier

=end

#First method:

def accountability_groups(array)
  number_of_groups = array.count / 5
  members_per_group = array.length / number_of_groups
  groups = array.each_slice(members_per_group).to_a
  print groups

end

accountability_groups(
island_foxes =
["Abraham Clark",
"Alan Alcesto",
"Aleksandra Nowak",
"Alexander Williams",
"Alicia Quezada",
"Amaar Fazlani",
"Becky Lehmann",
"Bernice Anne W Chua",
"Brian Bensch",
"Brian Wagner",
"Carolina Medellin",
"Chris Gomes",
"Chris Miklius",
"Christopher M. Guard",
"Clinton Weber",
"Daniel Andersen",
"Darius Atmar",
"Edward Gemson",
"Fatma Ocal",
"Gregory Wehmeier",
"Igor Kazimirov",
"Jacob Crofts",
"James Artz",
"Jon Clayton",
"Josh Shin",
"Joshua Virgil Monzon",
"Karla King",
"Kris Albert Lee",
"Logan Bresnahan",
"Luis Fernando Plaz",
"Malia Lehrer",
"Michael Duke",
"Michael Whelpley",
"Natalie Polen",
"Natasha Thapliyal",
"Nicola Beuscher",
"Nil Thacker",
"Nimi Samocha",
"Peter N Wood",
"Pratik Shah",
"Ryan Ho",
"Ryan Zell",
"Sabrina Unrein",
"Sasha Tailor",
"Scott Chou",
"Shawn Spears",
"Shea Munion",
"Solomon Fernandez",
"Tal Schwartz",
"Timothy Meixell",
"Trevor Newcomb",
"Walter Kerr",
"Will Granger",
"William Brinkert",
"Zach Schatz"])

# second method
def accountability_groups(array)
groups = array.shuffle.each_slice(5).to_a
  print groups
end

# Reflection

=begin
What was the most interesting and most difficult part of this challenge?

This was an intellectual challenge. The most difficult part was not using Ruby methods, because I could not think of any way to randomize the groups without using the .shuffle method. Playing around with new methods was definitely the most interesting part, and the most fun. It was really satsifying to see what they did and how they changed the way the groups divided.

Do you feel you are improving in your ability to write pseudocode and break the problem down?

My use of pseudocode has improved, but I think it could still use some work. I'm having trouble figuring out if I've broken the challenge down into too many pieces or not enough.

Was your approach for automating this task a good solution? What could have made it even better?

I was unable to find a way to keep track of previous groups made with the program, so I think a program that kept track of old groups as well as produce new ones would be even better.

What data structure did you decide to store the accountability groups in and why?

I used an array to store the names. I was tempted to figure out a way to assign values to each of the names and store them in a hash, but I couldn't figure out how to make it work properly. I figured since the names are inherently singular, and have no inherent pair, I would keep it simple in an array.

What did you learn in the process of refactoring your initial solution? Did you learn any new Ruby methods?

I did. I was able to use slice and shuffle, which were not methods that I had used before. In fact, I wasn't really sure what I was doing without them, and couldn't get my program to work right. I'm sure these methods will be very helpful in the future.
=end


text:
<?php

class FirstMigrationUsers extends CakeMigration {

/**
 * Migration description
 *
 * @var string
 * @access public
 */
	public $description = '';

/**
 * Actions to be performed
 *
 * @var array $migration
 * @access public
 */
	public $migration = array(
		'up' => array(
			'create_table' => array(
				'roles' => array(
					'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
					'title' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'alias' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 100, 'key' => 'unique', 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
					'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
					'indexes' => array(
						'PRIMARY' => array('column' => 'id', 'unique' => 1),
						'role_alias' => array('column' => 'alias', 'unique' => 1)
					),
					'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'InnoDB')
				),
				'roles_users' => array(
					'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'primary'),
					'user_id' => array('type' => 'integer', 'null' => false, 'default' => null, 'key' => 'index'),
					'role_id' => array('type' => 'integer', 'null' => false, 'default' => null),
					'granted_by' => array('type' => 'integer', 'null' => false, 'default' => null),
					'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
					'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
					'indexes' => array(
						'PRIMARY' => array('column' => 'id', 'unique' => 1),
						'pk_role_users' => array('column' => array('user_id', 'role_id'), 'unique' => 1)
					),
					'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'InnoDB')
				),
				'users' => array(
					'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 20, 'key' => 'primary'),
					'role_id' => array('type' => 'integer', 'null' => false, 'default' => null),
					'username' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 60, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'password' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'name' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 50, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'email' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 100, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'website' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 100, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'activation_key' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 60, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'image' => array('type' => 'string', 'null' => true, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'bio' => array('type' => 'text', 'null' => true, 'default' => null, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'timezone' => array('type' => 'string', 'null' => false, 'default' => '0', 'length' => 10, 'collate' => 'utf8_unicode_ci', 'charset' => 'utf8'),
					'status' => array('type' => 'boolean', 'null' => false, 'default' => '0'),
					'updated' => array('type' => 'datetime', 'null' => false, 'default' => null),
					'created' => array('type' => 'datetime', 'null' => false, 'default' => null),
					'indexes' => array(
						'PRIMARY' => array('column' => 'id', 'unique' => 1)
					),
					'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'InnoDB')
				),
			),
		),
		'down' => array(
			'drop_table' => array(
				'roles', 'roles_users', 'users'
			),
		),
	);

/**
 * Before migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function before($direction) {
		if ($direction === 'down') {
			return false;
		}
		return true;
	}

/**
 * After migration callback
 *
 * @param string $direction, up or down direction of migration process
 * @return boolean Should process continue
 * @access public
 */
	public function after($direction) {
		return true;
	}

}


text:
package com.shc.gwtal.client.webaudio.enums;

/**
 * @author Sri Harsha Chilakapati
 */
public enum ChannelInterpretation
{
    SPEAKERS("speakers"),
    DISCRETE("discrete");

    private String jsState;

    ChannelInterpretation(String jsState)
    {
        this.jsState = jsState;
    }

    public static ChannelInterpretation forJsState(String jsState)
    {
        for (ChannelInterpretation mode : values())
        {
            if (mode.getJsState().equalsIgnoreCase(jsState))
                return mode;
        }

        return null;
    }

    public String getJsState()
    {
        return jsState;
    }
}


text:
<?
/***************************************************************
* This page handles the backend of the "new group" function
* which splits a torrent off into a new group.
****************************************************************/

authorize();

if (!check_perms('torrents_edit')) {
	error(403);
}

$OldGroupID = $_POST['oldgroupid'];
$TorrentID = $_POST['torrentid'];
$ArtistName = db_string(trim($_POST['artist']));
$Title = db_string(trim($_POST['title']));
$Year = trim($_POST['year']);

if (!is_number($OldGroupID) || !is_number($TorrentID) || !is_number($Year) || !$OldGroupID || !$TorrentID || !$Year || empty($Title) || empty($ArtistName)) {
	error(0);
}

//Everything is legit, let's just confim they're not retarded
if (empty($_POST['confirm'])) {
	View::show_header();
?>

Split Confirm!

		<form class="confirm_form" name="torrent_group" action="torrents.php" method="post">
			<input type="hidden" name="action" value="newgroup" />
			<input type="hidden" name="auth" value="<?=$LoggedUser['AuthKey']?>" />
			<input type="hidden" name="confirm" value="true" />
			<input type="hidden" name="torrentid" value="<?=$TorrentID?>" />
			<input type="hidden" name="oldgroupid" value="<?=$OldGroupID?>" />
			<input type="hidden" name="artist" value="<?=display_str($_POST['artist'])?>" />
			<input type="hidden" name="title" value="<?=display_str($_POST['title'])?>" />
			<input type="hidden" name="year" value="<?=$Year?>" />

You are attempting to split the torrent <a href="torrents.php?torrentid=<?=$TorrentID?>"><?=$TorrentID?> off into a new group:

<?=display_str($_POST['artist'])?> - <?=display_str($_POST['title'])?> [<?=$Year?>]

			<input type="submit" value="Confirm" />
		</form>

<?
	View::show_footer();
} else {
	$DB->query("
		SELECT ArtistID, AliasID, Redirect, Name
		FROM artists_alias
		WHERE Name = '$ArtistName'");
	if (!$DB->has_results()) {
		$Redirect = 0;
		$DB->query("
			INSERT INTO artists_group (Name)
			VALUES ('$ArtistName')");
		$ArtistID = $DB->inserted_id();
		$DB->query("
			INSERT INTO artists_alias (ArtistID, Name)
			VALUES ('$ArtistID', '$ArtistName')");
		$AliasID = $DB->inserted_id();
	} else {
		list($ArtistID, $AliasID, $Redirect, $ArtistName) = $DB->next_record();
		if ($Redirect) {
			$AliasID = $Redirect;
		}
	}

	$DB->query("
		INSERT INTO torrents_group
			(ArtistID, CategoryID, Name, Year, Time, WikiBody, WikiImage)
		VALUES
			($ArtistID, '1', '$Title', '$Year', '".sqltime()."', '', '')");
	$GroupID = $DB->inserted_id();

	$DB->query("
		INSERT INTO torrents_artists
			(GroupID, ArtistID, AliasID, Importance, UserID)
		VALUES
			('$GroupID', '$ArtistID', '$AliasID', '1', '$LoggedUser[ID]')");

	$DB->query("
		UPDATE torrents
		SET GroupID = '$GroupID'
		WHERE ID = '$TorrentID'");

	// Delete old group if needed
	$DB->query("
		SELECT ID
		FROM torrents
		WHERE GroupID = '$OldGroupID'");
	if (!$DB->has_results()) {
		Torrents::delete_group($OldGroupID);
	} else {
		Torrents::update_hash($OldGroupID);
	}

	Torrents::update_hash($GroupID);

	$Cache->delete_value("torrent_download_$TorrentID");

	Misc::write_log("Torrent $TorrentID was edited by " . $LoggedUser['Username']);

	header("Location: torrents.php?id=$GroupID");
}
?>


text:
/***************************************************/
/*! \class ADSR
    \brief STK ADSR envelope class.

   This class implements a traditional ADSR (Attack, Decay, Sustain,
    Release) envelope.  It responds to simple keyOn and keyOff
    messages, keeping track of its state.  The \e state = ADSR::IDLE
    before being triggered and after the envelope value reaches 0.0 in
    the ADSR::RELEASE state.  All rate, target and level settings must
    be non-negative.  All time settings must be positive.

    by Perry R. Cook and Gary P. Scavone, 1995--2016.
*/
/***************************************************/

#include "ADSR.h"

namespace stk {

ADSR::ADSR() {
  target_ = 0.0;
  value_ = 0.0;
  attackRate_ = 0.001;
  decayRate_ = 0.001;
  releaseRate_ = 0.005;
  releaseTime_ = -1.0;
  sustainLevel_ = 0.5;
  state_ = IDLE;
  Stk::addSampleRateAlert(this);
}

ADSR::~ADSR() { Stk::removeSampleRateAlert(this); }

void ADSR::sampleRateChanged(StkFloat newRate, StkFloat oldRate) {
  if (!ignoreSampleRateChange_) {
    attackRate_ = oldRate * attackRate_ / newRate;
    decayRate_ = oldRate * decayRate_ / newRate;
    releaseRate_ = oldRate * releaseRate_ / newRate;
  }
}

void ADSR::keyOn() {
  if (target_ <= 0.0)
    target_ = 1.0;
  state_ = ATTACK;
}

void ADSR::keyOff() {
  target_ = 0.0;
  state_ = RELEASE;

  // FIXED October 2010 - Nick Donaldson
  // Need to make release rate relative to current value!!
  // Only update if we have set a TIME rather than a RATE,
  // in which case releaseTime_ will be -1
  if (releaseTime_ > 0.0)
    releaseRate_ = value_ / (releaseTime_ * Stk::sampleRate());
}

void ADSR::setAttackRate(StkFloat rate) {
  if (rate < 0.0) {
    oStream_ << "ADSR::setAttackRate: argument must be >= 0.0!";
    handleError(StkError::WARNING);
    return;
  }

  attackRate_ = rate;
}

void ADSR::setAttackTarget(StkFloat target) {
  if (target < 0.0) {
    oStream_ << "ADSR::setAttackTarget: negative target not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  target_ = target;
}

void ADSR::setDecayRate(StkFloat rate) {
  if (rate < 0.0) {
    oStream_ << "ADSR::setDecayRate: negative rates not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  decayRate_ = rate;
}

void ADSR::setSustainLevel(StkFloat level) {
  if (level < 0.0) {
    oStream_ << "ADSR::setSustainLevel: negative level not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  sustainLevel_ = level;
}

void ADSR::setReleaseRate(StkFloat rate) {
  if (rate < 0.0) {
    oStream_ << "ADSR::setReleaseRate: negative rates not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  releaseRate_ = rate;

  // Set to negative value so we don't update the release rate on keyOff()
  releaseTime_ = -1.0;
}

void ADSR::setAttackTime(StkFloat time) {
  if (time <= 0.0) {
    oStream_ << "ADSR::setAttackTime: negative or zero times not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  attackRate_ = 1.0 / (time * Stk::sampleRate());
}

void ADSR::setDecayTime(StkFloat time) {
  if (time <= 0.0) {
    oStream_ << "ADSR::setDecayTime: negative or zero times not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  decayRate_ = (1.0 - sustainLevel_) / (time * Stk::sampleRate());
}

void ADSR::setReleaseTime(StkFloat time) {
  if (time <= 0.0) {
    oStream_ << "ADSR::setReleaseTime: negative or zero times not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  releaseRate_ = sustainLevel_ / (time * Stk::sampleRate());
  releaseTime_ = time;
}

void ADSR::setAllTimes(StkFloat aTime, StkFloat dTime, StkFloat sLevel,
                        StkFloat rTime) {
  this->setAttackTime(aTime);
  this->setSustainLevel(sLevel);
  this->setDecayTime(dTime);
  this->setReleaseTime(rTime);
}

void ADSR::setTarget(StkFloat target) {
  if (target < 0.0) {
    oStream_ << "ADSR::setTarget: negative target not allowed!";
    handleError(StkError::WARNING);
    return;
  }

  target_ = target;

  this->setSustainLevel(target_);
  if (value_ < target_)
    state_ = ATTACK;
  if (value_ > target_)
    state_ = DECAY;
}

void ADSR::setValue(StkFloat value) {
  state_ = SUSTAIN;
  target_ = value;
  value_ = value;
  this->setSustainLevel(value);
  lastFrame_[0] = value;
}

}


text:
var gulp = require('gulp');
var rimraf = require('gulp-rimraf');

gulp.task('clean', function() {
  return gulp.src('./data/*', {
      read: false
    })
    .pipe(rimraf());
});


text:
package org.javers.hibernate.integration.entity;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "ebook")
public class Ebook {

    private String id;
    private String title;
    private Author author;
    private List<String> comments;

    public Ebook() {
    }

    public Ebook(String id, String title, Author author, List<String> comments) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.comments = comments;
    }

    @Id
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author authors) {
        this.author = authors;
    }

    @ElementCollection
    public List<String> getComments() {
        return comments;
    }

    public void setComments(List<String> comments) {
        this.comments = comments;
    }
}


text:
{% extends "base.html" %}
{% load i18n %}

{% block content %}
    <p>{% blocktrans %}Please check your email and follow the instructions to reset your password.
    If you don't receive an email, please make sure you have entered the address you registerd
    with and check your spam folder.{% endblocktrans %}</p>

{% endblock %}


text:
namespace drive {
namespace file_system {

class OpenFileOperationTest : public OperationTestBase {
 protected:
  virtual void SetUp() OVERRIDE {
    OperationTestBase::SetUp();

    operation_.reset(new OpenFileOperation(
        blocking_task_runner(), delegate(), scheduler(), metadata(), cache(),
        temp_dir()));
  }

  scoped_ptr<OpenFileOperation> operation_;
};

TEST_F(OpenFileOperationTest, OpenExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64 file_size = src_entry.file_info().size();

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      OPEN_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  int64 local_file_size;
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(file_size, local_file_size);

  ASSERT_FALSE(close_callback.is_null());
  close_callback.Run();
  EXPECT_EQ(1U, delegate()->updated_local_ids().count(src_entry.local_id()));
}

TEST_F(OpenFileOperationTest, OpenNonExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/not-exist.txt"));

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      OPEN_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();
  EXPECT_EQ(FILE_ERROR_NOT_FOUND, error);
  EXPECT_TRUE(close_callback.is_null());
}

TEST_F(OpenFileOperationTest, CreateExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      CREATE_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_EXISTS, error);
  EXPECT_TRUE(close_callback.is_null());
}

TEST_F(OpenFileOperationTest, CreateNonExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/not-exist.txt"));

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      CREATE_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(file_in_root));

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  int64 local_file_size;
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(0, local_file_size);  // Should be an empty file.

  ASSERT_FALSE(close_callback.is_null());
  close_callback.Run();
  EXPECT_EQ(1U,
            delegate()->updated_local_ids().count(GetLocalId(file_in_root)));
}

TEST_F(OpenFileOperationTest, OpenOrCreateExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64 file_size = src_entry.file_info().size();

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      OPEN_OR_CREATE_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  // Notified because 'available offline' status of the existing file changes.
  EXPECT_EQ(1U, delegate()->get_changed_files().size());
  EXPECT_TRUE(delegate()->get_changed_files().count(file_in_root));

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  int64 local_file_size;
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(file_size, local_file_size);

  ASSERT_FALSE(close_callback.is_null());
  close_callback.Run();
  EXPECT_EQ(1U, delegate()->updated_local_ids().count(src_entry.local_id()));

  ResourceEntry result_entry;
  EXPECT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &result_entry));
  EXPECT_TRUE(result_entry.file_specific_info().cache_state().is_present());
  EXPECT_TRUE(result_entry.file_specific_info().cache_state().is_dirty());
}

TEST_F(OpenFileOperationTest, OpenOrCreateNonExistingFile) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/not-exist.txt"));

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      OPEN_OR_CREATE_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  int64 local_file_size;
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(0, local_file_size);  // Should be an empty file.

  ASSERT_FALSE(close_callback.is_null());
  close_callback.Run();
  EXPECT_EQ(1U,
            delegate()->updated_local_ids().count(GetLocalId(file_in_root)));
}

TEST_F(OpenFileOperationTest, OpenFileTwice) {
  const base::FilePath file_in_root(
      FILE_PATH_LITERAL("drive/root/File 1.txt"));
  ResourceEntry src_entry;
  ASSERT_EQ(FILE_ERROR_OK, GetLocalResourceEntry(file_in_root, &src_entry));
  const int64 file_size = src_entry.file_info().size();

  FileError error = FILE_ERROR_FAILED;
  base::FilePath file_path;
  base::Closure close_callback;
  operation_->OpenFile(
      file_in_root,
      OPEN_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  int64 local_file_size;
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(file_size, local_file_size);

  // Open again.
  error = FILE_ERROR_FAILED;
  base::Closure close_callback2;
  operation_->OpenFile(
      file_in_root,
      OPEN_FILE,
      std::string(),  // mime_type
      google_apis::test_util::CreateCopyResultCallback(
          &error, &file_path, &close_callback2));
  content::RunAllBlockingPoolTasksUntilIdle();

  EXPECT_EQ(FILE_ERROR_OK, error);
  ASSERT_TRUE(base::PathExists(file_path));
  ASSERT_TRUE(base::GetFileSize(file_path, &local_file_size));
  EXPECT_EQ(file_size, local_file_size);

  ASSERT_FALSE(close_callback.is_null());
  ASSERT_FALSE(close_callback2.is_null());

  close_callback.Run();

  // There still remains a client opening the file, so it shouldn't be
  // uploaded yet.
  EXPECT_TRUE(delegate()->updated_local_ids().empty());

  close_callback2.Run();

  // Here, all the clients close the file, so it should be uploaded then.
  EXPECT_EQ(1U, delegate()->updated_local_ids().count(src_entry.local_id()));
}

}  // namespace file_system
}  // namespace drive


text:
normal_unless[:attr_load_order] = []
normal[:attr_load_order] << "circular-dep2::default"


text:
<?php namespace Ahzab\Slider\Repositories\Eloquent;

use App;
use Lang;
use Theme;
use Ahzab\Slider\Models\Slider as Slider;
use Ahzab\Slider\Interfaces\SliderInterface;

class SliderRepository extends BaseRepository implements SliderInterface
{
    public function __construct(Slider $Slider)
    {
        $this->model = $Slider;
    }

    public function getSlider($slug)
    {
        $Slider 	= $this -> model -> whereSlug($slug) -> first();

        if (!$Slider) {
            $Slider   = $this -> model -> whereSlug('404') -> first();
        }

        if (!$Slider) {
            App::abort(404, Lang::get("Slider::messages.noSlider"));
        }

        $this -> compile($Slider);
        return $Slider;
    }

    public function heading($slug)
    {
        return $this -> SliderPart($slug, 'heading');
    }

    public function content($slug)
    {
        return $this -> SliderPart($slug, 'content');
    }

    public function title($slug)
    {
        return $this -> SliderPart($slug, 'title');
    }

    public function keyword($slug)
    {
        return $this -> SliderPart($slug, 'keyword');
    }

    public function description($slug)
    {
        return $this -> SliderPart($slug, 'description');
    }

    public function banner($slug)
    {
        return $this -> SliderPart($slug, 'banner');
    }

    public function SliderPart($slug, $field)
    {
        $Slider 	= $this -> model -> whereSlug($slug) -> first();

        if (!$Slider) {
           return Lang::get("Slider::messages.noSlider");
        }

        return $Slider->$field;
    }

    public function errors()
    {
        return $this -> model -> errors();

    }

    public function compile(&$Slider)
    {
        $compiler = $Slider->compiler;

        if ($compiler == 'blade')
            $Slider->content = Theme::blader($Slider -> content, array());
        elseif ($compiler == 'twig')
            $Slider->content = Theme::twigy($Slider -> content, array());

    }
}


text:
/**
 * Convert a value to an array.
 * @param {*} value the value to convert
 * @returns {Array} the array
 * @private
 */
export function toArray(value) {
    return value ? Array.prototype.slice.call(value) : [];
}

/**
 * Convert undefined and null value to empty string.
 * @param {string} value the value to sanitize
 * @returns {string} the sanitized value
 * @private
 */
export function sanitize(value) {
    return value === undefined || value === null ? '' : value;
}

/**
 * Transform an array to an object.
 * The first value is the key, the second its value and so one.
 * @param {Array} array the array
 * @returns {object} the object
 * @private
 */
export function fromArrayToObject(array) {
    const object = {};
    if (!array) {
        return object;
    }
    const max = array.length;
    for (let i = 0; i < max; i = i + 2) {
        object[array[i]] = array[i + 1];
    }
    return object;
}

/**
 * According to the given parent, try to find a node matching with the given key.
 * @param {!Element} parent the parent element
 * @param {!number} from the index of the starting node
 * @param {!string} key the key to find
 * @returns {Node}
 * @private
 */
export function findNodeFromKey(parent, from, key) {
    const end = parent.childNodes.length;
    for (let i = from; i < end; i++) {
        const child = parent.childNodes.item(i);
        if (child.dataset && child.dataset.fcKey === key) {
            return child;
        }
    }
}

/**
 * Update the given element's attributes according to the new one.
 * @param {!Element} element the element
 * @param {Array.<undefined|null|string|number|boolean>} [attributes] the new attributes
 * @private
 */
export function updateAttributes(element, attributes) {
    attributes = attributes ? attributes : [];
    const updatedAttributes = {};
    const max = attributes.length;
    for (let i = 0; i < max; i = i + 2) {
        const name = attributes[i];
        const value = attributes[i + 1];
        const type = typeof value;
        if (type === 'boolean') {
            if (value) {
                element.setAttribute(name, '');
                updatedAttributes[name] = true;
            }
        } else if (type === 'number') {
            element.setAttribute(name, value);
            updatedAttributes[name] = true;
        } else if (value) {
            element.setAttribute(name, sanitize(value));
            updatedAttributes[name] = true;
        }
    }
    toArray(element.attributes)
        .filter((attr) => !updatedAttributes[attr.name])
        .forEach((attr) => element.removeAttribute(attr.name));
}

/**
 * Update the given element's properties according to the new one.
 * @param {!Element} element the element
 * @param {Array} [properties] the new attributes
 * @private
 */
export function updateProperties(element, properties) {
    properties = properties ? properties : [];
    const updatedProperties = {};
    const max = properties.length;
    for (let i = 0; i < max; i = i + 2) {
        const name = properties[i];
        element[name] = properties[i + 1];
        updatedProperties[name] = true;
    }
    toArray(element.updatedProperties)
        .filter((name) => !updatedProperties[name])
        .forEach((name) => element[name] = undefined);
    element.updatedProperties = Object.keys(updatedProperties);
}


text:
from __future__ import with_statement

import unittest

import greenhouse
import greenhouse.poller

from test_base import TESTING_TIMEOUT, StateClearingTestCase

class OneWayPoolTestCase(StateClearingTestCase):
    POOL = greenhouse.OneWayPool

    def empty_out(self, pool, size):
        return []

    def test_shuts_down(self):
        def f(x):
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        self.empty_out(pool, 30)

        pool.close()

        for x in xrange(30):
            pool.put(x)

        greenhouse.pause()

        self.assertEqual(len(pool.inq._data), 30)

    def test_kills_all_coros(self):
        class Pool(self.POOL):
            def __init__(self, *args, **kwargs):
                super(Pool, self).__init__(*args, **kwargs)
                self.finished = []

            def _runner(self):
                super(Pool, self)._runner()
                self.finished.append(None)

        def f(x):
            return x ** 2

        pool = Pool(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        self.empty_out(pool, 30)

        pool.close()

        greenhouse.pause()

        self.assertEqual(len(pool.finished), pool.size)

    def test_as_context_manager(self):
        l = []

        def f(x):
            l.append(x ** 2)

        with self.POOL(f) as pool:
            for x in xrange(30):
                pool.put(x)

        greenhouse.pause()
        greenhouse.pause()
        greenhouse.pause()

        l.sort()
        assert l == [x ** 2 for x in xrange(30)]

    def test_exception_resiliency(self):
        l = []

        count = 5

        def runner(item):
            if item < count:
                raise AttributeError("blah")
            l.append(item ** 2)

        pool = self.POOL(runner, count)
        pool.start()

        for i in xrange(count):
            pool.put(i)

        greenhouse.pause()
        self.assertEqual(l, [])

        for i in xrange(count, count * 3):
            pool.put(i)

        greenhouse.pause()
        self.assertEqual(sorted(l), [x ** 2 for x in xrange(count, count * 3)])

        pool.close()

class PoolTestCase(OneWayPoolTestCase):
    POOL = greenhouse.Pool

    def empty_out(self, pool, size):
        return [pool.get() for i in xrange(size)]

    def test_as_context_manager(self):
        def f(x):
            return x ** 2

        with self.POOL(f) as pool:
            for x in xrange(30):
                pool.put(x)

            l = self.empty_out(pool, 30)

        l.sort()
        assert l == [x ** 2 for x in xrange(30)]

    def test_basic_two_way(self):
        def f(x):
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        l = self.empty_out(pool, 30)

        l.sort()
        assert l == [x ** 2 for x in xrange(30)]

        pool.close()

    def test_starting_back_up(self):
        def f(x):
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        self.empty_out(pool, 30)

        pool.close()

        greenhouse.pause()

        pool.start()

        for x in xrange(30):
            pool.put(x)

        l = self.empty_out(pool, 30)

        l.sort()
        assert l == [x ** 2 for x in xrange(30)]

    def test_two_way_with_blocking(self):
        def f(x):
            if x % 2:
                greenhouse.pause()
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        l = self.empty_out(pool, 30)

        l.sort()
        assert l == [x ** 2 for x in xrange(30)]

        pool.close()

    def test_get_raises(self):
        count = 5

        def runner(item):
            if item < count:
                raise AttributeError("blah")
            else:
                return item ** 2

        pool = self.POOL(runner, count)
        pool.start()

        for i in xrange(count):
            pool.put(i)

        for i in xrange(count):
            self.assertRaises(AttributeError, pool.get)

        for i in xrange(count, count * 3):
            pool.put(i)

        l = []
        for i in xrange(count * 2):
            l.append(pool.get())

        self.assertEqual(sorted(l), [x ** 2 for x in xrange(count, count * 3)])

        pool.close()

    def test_getters_raise_on_close(self):
        l = []
        raised = [False]

        def runner(item):
            return item ** 2

        pool = self.POOL(runner, 5)
        pool.start()

        @greenhouse.schedule
        def getter():
            try:
                while 1:
                    l.append(pool.get())
            except StandardError:
                raised[0] = True

        for i in xrange(10):
            pool.put(i)
        greenhouse.pause()

        self.assertEqual(l, [x ** 2 for x in xrange(10)])

        pool.close()
        greenhouse.pause()

        assert raised[0]

    def test_iteration(self):
        def runner(x):
            if x > 10:
                pool.close()
            return x ** 2

        def putter(pool):
            i = 0
            while 1:
                i += 1
                pool.put(i)
                greenhouse.pause()

        pool = self.POOL(runner, 3)
        pool.start()

        greenhouse.schedule(putter, args=(pool,))

        results = []
        for item in pool:
            results.append(item)

        self.assertEqual(results, [x ** 2 for x in xrange(1, 11)])

class OrderedPoolTestCase(PoolTestCase):
    POOL = greenhouse.OrderedPool

    def test_ordered_basic(self):
        def f(x):
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        l = []
        for x in xrange(30):
            l.append(pool.get())

        assert l == [x ** 2 for x in xrange(30)]

        pool.close()

    def test_ordered_with_blocking(self):
        def f(x):
            if x % 2:
                greenhouse.pause()
                greenhouse.pause()
                greenhouse.pause()
            return x ** 2

        pool = self.POOL(f)
        pool.start()

        for x in xrange(30):
            pool.put(x)

        l = []
        for x in xrange(30):
            l.append(pool.get())

        assert l == [x ** 2 for x in xrange(30)]

        pool.close()

if __name__ == '__main__':
    unittest.main()


text:
namespace syncer {

NullInvalidationStateTracker::NullInvalidationStateTracker() {}
NullInvalidationStateTracker::~NullInvalidationStateTracker() {}

InvalidationStateMap
NullInvalidationStateTracker::GetAllInvalidationStates() const {
  return InvalidationStateMap();
}

void NullInvalidationStateTracker::SetMaxVersionAndPayload(
    const invalidation::ObjectId& id,
    int64 max_invalidation_version,
    const std::string& payload) {
  LOG(INFO) << "Setting max invalidation version for "
          << ObjectIdToString(id) << " to " << max_invalidation_version
          << " with payload " << payload;
}

void NullInvalidationStateTracker::Forget(const ObjectIdSet& ids) {
  for (ObjectIdSet::const_iterator it = ids.begin(); it != ids.end(); ++it) {
    LOG(INFO) << "Forgetting invalidation state for " << ObjectIdToString(*it);
  }
}

void NullInvalidationStateTracker::SetInvalidatorClientId(
    const std::string& data) {
  LOG(INFO) << "Setting invalidator client ID to: " << data;
}

std::string NullInvalidationStateTracker::GetInvalidatorClientId() const {
  return std::string();
}

std::string NullInvalidationStateTracker::GetBootstrapData() const {
  return std::string();
}

void NullInvalidationStateTracker::SetBootstrapData(const std::string& data) {
  std::string base64_data;
  CHECK(base::Base64Encode(data, &base64_data));
  LOG(INFO) << "Setting bootstrap data to: " << base64_data;
}

void NullInvalidationStateTracker::GenerateAckHandles(
    const ObjectIdSet& ids,
    const scoped_refptr<base::TaskRunner>& task_runner,
    base::Callback<void(const AckHandleMap&)> callback) {
  AckHandleMap ack_handles;
  for (ObjectIdSet::const_iterator it = ids.begin(); it != ids.end(); ++it) {
    ack_handles.insert(std::make_pair(*it, AckHandle::InvalidAckHandle()));
  }
  CHECK(task_runner->PostTask(FROM_HERE, base::Bind(callback, ack_handles)));
}

void NullInvalidationStateTracker::Acknowledge(const invalidation::ObjectId& id,
                                               const AckHandle& ack_handle) {
  LOG(INFO) << "Received ack for " << ObjectIdToString(id);
}

}  // namespace syncer


text:
angular.module('myClothingApp')
    .directive('breadcrumbDirective', function() {
       'use strict';

       return {
           restrict: 'E',
           scope: {
               gender: '=',
               category: '=',
               location: '='
           },
           templateUrl: 'app/product/breadcrumb.html'
       }
    });


text:
(function (root, factory) {
    // UMD boilerplate from https://github.com/umdjs/umd/blob/master/returnExportsGlobal.js
    'use strict';

    /* istanbul ignore next */
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['xmlhttprequest', 'js-base64'], function (XMLHttpRequest, b64encode) {
            return (root.Github = factory(XMLHttpRequest.XMLHttpRequest, b64encode.Base64.encode));
        });
    } else if (typeof module === 'object' && module.exports) {
        if (typeof window !== 'undefined') { // jscs:ignore
            module.exports = factory(window.XMLHttpRequest, window.btoa);
        } else { // jscs:ignore
            module.exports = factory(require('xmlhttprequest').XMLHttpRequest, require('js-base64').Base64.encode);
        }
    } else {
        // Browser globals
        var b64encode = function(str) {
            return root.btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
        };

        root.Github = factory(root.XMLHttpRequest, b64encode);
    }
}(this, function (XMLHttpRequest, b64encode) {
    'use strict';

    // Initial Setup
    // -------------

    var Github = function(options) {
        var API_URL = options.apiUrl || 'https://api.github.com';

        // HTTP Request Abstraction
        // =======
        //
        // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

        var _request = Github._request = function _request(method, path, data, cb, raw, sync) {
            function getURL() {
                var url = path.indexOf('//') >= 0 ? path : API_URL + path;

                url += ((/\?/).test(url) ? '&' : '?');

                if (data && typeof data === 'object' && ['GET', 'HEAD', 'DELETE'].indexOf(method) > -1) {
                    for(var param in data) {
                        if (data.hasOwnProperty(param))
                            url += '&' + encodeURIComponent(param) + '=' + encodeURIComponent(data[param]);
                    }
                }

                return url.replace(/(&timestamp=\d+)/, '') +
                    (typeof window !== 'undefined' ? '&timestamp=' + new Date().getTime() : '');
            }

            var xhr = new XMLHttpRequest();

            xhr.open(method, getURL(), !sync);

            if (!sync) {
                xhr.onreadystatechange = function () {
                    if (this.readyState === 4) {
                        if (this.status >= 200 && this.status < 300 || this.status === 304) {
                            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true, this);
                        } else {
                            cb({
                                path: path, request: this, error: this.status
                            });
                        }
                    }
                };
            }

            if (!raw) {
                xhr.dataType = 'json';
                xhr.setRequestHeader('Accept', 'application/vnd.github.v3+json');
            } else {
                xhr.setRequestHeader('Accept', 'application/vnd.github.v3.raw+json');
            }

            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

            if ((options.token) || (options.username && options.password)) {
                var authorization = options.token ? 'token ' + options.token :
                'Basic ' + b64encode(options.username + ':' + options.password);

                xhr.setRequestHeader('Authorization', authorization);
            }

            if (data) {
                xhr.send(JSON.stringify(data));
            } else {
                xhr.send();
            }

            if (sync) {
                return xhr.response;
            }
        };

        var _requestAllPages = Github._requestAllPages = function _requestAllPages(path, cb) {
            var results = [];

            (function iterate() {
                _request('GET', path, null, function(err, res, xhr) {
                    if (err) {
                        return cb(err);
                    }

                    results.push.apply(results, res);

                    var links = (xhr.getResponseHeader('link') || '').split(/\s*,\s*/g);
                    var next = null;

                    links.forEach(function(link) {
                        next = /rel="next"/.test(link) ? link : next;
                    });

                    if (next) {
                        next = (/<(.*)>/.exec(next) || [])[1];
                    }

                    if (!next) {
                        cb(err, results);
                    } else {
                        path = next;
                        iterate();
                    }
                });
            })();
        };

        // User API
        // =======

        Github.User = function() {
            this.repos = function(options, cb) {
                if (arguments.length === 1 && typeof arguments[0] === 'function') {
                    cb = options;
                    options = {};
                }

                options = options || {};

                var url = '/user/repos';
                var params = [];

                params.push('type=' + encodeURIComponent(options.type || 'all'));
                params.push('sort=' + encodeURIComponent(options.sort || 'updated'));
                params.push('per_page=' + encodeURIComponent(options.per_page || '1000')); // jscs:ignore

                if (options.page) {
                    params.push('page=' + encodeURIComponent(options.page));
                }

                url += '?' + params.join('&');

                _request('GET', url, null, cb);
            };

            // List user organizations
            // -------

            this.orgs = function(cb) {
                _request('GET', '/user/orgs', null, cb);
            };

            // List authenticated user's gists
            // -------

            this.gists = function(cb) {
                _request('GET', '/gists', null, cb);
            };

            // List authenticated user's unread notifications
            // -------

            this.notifications = function(options, cb) {
                if (arguments.length === 1 && typeof arguments[0] === 'function') {
                    cb = options;
                    options = {};
                }

                options = options || {};
                var url = '/notifications';
                var params = [];

                if (options.all) {
                    params.push('all=true');
                }

                if (options.participating) {
                    params.push('participating=true');
                }

                if (options.since) {
                    var since = options.since;

                    if (since.constructor === Date) {
                        since = since.toISOString();
                    }

                    params.push('since=' + encodeURIComponent(since));
                }

                if (options.before) {
                    var before = options.before;

                    if (before.constructor === Date) {
                        before = before.toISOString();
                    }

                    params.push('before=' + encodeURIComponent(before));
                }

                if (options.page) {
                    params.push('page=' + encodeURIComponent(options.page));
                }

                if (params.length > 0) {
                    url += '?' + params.join('&');
                }

                _request('GET', url, null, cb);
            };

            // Show user information
            // -------

            this.show = function(username, cb) {
                var command = username ? '/users/' + username : '/user';

                _request('GET', command, null, cb);
            };

            // List user repositories
            // -------

            this.userRepos = function(username, cb) {
                // Github does not always honor the 1000 limit so we want to iterate over the data set.
                _requestAllPages('/users/' + username + '/repos?type=all&per_page=1000&sort=updated', cb);
            };

            // List user starred repositories
            // -------

            this.userStarred = function(username, cb) {
                // Github does not always honor the 1000 limit so we want to iterate over the data set.
                _requestAllPages('/users/' + username + '/starred?type=all&per_page=1000', function(err, res) {
                    cb(err, res);
                });
            };

            // List a user's gists
            // -------

            this.userGists = function(username, cb) {
                _request('GET', '/users/' + username + '/gists', null, cb);
            };

            // List organization repositories
            // -------

            this.orgRepos = function(orgname, cb) {
                // Github does not always honor the 1000 limit so we want to iterate over the data set.
                _requestAllPages('/orgs/' + orgname + '/repos?type=all&&page_num=1000&sort=updated&direction=desc', cb);
            };

            // Follow user
            // -------

            this.follow = function(username, cb) {
                _request('PUT', '/user/following/' + username, null, cb);
            };

            // Unfollow user
            // -------

            this.unfollow = function(username, cb) {
                _request('DELETE', '/user/following/' + username, null, cb);
            };

            // Create a repo
            // -------
            this.createRepo = function(options, cb) {
                _request('POST', '/user/repos', options, cb);
            };
        };

        // Repository API
        // =======

        Github.Repository = function(options) {
            var repo = options.name;
            var user = options.user;
            var fullname = options.fullname;

            var that = this;
            var repoPath;

            if (fullname) {
                repoPath = '/repos/' + fullname;
            } else {
                repoPath = '/repos/' + user + '/' + repo;
            }

            var currentTree = {
                branch: null,
                sha: null
            };

            // Uses the cache if branch has not been changed
            // -------

            function updateTree(branch, cb) {
                if (branch === currentTree.branch && currentTree.sha) {
                    return cb(null, currentTree.sha);
                }

                that.getRef('heads/' + branch, function(err, sha) {
                    currentTree.branch = branch;
                    currentTree.sha = sha;
                    cb(err, sha);
                });
            }

            // Get a particular reference
            // -------

            this.getRef = function(ref, cb) {
                _request('GET', repoPath + '/git/refs/' + ref, null, function(err, res, xhr) {
                    if (err) {
                        return cb(err);
                    }

                    cb(null, res.object.sha, xhr);
                });
            };

            // Create a new reference
            // --------
            //
            // {
            //   "ref": "refs/heads/my-new-branch-name",
            //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
            // }

            this.createRef = function(options, cb) {
                _request('POST', repoPath + '/git/refs', options, cb);
            };

            // Delete a reference
            // --------
            //
            // Repo.deleteRef('heads/gh-pages')
            // repo.deleteRef('tags/v1.0')

            this.deleteRef = function(ref, cb) {
                _request('DELETE', repoPath + '/git/refs/' + ref, options, function(err, res, xhr) {
                    cb(err, res, xhr);
                });
            };

            // Create a repo
            // -------

            this.createRepo = function(options, cb) {
                _request('POST', '/user/repos', options, cb);
            };

            // Delete a repo
            // --------

            this.deleteRepo = function(cb) {
                _request('DELETE', repoPath, options, cb);
            };

            // List all tags of a repository
            // -------

            this.listTags = function(cb) {
                _request('GET', repoPath + '/tags', null, function(err, tags, xhr) {
                    if (err) {
                        return cb(err);
                    }

                    cb(null, tags, xhr);
                });
            };

            // List all pull requests of a respository
            // -------

            this.listPulls = function(options, cb) {
                options = options || {};
                var url = repoPath + '/pulls';
                var params = [];

                if (typeof options === 'string') {
                    // Backward compatibility
                    params.push('state=' + options);
                } else {
                    if (options.state) {
                        params.push('state=' + encodeURIComponent(options.state));
                    }

                    if (options.head) {
                        params.push('head=' + encodeURIComponent(options.head));
                    }

                    if (options.base) {
                        params.push('base=' + encodeURIComponent(options.base));
                    }

                    if (options.sort) {
                        params.push('sort=' + encodeURIComponent(options.sort));
                    }

                    if (options.direction) {
                        params.push('direction=' + encodeURIComponent(options.direction));
                    }

                    if (options.page) {
                        params.push('page=' + options.page);
                    }

                    if (options.per_page) {
                        params.push('per_page=' + options.per_page);
                    }
                }

                if (params.length > 0) {
                    url += '?' + params.join('&');
                }

                _request('GET', url, null, function(err, pulls, xhr) {
                    if (err) return cb(err);
                    cb(null, pulls, xhr);
                });
            };

            // Gets details for a specific pull request
            // -------

            this.getPull = function(number, cb) {
                _request('GET', repoPath + '/pulls/' + number, null, function(err, pull, xhr) {
                    if (err) return cb(err);
                    cb(null, pull, xhr);
                });
            };

            // Retrieve the changes made between base and head
            // -------

            this.compare = function(base, head, cb) {
                _request('GET', repoPath + '/compare/' + base + '...' + head, null, function(err, diff, xhr) {
                    if (err) return cb(err);
                    cb(null, diff, xhr);
                });
            };

            // List all branches of a repository
            // -------

            this.listBranches = function(cb) {
                _request('GET', repoPath + '/git/refs/heads', null, function(err, heads, xhr) {
                    if (err) return cb(err);
                    cb(null, heads.map(function(head) {
                        return head.ref.replace(/^refs\/heads\//, '');
                    }), xhr);
                });
            };

            // Retrieve the contents of a blob
            // -------

            this.getBlob = function(sha, cb) {
                _request('GET', repoPath + '/git/blobs/' + sha, null, cb, 'raw');
            };

            // For a given file path, get the corresponding sha (blob for files, tree for dirs)
            // -------

            this.getCommit = function(branch, sha, cb) {
                _request('GET', repoPath + '/git/commits/' + sha, null, function(err, commit, xhr) {
                    if (err) return cb(err);
                    cb(null, commit, xhr);
                });
            };

            // For a given file path, get the corresponding sha (blob for files, tree for dirs)
            // -------

            this.getSha = function(branch, path, cb) {
                if (!path || path === '') return that.getRef('heads/' + branch, cb);
                _request('GET', repoPath + '/contents/' + path + (branch ? '?ref=' + branch : ''),
                    null, function(err, pathContent, xhr) {
                        if (err) return cb(err);
                        cb(null, pathContent.sha, xhr);
                    });
            };

            // Get the statuses for a particular SHA
            // -------

            this.getStatuses = function(sha, cb) {
                _request('GET', repoPath + '/statuses/' + sha, null, cb);
            };

            // Retrieve the tree a commit points to
            // -------

            this.getTree = function(tree, cb) {
                _request('GET', repoPath + '/git/trees/' + tree, null, function(err, res, xhr) {
                    if (err) return cb(err);
                    cb(null, res.tree, xhr);
                });
            };

            // Post a new blob object, getting a blob SHA back
            // -------

            this.postBlob = function(content, cb) {
                if (typeof (content) === 'string') {
                    content = {
                        content: content,
                        encoding: 'utf-8'
                    };
                } else {
                    content = {
                        content: b64encode(content),
                        encoding: 'base64'
                    };
                }

                _request('POST', repoPath + '/git/blobs', content, function(err, res) {
                    if (err) return cb(err);
                    cb(null, res.sha);
                });
            };

            // Update an existing tree adding a new blob object getting a tree SHA back
            // -------

            this.updateTree = function(baseTree, path, blob, cb) {
                var data = {
                    base_tree: baseTree,
                    tree: [
                        {
                            path: path,
                            mode: '100644',
                            type: 'blob',
                            sha: blob
                        }
                    ]
                };

                _request('POST', repoPath + '/git/trees', data, function(err, res) {
                    if (err) return cb(err);
                    cb(null, res.sha);
                });
            };

            // Post a new tree object having a file path pointer replaced
            // with a new blob SHA getting a tree SHA back
            // -------

            this.postTree = function(tree, cb) {
                _request('POST', repoPath + '/git/trees', {
                    tree: tree
                }, function(err, res) {
                    if (err) return cb(err);
                    cb(null, res.sha);
                });
            };

            // Create a new commit object with the current commit SHA as the parent
            // and the new tree SHA, getting a commit SHA back
            // -------

            this.commit = function(parent, tree, message, cb) {
                var user = new Github.User();

                user.show(null, function(err, userData) {
                    if (err) return cb(err);
                    var data = {
                        message: message,
                        author: {
                            name: options.user,
                            email: userData.email
                        },
                        parents: [
                            parent
                        ],
                        tree: tree
                    };

                    _request('POST', repoPath + '/git/commits', data, function(err, res) {
                        if (err) return cb(err);
                        currentTree.sha = res.sha; // Update latest commit
                        cb(null, res.sha);
                    });
                });
            };

            // Update the reference of your head to point to the new commit SHA
            // -------

            this.updateHead = function(head, commit, cb) {
                _request('PATCH', repoPath + '/git/refs/heads/' + head, {
                    sha: commit
                }, function(err) {
                    cb(err);
                });
            };

            // Show repository information
            // -------

            this.show = function(cb) {
                _request('GET', repoPath, null, cb);
            };

            // Show repository contributors
            // -------

            this.contributors = function (cb, retry) {
                retry = retry || 1000;
                var that = this;

                _request('GET', repoPath + '/stats/contributors', null, function (err, data, xhr) {
                    if (err) return cb(err);

                    if (xhr.status === 202) {
                        setTimeout(
                            function () {
                                that.contributors(cb, retry);
                            },
                            retry
                        );
                    } else {
                        cb(err, data, xhr);
                    }
                });
            };

            // Get contents
            // --------

            this.contents = function(ref, path, cb) {
                path = encodeURI(path);
                _request('GET', repoPath + '/contents' + (path ? '/' + path : ''), {
                    ref: ref
                }, cb);
            };

            // Fork repository
            // -------

            this.fork = function(cb) {
                _request('POST', repoPath + '/forks', null, cb);
            };

            // List forks
            // --------

            this.listForks = function(cb) {
                _request('GET', repoPath + '/forks', null, cb);
            };

            // Branch repository
            // --------

            this.branch = function(oldBranch, newBranch, cb) {
                if (arguments.length === 2 && typeof arguments[1] === 'function') {
                    cb = newBranch;
                    newBranch = oldBranch;
                    oldBranch = 'master';
                }

                this.getRef('heads/' + oldBranch, function(err, ref) {
                    if (err && cb) return cb(err);
                    that.createRef({
                        ref: 'refs/heads/' + newBranch,
                        sha: ref
                    }, cb);
                });
            };

            // Create pull request
            // --------

            this.createPullRequest = function(options, cb) {
                _request('POST', repoPath + '/pulls', options, cb);
            };

            // List hooks
            // --------

            this.listHooks = function(cb) {
                _request('GET', repoPath + '/hooks', null, cb);
            };

            // Get a hook
            // --------

            this.getHook = function(id, cb) {
                _request('GET', repoPath + '/hooks/' + id, null, cb);
            };

            // Create a hook
            // --------

            this.createHook = function(options, cb) {
                _request('POST', repoPath + '/hooks', options, cb);
            };

            // Edit a hook
            // --------

            this.editHook = function(id, options, cb) {
                _request('PATCH', repoPath + '/hooks/' + id, options, cb);
            };

            // Delete a hook
            // --------

            this.deleteHook = function(id, cb) {
                _request('DELETE', repoPath + '/hooks/' + id, null, cb);
            };

            // Read file at given path
            // -------

            this.read = function(branch, path, cb) {
                _request('GET', repoPath + '/contents/' + encodeURI(path) + (branch ? '?ref=' + branch : ''),
                    null, function(err, obj, xhr) {
                        if (err && err.error === 404) return cb('not found', null, null);

                        if (err) return cb(err);
                        cb(null, obj, xhr);
                    }, true);
            };

            // Remove a file
            // -------

            this.remove = function(branch, path, cb) {
                that.getSha(branch, path, function(err, sha) {
                    if (err) return cb(err);
                    _request('DELETE', repoPath + '/contents/' + path, {
                        message: path + ' is removed',
                        sha: sha,
                        branch: branch
                    }, cb);
                });
            };

            // Alias for repo.remove for backwards comapt.
            // -------
            this.delete = this.remove;

            // Move a file to a new location
            // -------

            this.move = function(branch, path, newPath, cb) {
                updateTree(branch, function(err, latestCommit) {
                    that.getTree(latestCommit + '?recursive=true', function(err, tree) {
                        // Update Tree
                        tree.forEach(function(ref) {
                            if (ref.path === path) ref.path = newPath;

                            if (ref.type === 'tree') delete ref.sha;
                        });

                        that.postTree(tree, function(err, rootTree) {
                            that.commit(latestCommit, rootTree, 'Deleted ' + path , function(err, commit) {
                                that.updateHead(branch, commit, function(err) {
                                    cb(err);
                                });
                            });
                        });
                    });
                });
            };

            // Write file contents to a given branch and path
            // -------

            this.write = function(branch, path, content, message, options, cb) {
                if (typeof cb === 'undefined') {
                    cb = options;
                    options = {};
                }

                that.getSha(branch, encodeURI(path), function(err, sha) {
                    var writeOptions = {
                        message: message,
                        content: typeof options.encode === 'undefined' || options.encode ? b64encode(content) : content,
                        branch: branch,
                        committer: options && options.committer ? options.committer : undefined,
                        author: options && options.author ? options.author : undefined
                    };

                    // If no error, we set the sha to overwrite an existing file
                    if (!(err && err.error !== 404)) writeOptions.sha = sha;
                    _request('PUT', repoPath + '/contents/' + encodeURI(path), writeOptions, cb);
                });
            };

            // List commits on a repository. Takes an object of optional paramaters:
            // sha: SHA or branch to start listing commits from
            // path: Only commits containing this file path will be returned
            // since: ISO 8601 date - only commits after this date will be returned
            // until: ISO 8601 date - only commits before this date will be returned
            // -------

            this.getCommits = function(options, cb) {
                options = options || {};
                var url = repoPath + '/commits';
                var params = [];

                if (options.sha) {
                    params.push('sha=' + encodeURIComponent(options.sha));
                }

                if (options.path) {
                    params.push('path=' + encodeURIComponent(options.path));
                }

                if (options.since) {
                    var since = options.since;

                    if (since.constructor === Date) {
                        since = since.toISOString();
                    }

                    params.push('since=' + encodeURIComponent(since));
                }

                if (options.until) {
                    var until = options.until;

                    if (until.constructor === Date) {
                        until = until.toISOString();
                    }

                    params.push('until=' + encodeURIComponent(until));
                }

                if (options.page) {
                    params.push('page=' + options.page);
                }

                if (options.perpage) {
                    params.push('per_page=' + options.perpage);
                }

                if (params.length > 0) {
                    url += '?' + params.join('&');
                }

                _request('GET', url, null, cb);
            };
        };

        // Gists API
        // =======

        Github.Gist = function(options) {
            var id = options.id;
            var gistPath = '/gists/' + id;

            // Read the gist
            // --------

            this.read = function(cb) {
                _request('GET', gistPath, null, cb);
            };

            // Create the gist
            // --------
            // {
            //  "description": "the description for this gist",
            //    "public": true,
            //    "files": {
            //      "file1.txt": {
            //        "content": "String file contents"
            //      }
            //    }
            // }

            this.create = function(options, cb) {
                _request('POST', '/gists', options, cb);
            };

            // Delete the gist
            // --------

            this.delete = function(cb) {
                _request('DELETE', gistPath, null, cb);
            };

            // Fork a gist
            // --------

            this.fork = function(cb) {
                _request('POST', gistPath + '/fork', null, cb);
            };

            // Update a gist with the new stuff
            // --------

            this.update = function(options, cb) {
                _request('PATCH', gistPath, options, cb);
            };

            // Star a gist
            // --------

            this.star = function(cb) {
                _request('PUT', gistPath + '/star', null, cb);
            };

            // Untar a gist
            // --------

            this.unstar = function(cb) {
                _request('DELETE', gistPath + '/star', null, cb);
            };

            // Check if a gist is starred
            // --------

            this.isStarred = function(cb) {
                _request('GET', gistPath + '/star', null, cb);
            };
        };

        // Issues API
        // ==========

        Github.Issue = function(options) {
            var path = '/repos/' + options.user + '/' + options.repo + '/issues';

            this.list = function(options, cb) {
                var query = [];

                for(var key in options) {
                    if (options.hasOwnProperty(key)) {
                        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(options[key]));
                    }
                }

                _requestAllPages(path + '?' + query.join('&'), cb);
            };

            this.comment = function(issue, comment, cb) {
                _request('POST', issue.comments_url, {
                    body: comment
                }, function(err, res) {
                    cb(err, res);
                });
            };
        };

        // Search API
        // ==========

        Github.Search = function(options) {
            var path = '/search/';
            var query = '?q=' + options.query;

            this.repositories = function(options, cb) {
                _request('GET', path + 'repositories' + query, options, cb);
            };

            this.code = function(options, cb) {
                _request('GET', path + 'code' + query, options, cb);
            };

            this.issues = function(options, cb) {
                _request('GET', path + 'issues' + query, options, cb);
            };

            this.users = function(options, cb) {
                _request('GET', path + 'users' + query, options, cb);
            };
        };

        return Github;
    };

    // Top Level API
    // -------

    Github.getIssues = function(user, repo) {
        return new Github.Issue({
            user: user, repo: repo
        });
    };

    Github.getRepo = function(user, repo) {
        if (!repo) {
            var fullname = user;

            return new Github.Repository({
                fullname: fullname
            });
        } else {
            return new Github.Repository({
                user: user, name: repo
            });
        }
    };

    Github.getUser = function() {
        return new Github.User();
    };

    Github.getGist = function(id) {
        return new Github.Gist({
            id: id
        });
    };

    Github.getSearch = function(query) {
        return new Github.Search({
            query: query
        });
    };

    return Github;
}));


text:
<?php

namespace AppBundle\EvenListener;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use AppBundle\Entity\Question;
use AppBundle\Entity\Video;
use AppBundle\FileUploader;

class FileUploadListener
{
    private $uploader;
    private $path_video;
    private $path_question;

    public function __construct(FileUploader $uploader, $path_question,  $path_video)
    {
        $this->uploader = $uploader;
        $this->path_question = $path_question;
        $this->path_video = $path_video;
    }

    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    public function preUpdate(PreUpdateEventArgs $args)
    {
        $entity = $args->getEntity();

        $this->uploadFile($entity);
    }

    private function uploadFile($entity)
    {
        $path = '';

        if ($entity instanceof Video) {
            $path = $this->path_video;
        }
        if ($entity instanceof Question) {
            $path = $this->path_question;
        }

        $file = $entity->getFile();

        if (!$file instanceof UploadedFile) {
            return;
        }

        $fileName = $this->uploader->upload($file,$path);
        $entity->setFile($fileName);
    }

    public function postRemove(LifecycleEventArgs $args)
    {
        $file = $args->getEntity()->getFile();
        $filePath = $this->uploader->getTargetDir().$file;

        if (file_exists($filePath)) {
            unlink($filePath);
        }
    }

}