text:
var nodejs = false;
if (typeof window === 'undefined') {
	nodejs = true;
	var Firebase = require('firebase');
	var twitterAPI = require('node-twitter-api');
	var keysAPI = require('./keys.js');
	var utilsAPI = require('./utils.js');
	var utils = new utilsAPI();
	var document = {};
}

function tweet(boidieName) {
	this.boidieName = boidieName;
	var myDataRef = new Firebase('https://blinding-fire-4882.firebaseio.com/');
	this.retweetsRef = myDataRef.child("retweets");
	this.actionRef = myDataRef.child("actions");

	this.keys = new keysAPI(boidieName);

	this.twitter = new twitterAPI({
		consumerKey: this.keys.twitterKey,
		consumerSecret: this.keys.twitterSecret,
		callback: 'http://local.twitter.com/'
	});
}

// Doesn't work
tweet.prototype.doGetToken = function() {
	this.twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
	    if (error) {
		console.log("Error getting OAuth request token : ");
		console.log(error);
	    } else {
		//store token and tokenSecret somewhere, you'll need them later; redirect user
		console.log(error);
		console.log(requestToken);
		console.log(requestTokenSecret);
		console.log(results);
		doSearch("fitness since:2014-08-08", handleSearchResults);
		this.twitter.getAccessToken(requestToken, requestTokenSecret, oauth_verifier, function(error, accessToken, accessTokenSecret, results) {
		    if (error) {
			console.log(error);
		    } else {
			keys.accessToken = requestToken;
			keys.accessTokenSecret = requestTokenSecret;
			//store accessToken and accessTokenSecret somewhere (associated to the user)
			//Step 4: Verify Credentials belongs here
			console.log(results);
			doSearch("fitness since:2014-08-08", handleSearchResults);
		    }
		});
	    }
	});
}

tweet.prototype.doPost = function(msg) {
	this.twitter.statuses("update", {
		status: msg
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Success!");
		    console.log(data);
		}
	    }
	);
}

tweet.prototype.doRetweet = function(id, callback) {
	this.twitter.statuses("retweet", {
		id: id
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("Retweet Error!!!"+id);
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Retweet Success!"+id);
		    console.log(data);
		}
	    }
	);
}
tweet.prototype.doFavorite = function(id, callback) {
	this.twitter.favorites("create", {
		id: id
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("favorites Error!!!"+id);
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("favorites Success!"+id);
		    console.log(data);
		}
	    }
	);
}
tweet.prototype.doFollow = function(id, callback) {
	this.twitter.friendships("create", {
		user_id: id
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("Follow Error!!!"+id);
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Follow Success!"+id);
		    console.log(data);
		}
	    }
	);
}

tweet.prototype.doUsers = function(id, callback) {
	var out = {success:0, msg:''};
	this.twitter.users("show", {
		screen_name: id
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("users Error!!!"+id);
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    //console.log("users Success!"+id);
		    //console.log(data);
		    out['success'] = 1;
		    out['data'] = data;
		}
		if(callback != undefined) {
			callback(out);
		}
	    }
	);
}

tweet.prototype.doSearch = function(term, callback) {
	var out = {success:0, msg:''};
	this.twitter.search({
		q: term,
		count: 100,
		lang: 'en',
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
			out['msg'] = error;
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    //console.log("Success!");
		    //console.log(data);
		    out['success'] = 1;
		    out['data'] = data;
		}
		callback(out);
	    }
	);
}

tweet.prototype.checkMessages = function(callback) {
	var out = {success:0, msg:''};
	this.twitter.direct_messages('direct_messages', {
		count: 100,
	    },
	    this.keys.accessToken,
	    this.keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
			out['msg'] = error;
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    //console.log("Success!");
		    //console.log(data);
		    out['success'] = 1;
		    out['data'] = data;
		}
		callback(out);
	    }
	);
}

tweet.prototype.handleSearchResults = function(result) {
	if(result['success']) {
		var dups = {}
		var alreadyRetweeted = false;
		var threshold = 20;
		if(false) {
			console.log(result['data']);
		}
		var statuses = result['data']['statuses'];
		for(var i in statuses) {
			var originalID = 0;
			var status = statuses[i];
			var crc = utils.crc32(status['text']);
			if(crc in dups) {
				console.log("Dup");
			} else {
				dups[crc] = 1;
			}
			console.log(status['id'] + ":" + status['text']);
			if(status['text'].substr(0, 2) == 'RT') {
				//console.log(status['retweeted_status']);
				if('retweeted_status' in status) {
					originalID = status['retweeted_status']['id_str'];
					console.log("...RETWEET of: "+ originalID);
				}
			}
			var popularity = status['favorite_count'] + status['retweet_count'];
			if(status['favorite_count'] > 0) {
				console.log('...Favorited!!!');
			}
			if(status['retweet_count'] > 0) {
				console.log('Retweeted '+status['retweet_count']+' times!!!');
				if(!alreadyRetweeted && popularity > threshold) {
					if(status['text'].toLowerCase().indexOf('nigga') != -1) {
						continue;
					}

					alreadyRetweeted = true;
					var id = status['id_str'];
					if(originalID) {
						id = originalID;
					}
					console.log("_________________Retweeting: "+id);
					tweetr.retweetsRef.child(id).set({ name: boidieName });

					tweetr.doRetweet(id);

				}
			}
		}
		console.log("Done. _________________");
	}
};

tweet.prototype.retweetPopular = function(result, threshold) {
	if(threshold == undefined) {
		threshold = 20;
	} else {
		console.log("Custom threshold: " + threshold);
	}
	if(result['success']) {
		var dups = {}
		var alreadyRetweeted = false;
		if(false) {
			console.log(result['data']);
		}
		var statuses = result['data']['statuses'];
		for(var i in statuses) {
			console.log("____________________________________________");
			var originalID = 0;
			var status = statuses[i];
			var crc = utils.crc32(status['text']);
			if(crc in dups) {
				console.log("Dup: " + status['text']);
				continue;
			} else {
				dups[crc] = 1;
			}
			console.log(status['id'] + ":" + status['text']);
			if(status['text'].substr(0, 2) == 'RT') {
				if('retweeted_status' in status) {
					originalID = status['retweeted_status']['id_str'];
					console.log("...RETWEET of: "+ originalID);
				}
			}
			var popularity = status['favorite_count'] + status['retweet_count'];
			if(status['favorite_count'] > 0) {
				console.log('...Favorited!!!');
			}
			if(status['retweet_count'] > 0) {
				console.log('Retweeted '+status['retweet_count']+' times!!!');
				if(!alreadyRetweeted && popularity > threshold) {
					if(status['text'].toLowerCase().indexOf('nigga') != -1) {
						continue;
					}
					alreadyRetweeted = true;
					var id = status['id_str'];
					if(originalID) {
						id = originalID;
					}
					console.log("_________________Retweeting: "+id);
					this.retweetsRef.child(id).set({ name: true });
					this.actionRef.push({ bid: '-JUPIlRMOl-KiCQXUbRb', type: "tweet", msg: status['text'], url: "halmrippetoe" });

					var bucket = Math.floor( Math.random() * 100);
					console.log("*** Bucket tweeter: " + bucket);

					if(bucket > 50) {
						this.doRetweet(id);
					} else if(bucket > 25) {
						this.doFollow(status['user']['id_str']);
					} else {
						this.doFavorite(id);
					}

				}
			}
		}
		console.log("Done. _________________");
	}
};

module.exports = tweet;


text:
using System;
using System.Drawing;
using System.Globalization;
using TQVaultAE.Data;
using TQVaultAE.Entities;
using TQVaultAE.GUI.Components;
using TQVaultAE.GUI.Models;
using TQVaultAE.Presentation;
using TQVaultAE.Presentation.Html;

namespace TQVaultAE.GUI
{
	internal partial class MainForm
	{

		/// <summary>
		/// Creates the form's internal panels
		/// </summary>
		private void CreatePanels()
		{
			this.CreatePlayerPanel();

			// Put the secondary vault list on top of the player list drop down
			// since only one can be shown at a time.
			this.secondaryVaultListComboBox.Location = this.characterComboBox.Location;
			this.secondaryVaultListComboBox.Enabled = false;
			this.secondaryVaultListComboBox.Visible = false;

			this.GetPlayerList();

			// Added support for custom map character list
			if (TQData.IsCustom)
			{
				this.customMapText.Visible = true;
				this.customMapText.Text = string.Format(CultureInfo.CurrentCulture, Resources.MainFormCustomMapLabel, TQData.MapName);
			}
			else
			{
				this.customMapText.Visible = false;
			}

			this.CreateVaultPanel(12); // # of bags in a vault.  This number is also buried in the CreateVault() function
			this.CreateSecondaryVaultPanel(12); // # of bags in a vault.  This number is also buried in the CreateVault() function
			this.secondaryVaultPanel.Enabled = false;
			this.secondaryVaultPanel.Visible = false;
			this.lastBag = -1;

			int textPanelOffset = Convert.ToInt32(18.0F * UIService.UI.Scale);
			this.itemTextPanel.Size = new Size(this.vaultPanel.Width, Convert.ToInt32(22.0F * UIService.UI.Scale));
			this.itemTextPanel.Location = new Point(this.vaultPanel.Location.X, this.ClientSize.Height - (this.itemTextPanel.Size.Height + textPanelOffset));
			this.itemText.Width = this.itemTextPanel.Width - Convert.ToInt32(4.0F * UIService.UI.Scale);
			this.GetVaultList(false);

			// Now we always create the stash panel since everyone can have equipment
			this.CreateStashPanel();
			this.stashPanel.CurrentBag = 0; // set to default to the equipment panel
		}

		/// <summary>
		/// Used to toggle the upper display between the player panel or another vault.
		/// </summary>
		private void UpdateTopPanel()
		{
			if (this.showSecondaryVault)
			{
				this.playerPanel.Enabled = false;
				this.playerPanel.Visible = false;
				this.playerPanel.SackPanel.ClearSelectedItems();
				this.playerPanel.BagSackPanel.ClearSelectedItems();
				this.stashPanel.Visible = false;
				this.stashPanel.Enabled = false;
				this.secondaryVaultPanel.Enabled = true;
				this.secondaryVaultPanel.Visible = true;
				this.panelSelectButton.Text = Resources.MainFormBtnShowPlayer;
				this.characterComboBox.Enabled = false;
				this.characterComboBox.Visible = false;
				this.secondaryVaultListComboBox.Enabled = true;
				this.secondaryVaultListComboBox.Visible = true;
				this.characterLabel.Text = Resources.MainForm2ndVault;
				this.lastStash = this.stashPanel.Stash;
				this.lastBag = this.stashPanel.CurrentBag;
				this.stashPanel.Player = null;
				this.stashPanel.Stash = null;
				if (this.stashPanel.CurrentBag != 1)
				{
					this.stashPanel.SackPanel.ClearSelectedItems();
					this.stashPanel.CurrentBag = 1;
				}

				this.vaultPanel.SackPanel.SecondaryVaultShown = true;
				this.stashPanel.SackPanel.SecondaryVaultShown = true;

				this.secondaryVaultPanel.SackPanel.IsSecondaryVault = true;
				this.GetSecondaryVaultList();
			}
			else
			{
				this.stashPanel.Visible = true;
				this.stashPanel.Enabled = true;
				this.secondaryVaultPanel.Enabled = false;
				this.secondaryVaultPanel.Visible = false;
				this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
				this.playerPanel.Enabled = true;
				this.playerPanel.Visible = true;
				this.panelSelectButton.Text = Resources.MainFormBtnPanelSelect;
				this.characterComboBox.Enabled = true;
				this.characterComboBox.Visible = true;
				this.secondaryVaultListComboBox.Enabled = false;
				this.secondaryVaultListComboBox.Visible = false;
				this.characterLabel.Text = Resources.MainFormLabel1;
				this.stashPanel.Player = this.playerPanel.Player;
				if (this.lastStash != null)
				{
					this.stashPanel.Stash = this.lastStash;
					if (this.lastBag != -1 && this.lastBag != this.stashPanel.CurrentBag)
					{
						this.stashPanel.CurrentBag = this.lastBag;
						this.stashPanel.SackPanel.ClearSelectedItems();
					}
				}

				this.vaultPanel.SackPanel.SecondaryVaultShown = false;
				this.stashPanel.SackPanel.SecondaryVaultShown = false;
			}
		}

		/// <summary>
		/// Callback for highlighting a new item.
		/// Updates the text box on the main form.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">SackPanelEventArgs data</param>
		private void NewItemHighlightedCallback(object sender, SackPanelEventArgs e)
		{
			Item item = e.Item;
			SackCollection sack = e.Sack;
			SackPanel sackPanel = (SackPanel)sender;
			if (item == null)
			{
				// Only do something if this sack is the "owner" of the current item highlighted.
				if (sack == this.lastSackHighlighted)
				{
					this.itemText.Text = string.Empty;

					// hide the tooltip
					this.tooltipText = null;
					this.tooltip.ChangeText(this.tooltipText);
				}
			}
			else
			{
				var result = ItemHtmlHelper.NewItemHighlightedTooltip(item);
				this.itemText.ForeColor = result.ForeColor;
				this.itemText.Text = result.FriendlyName;
				this.tooltipText = result.TooltipText;
				this.tooltip.ChangeText(this.tooltipText);
			}

			this.lastSackHighlighted = sack;
			this.lastSackPanelHighlighted = sackPanel;
		}

		/// <summary>
		/// Used to clear out selections on other panels if the user tries to select across multiple panels.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">SackPanelEventArgs data</param>
		private void ItemSelectedCallback(object sender, SackPanelEventArgs e)
		{
			SackPanel sackPanel = (SackPanel)sender;

			if (this.playerPanel.SackPanel == sackPanel)
			{
				this.playerPanel.BagSackPanel.ClearSelectedItems();
				this.vaultPanel.SackPanel.ClearSelectedItems();
				this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
				this.stashPanel.SackPanel.ClearSelectedItems();
			}
			else if (this.playerPanel.BagSackPanel == sackPanel)
			{
				this.playerPanel.SackPanel.ClearSelectedItems();
				this.vaultPanel.SackPanel.ClearSelectedItems();
				this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
				this.stashPanel.SackPanel.ClearSelectedItems();
			}
			else if (this.vaultPanel.SackPanel == sackPanel)
			{
				this.playerPanel.SackPanel.ClearSelectedItems();
				this.playerPanel.BagSackPanel.ClearSelectedItems();
				this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
				this.stashPanel.SackPanel.ClearSelectedItems();
			}
			else if (this.secondaryVaultPanel.SackPanel == sackPanel)
			{
				this.playerPanel.SackPanel.ClearSelectedItems();
				this.playerPanel.BagSackPanel.ClearSelectedItems();
				this.vaultPanel.SackPanel.ClearSelectedItems();
				this.stashPanel.SackPanel.ClearSelectedItems();
			}
			else if (this.stashPanel.SackPanel == sackPanel)
			{
				this.playerPanel.SackPanel.ClearSelectedItems();
				this.playerPanel.BagSackPanel.ClearSelectedItems();
				this.vaultPanel.SackPanel.ClearSelectedItems();
				this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
			}
		}

		/// <summary>
		/// Used to clear the selection when a bag button is clicked.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">SackPanelEventArgs data</param>
		private void ClearAllItemsSelectedCallback(object sender, SackPanelEventArgs e)
		{
			this.playerPanel.SackPanel.ClearSelectedItems();
			this.playerPanel.BagSackPanel.ClearSelectedItems();
			this.vaultPanel.SackPanel.ClearSelectedItems();
			this.secondaryVaultPanel.SackPanel.ClearSelectedItems();
			this.stashPanel.SackPanel.ClearSelectedItems();
		}

		/// <summary>
		/// Callback for activating the search text box.
		/// Used when a hot key is pressed.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">SackPanelEventArgs data</param>
		private void ActivateSearchCallback(object sender, SackPanelEventArgs e)
		{
			this.OpenSearchDialog();
		}

		/// <summary>
		/// Used for sending items between sacks or panels.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">SackPanelEventArgs data</param>
		private void AutoMoveItemCallback(object sender, SackPanelEventArgs e)
		{
			SackPanel sackPanel = (SackPanel)sender;

			// Make sure we have to move something.
			if (this.dragInfo.IsAutoMoveActive)
			{
				SackCollection oldSack = null;
				VaultPanel destinationPlayerPanel = null;
				int sackNumber = 0;

				SackPanel destinationSackPanel = null;
				if (this.dragInfo.AutoMove < AutoMoveLocation.Vault)
				{
					// This is a sack to sack move on the same panel.
					destinationSackPanel = sackPanel;
					switch (sackPanel.SackType)
					{
						case SackType.Vault:
							{
								if (sackPanel.IsSecondaryVault)
								{
									destinationPlayerPanel = this.secondaryVaultPanel;
								}
								else
								{
									destinationPlayerPanel = this.vaultPanel;
								}

								break;
							}

						default:
							{
								destinationPlayerPanel = this.playerPanel;
								break;
							}
					}

					sackNumber = (int)this.dragInfo.AutoMove;
				}
				else if (this.dragInfo.AutoMove == AutoMoveLocation.Vault)
				{
					// Vault
					destinationPlayerPanel = this.vaultPanel;
					destinationSackPanel = destinationPlayerPanel.SackPanel;
					sackNumber = destinationPlayerPanel.CurrentBag;
				}
				else if (this.dragInfo.AutoMove == AutoMoveLocation.Player)
				{
					// Player
					destinationPlayerPanel = this.playerPanel;
					destinationSackPanel = ((PlayerPanel)destinationPlayerPanel).SackPanel;

					// Main Player panel
					sackNumber = 0;
				}
				else if (this.dragInfo.AutoMove == AutoMoveLocation.SecondaryVault)
				{
					// Secondary Vault
					destinationPlayerPanel = this.secondaryVaultPanel;
					destinationSackPanel = destinationPlayerPanel.SackPanel;
					sackNumber = destinationPlayerPanel.CurrentBag;
				}

				// Special Case for moving to stash.
				if (this.dragInfo.AutoMove == AutoMoveLocation.Stash)
				{
					// Check if we are moving to the player's stash
					if (this.stashPanel.CurrentBag == 2 && this.stashPanel.Player == null)
					{
						// We have nowhere to send the item so cancel the move.
						this.dragInfo.Cancel();
						return;
					}

					// Check for the equipment panel
					if (this.stashPanel.CurrentBag == 0)
					{
						// Equipment Panel is active so switch to the transfer stash.
						this.stashPanel.CurrentBag = 1;
					}

					// Check the transfer stash
					if (this.stashPanel.TransferStash == null && this.stashPanel.CurrentBag == 1)
					{
						// We have nowhere to send the item so cancel the move.
						this.dragInfo.Cancel();
						return;
					}

					// Check the relic vault stash
					if (this.stashPanel.RelicVaultStash == null && this.stashPanel.CurrentBag == 3)
					{
						// We have nowhere to send the item so cancel the move.
						this.dragInfo.Cancel();
						return;
					}

					// See if we have an open space to put the item.
					Point location = this.stashPanel.SackPanel.FindOpenCells(this.dragInfo.Item.Width, this.dragInfo.Item.Height);

					// We have no space in the sack so we cancel.
					if (location.X == -1)
					{
						this.dragInfo.Cancel();
					}
					else
					{
						Item dragItem = this.dragInfo.Item;

						if (!this.stashPanel.SackPanel.IsItemValidForPlacement(dragItem))
						{
							this.dragInfo.Cancel();
							return;
						}

						// Use the same method as if we used to mouse to pickup and place the item.
						this.dragInfo.MarkPlaced(-1);
						dragItem.PositionX = location.X;
						dragItem.PositionY = location.Y;
						this.stashPanel.SackPanel.Sack.AddItem(dragItem);

						this.lastSackPanelHighlighted.Invalidate();
						this.stashPanel.Refresh();
					}
				}
				else
				{
					// The stash is not involved.
					if (destinationPlayerPanel.Player == null)
					{
						// We have nowhere to send the item so cancel the move.
						this.dragInfo.Cancel();
						return;
					}

					// Save the current sack.
					oldSack = destinationSackPanel.Sack;

					// Find the destination sack.
					destinationSackPanel.Sack = destinationPlayerPanel.Player.GetSack(sackNumber);

					// See if we have an open space to put the item.
					Point location = destinationSackPanel.FindOpenCells(this.dragInfo.Item.Width, this.dragInfo.Item.Height);

					// CurrentBag only returns the values for the bag panels and is zero based.  Main sack is not included.
					int destination = destinationPlayerPanel.CurrentBag;

					// We need to accout for the player panel offsets.
					if (sackPanel.SackType == SackType.Sack)
					{
						destination++;
					}
					else if (sackPanel.SackType == SackType.Player)
					{
						destination = 0;
					}

					// We either have no space or are sending the item to the same sack so we cancel.
					if (location.X == -1 || (int)this.dragInfo.AutoMove == destination)
					{
						destinationSackPanel.Sack = oldSack;
						this.dragInfo.Cancel();
					}
					else
					{
						Item dragItem = this.dragInfo.Item;

						// Use the same method as if we used to mouse to pickup and place the item.
						this.dragInfo.MarkPlaced(-1);
						dragItem.PositionX = location.X;
						dragItem.PositionY = location.Y;
						destinationSackPanel.Sack.AddItem(dragItem);

						// Set it back to the original sack so the display does not change.
						destinationSackPanel.Sack = oldSack;
						sackPanel.Invalidate();
						destinationPlayerPanel.Refresh();
					}
				}
			}
		}

		/// <summary>
		/// Handler for clicking the panel selection button.
		/// Switches between the player panel and seconday vault panel.
		/// </summary>
		/// <param name="sender">sender object</param>
		/// <param name="e">EventArgs strucure</param>
		private void PanelSelectButtonClick(object sender, EventArgs e)
		{
			this.showSecondaryVault = !this.showSecondaryVault;
			this.UpdateTopPanel();
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace JamesMoss\Flywheel;

/**
 * Query
 *
 * Builds an executes a query whichs searches and sorts documents from a
 * repository.
 */
class Predicate
{
    const LOGICAL_AND = 'and';
    const LOGICAL_OR = 'or';

    protected $predicates = array();
    protected $operators = array(
        '>', '>=', '<', '<=', '==', '===', '!=', '!==',
    );

    public function getAll()
    {
        return $this->predicates;
    }

    public function where($field, $operator = null, $value = null)
    {
        return $this->andWhere($field, $operator, $value);
    }

    public function andWhere($field, $operator = null, $value = null)
    {
        $this->addPredicate(self::LOGICAL_AND, $field, $operator, $value);

        return $this;
    }

    public function orWhere($field, $operator = null, $value = null)
    {
        $this->addPredicate(self::LOGICAL_OR, $field, $operator, $value);

        return $this;
    }

    protected function addPredicate($type, $field, $operator = null, $value = null)
    {
        if (!$this->predicates) {
            $type = false;
        }

        if ($field instanceof \Closure) {
            $sub = new self();
            call_user_func($field, $sub);

            $this->predicates[] = array($type, $sub->getAll());

            return $this;
        }

        $field = trim($field);

        if ($field == '') {
            throw new \InvalidArgumentException('Field name cannot be empty.');
        }

        if (!in_array($operator, $this->operators)) {
            throw new \InvalidArgumentException('Unknown operator `'.$operator.'`.');
        }

        $this->predicates[] = array($type, $field, $operator, $value);

        return $this;
    }
}


text:
<?php

/**
 * Convert validator abstract
 *
 * @category   Varien
 * @package    Varien_Convert
 * @author      Magento Core Team <core@magentocommerce.com>
 */
abstract class Varien_Convert_Validator_Abstract extends Varien_Convert_Container_Abstract implements Varien_Convert_Validator_Interface
{

}


text:
<?xml version="1.0" ?>
<library  version="2.0" name="sap.ui.suite">
  <module name="sap/ui/suite/QuickViewUtils.js" size="6327" compressedSize="3993">
    <description>Provides</description>
    <requires>
      <module name="jquery.sap.global.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/TaskCircle.js" size="3332" compressedSize="1105">
    <description>Provides control sap.ui.suite.TaskCircle.</description>
    <requires>
      <module name="jquery.sap.global.js"/>
      <module name="sap/ui/core/Control.js"/>
      <module name="sap/ui/core/EnabledPropagator.js"/>
      <module name="sap/ui/suite/library.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/TaskCircleRenderer.js" size="3571" compressedSize="1777">
    <description>provides default renderer for sap.ui.suite.TaskCircle</description>
    <requires>
      <module name="jquery.sap.global.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/VerticalProgressIndicator.js" size="4424" compressedSize="1310">
    <description>Provides control sap.ui.suite.VerticalProgressIndicator.</description>
    <requires>
      <module name="jquery.sap.global.js"/>
      <module name="sap/ui/core/Control.js"/>
      <module name="sap/ui/core/EnabledPropagator.js"/>
      <module name="sap/ui/suite/library.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/VerticalProgressIndicatorRenderer.js" size="2553" compressedSize="1200">
    <description>provides default renderer for sap.ui.suite.VerticalProgressIndicator</description>
    <requires>
      <module name="jquery.sap.global.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/library.js" size="1387" compressedSize="618">
    <description>Initialization Code and shared classes of library sap.ui.suite.</description>
    <requires>
      <module name="jquery.sap.global.js"/>
      <module name="sap/ui/core/library.js"/>
    </requires>
  </module>
  <module name="sap/ui/suite/manifest.json" size="736">
  </module>
</library>


text:
from django.template.defaultfilters import slice_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe

from ..utils import setup

class SliceTests(SimpleTestCase):

    @setup({'slice01': '{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'})
    def test_slice01(self):
        output = self.engine.render_to_string('slice01', {'a': 'a&b', 'b': mark_safe('a&b')})
        self.assertEqual(output, '&b &b')

    @setup({'slice02': '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}{% endautoescape %}'})
    def test_slice02(self):
        output = self.engine.render_to_string('slice02', {'a': 'a&b', 'b': mark_safe('a&b')})
        self.assertEqual(output, '&b &b')

class FunctionTests(SimpleTestCase):

    def test_zero_length(self):
        self.assertEqual(slice_filter('abcdefg', '0'), '')

    def test_index(self):
        self.assertEqual(slice_filter('abcdefg', '1'), 'a')

    def test_negative_index(self):
        self.assertEqual(slice_filter('abcdefg', '-1'), 'abcdef')

    def test_range(self):
        self.assertEqual(slice_filter('abcdefg', '1:2'), 'b')

    def test_range_multiple(self):
        self.assertEqual(slice_filter('abcdefg', '1:3'), 'bc')

    def test_range_step(self):
        self.assertEqual(slice_filter('abcdefg', '0::2'), 'aceg')

    def test_fail_silently(self):
        obj = object()
        self.assertEqual(slice_filter(obj, '0::2'), obj)


text:
//
//  TWTRScribeEvent.h
//
//  Created by Mustafa Furniturewala on 7/21/14.
//  Copyright (c) 2014 Twitter. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "TFSScribe.h"
#import "TWTRScribeClientEventNamespace.h"
#import "TWTRScribeItem.h"

NS_ASSUME_NONNULL_BEGIN

FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionClient;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionPage;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionSectionTweet;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionSectionQuoteTweet;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionSectionVideo;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionSectionGallery;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionSectionAuth;

FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionComponent;
FOUNDATION_EXPORT NSString *const TWTRScribeEmptyKey;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionTypeLoad;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionTypeImpression;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionTypeShare;
FOUNDATION_EXPORT NSString *const TWTRScribeEventImpressionAction;
FOUNDATION_EXPORT NSString *const TWTRScribeEventActionClick;
FOUNDATION_EXPORT NSString *const TWTRScribeEventActionFilter;

FOUNDATION_EXPORT NSString *const TWTRScribeEventUniquesClient;
FOUNDATION_EXPORT NSString *const TWTRScribeEventUniquesPageTweetViews;
FOUNDATION_EXPORT NSString *const TWTRScribeEventUniquesPageLogin;
FOUNDATION_EXPORT NSString *const TWTRScribeEventUniquesAction;

FOUNDATION_EXPORT NSString *const TWTRScribeActionLike;
FOUNDATION_EXPORT NSString *const TWTRScribeActionUnlike;
FOUNDATION_EXPORT NSString *const TWTRScribeActionStart;
FOUNDATION_EXPORT NSString *const TWTRScribeActionSuccess;
FOUNDATION_EXPORT NSString *const TWTRScribeActionCancelled;
FOUNDATION_EXPORT NSString *const TWTRScribeActionFailure;

/**
 *  Possible values for which category to scribe events to.
 */
typedef NS_ENUM(NSUInteger, TWTRScribeEventCategory) {
    /**
     *  Used for logging impressions and feature usage for Tweet views.
     */
    TWTRScribeEventCategoryImpressions = 1,
    /**
     *  Used only for logging number of uniques using the Kit. There are no browsing history logged,
     *  so we can keep the events longer to calculate monthly actives.
     */
    TWTRScribeEventCategoryUniques
};

@interface TWTRScribeEvent : NSObject <TFSScribeEventParameters>

@property (nonatomic, copy, readonly, nullable) NSString *userID;
@property (nonatomic, copy, readonly, nullable) NSString *tweetID;
@property (nonatomic, copy, readonly) NSString *eventInfo;
@property (nonatomic, assign, readonly) TWTRScribeEventCategory category;
@property (nonatomic, copy, readonly) TWTRScribeClientEventNamespace *eventNamespace;
@property (nonatomic, copy, readonly) NSArray<TWTRScribeItem *> *items;

- (instancetype)init __unavailable;
- (instancetype)initWithUserID:(nullable NSString *)userID tweetID:(nullable NSString *)tweetID category:(TWTRScribeEventCategory)category eventNamespace:(TWTRScribeClientEventNamespace *)eventNamespace items:(nullable NSArray<TWTRScribeItem *> *)items;

- (instancetype)initWithUserID:(nullable NSString *)userID eventInfo:(nullable NSString *)eventInfo category:(TWTRScribeEventCategory)category eventNamespace:(TWTRScribeClientEventNamespace *)eventNamespace items:(nullable NSArray<TWTRScribeItem *> *)items;

#pragma mark - TFSScribeEventParameters

- (NSDictionary *)dictionaryRepresentation;
- (NSString *)userID;
- (NSData *)data;

@end

/**
 *  A Scribe event for logging errors to the Twitter backend
 */
@interface TWTRErrorScribeEvent : TWTRScribeEvent

@property (nonatomic, readonly) NSError *error;
@property (nonatomic, copy, readonly) NSString *errorMessage;

/**
 *  Initializer
 *
 *  @param error        (optional) An NSError object representing this error case.
 *  @param errorMessage (required) An error message describing the error situation.
 *
 *  @return A fully initialized scribe object ready to enqueue or nil if any of
 *          the required parameters are missing.
 */
- (instancetype)initWithError:(nullable NSError *)error message:(NSString *)errorMessage;

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.flink.table.dataview

import java.util
import java.lang.{Iterable => JIterable}

import org.apache.flink.api.common.state.MapState
import org.apache.flink.table.api.dataview.MapView

/**
  * [[MapView]] use state backend.
  *
  * @param state map state
  * @tparam K key type
  * @tparam V value type
  */
class StateMapView[K, V](state: MapState[K, V]) extends MapView[K, V] {

  override def get(key: K): V = state.get(key)

  override def put(key: K, value: V): Unit = state.put(key, value)

  override def putAll(map: util.Map[K, V]): Unit = state.putAll(map)

  override def remove(key: K): Unit = state.remove(key)

  override def contains(key: K): Boolean = state.contains(key)

  override def entries: JIterable[util.Map.Entry[K, V]] = state.entries()

  override def keys: JIterable[K] = state.keys()

  override def values: JIterable[V] = state.values()

  override def iterator: util.Iterator[util.Map.Entry[K, V]] = state.iterator()

  override def isEmpty(): Boolean = state.isEmpty

  override def clear(): Unit = state.clear()
}


text:
package com.amazonaws.services.s3.model.analytics;

import java.io.Serializable;

/**
 * The configuration and any analysis for the analytics filter.
 */
public class AnalyticsConfiguration implements Serializable {
    private String id;
    private AnalyticsFilter filter;
    private StorageClassAnalysis storageClassAnalysis;

    /**
     * Returns the identifier used to represent an analytics configuration.
     */
    public String getId() {
        return id;
    }

    /**
     * Sets the identifier used to represent an analytics configuration.
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * Sets the identifier used to represent an analytics configuration
     * and returns the {@link AnalyticsConfiguration} object
     * for method chaining.
     */
    public AnalyticsConfiguration withId(String id) {
        setId(id);
        return this;
    }

    /**
     * Returns the filter used to describe a set of objects for analysis.
     */
    public AnalyticsFilter getFilter() {
        return filter;
    }

    /**
     * Sets the filter used to describe a set of objects for analysis.
     * If no filter is provided, all objects will be considered in any analysis.
     */
    public void setFilter(AnalyticsFilter filter) {
        this.filter = filter;
    }

    /**
     * Sets the filter used to describe a set of objects for analysis.
     * If no filter is provided, all objects will be considered in any analysis.
     *
     * The {@link AnalyticsConfiguration} object is returned for method chaining.
     */
    public AnalyticsConfiguration withFilter(AnalyticsFilter filter) {
        setFilter(filter);
        return this;
    }

    /**
     * Returns the {@link StorageClassAnalysis} object.
     * If present, it indicates that data related to access patterns will be collected
     * and made available to analyze the tradeoffs between different storage classes.
     */
    public StorageClassAnalysis getStorageClassAnalysis() {
        return storageClassAnalysis;
    }

    /**
     * Sets the StorageClassAnalysis object which indicates that data related to access patterns
     * will be collected and made available to analyze the tradeoffs between different storage classes.
     */
    public void setStorageClassAnalysis(StorageClassAnalysis storageClassAnalysis) {
        this.storageClassAnalysis = storageClassAnalysis;
    }

    /**
     * Sets the StorageClassAnalysis object which indicates that data related to access patterns
     * will be collected and made available to analyze the tradeoffs between different storage classes.
     *
     * The {@link AnalyticsConfiguration} object is returned for method chaining.
     */
    public AnalyticsConfiguration withStorageClassAnalysis(StorageClassAnalysis storageClassAnalysis) {
        setStorageClassAnalysis(storageClassAnalysis);
        return this;
    }
}


text:
# markdown-it <!-- omit in toc -->

[![CI](https://github.com/markdown-it/markdown-it/workflows/CI/badge.svg)](https://github.com/markdown-it/markdown-it/actions)
[![NPM version](https://img.shields.io/npm/v/markdown-it.svg?style=flat)](https://www.npmjs.org/package/markdown-it)
[![Coverage Status](https://coveralls.io/repos/markdown-it/markdown-it/badge.svg?branch=master&service=github)](https://coveralls.io/github/markdown-it/markdown-it?branch=master)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/markdown-it/markdown-it)

> Markdown parser done right. Fast and easy to extend.

__[Live demo](https://markdown-it.github.io)__

- Follows the __[CommonMark spec](http://spec.commonmark.org/)__ + adds syntax extensions & sugar (URL autolinking, typographer).
- Configurable syntax! You can add new rules and even replace existing ones.
- High speed.
- [Safe](https://github.com/markdown-it/markdown-it/tree/master/docs/security.md) by default.
- Community-written __[plugins](https://www.npmjs.org/browse/keyword/markdown-it-plugin)__ and [other packages](https://www.npmjs.org/browse/keyword/markdown-it) on npm.

__Table of content__

- [Install](#install)
- [Usage examples](#usage-examples)
  - [Simple](#simple)
  - [Init with presets and options](#init-with-presets-and-options)
  - [Plugins load](#plugins-load)
  - [Syntax highlighting](#syntax-highlighting)
  - [Linkify](#linkify)
- [API](#api)
- [Syntax extensions](#syntax-extensions)
  - [Manage rules](#manage-rules)
- [Benchmark](#benchmark)
- [markdown-it for enterprise](#markdown-it-for-enterprise)
- [Authors](#authors)
- [References / Thanks](#references--thanks)

## Install

**node.js**:

```bash
npm install markdown-it --save
```

**browser (CDN):**

- [jsDeliver CDN](http://www.jsdelivr.com/#!markdown-it "jsDelivr CDN")
- [cdnjs.com CDN](https://cdnjs.com/libraries/markdown-it "cdnjs.com")

## Usage examples

See also:

- __[API documentation](https://markdown-it.github.io/markdown-it/)__ - for more
  info and examples.
- [Development info](https://github.com/markdown-it/markdown-it/tree/master/docs) -
  for plugins writers.

### Simple

```js
// node.js, "classic" way:
var MarkdownIt = require('markdown-it'),
    md = new MarkdownIt();
var result = md.render('# markdown-it rulezz!');

// node.js, the same, but with sugar:
var md = require('markdown-it')();
var result = md.render('# markdown-it rulezz!');

// browser without AMD, added to "window" on script load
// Note, there is no dash in "markdownit".
var md = window.markdownit();
var result = md.render('# markdown-it rulezz!');
```

Single line rendering, without paragraph wrap:

```js
var md = require('markdown-it')();
var result = md.renderInline('__markdown-it__ rulezz!');
```

### Init with presets and options

(*) presets define combinations of active rules and options. Can be
`"commonmark"`, `"zero"` or `"default"` (if skipped). See
[API docs](https://markdown-it.github.io/markdown-it/#MarkdownIt.new) for more details.

```js
// commonmark mode
var md = require('markdown-it')('commonmark');

// default mode
var md = require('markdown-it')();

// enable everything
var md = require('markdown-it')({
  html: true,
  linkify: true,
  typographer: true
});

// full options list (defaults)
var md = require('markdown-it')({
  html:         false,        // Enable HTML tags in source
  xhtmlOut:     false,        // Use '/' to close single tags (<br />).
                              // This is only for full CommonMark compatibility.
  breaks:       false,        // Convert '\n' in paragraphs into <br>
  langPrefix:   'language-',  // CSS language prefix for fenced blocks. Can be
                              // useful for external highlighters.
  linkify:      false,        // Autoconvert URL-like text to links

  // Enable some language-neutral replacement + quotes beautification
  // For the full list of replacements, see https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/replacements.js
  typographer:  false,

  // Double + single quotes replacement pairs, when typographer enabled,
  // and smartquotes on. Could be either a String or an Array.
  //
  // For example, you can use '«»""' for Russian, '""''' for German,
  // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
  quotes: '""''',

  // Highlighter function. Should return escaped HTML,
  // or '' if the source string is not changed and should be escaped externally.
  // If result starts with <pre... internal wrapper is skipped.
  highlight: function (/*str, lang*/) { return ''; }
});
```

### Plugins load

```js
var md = require('markdown-it')()
            .use(plugin1)
            .use(plugin2, opts, ...)
            .use(plugin3);
```

### Syntax highlighting

Apply syntax highlighting to fenced code blocks with the `highlight` option:

```js
var hljs = require('highlight.js'); // https://highlightjs.org

// Actual default values
var md = require('markdown-it')({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value;
      } catch (__) {}
    }

    return ''; // use external default escaping
  }
});
```

Or with full wrapper override (if you need assign class to `<pre>`):

```js
var hljs = require('highlight.js'); // https://highlightjs.org

// Actual default values
var md = require('markdown-it')({
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return '<pre class="hljs"><code>' +
               hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
               '</code></pre>';
      } catch (__) {}
    }

    return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>';
  }
});
```

### Linkify

`linkify: true` uses [linkify-it](https://github.com/markdown-it/linkify-it). To
configure linkify-it, access the linkify instance through `md.linkify`:

```js
md.linkify.set({ fuzzyEmail: false });  // disables converting email to link
```

## API

__[API documentation](https://markdown-it.github.io/markdown-it/)__

If you are going to write plugins, please take a look at
[Development info](https://github.com/markdown-it/markdown-it/tree/master/docs).

## Syntax extensions

Embedded (enabled by default):

- [Tables](https://help.github.com/articles/organizing-information-with-tables/) (GFM)
- [Strikethrough](https://help.github.com/articles/basic-writing-and-formatting-syntax/#styling-text) (GFM)

Via plugins:

- [subscript](https://github.com/markdown-it/markdown-it-sub)
- [superscript](https://github.com/markdown-it/markdown-it-sup)
- [footnote](https://github.com/markdown-it/markdown-it-footnote)
- [definition list](https://github.com/markdown-it/markdown-it-deflist)
- [abbreviation](https://github.com/markdown-it/markdown-it-abbr)
- [emoji](https://github.com/markdown-it/markdown-it-emoji)
- [custom container](https://github.com/markdown-it/markdown-it-container)
- [insert](https://github.com/markdown-it/markdown-it-ins)
- [mark](https://github.com/markdown-it/markdown-it-mark)
- ... and [others](https://www.npmjs.org/browse/keyword/markdown-it-plugin)

### Manage rules

By default all rules are enabled, but can be restricted by options. On plugin
load all its rules are enabled automatically.

```js
// Activate/deactivate rules, with currying
var md = require('markdown-it')()
            .disable([ 'link', 'image' ])
            .enable([ 'link' ])
            .enable('image');

// Enable everything
md = require('markdown-it')({
  html: true,
  linkify: true,
  typographer: true,
});
```

You can find all rules in sources:

- [`parser_core.js`](lib/parser_core.js)
- [`parser_block.js`](lib/parser_block.js)
- [`parser_inline.js`](lib/parser_inline.js)

## Benchmark

Here is the result of readme parse at MB Pro Retina 2013 (2.4 GHz):

```bash
make benchmark-deps
benchmark/benchmark.js readme

Selected samples: (1 of 28)
 > README

Sample: README.md (7774 bytes)
 > commonmark-reference x 1,222 ops/sec ±0.96% (97 runs sampled)
 > current x 743 ops/sec ±0.84% (97 runs sampled)
 > current-commonmark x 1,568 ops/sec ±0.84% (98 runs sampled)
 > marked x 1,587 ops/sec ±4.31% (93 runs sampled)
```

__Note.__ CommonMark version runs with [simplified link normalizers](https://github.com/markdown-it/markdown-it/blob/master/benchmark/implementations/current-commonmark/index.js)
for more "honest" compare. Difference is ≈1.5×.

As you can see, `markdown-it` doesn't pay with speed for its flexibility.
Slowdown of "full" version caused by additional features not available in
other implementations.

## markdown-it for enterprise

Available as part of the Tidelift Subscription.

The maintainers of `markdown-it` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-markdown-it?utm_source=npm-markdown-it&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

## Authors

- Alex Kocharin [github/rlidwka](https://github.com/rlidwka)
- Vitaly Puzrin [github/puzrin](https://github.com/puzrin)

_markdown-it_ is the result of the decision of the authors who contributed to
99% of the _Remarkable_ code to move to a project with the same authorship but
new leadership (Vitaly and Alex). It's not a fork.

## References / Thanks

Big thanks to [John MacFarlane](https://github.com/jgm) for his work on the
CommonMark spec and reference implementations. His work saved us a lot of time
during this project's development.

**Related Links:**

- https://github.com/jgm/CommonMark - reference CommonMark implementations in C & JS,
  also contains latest spec & online demo.
- http://talk.commonmark.org - CommonMark forum, good place to collaborate
  developers' efforts.

**Ports**

- [motion-markdown-it](https://github.com/digitalmoksha/motion-markdown-it) - Ruby/RubyMotion
- [markdown-it-py](https://github.com/ExecutableBookProject/markdown-it-py)- Python


text:
using System.Linq;
using System.Threading.Tasks;
using AutoFixture.Idioms;
using AutoFixture.Xunit2;
using FluentAssertions;
using Tranquire;
using Tranquire.Tests;
using Xunit;
using NUnitF = NUnit.Framework;

namespace Tranquire.NUnit.Tests
{
    [Trait("Category", "")]
    public class VerifiesExtensionsTests
    {
        [Theory, DomainAutoData]
        public void Sut_VerifyGuardClause(GuardClauseAssertion assertion)
        {
            assertion.Verify(typeof(VerifiesExtensions));
        }

        private static IQuestion<T> Question<T>(T value) => Questions.Create("Question", _ => value);
        private static IQuestion<Task<T>> QuestionAsync<T>(T value) => Question(Task.FromResult(value));

        #region Synchronous
        [Theory, DomainAutoData]
        public void Then_WithConstraints_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected)
        {
            // arrange
            var question = Question(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = actor.Then(question, constraint);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public void Then_WithConstraints_WhenFailing_ShouldThrow(
            [Modest]Actor actor)
        {
            // arrange
            var question = Question(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            Assert.Throws<NUnitF.AssertionException>(() => actor.Then(question, constraint));
        }

        [Theory, DomainAutoData]
        public void Then_WithConstraints_AndFuncExceptionMessage_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected,
            string message)
        {
            // arrange
            var question = Question(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = actor.Then(question, constraint, () => message);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public void Then_WithConstraints_AndFuncExceptionMessage_WhenFailing_ShouldThrow(
            [Modest]Actor actor,
            string message)
        {
            // arrange
            var question = Question(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            new System.Action(() => actor.Then(question, constraint, () => message))
                .Should().Throw<NUnitF.AssertionException>()
                .Where(ex => ex.Message.Contains(message));
        }

        [Theory, DomainAutoData]
        public void Then_WithConstraints_AndExceptionMessage_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected,
            string message,
            object[] args)
        {
            // arrange
            var question = Question(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = actor.Then(question, constraint, message, args);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public void Then_WithConstraints_AndExceptionMessage_WhenFailing_ShouldThrow(
            [Modest]Actor actor,
            string[] args)
        {
            // arrange
            var message = string.Join("", args.Select((_, i) => $"{{{i}}}"));
            var question = Question(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            var expectedMessage = string.Format(message, args);
            new System.Action(() => actor.Then(question, constraint, message, args))
                .Should().Throw<NUnitF.AssertionException>()
                .Where(ex => ex.Message.Contains(expectedMessage));
        }
        #endregion

        #region Async
        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected)
        {
            // arrange
            var question = QuestionAsync(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = await actor.Then(question, constraint);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_WhenFailing_ShouldThrow(
            [Modest]Actor actor)
        {
            // arrange
            var question = QuestionAsync(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            await Assert.ThrowsAsync<NUnitF.AssertionException>(() => actor.Then(question, constraint));
        }

        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_AndFuncExceptionMessage_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected,
            string message)
        {
            // arrange
            var question = QuestionAsync(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = await actor.Then(question, constraint, () => message);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_AndFuncExceptionMessage_WhenFailing_ShouldThrow(
            [Modest]Actor actor,
            string message)
        {
            // arrange
            var question = QuestionAsync(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            var ex = await Assert.ThrowsAsync<NUnitF.AssertionException>(() => actor.Then(question, constraint, () => message));
            Assert.Contains(message, ex.Message);
        }

        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_AndExceptionMessage_ShouldReturnCorrectValue(
            [Modest]Actor actor,
            object expected,
            string message,
            object[] args)
        {
            // arrange
            var question = QuestionAsync(expected);
            var constraint = NUnitF.Is.EqualTo(expected);
            // act
            var actual = await actor.Then(question, constraint, message, args);
            // assert
            actual.Should().Be(expected);
        }

        [Theory, DomainAutoData]
        public async Task Then_Async_WithConstraints_AndExceptionMessage_WhenFailing_ShouldThrow(
            [Modest]Actor actor,
            string[] args)
        {
            // arrange
            var message = string.Join("", args.Select((_, i) => $"{{{i}}}"));
            var question = QuestionAsync(new object());
            var constraint = NUnitF.Is.EqualTo(new object());
            // act and assert
            var expectedMessage = string.Format(message, args);
            var ex = await Assert.ThrowsAsync<NUnitF.AssertionException>(() => actor.Then(question, constraint, message, args));
            Assert.Contains(expectedMessage, ex.Message);
        }
        #endregion
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns:orx="http://openrosa.org/jr/xforms"
        xmlns="http://www.w3.org/2002/xforms"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:jr="http://openrosa.org/javarosa"
        xmlns:vellum="http://commcarehq.org/xforms/vellum">
    <h:head>
        <h:title>Untitled Form</h:title>
        <model>
            <instance>
                <data xmlns:jrm="http://dev.commcarehq.org/jr/xforms"
                      xmlns="undefined" uiVersion="1" version="1" name="Untitled Form">
                    <with_markdown />
                    <markdown_veto />
                </data>
            </instance>
            <bind nodeset="/data/with_markdown" type="xsd:string" />
            <bind nodeset="/data/markdown_veto" type="xsd:string" />
            <itext>
                <translation lang="en" default="">
                    <text id="with_markdown-label">
                        <value>No Markdown in English</value>
                    </text>
                    <text id="markdown_veto-label">
                        <value>*Not* Markdown</value>
                    </text>
                </translation>
                <translation lang="afr">
                    <text id="with_markdown-label">
                        <value>*Met* Markdown in Afrikaans</value>
                        <value form="markdown">*Met* Markdown in Afrikaans</value>
                    </text>
                    <text id="markdown_veto-label">
                        <value>Nie Markdown nie</value>
                    </text>
                </translation>
                <translation lang="fra">
                    <text id="with_markdown-label">
                        <value>Sans le Markdown en Français</value>
                    </text>
                    <text id="markdown_veto-label">
                        <value>Ne Markdown pas</value>
                    </text>
                </translation>
            </itext>
        </model>
    </h:head>
    <h:body>
        <input ref="/data/with_markdown">
            <label ref="jr:itext('with_markdown-label')" />
        </input>
        <input ref="/data/markdown_veto">
            <label ref="jr:itext('markdown_veto-label')" />
        </input>
    </h:body>
</h:html>


text:
package f3.core

package object stats {}


text:
package com.google.mr4c.config.resources;

import com.google.mr4c.config.category.Category;

class TestResourceInfo implements ResourceInfo {

	private String m_name;
	private Category m_category;
	private String m_minConf;
	private String m_maxConf;
	private String m_hadoop;
	private String m_maxHadoop;

	TestResourceInfo(
		String name,
		Category category
	) {
		m_name = name;
		m_category = category;
		m_minConf = name + ".min";
		m_maxConf = name + ".max";
		m_hadoop = "hadoop." + name;
		m_maxHadoop = m_hadoop + ".max";
	}

	public String getResourceName() {
		return m_name;
	}

	public Category getConfigCategory() {
		return m_category;
	}

	public String getMinConfigName() {
		return m_minConf;
	}

	public String getMaxConfigName() {
		return m_maxConf;
	}

	public String getHadoopName() {
		return m_hadoop;
	}

	public String getMaxHadoopName() {
		return m_maxHadoop;
	}

}


text:
The easiest way to run these samples is usint `ts-node`.

```
npm install -g ts-node
ts-node ./samples/basic.ts
```


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Registrations extends CI_Controller {
    /*
     * Constructor
     */

    public function __construct() {
        parent::__construct();
        $this->load->helper(array('form', 'security'));
        $this->load->library('form_validation','session');
        $this->load->model('School_model');
    }

    public function index() {

        $data['data'] = $this->School_model->GetRegistered();
        $data['title'] = 'ADMIN | Dashboard';
        $this->load->view('admin/registrations', $data);
    }
    public function setUser()
    {
        //$user = $this->input->get();
        //$user = 1;
        $user['userid'] = $this->uri->segment(4);

        $this->session->set_userdata($user);
        redirect('admin/survey/School');
    }

}


text:
#include "selock.h"
#include <assert.h>

SELock::SELock(void)
   : m_write(false)
   , m_writers(0)
   , m_readers(0)
{
   #ifdef TIME_LOCKS
   _timer = TotalTimer::getTimerByStacktrace("selock@" + itostr(this));
   #endif
}

#define WAIT_WHILE(condition)                      \
   /* First busy wait a little */                  \
   for(int i = 0; i < 10000 && (condition); ++i) ; \
   while(condition) {                              \
      /* Then reschedule */                        \
      sched_yield();                               \
   }

// Acquire exclusive access
void
SELock::acquire_exclusive(void)
{
   #ifdef TIME_LOCKS
   ScopedTimer tt(*_timer);
   #endif

   // Tell everyone we want to write
   __sync_add_and_fetch(&m_writers, 1);

   while(true) {
      // Wait until the current writer and all readers have left
      WAIT_WHILE(m_write || m_readers);

      // No readers can come in, but another writer may have beaten us
      if (__sync_lock_test_and_set(&m_write, 1) == 1) {
         // Yep, someone was there already, retry
         continue;
      }

      // m_write was already set by the test_and_set above
      // Remove ourselves from the waiting writers count
      __sync_sub_and_fetch(&m_writers, 1);

      break;
   }
}

// Release exclusive access
void
SELock::release_exclusive(void)
{
   assert(m_write == true);

   m_write = 0;
}

// Acquire shared access
void
SELock::acquire_shared(void)
{
   #ifdef TIME_LOCKS
   ScopedTimer tt(*_timer);
   #endif

   while(true) {
      // Wait until the current writer has left
      WAIT_WHILE(m_write);

      // Now increment m_readers, but we need to be sure no writer comes in inbetween
      // Thus, make ourselves writer for a bit
      // Note that we did not wait for m_readers == 0, so there is no(t much) extra delay

      if (__sync_lock_test_and_set(&m_write, 1) == 1) {
         // A writer already came in, retry
         continue;
      }

      // Increment the readers count
      __sync_add_and_fetch(&m_readers, 1);

      m_write = 0;
      break;
   }
}

// Release shared access
void
SELock::release_shared(void)
{
   assert(m_readers > 0);

   __sync_sub_and_fetch(&m_readers, 1);
}

void
SELock::upgrade(void)
{
   assert(m_readers > 0);

   // Tell everyone we want to write
   UInt64 prev_writers = __sync_add_and_fetch(&m_writers, 1);

   if (prev_writers) {
      // Someone is waiting to write. Release our read lock, and go the long way (same as acquire_exclusive)
      __sync_sub_and_fetch(&m_readers, 1);

      while(true) {
         // Wait until the current writer and all readers have left
         WAIT_WHILE(m_write || m_readers);

         // No readers can come in, but another writer may have beaten us
         if (__sync_lock_test_and_set(&m_write, 1) == 1) {
            // Yep, someone was there already, retry
            continue;
         }

         // m_write was already set by the test_and_set above
         // Remove ourselves from the waiting writers count
         __sync_sub_and_fetch(&m_writers, 1);

         break;
      }

   } else {
      // There were no previous waiting writers. We don't need to release the shared lock we already have

      // Wait until the current writer and all readers have left
      WAIT_WHILE(m_write || m_readers);

      // No readers can come in, nor any other writer since we kept our readers count
      m_write = 1;

      // Now remove ourselves from the readers
      __sync_sub_and_fetch(&m_readers, 1);

      // m_write was already set by the test_and_set above
      // Remove ourselves from the waiting writers count
      __sync_sub_and_fetch(&m_writers, 1);
   }
}

void
SELock::downgrade(void)
{
   assert(m_write == true);

   // First make ourselves a reader, so no other potential writer may come in yet (until we fully release)
   __sync_add_and_fetch(&m_readers, 1);

   m_write = 0;
}


text:
/**@file
 *
 * @defgroup nrf_log_str_formatter String formatter for the logger messages
 * @{
 * @ingroup nrf_log
 */

#ifndef NRF_LOG_STR_FORMATTER_H
#define NRF_LOG_STR_FORMATTER_H

#include <stdint.h>
#include "nrf_fprintf.h"
#include "nrf_log_ctrl.h"

#ifdef __cplusplus
extern "C" {
#endif

typedef struct
{
    uint32_t            timestamp;
    uint16_t            module_id;
    uint16_t            dropped;
    nrf_log_severity_t  severity;
    uint8_t             use_colors;
} nrf_log_str_formatter_entry_params_t;

void nrf_log_std_entry_process(char const * p_str,
                               uint32_t const * p_args,
                               uint32_t nargs,
                               nrf_log_str_formatter_entry_params_t * p_params,
                               nrf_fprintf_ctx_t * p_ctx);

void nrf_log_hexdump_entry_process(uint8_t * p_data,
                                   uint32_t data_len,
                                   nrf_log_str_formatter_entry_params_t * p_params,
                                   nrf_fprintf_ctx_t * p_ctx);

void nrf_log_str_formatter_timestamp_freq_set(uint32_t freq);
#ifdef __cplusplus
}
#endif

#endif //NRF_LOG_STR_FORMATTER_H
/** @} */


text:
// @flow
/* global SETTINGS: false */
import React from "react"
import { mount } from "enzyme"
import { assert } from "chai"
import sinon from "sinon"
import { MuiThemeProvider, createMuiTheme } from "@material-ui/core/styles"

import StaffLearnerInfoCard from "./StaffLearnerInfoCard"
import { DASHBOARD_RESPONSE } from "../test_constants"
import { stringStrip } from "../util/test_utils"
import { calculatePrices } from "../lib/coupon"

describe("StaffLearnerInfoCard", () => {
  let sandbox

  beforeEach(() => {
    sandbox = sinon.sandbox.create()
    SETTINGS.roles.push({ role: "staff" })
  })

  afterEach(() => {
    sandbox.restore()
  })

  const renderCard = (program = DASHBOARD_RESPONSE.programs[0], price = 1000) =>
    mount(
      <MuiThemeProvider theme={createMuiTheme()}>
        <StaffLearnerInfoCard
          program={program}
          prices={calculatePrices(
            [program],
            [
              {
                program_id:                 program.id,
                price:                      price,
                financial_aid_availability: false,
                has_financial_aid_request:  false
              }
            ],
            []
          )}
          setShowGradeDetailDialog={() => undefined}
          dialogVisibility={{}}
        />
      </MuiThemeProvider>
    )

  it("should have the program title", () => {
    const card = renderCard()
    assert.include(
      stringStrip(card.text()),
      `Progress ${DASHBOARD_RESPONSE.programs[0].title}`
    )
  })

  it("should render the progress display", () => {
    const card = renderCard()
    assert.include(stringStrip(card.text()), "1 4 Courses complete")
  })

  it("should show average grade, if present", () => {
    const program = { ...DASHBOARD_RESPONSE.programs[0] }
    program.grade_average = 62
    const badge = renderCard(program).find(
      ".average-program-grade .program-badge"
    )
    assert.equal(badge.text(), "62%")
  })

  it('should show "--" if the grade is not present', () => {
    const badge = renderCard().find(".average-program-grade .program-badge")
    assert.equal(badge.text(), "--")
  })
})


text:
/* Author: André Roberge
   License: MIT
 */

/*jshint  -W002,browser:true, devel:true, indent:4, white:false, plusplus:false */
/*globals RUR */

RUR.world = {};

RUR.world.create_empty_world = function (blank_canvas) {
    "use strict";
    var world = {};
    if (blank_canvas) {
        world.blank_canvas = true;
        return world;
    }
    world.robots = [];
    world.walls = {};
    world.tokens = {};
    world.shapes = {};
    return world;
};
RUR.current_world = RUR.world.create_empty_world();

RUR.world.export_world = function () {
    return JSON.stringify(RUR.current_world, null, '');
};

RUR.world.import_world = function (json_string) {
    var body;
    if (json_string === undefined){
        return {};
    }
    try {
        RUR.current_world = JSON.parse(json_string) || RUR.world.create_empty_world();
    } catch (e) {
        console.log("exception caught in import_world");
        console.log(json_string);
        console.log(e);
        return;
    }
    if (RUR.current_world.robots !== undefined) {
        if (RUR.current_world.robots[0] !== undefined) {
            body = RUR.current_world.robots[0];
            body._prev_x = body.x;
            body._prev_y = body.y;
            body._prev_orientation = body.orientation;
        }
    }
    if (RUR.current_world.large_world !== undefined) {
        RUR.LARGE_WORLD = RUR.current_world.large_world;
    } else {
        RUR.LARGE_WORLD = false;
    }
    RUR.world.saved_world = RUR.world.clone_world();
    RUR.vis_world.draw_all();
    if (RUR.we.editing_world) {
        RUR.we.change_edit_robot_menu();
    }
};

RUR.world.clone_world = function (world) {
    if (world === undefined) {
        return JSON.parse(JSON.stringify(RUR.current_world));
    } else {
        return JSON.parse(JSON.stringify(world));
    }
};

RUR.world.reset = function () {
    RUR.current_world = RUR.world.clone_world(RUR.world.saved_world);
    RUR.MAX_STEPS = 1000;
    RUR.TRACE_CTX.clearRect(0, 0, RUR.WIDTH, RUR.HEIGHT);
    RUR.vis_world.refresh();
};

RUR.world.add_robot = function (robot) {
    if (RUR.current_world.robots === undefined){
        RUR.current_world.robots = [];
    }
    RUR.current_world.robots.push(robot);
    RUR.rec.record_frame();
};


text:
import React from 'react';
import bind from 'react-autobind';
import DoorSprite from './sprite';

class Door extends React.Component {
  constructor(props) {
    super(props);
    bind(this);
    this.doorSprite = {};
    this.loadAnimations();
    this.createSprite();
    const position = this.props.position;
    this.state = {
      position,
      status: 'closed',
    };
  }

  createSprite() {
    const sprite = new window.PIXI.extras.AnimatedSprite(this.openingFrames);
    sprite.interactive = true;
    sprite.buttonMode = true;
    this.sprite = sprite;
  }

  loadAnimations() {
    this.openingFrames = [];
    for (let i = 0; i <= 16; i++) {
      this.openingFrames.push(window.PIXI.Texture.fromFrame(`door_01 ${i}.ase`));
    }
  }

  updateStatus(status) {
    if (this.state.status !== status) {
      this.setState({ status });
    }
  }

  render() {
    const id = this.props.id;
    const position = this.state.position;
    const status = this.props.doorStatus;
    const updateCurrentDoorFrame = this.props.updateCurrentDoorFrame;
    return (
      <DoorSprite
        id={id}
        position={position}
        sprite={this.sprite}
        status={status}
        updateCurrentDoorFrame={updateCurrentDoorFrame}
      />
    );
  }
}

export default Door;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. mycol. Fr. 67(3): 292 (1952)

#### Original name
Cortinarius fulvo-olivaceus Rob. Henry

### Remarks
null


text:
@interface GDWNavigationController : UINavigationController

@end


text:
//  ----------------------------------------------------------------------------------
//  Copyright Microsoft Corporation
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//  ----------------------------------------------------------------------------------

namespace DurableTask.AzureServiceFabric
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;

    sealed class AsyncManualResetEvent
    {
        TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();

        public async Task<bool> WaitAsync(TimeSpan timeout, CancellationToken cancellationToken)
        {
            if (timeout < TimeSpan.Zero)
            {
                timeout = TimeSpan.Zero;
            }

            var delayTask = Task.Delay(timeout, cancellationToken);
            var resultTask = await Task.WhenAny(delayTask, this.taskCompletionSource.Task);
            return delayTask != resultTask;
        }

        public void Set()
        {
            this.taskCompletionSource.TrySetResult(true);
        }

        public void Reset()
        {
            while (true)
            {
                var thisTcs = this.taskCompletionSource;

                if (!thisTcs.Task.IsCompleted || Interlocked.CompareExchange(ref this.taskCompletionSource, new TaskCompletionSource<bool>(), thisTcs) == thisTcs)
                {
                    return;
                }
            }
        }
    }
}


text:
<?php

namespace ClickNow\Checker\Task;

use ClickNow\Checker\Process\ArgumentsCollection;

/**
 * @group  task
 * @covers \ClickNow\Checker\Task\SassLint
 */
class SassLintTest extends AbstractExternalTaskTest
{
    protected $class = SassLint::class;

    public function testGetName()
    {
        $this->assertSame('SassLint', $this->externalTask->getName());
    }

    /**
     * Mock arguments
     *
     * @param \ClickNow\Checker\Process\ArgumentsCollection $args
     *
     * @return void
     */
    protected function mockArguments(ArgumentsCollection $args)
    {
        $this->processBuilder->shouldReceive('createArgumentsForCommand')->with('sass-lint')->once()->andReturn($args);
    }
}


text:
Introduction
============

This is the documentation for the modesolverpy API.


text:
using JetBrains.Annotations;
using RiceDoctor.Shared;

namespace RiceDoctor.SemanticCodeInterpreter
{
    public class SingularNode : SemanticNode
    {
        public SingularNode([NotNull] string tag)
        {
            Check.NotEmpty(tag, nameof(tag));

            Tag = tag;
        }

        public string Tag { get; }

        public override string ToString()
        {
            return $"<{Tag}/>";
        }
    }
}


text:
function [spectrum, freqoi, timeoi] = ft_specest_tfr(dat, time, varargin)

% FT_SPECEST_TFR performs time-frequency analysis on any time series trial data using
% the 'wavelet method' based on Morlet wavelets, doing convolution in the time
% domain.
%
% Use as
%   [spectrum,freqoi,timeoi] = ft_specest_convol(dat,time,...)
% where
%   dat       = matrix of chan*sample
%   time      = vector, containing time in seconds for each sample
%   spectrum  = array of chan*freqoi*timeoi of fourier coefficients
%   freqoi    = vector of frequencies in spectrum
%   timeoi    = vector of timebins in spectrum
%
% Optional arguments should be specified in key-value pairs and can include
%   timeoi    = vector, containing time points of interest (in seconds, analysis window will be centered around these time points)
%   freqoi    = vector, containing frequencies (in Hz)
%   width     = number or vector, width of the wavelet, determines the temporal and spectral resolution (default = 7)
%   gwidth    = number, determines the length of the used wavelets in standard deviations of the implicit Gaussian kernel
%   verbose   = output progress to console (0 or 1, default 1)
%   polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component)
%
% See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_MTMCONVOL, FT_SPECEST_HILBERT, FT_SPECEST_NANFFT, FT_SPECEST_WAVELET

% Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_specest_tfr.m 10451 2015-06-10 22:00:07Z roboos $

% get the optional input arguments
freqoi    = ft_getopt(varargin, 'freqoi', 'all');
timeoi    = ft_getopt(varargin, 'timeoi', 'all');
width     = ft_getopt(varargin, 'width', 7);
gwidth    = ft_getopt(varargin, 'gwidth', 3);
pad       = ft_getopt(varargin, 'pad');
polyorder = ft_getopt(varargin, 'polyorder', 0);
fbopt     = ft_getopt(varargin, 'feedback');
verbose   = ft_getopt(varargin, 'verbose', true);

if isempty(fbopt),
  fbopt.i = 1;
  fbopt.n = 1;
end

% Set n's
[nchan,ndatsample] = size(dat);

% This does not work on integer data
typ = class(dat);
if ~strcmp(typ, 'double') && ~strcmp(typ, 'single')
  dat = cast(dat, 'double');
end

% Remove polynomial fit from the data -> default is demeaning
if polyorder >= 0
  dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample);
end

% Determine fsample and set total time-length of data
fsample = 1./mean(diff(time));
dattime = ndatsample / fsample; % total time in seconds of input data

% Zero padding
if round(pad * fsample) < ndatsample
  error('the padding that you specified is shorter than the data');
end
if isempty(pad) % if no padding is specified padding is equal to current data length
  pad = dattime;
end
endnsample = round(pad * fsample);  % total number of samples of padded data
endtime    = pad;            % total time in seconds of padded data
prepad     = zeros(1,floor(((pad - dattime) * fsample) ./ 2));
postpad    = zeros(1,ceil(((pad - dattime) * fsample) ./ 2));

% Set freqboi and freqoi
freqoiinput = freqoi;
if isnumeric(freqoi) % if input is a vector
  freqboi   = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 1;
  freqboi   = unique(freqboi);
  freqoi    = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output
elseif strcmp(freqoi,'all') % if input was 'all'
  freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1;
  freqboi    = freqboilim(1):1:freqboilim(2);
  freqoi     = (freqboi-1) ./ endtime;
end
% check for freqoi = 0 and remove it, there is no wavelet for freqoi = 0
if freqoi(1)==0
  freqoi(1)  = [];
  freqboi(1) = [];
end
nfreqboi = length(freqboi);
nfreqoi  = length(freqoi);

% throw a warning if input freqoi is different from output freqoi
if isnumeric(freqoiinput)
  % check whether padding is appropriate for the requested frequency resolution
  rayl = 1/endtime;
  if any(rem(freqoiinput,rayl)) % not always the case when they mismatch
    ft_warning('padding not sufficient for requested frequency resolution, for more information please see the FAQs on www.ru.nl/neuroimaging/fieldtrip');
  end
  if numel(freqoiinput) ~= numel(freqoi) % freqoi will not contain double frequency bins when requested
    ft_warning('output frequencies are different from input frequencies, multiples of the same bin were requested but not given');
  else
    if any(abs(freqoiinput-freqoi) >= eps*1e6)
      ft_warning('output frequencies are different from input frequencies');
    end
  end
end

% Set timeboi and timeoi
timeoiinput = timeoi;
offset = round(time(1)*fsample);
if isnumeric(timeoi) % if input is a vector
  timeoi   = unique(round(timeoi .* fsample) ./ fsample);
  timeboi  = round(timeoi .* fsample - offset) + 1;
  ntimeboi = length(timeboi);
elseif strcmp(timeoi,'all') % if input was 'all'
  timeboi  = 1:length(time);
  ntimeboi = length(timeboi);
  timeoi   = time;
end

% throw a warning if input timeoi is different from output timeoi
if isnumeric(timeoiinput)
  if numel(timeoiinput) ~= numel(timeoi) % timeoi will not contain double time-bins when requested
    ft_warning('output time-bins are different from input time-bins, multiples of the same bin were requested but not given');
  else
    if any(abs(timeoiinput-timeoi) >= eps*1e6)
      ft_warning('output time-bins are different from input time-bins');
    end
  end
end

% Creating wavelets
% expand width to array if constant width
if numel(width) == 1
  width = ones(1,nfreqoi) * width;
end
wavelet = cell(nfreqoi,1);
for ifreqoi = 1:nfreqoi
  dt = 1/fsample;
  sf = freqoi(ifreqoi) / width(ifreqoi);
  st = 1/(2*pi*sf);
  toi2 = -gwidth*st:dt:gwidth*st;
  A = 1/sqrt(st*sqrt(pi));
  tap = (A*exp(-toi2.^2/(2*st^2)))';
  acttapnumsmp = size(tap,1);
  taplen(ifreqoi) = acttapnumsmp;
  ins = ceil(endnsample./2) - floor(acttapnumsmp./2);
  %prezer = zeros(ins,1);
  %pstzer = zeros(endnsample - ((ins-1) + acttapnumsmp)-1,1);

  % produce angle with convention: cos must always be 1  and sin must always be centered in upgoing flank, so the centre of the wavelet (untapered) has angle = 0
  ind  = (-(acttapnumsmp-1)/2 : (acttapnumsmp-1)/2)'   .*  ((2.*pi./fsample) .* freqoi(ifreqoi));

  % create wavelet and fft it
  %wavelet{ifreqoi} = complex(vertcat(prezer,tap.*cos(ind),pstzer), vertcat(prezer,tap.*sin(ind),pstzer));
  wavelet{ifreqoi} = complex(vertcat(tap.*cos(ind)), vertcat(tap.*sin(ind)));

  %%%% debug plotting
  %   figure('name',['wavelet @ ' num2str(freqoi(ifreqoi)) 'Hz' ],'NumberTitle','off');
  %   subplot(2,1,1);
  %   hold on;
  %   plot(real(wavelet));
  %   plot(imag(wavelet),'color','r');
  %   legend('real','imag');
  %   tline = length(wavelet)/2;
  %   if mod(tline,2)==0
  %     line([tline tline],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--')
  %   else
  %     line([ceil(tline) ceil(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--');
  %     line([floor(tline) floor(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--');
  %   end;
  %   subplot(2,1,2);
  %   plot(angle(wavelet),'color','g');
  %   if mod(tline,2)==0,
  %     line([tline tline],[-pi pi],'color','r','linestyle','--')
  %   else
  %     line([ceil(tline) ceil(tline)],[-pi pi],'color','r','linestyle','--')
  %     line([floor(tline) floor(tline)],[-pi pi],'color','r','linestyle','--')
  %   end
  %%%% debug plotting

end

% compute spectrum by convolving the wavelets with the data
spectrum = complex(nan(nchan,nfreqoi,ntimeboi),nan(nchan,nfreqoi,ntimeboi));
for ifreqoi = 1:nfreqoi
  str = sprintf('frequency %d (%.2f Hz)', ifreqoi,freqoi(ifreqoi));
  [st, cws] = dbstack;
  if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose
    % specest_convol has been called by ft_freqanalysis, meaning that ft_progress has been initialised
    ft_progress(fbopt.i./fbopt.n, ['trial %d, ',str,'\n'], fbopt.i);
  elseif verbose
    fprintf([str, '\n']);
  end

  % compute indices that will be used to extracted the requested output (this keeps nans when the wavelet is not fully immersed in the data)
  nsamplefreqoi    = taplen(ifreqoi);
  reqtimeboiind    = find((timeboi >=  (nsamplefreqoi ./ 2)) & (timeboi < (ndatsample - (nsamplefreqoi ./2))));
  reqtimeboi       = timeboi(reqtimeboiind);

  % do convolution, if there are reqtimeboi's that have data
  if ~isempty(reqtimeboi)
    dum = complex(zeros(nchan,numel(reqtimeboi)));
    for ichan = 1:nchan
      dumconv = conv(dat(ichan,:),  wavelet{ifreqoi}, 'same');
      dum(ichan,:) = dumconv(reqtimeboi); % keeping nans nans when the wavelet is not fully immersed in the data
    end
    spectrum(:,ifreqoi,reqtimeboiind) = dum;
  end
end

% old code used to create wavelets
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% % SUBFUNCTION for waveletanalysis
% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function M = waveletfam(foi,fsample,waveletwidth)
% dt = 1/fsample;
% for k=1:length(foi)
%   sf  = foi(k)/waveletwidth;
%   st  = 1/(2*pi*sf);
%   toi = -3.5*st:dt:3.5*st;
%   A   = 1/sqrt(st*sqrt(pi));
%   M{k}= A*exp(-toi.^2/(2*st^2)).*exp(i*2*pi*foi(k).*toi);
% end


text:
var assert = require('assert');

var FUNCTION_TYPE_RE = /Function/;
var PAREN_KEYWORD_TYPE_RE = /Statement$|^CatchClause$/;
var NO_PAREN_KEYWORD_TYPE_RE = /^ExpressionStatement$|^ReturnStatement$|^ThrowStatement$/;
var QUASI_STATEMENT_TYPE_RE = /Statement$|Declaration$/;

/**
 * Returns the type of AST node or ECMAScript production in which the provided
 * open parenthesis token is included.
 *
 * @param {Object} token
 * @param {JsFile} file
 * @returns {String}
 */
exports.categorizeOpenParen = function(token, file) {
    assert(token.value === '(', 'Input token must be a parenthesis');
    var node = file.getNodeByRange(token.range[0]);
    var nodeType = node.type;
    var prevToken = token.previousCodeToken;

    // Outermost grouping parenthesis
    if (!prevToken) {
        return 'ParenthesizedExpression';
    }

    // Part of a parentheses-bearing statement (if, with, while, switch, etc.)
    if (prevToken.type === 'Keyword' && PAREN_KEYWORD_TYPE_RE.test(nodeType) &&
        !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {

        return 'Statement';
    }

    // Part of a function definition (declaration, expression, method, etc.)
    if (FUNCTION_TYPE_RE.test(nodeType) &&

        // Name is optional for function expressions
        (prevToken.type === 'Identifier' || prevToken.value === 'function')) {

        return 'Function';
    }

    // Part of a call expression
    var prevNode = file.getNodeByRange(prevToken.range[0]);
    if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&

        // Must not be inside an arguments list or other grouping parentheses
        prevToken.value !== ',' && prevToken.value !== '(' &&

        // If the callee is parenthesized (e.g., `(foo.bar)()`), prevNode will match node
        // Otherwise (e.g., `foo.bar()`), prevToken must be the last token of the callee node
        (prevNode === node || prevToken === file.getLastNodeToken(node.callee))) {

        return 'CallExpression';
    }

    // All remaining cases are grouping parentheses
    return 'ParenthesizedExpression';
};

/**
 * Returns the type of AST node or ECMAScript production in which the provided
 * close parenthesis token is included.
 *
 * @param {Object} token
 * @param {JsFile} file
 * @returns {String}
 */
exports.categorizeCloseParen = function(token, file) {
    assert(token.value === ')', 'Input token must be a parenthesis');
    var node = file.getNodeByRange(token.range[0]);
    var nodeType = node.type;
    var nextToken = file.getNextToken(token);

    // Terminal statement
    if (nextToken.type === 'EOF') {
        switch (nodeType) {
            case 'DoWhileStatement':
                return 'Statement';
            case 'CallExpression':
            case 'NewExpression':
                return 'CallExpression';
            default:
                return 'ParenthesizedExpression';
        }
    }

    // Part of a parentheses-bearing statement (if, with, while, switch, etc.)
    if (PAREN_KEYWORD_TYPE_RE.test(nodeType) && !NO_PAREN_KEYWORD_TYPE_RE.test(nodeType)) {
        // Closing parentheses for `switch` and `catch` must be followed by "{"
        // Closing parentheses for `do..while` may be the last punctuation inside a block
        if (nextToken.value === '{' || nextToken.value === '}') {
            return 'Statement';
        }

        // Closing parentheses for other statements must be followed by a statement or declaration
        var nextNode = file.getNodeByRange(nextToken.range[0]);
        while (nextNode.range[0] >= token.range[1]) {
            if (QUASI_STATEMENT_TYPE_RE.test(nextNode.type)) {
                return 'Statement';
            }
            nextNode = nextNode.parentElement;
        }
    }

    // Part of a function definition (declaration, expression, method, etc.)
    if (nextToken.value === '{' && FUNCTION_TYPE_RE.test(nodeType)) {
        return 'Function';
    }

    // Part of a call expression
    if ((nodeType === 'CallExpression' || nodeType === 'NewExpression') &&
        nextToken.range[0] >= node.range[1]) {

        return 'CallExpression';
    }

    // All remaining cases are grouping parentheses
    return 'ParenthesizedExpression';
};


text:
<?php

require_once( 'Light/Database/Object/Cache.php' );

class CTM_Test_Machine_Browser_Cache extends Light_Database_Object_Cache
{
   private $_cache;

   public function init()
   {
      $this->setObject('CTM_Test_Machine_Browser');
   }

}


text:
module MiqAeMethodService
  class MiqAeServiceOrchestrationTemplate < MiqAeServiceModelBase
    expose :stacks, :association => true
  end
end


text:
describe('#MapPan', function () {

    var container;
    var map;
    var center = new maptalks.Coordinate(118.846825, 32.046534);

    beforeEach(function () {
        container = document.createElement('div');
        container.style.width = '2px';
        container.style.height = '2px';
        document.body.appendChild(container);
        var option = {
            zoomAnimation:false,
            zoom: 17,
            center: center
        };
        map = new maptalks.Map(container, option);
    });

    afterEach(function () {
        map.remove();
        REMOVE_CONTAINER(container);
    });

    it('panTo without animation', function () {
        var coord = center.substract(1, 1);
        map.panTo(coord, { 'animation' : false });
        expect(map.getCenter()).to.be.closeTo(coord);
    });

    it('panTo', function (done) {
        var coord = center.substract(1, 1);
        map.once('moveend', function () {
            expect(map.getCenter()).to.be.closeTo(coord);
            done();
        });
        map.panTo(coord, { 'animation' : true });
    });

    it('when panning map to a point, call the callback function in each frame', function (done) {
        var coord = center.substract(1, 1);
        var spy = sinon.spy();
        var t = 100;
        map.panTo(coord, {
           'animation' : true,
           'duration': t
        }, spy);
        expect(spy.called).to.not.be.ok();
        setTimeout(function(){
           expect(spy.called).to.be.ok();
           done();
        }, 50);
    });

    it('panBy without animation', function (done) {
        map.setBearing(90);
        var offset = { x: 20, y: 0 };
        map.once('moveend', function () {
            expect(+map.getCenter().x.toFixed(6)).to.be.eql(center.x);
            expect(map.getCenter().y).not.to.be.eql(center.y);
            done();
        });
        map.panBy(offset, { 'animation' : false });
    });

    it('panBy with animation', function (done) {
        var offset = { x: 20, y: 20 };
        map.once('moveend', function () {
            expect(map.getCenter()).not.to.be.eql(center);
            done();
        });
        map.panBy(offset, { 'animation' : true });
    });

    it('panBy with callback', function (done) {
        var offset = { x: 20, y: 20 };
        var spy = sinon.spy();
        var t = 100;
        map.panBy(offset, { 'animation' : true, 'duration': t }, spy);
        expect(spy.called).to.not.be.ok();
        setTimeout(function(){
           expect(spy.called).to.be.ok();
           done();
        }, 50);
    });

    it('change zoom or center during panning', function (done) {
        var coord = center.substract(1, 1),
            newCenter = center.add(1, 1);
        map.once('moveend', function () {
            expect(map.getCenter()).to.be.closeTo(newCenter);
            done();
        });
        map.panTo(coord, { 'animation' : true });
        map.setCenterAndZoom(newCenter, map.getZoom() + 1);
    });
});


text:
/*
* Author: digitkhrisnaa
*/

//import dependecies
var express = require ("express");
var expressJWT = require("express-jwt");
var bodyParser   = require('body-parser');
var config = require("./src/util/config");
var MongoClient = require('mongodb').MongoClient , assert = require('assert');
var versionRoutes = require("./src/routes/version_routes");
var userRoutes = require("./src/routes/user_routes");
var mobileRoutes = require("./src/routes/mobile_routes")

//Use express
var app = express();

//Set bodyParser
app.use(bodyParser.urlencoded({ extended: false }));
//app.use(bodyParser.json());

//Except JWT header for login path
//app.use(expressJWT({secret:config.secret}).unless({path:['/api/v1/index']}));

//Create routes
versionRoutes(app);
userRoutes(app);
mobileRoutes(app);

//Open port and start application
app.listen(config.port, () => console.log('App started listening on port', config.port));