text:
/**
 * This class provides access to the device media, interfaces to both sound and video
 * @constructor
 */
function Audio(src, successCallback, errorCallback) {
	this.src = src;
	this.successCallback = successCallback;
	this.errorCallback = errorCallback;
}

Audio.prototype.record = function() {
};

Audio.prototype.play = function() {
try {
	if (document.getElementById('gapsound'))
		document.body.removeChild(document.getElementById('gapsound'));
	var obj;
	obj = document.createElement("embed");
	obj.setAttribute("id", "gapsound");
	obj.setAttribute("type", "audio/x-mpeg");
	obj.setAttribute("width", "0");
	obj.setAttribute("width", "0");
	obj.setAttribute("hidden", "true");
	obj.setAttribute("autostart", "true");
	obj.setAttribute("src", this.src);
	document.body.appendChild(obj);
} catch (ex) { debug.log(ex.name + ": " + ex.message); }
};

Audio.prototype.pause = function() {
};

Audio.prototype.stop = function() {
	document.body.removeChild(document.getElementById('gapsound'));
};


text:
package org.inaetics.dronessimulator.drone.components.gps;

import org.inaetics.dronessimulator.common.Settings;
import org.inaetics.dronessimulator.common.protocol.StateMessage;
import org.inaetics.dronessimulator.common.vector.D3PolarCoordinate;
import org.inaetics.dronessimulator.common.vector.D3Vector;
import org.inaetics.dronessimulator.drone.droneinit.DroneInit;
import org.inaetics.pubsub.api.pubsub.Subscriber;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * The GPS drone component
 */
public class GPS implements Subscriber {
    private final Set<GPSCallback> callbacks = new HashSet<>();
    /** The drone instance that can be used to get information about the current drone */
    private volatile DroneInit drone;
    private StateMessage previousMessage;
    //OSGi constructor
    public GPS() {
    }
    //Testing constructor
    public GPS(DroneInit drone, StateMessage previousMessage, D3Vector position, D3Vector velocity, D3Vector acceleration, D3PolarCoordinate direction) {
        this.drone = drone;
        this.previousMessage = previousMessage;
        this.position = position;
        this.velocity = velocity;
        this.acceleration = acceleration;
        this.direction = direction;
    }

    /**
     * Create the logger
     */
    private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(GPS.class);
    /**
     * Last known position of this drone in the architecture
     */
    private volatile D3Vector position = new D3Vector();

    public D3Vector getPosition() {
        return position;
    }

    public void setPosition(D3Vector position) {
        this.position = position;
    }

    /**
     * Last known velocity of this drone in the architecture
     */
    private volatile D3Vector velocity = new D3Vector();

    public D3Vector getVelocity() {
        return velocity;
    }

    public void setVelocity(D3Vector velocity) {
        this.velocity = velocity;
    }
    /**
     * Last known acceleration of this drone in the architecture
     */
    private volatile D3Vector acceleration = new D3Vector();

    public D3Vector getAcceleration() {
        return acceleration;
    }

    public void setAcceleration(D3Vector acceleration) {
        this.acceleration = acceleration;
    }

    /**
     * Last known direction of this drone in the architecture
     */
    private volatile D3PolarCoordinate direction = new D3PolarCoordinate();

    public D3PolarCoordinate getDirection() {
        return direction;
    }

    public void setDirection(D3PolarCoordinate direction) {
        this.direction = direction;
    }

    /**
     * Start the GPS (called from Apache Felix). This initializes to what messages the subscriber should listen.
     */
    public void start() {
        try {
            Thread.sleep(5000); // To ensure PubSubAdmin can give us a subscriber.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // Subcriber initialization is now done by the Activator.
    }

    @Override
    public void receive(Object o, MultipartCallbacks multipartCallbacks) {
        System.out.println("[GPS] Got message " + o);
        if (o instanceof StateMessage && ((StateMessage) o).getIdentifier().equals(this.drone.getIdentifier())) {
            StateMessage message = (StateMessage) o;
            //Prepare some variables
            double deltaNow = ChronoUnit.MILLIS.between(message.getTimestamp(), LocalTime.now());
            Optional<D3Vector> optionalPosition = message.getPosition() == null ?
                    Optional.empty() : Optional.of(message.getPosition());
            Optional<D3Vector> optionalVelocity = message.getVelocity() == null ?
                    Optional.empty() : Optional.of(message.getVelocity());
            Optional<D3Vector> optionalAcceleration = message.getAcceleration() == null ?
                    Optional.empty() : Optional.of(message.getAcceleration());
            Optional<D3PolarCoordinate> optionalDirection = message.getDirection() == null ?
                    Optional.empty() : Optional.of(message.getDirection());

            //Check if the message is recent
            if (previousMessage != null && deltaNow > Settings.getTickTime(ChronoUnit.MILLIS)) {
                double deltaMessages = ChronoUnit.MILLIS.between(previousMessage.getTimestamp(), message.getTimestamp());
                if (deltaMessages <= 0) {
                    //We cannot use two messages that were send at the same time since this will create a NaN. To avoid getting this multiple times, we do not update the last message.
                    return;
                }
                interpolateMessages(deltaNow, deltaMessages, message);
            } else {
                optionalPosition.ifPresent(this::setPosition);
                optionalAcceleration.ifPresent(this::setAcceleration);
                optionalVelocity.ifPresent(this::setVelocity);
                optionalDirection.ifPresent(this::setDirection);
            }
            previousMessage = message;
            //Run callbacks
            callbacks.forEach(callback -> callback.run(message));
        }
    }

    /**
     * Interpolate the position, velocity and acceleration from the previous message and the current message. The estimated values are also set to the corresponding
     * fields. This method makes use of the other interpolate methods to achieve this.
     *
     * @param deltaNow      the difference between the moment the message was send and the current time.
     * @param deltaMessages the difference between the moment the previous message was send and the current message was send.
     * @param message       The current message
     */
    private void interpolateMessages(double deltaNow, double deltaMessages, StateMessage message) {
        Optional<D3Vector> optionalPosition = message.getPosition() == null ?
                Optional.empty() : Optional.of(message.getPosition());
        Optional<D3Vector> optionalVelocity = message.getVelocity() == null ?
                Optional.empty() : Optional.of(message.getVelocity());
        Optional<D3Vector> optionalAccelration = message.getAcceleration() == null ?
                Optional.empty() : Optional.of(message.getAcceleration());
        Optional<D3Vector> optionalPreviousPosition = previousMessage.getPosition() == null ?
                Optional.empty() : Optional.of(previousMessage.getPosition());
        Optional<D3Vector> optionalPreviousVelocity = previousMessage.getVelocity() == null ?
                Optional.empty() : Optional.of(previousMessage.getVelocity());
        Optional<D3Vector> optionalPreviousAcceleration = previousMessage.getAcceleration() == null ?
                Optional.empty() : Optional.of(previousMessage.getAcceleration());

        //Use the previous message to make a better guess of the location the drone probably is.
        if (optionalAccelration.isPresent() && optionalPreviousAcceleration.isPresent()) {
            D3Vector estimatedAcceleration = interpolateAcceleration(deltaNow, deltaMessages, optionalAccelration.get(), optionalPreviousAcceleration.get());

            if (optionalVelocity.isPresent() && optionalPreviousVelocity.isPresent()) {
                D3Vector estimatedVelocity = interpolateVelocity(deltaNow, deltaMessages, optionalVelocity.get(), optionalAccelration.get(), optionalPreviousVelocity.get(),
                        estimatedAcceleration);

                if (optionalPosition.isPresent() && optionalPreviousPosition.isPresent()) {
                    interpolatePosition(deltaNow, deltaMessages, optionalPosition.get(), optionalAccelration.get(), optionalPreviousPosition.get(), estimatedVelocity);
                }
            }
        }
    }

    private void interpolatePosition(double deltaNow, double deltaMessages, D3Vector optionalPosition, D3Vector optionalAccelration, D3Vector optionalPreviousPosition, D3Vector estimatedVelocity) {
        D3Vector deltaPosition;
        if (optionalAccelration.equals(D3Vector.ZERO)) {
            deltaPosition = D3Vector.ZERO;
        } else {
            deltaPosition = optionalPosition.normalize().scale(optionalPosition.sub(optionalPreviousPosition).length() / deltaMessages);
        }
        D3Vector estimatedPosition = optionalPosition.add(deltaPosition.scale(deltaNow / 1000)).add(estimatedVelocity.scale(Settings.getTickTime(ChronoUnit.SECONDS)));
        setPosition(estimatedPosition);
    }

    private D3Vector interpolateVelocity(double deltaNow, double deltaMessages, D3Vector optionalVelocity, D3Vector optionalAccelration, D3Vector optionalPreviousVelocity, D3Vector estimatedAcceleration) {
        D3Vector deltaVelocity;
        if (optionalAccelration.equals(D3Vector.ZERO)) {
            deltaVelocity = D3Vector.ZERO;
        } else {
            deltaVelocity = optionalVelocity.normalize().scale(optionalVelocity.sub(optionalPreviousVelocity).length() / deltaMessages);
        }
        D3Vector estimatedVelocity = optionalVelocity.add(deltaVelocity.scale(deltaNow / 1000)).add(estimatedAcceleration.scale(Settings.getTickTime(ChronoUnit.SECONDS)));
        setVelocity(estimatedVelocity);
        return estimatedVelocity;
    }

    private D3Vector interpolateAcceleration(double deltaNow, double deltaMessages, D3Vector acceleration, D3Vector previousAcceleration) {
        D3Vector deltaAcceleration;
        if (acceleration.equals(D3Vector.ZERO)) {
            deltaAcceleration = D3Vector.ZERO;
        } else {
            deltaAcceleration = acceleration.normalize().scale(acceleration.sub(previousAcceleration).length() / deltaMessages);
        }
        D3Vector estimatedAcceleration = acceleration.add(deltaAcceleration.scale(deltaNow / 1000));
        setAcceleration(estimatedAcceleration);
        return estimatedAcceleration;
    }

    /**
     * Submit a callback-function that is called after each state update is received. The StateMessage is a parameter for this callback.
     *
     * @param callback the function to be called
     */
    public final void registerCallback(GPSCallback callback) {
        callbacks.add(callback);
    }

    @FunctionalInterface
    public interface GPSCallback {
        void run(StateMessage newState);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using CryptoKnight.Server.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace CryptoKnight.Server.Test
{
    [TestClass]
    public class LicenseServerTest
    {
        private static readonly User Admin = new User
        {
            Email = "admin@host.com",
            PasswordHash = "test"
        };
        private static readonly User User = new User
        {
            Email = "user@host.com",
            PasswordHash = "user"
        };
        private static ILicenseService licencService;
        private static IAuthService authService;

        [TestMethod]
        public void TestActivations()
        {
            licencService = new DefaultLicenseService();
            for (var i = 0; i < LicenseGroup.MaxLicenseKeys; i++)
            {
                Assert.IsNotNull(licencService.RequestLicenseKey(Admin));
            }
            Assert.IsNull(licencService.RequestLicenseKey(Admin));
        }

        [TestMethod]
        public void TestKeyHash()
        {
            licencService = new DefaultLicenseService();
            System.Console.WriteLine(licencService.RequestLicenseKey(User).Code);
        }

        [TestMethod]
        public void TestSingleLogin()
        {
            licencService = new DefaultLicenseService();
            authService = new DefaultAuthService();
            var key = licencService.RequestLicenseKey(User);
            Assert.IsTrue(authService.Login(User, key));
            Assert.IsFalse(authService.Login(User, key));
        }
    }
}


text:
<?php

define ('MSG_TXT',1);
define ('MSG_HTML',2);
define ('MSG_ATT',4);
class SendMail {
	/**
	 * $sender and $receiver
	 * array containing ['name'] and ['email'] variables
	**/
	public $sender;
	public $receiver;
	/**
	 * $file
	 * Associative array including the ['filename'], the MIME ['type'] of the file, and
	 * the ['base64']-encoded file itself
	**/
	private $file;

	/**
	 * $cc, $bcc
	 * Array of Associative Arrays ['name'], ['email'] for CC and BCC's
	**/
	private $cc = array();
	private $bcc = array();

	/**
	 * $smtp_settings
	 * Associative array which will contain SMTP settings
	**/
	public $smtp_settings = array(
		'host'=>'',
		'port'=>-1,
		'username'=>'',
		'password'=>''
	);
	/**
	 * $smtp
	 * true or false if SMTP will be used
	 * Defaults to FALSE
	**/
	public $smtp = false;

	/**
	 * Other basic message variables
	**/
	public $subject;
	public $headers;
	public $css;
	public $html_message;
	public $text_message;
	public $footer;

	public $send_return_message;
	public $send_return_to_cc;
	public $send_return_to_bcc;
	public $return_subject;
	public $return_html;
	public $return_text;

	/**
	 * $yahoo_type
	 * if $yahoo_type is set to TRUE then a special header must be sent through the mail() function
	 * So called because it's the only instance I've found this needs to be set.
	**/
	private $yahoo_type;

	/**	Message types supported are:
	 *		MSG_TXT = Send Message as Text
	 *		MSG_HTML = Send Message as HTML
	 *		MSG_ATT = Send Message with Attachment
	 *
	 * In order to set this when constructing, use the format MSG_TXT + MSG_HTML + MSG_ATT
	**/
	private $msg_type;

	/**
	 * $debug_mode
	 * If set to TRUE, outputs "email" direct to screen, and returns TRUE
	 * If not set, or set to FALSE, the object operates normally.
	**/
	private $debug_mode;
/* STARTUP FUNCTIONS */

	function __Construct($msgtype = MSG_TXT, $return_email = FALSE, $yah = FALSE,$debug = FALSE) {

		$message_footer = '';

		$this->footer = $message_footer;
		$this->yahoo_type = $yah;
		$this->msg_type = $msgtype;
		$this->send_return_message = $return_email;
		$this->headers = NULL;
		$this->debug_mode = $debug;
	}

/* FUNCTIONS TO SET THE DATA */
	function setSendReturnMessage ($do_you_want_to_send_a_return_message) { $this->send_return_message = $do_you_want_to_send_a_return_message; }
	function setDebugMode ($debug_mode) { $this->debug_mode = $debug_mode; }
	function setSender ($name,$email) { $this->sender['name'] = $name; $this->sender['email'] = $email; }
	function setReceiver ($name,$email) { $this->receiver['name'] = $name; $this->receiver['email'] = $email; }
	function setHtmlCss ($css) { $this->css = $css; }
	function setHtmlStyle ($css) { $this->setHtmlCss ($css); }
	function addHeader ($head) { $this->headers .= trim($head)."\n"; }
	function setFooter ($foot) { $this->footer = $foot; }
	function setSubject ($message_subject) { $this->subject = $message_subject; }
	function setTextMessage ($text_message) { $this->text_message = $text_message; echo "ttttxtmsg::".$this->text_message;}
	function setHtmlMessage ($html_message) { $this->html_message = $html_message; }
	function setReturnMail ($do_you_want_to_send_a_return_message, $cc_array_A, $bcc_array_A) {
		$this->send_return_message = $do_you_want_to_send_a_return_message;
		$this->send_return_to_cc = $cc_array_A;
		$this->send_return_to_bcc = $bcc_array_A;
	}
	function setReturnSubject ($return_subjecg) { $this->return_subject = $return_subjecg; }
	function setReturnTextMessage ($text_message) { $this->return_text = $text_message; }
	function setReturnHtmlMessage ($html_message) { $this->return_html = $html_message; }

	/**
	 * setSMTP
	 * Sets the parameters necessary for sending through SMTP
	 *
	 * @param String $host
	 * @param Int $port
	 * @param String $username
	 * @param String $password
	**/
	function setSMTP ( $host , $port , $username , $password ) {
		$this->smtp_settings['host'] = $host;
		$this->smtp_settings['port'] = $port;
		$this->smtp_settings['username'] = base64_encode ($username);
		$this->smtp_settings['password'] = base64_encode ($password);
		$this->smtp = true;
	}

	/**
	 * addCC, addBCC
	 * Adds an email address to the CC or BCC list
	 *
	 * @param String $name The new recipient's name
	 * @param String $email The new recipient's email address
	 *
	 * @Return Bool Whether or not the recipient was added
	**/
	function addCC ($name, $email) {
		foreach ($this->cc as $i) {
			if ($i['email'] == $email) return false;
		}
		array_push ($this->cc, array ('name' => $name , 'email' => $email));
		return true;
	}
	function addBCC ($name, $email) {
		foreach ($this->bcc as $i) {
			if ($i['email'] == $email) return false;
		}
		array_push ($this->bcc, array ('name' => $name , 'email' => $email));
		return true;
	}

	/**
	 * removeCC, removeBCC
	 * Searches to see if email address is in said list and deletes it.
	 *
	 * @param String $email email address to delete
	 *
	 * @return Bool True or false, if item was deleted.
	**/
	function removeCC ($email) { return $this->remove_from_array ($email, $this->cc); }
	function removeBCC ($email) { return $this->remove_from_array ($email, $this->bcc); }

	private function remove_from_array ($needle, &$array) {
		for ($cnt = 0; $cnt < sizeof ($array); $cnt++) {
			if ($array[$cnt]['email'] == $needle) {
				unset ($array[$cnt]);
				$array = array_values ($array);
				return true;
			}
		}
		return false;
	}
	/**
	 * Aliases for removeCC or removeBCC
	**/
	function deleteCC ($email) { return $this->removeCC ($email); }
	function deleteBCC ($email) { return $this->removeBCC ($email); }
	function delCC ($email) { return $this->removeCC ($email); }
	function delBCC ($email) { return $this->removeBCC ($email); }

	/**
	 * getCC, getBCC
	 * Returns the array of values
	**/
	function getCC() { return $this->cc; }
	function getBCC() { return $this->bcc; }

	/**
	 * setFile (and setAttachment)
	 * Adds the file information to the object
	 *
	 * @param Array $a
	 * $a is an associative array parsed as follows:
	 *		'filename' => the name of the file
	 *		'type' => the file's MIME-TYPE
	 *		'base64' => base64-encoded file contents
	**/
	function setFile ($a) {
		$this->file = $a;
	}
	function setAttachment ($a) {
		$this->file = $a;
	}
	/**
	 * reparseMail
	 * Meant to be run before message body is created, this
	 * function will change any variables passed.
	 * Variables that look like {$variable} will be replaced.
	 * Function changes actual string variable you passed in.
	 *
	 * @param String &$msg The message to send.
	 * @param Array $replace An array as follows:
	 *		(key) => (value)
	 *		(key) => (value)
	 *
	 * @return null
	**/
	function reparseMail (&$msg, $replace) {
		foreach ($replace as $key => $value) {
			$msg = str_replace ( "{\$".$key."}", $value, $msg );
		}
	}

	/**
	 * getEmailFromFile
	 * Reads an email from a file.
	 *
	 * @param String $filename Full or relative path required as server dictates.
	 *
	 * @return String Contents of File
	**/
	function GetEmailFromFile ($filename) {
		$fh = fopen ( $filename , "r" );
		if (!$fh) return flase;
		$full_file = '';
		while ( $line = fgets ( $fh ) ) {
			$full_file .= $line;
		}
		return $full_file;
	}
	/**
	 * send
	 * Handles the sending of the message and the return message if set.
	**/
	public function send () {
            echo 'inside send fun()::'.$this->text_message;
		$to = array (
			'name'=>$this->receiver['name'],
			'email'=>$this->receiver['email']
		);
		$from = array (
			'name'=>$this->sender['name'],
			'email'=>$this->sender['email']
		);
		echo "to:".var_dump($to);
                echo"txtmsg::".$this->text_message;
                echo "html msg::".$this->html_message;echo"end:::";
		$result = $this->send_message ($to, $from, $this->subject, $this->text_message, $this->html_message);

		if ($result && $this->send_return_message) {
			if (!$this->send_return_to_cc) $this->cc = array();
			if (!$this->send_return_to_bcc) $this->bcc = array();
			$a = $this->send_message ($from, $to, $this->return_subject, $this->return_text, $this->return_html);
		}

		return $result;
	}
/* ------------------------------------------------------------------------------------------ */
	/**
	 * to_header_string
	 * Breaks up an array of ['name'] ['email'] arrays into a string for the email header.
	 *
	 * @param String $type The email type, like Cc or Bcc.
	 * @param Array $emails The array of email addresses to add.
	 *
	 * @returns Mixed the String representation of the Array, or FALSE if something went wrong.
	**/
	function to_header_string ($type, $emails) {
		$return_string = '';
		foreach ($emails as $i) {
			$return_string .= "{$type}: {$i['name']} <{$i['email']}>\n";
		}
		return trim($return_string);
	}
	/**
	 * get_content_type_string
	 * Creates the Content-Type line for the header
	 *
	 * @param Int $msg_type The message type, so we know which header to create
	 * @param String $mime_boundary (if applicable) The boundary string for Multi-part emails.
	 *
	 * @return String the Content-Type, Mime-Version, etc -- well, the string to drop into the email header.
	**/
	private function get_content_type_string ($a,$mime_boundary = '') {
		if ($a & MSG_ATT)
			return "MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"mix-{$mime_boundary}\"";
		if ($a & MSG_TXT && $a & MSG_HTML)
			return "MIME-Version: 1.0\nContent-Type: multipart/alternative; charset=iso-8859-1; boundary=\"{$mime_boundary}\"";
		if ($a & MSG_TXT )
			return "Content-Type: text/plain; charset=iso-8859-1\nContent-Transfer-Encoding: 7bit";
		if ($a & MSG_HTML )
			return "Content-Type: text/html; charset=iso-8859-1";
	}

	/**
	 * sendViaSMTP
	 * Add-on to support SMTP email.
	 *
	**/
	private function send_via_smtp ($msg ) {
		//

		echo "
"; var_dump ($this->smtp_settings); echo "
";

		$smtp_connection = fsockopen ($this->smtp_settings['host'], $this->smtp_settings['port'] , $err_no , $err_string );
		if ( $smtp_connection ) {
			echo ":::smpt connected:::";
			$my_host = $_SERVER['HTTP_HOST'] != 'localhost' ? $_SERVER['HTTP_HOST'] : $_SERVER['REMOTE_ADDR'];

			$output = "EHLO {$my_host}\n";
			$still_connected = fputs ($smtp_connection, $output);
			echo "::1111::";
			if ( $still_connected ) {
                            echo "::2222::";
				$talk["hello"] = fgets ( $smtp_connection,1024 );
				$output = "auth login\n";
				$still_connected = fputs ($smtp_connection, $output);
			}

			if ( $still_connected ) {
                            echo "::333::";
				$talk["res"]=fgets($smtp_connection,1024);
				$output = $this->smtp_settings['username']."\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
                            echo "::4444::";
				$talk["user"]=fgets($smtp_connection,1024);
				$output = $this->smtp_settings['password']."\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
				$talk["pass"]=fgets($smtp_connection,256);
				$output = "MAIL FROM: <".$this->sender['email'].">\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
                            echo "::5555::";
				$talk["From"] = fgets ( $smtp_connection, 1024 );
				$output = "RCPT TO: <".$this->receiver['email'].">\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
                            echo "::66666::";
				$talk["To"] = fgets ($smtp_connection, 1024);
				$output = "DATA\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
                            echo "::77777::".$msg;
				$talk["data"]=fgets( $smtp_connection,1024 );
				$output = "To: <".$this->receiver['email'].">\nFrom: <".$this->receiver['email'].">\nSubject:".$this->subject."\n\n\n".$msg."\n.\n";
				$still_connected = fputs ($smtp_connection, $output);
			}
			if ( $still_connected ) {
                            echo "::88888::";
				$talk["send"]=fgets($smtp_connection,256);
				$still_connected = fputs ($smtp_connection, "QUIT\n");
				$result = true;
			}
			fclose($smtp_connection);
			//
		} else {
                    echo "smtp not connectted";
			$result = false;
		}
		return $result;
	}
	/**
	 * send_message
	 * Builds and sends the email using PHP's mail() function
	 *
	**/
	private function send_message ($to, $from, $subject, $txt_msg, $html_msg) {
		echo "inside send_message";
		if ($this->debug_mode);// echo "Parsing Info...
\n";

		@$sender_name = $from['name'];
		@$sender_email = $from['email'];
		@$recipient_name = $to['name'];
		@$recipient_email = $to['email'];
		@$file_info = $this->file;

		if ($this->debug_mode) echo "From: {$sender_name} <{$sender_email}>
To: {$recipient_name} <{$recipient_email}>
\n";

		if ( $sender_name == '' ||
			$sender_email == '' ||
			$recipient_email == ''
		) return FALSE;
		if ($this->debug_mode) echo "Creating Headers...
\n";

		$random_hash = md5(date('r', time()));
		$mime_boundary = "==PHP-alt-{$random_hash}";
		$phpversion = phpversion();

		$content_type = trim($this->get_content_type_string ($this->msg_type,$mime_boundary));
		$additional_headers = trim ($this->headers);
		$cc = $this->to_header_string ("Cc",$this->cc);
		$bcc = $this->to_header_string ("Bcc",$this->bcc);

		$headers = "From: {$sender_name} <{$sender_email}>\n";
		$headers .= "Reply-To: {$sender_name} <{$sender_email}>\n";
		$headers .= "X-MAILER: PHP/{$phpversion}\n";
		if ($cc) $headers .= "{$cc}\n";
		if ($bcc) $headers .= "{$bcc}\n";
		if ($additional_headers) $headers .= "{$additional_headers}\n";
		$headers .= "{$content_type}\n";
		$headers = trim($headers)."\n";

		$html_style = $this->css;
		echo "::msgType::".$this->msg_type;
		switch ($this->msg_type) {
// BEGIN TEXT MESSAGE -----------------------------------------------------------------------------------------------------------
			case 2:
                                echo "case 2";
				$total_msg = <<<EOR
{$html_msg}{$this->footer}
EOR;
				$total_msg = stripslashes ($total_msg);
				break;
// BEGIN HTML MESSAGE -----------------------------------------------------------------------------------------------------------
			case 1:
                                echo "case 1:msg::".$txt_msg;
				$total_msg = "{$txt_msg}\n\n\n";
				$total_msg .= "".strip_tags ($this->footer);
                                echo "ENENENEND::::".$total_msg;
				break;
// BEGIN FILE_ATTACHMENT MESSAGE ------------------------------------------------------------------------------------------------
			case 4:
                                echo "case 4";
				$txt_message_footer = strip_tags ($this->footer);
				$total_msg = <<<HTML_ALL

--mix-{$mime_boundary}
Content-Type: multipart/alternative; charset=utf-8; boundary="{$mime_boundary}"
--{$mime_boundary}
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
{$txt_msg}
----------
{$txt_message_footer}
--{$mime_boundary}
Content-Type: text/html; charset=iso-8859-1
{$html_msg}{$this->footer}
--{$mime_boundary}--
--mix-{$mime_boundary}
Content-Type: {$file_info['type']}; name="{$file_info['filename']}"
Content-Transfer-Encoding: base64
Content-Disposition: Attachment; filename="{$file_info['filename']}"
{$file_info['base64']}
--mix-{$mime_boundary}--
HTML_ALL;
				$total_msg = stripslashes ($total_msg);
				break;
// BEGIN HTML/TEXT MESSAGE ----------------------------------------------------------------------------------------------------
		case 3:
			default:
				$txt_footer = strip_tags ($this->footer);
				$total_msg = <<<HTXT
--{$mime_boundary}
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
{$txt_msg}
----------
{$txt_footer}
--{$mime_boundary}
Content-Type: text/html; charset=iso-8859-1
{$html_msg}
{$this->footer}
--{$mime_boundary}--
HTXT;
				$total_msg = stripslashes ($total_msg);
				break;
		}

		// the @ suppresses errors, and the mail() function will return a boolean of TRUE or FALSE.

		if ($this->debug_mode) {
                    echo ":::::debug_mode::";
			$p = "Mailto: {$recipient_name} <{$recipient_email}>\n".$headers.$total_msg;
			$p = htmlspecialchars ($p);
			echo "
\n{$p}\n
";
			$sendmail = TRUE;
		} elseif ($this->smtp) {
                    echo ":::::smtp::";
			$sendmail = $this->send_via_smtp ( $total_msg );
		} else {
			if (!$this->yahoo_type)
				@$sendmail = mail ($recipient_email, $subject, $total_msg, $headers);
			else
				@$sendmail = mail ($recipient_email, $subject, $total_msg, $headers, $this->additional_parameters);
		}

		return $sendmail;
	}
}
?>


text:
{-# LANGUAGE OverloadedStrings, FlexibleContexts, ImpredicativeTypes #-}
module Scheme.Evaluator
    ( eval
    , primitiveBindings
    ) where

import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.Either
import qualified Data.Text as T
import Safe

-- Not ideal but should in theory work for now
import System.Random

import Scheme.Types
import Scheme.Env
import Scheme.Primitives

import Debug.Trace

-- TODO: support other like cond/case expressions
eval :: LispEnv s -> LispVal s -> ST s (ThrowsError (LispVal s))
eval _ val@(String _) = return $ Right val
eval _ val@(Number _) = return $ Right val
eval _ val@(Bool _)   = return $ Right val
eval env (Atom id') = getVar env id'
eval _ (List [Atom "quote", val]) = return $ Right val

-- TODO: only accept Bool and throw on any other value
eval env (List [Atom "if", pred', conseq, alt]) = do
    result <- eval env pred'
    case result of
        Left _  -> return result
        Right val ->
            case val of
                Bool False -> eval env alt
                _          -> eval env conseq

eval env (List [Atom "set!", Atom var, form]) = do
    result <- eval env form
    case result of
        Left _  -> return result
        Right val -> setVar env var val

eval env (List [Atom "define", Atom var, form]) = do
    result <- eval env form
    case result of
        Left _  -> return result
        Right val -> defineVar env var val

eval env (List (Atom "define" : List (Atom var : params') : body')) =
    makeNormalFunc env params' body' >>= defineVar env var
eval env (List (Atom "define" : DottedList (Atom var : params') varargs : body')) =
    makeVarargs varargs env params' body' >>= defineVar env var

eval env (List (Atom "lambda" : List params' : body')) =
    liftM Right $ makeNormalFunc env params' body'

eval env (List (Atom "lambda" : DottedList params' varargs : body')) =
    liftM Right $ makeVarargs varargs env params' body'

eval env (List (Atom "lambda" : varargs@(Atom _) : body')) =
    liftM Right $ makeVarargs varargs env [] body'

-- TODO: abstract this out of the eval better later on
eval env (List (Atom "randInt" : val)) = randIntProc env val

eval env (List (function : args)) = do
    func <- eval env function
    case func of
        Left _   -> return func
        Right fval -> do
            argVals <- mapM (eval env) args
            -- TODO: make this better, we just grab the first error and
            -- return it up the stack instead of them all
            let (err, vals) = partitionEithers argVals

            if null err
            then apply fval vals
            else return $ Left $ headDef (Default "eval safehead") err

eval _ badForm = return $ Left $ BadSpecialForm "Unrecognized special form" (expand badForm)

makeFunc :: Show a => Maybe T.Text -> LispEnv s -> [a] -> [LispVal s] -> ST s (LispVal s)
makeFunc varargs env params' body' = return $ Func (map (T.pack . show) params') varargs body' env

makeNormalFunc :: LispEnv s -> [LispVal s] -> [LispVal s] -> ST s (LispVal s)
makeNormalFunc = makeFunc Nothing

makeVarargs :: LispVal s -> LispEnv s -> [LispVal s] -> [LispVal s] -> ST s (LispVal s)
makeVarargs = makeFunc . Just . T.pack . show

apply :: LispVal s -> [LispVal s] -> ST s (ThrowsError (LispVal s))
apply (PrimitiveFunc func) args = return $ func args
apply (StatefulFunc func) args = func args
apply (Func params' varargs body' closure') args =
    if num params' /= num args && isNothing varargs
    then return $ Left $ NumArgs (num params') (map expand args)
    else envEval params' varargs body' closure' args

-- TODO: this doesn't seem right
apply var (PrimitiveFunc func : args) = return $ func (var : args)

-- Fallthrough - debugging
-- TODO: clean up the trace
apply func args = traceShow ("apply-debug:" :: String, func, args) $ return $ Right func

num :: [a] -> Integer
num = toInteger . length

remainingArgs :: [a] -> [b] -> [b]
remainingArgs params' = drop (length params')

evalBody :: [LispVal s] -> LispEnv s -> ST s (ThrowsError (LispVal s))
evalBody body' env = liftM (lastDef (Left $ Default "evalBody - last")) $ mapM (eval env) body'

envEval :: [T.Text] -> Maybe T.Text -> [LispVal s] -> LispEnv s -> [LispVal s] -> ST s (ThrowsError (LispVal s))
envEval params' varargs body' closure' args = do
    env  <- bindVars closure' $ zip params' args
    env' <- bindVarArgs params' args varargs env
    evalBody body' env'

bindVarArgs :: [a] -> [LispVal s] -> Maybe T.Text -> LispEnv s -> ST s (LispEnv s)
bindVarArgs params' args arg env = case arg of
    Just argName -> bindVars env [(argName, List $ remainingArgs params' args)]
    Nothing -> return env

-- TODO: another semi-hack this probably should be half in primitive and half not for stateful primitives
primitiveBindings :: ST s (LispEnv s)
primitiveBindings = nullEnv >>= flip bindVars (map (makeFunc' PrimitiveFunc) primitives ++ map (makeFunc' StatefulFunc) closurePrimitives)
     where makeFunc' constructor (var, func) = (var, constructor func)

-- Primitives that closes over some nested environment
closurePrimitives :: [(T.Text, [LispVal s] -> ST s (ThrowsError (LispVal s)))]
closurePrimitives = [ ("apply", applyProc) ]

-- TODO: need to pattern match []
applyProc :: [LispVal s] -> ST s (ThrowsError (LispVal s))
applyProc [func, List args] = apply func args
applyProc (func : args)     = apply func args
applyProc []                = return $ Left $ Default "applyProc booper"

-- TODO: add in support for handling a list vs 2 integers
randIntProc :: LispEnv s -> [LispVal s] -> ST s (ThrowsError (LispVal s))

-- TODO: custom handling to handle being handed an "variable" instead of
-- a hardcoded number to support reuse in define
randIntProc env [Atom n]   = do
    var <- getVar env n
    case var of
        Left err  -> return $ Left err
        Right val -> randIntProc env [val]

randIntProc env [Number n] = do
    gen <- getVar env "stdRngGen"
    case gen of
        Left err -> return $ Left err
        Right (Random gen') -> do
            let (val, gen'') = randomR (1, n) gen'
            _ <- setVar env "stdRngGen" (Random gen'')

            return $ Right $ Number val
        -- TODO: non-exhaustive pattern matches
        Right _ -> return $ Left $ Default "randIntProc booper"

randIntProc _ [badArg]          = return $ Left $ TypeMismatch "Number" (expand badArg)
randIntProc _ badArgList        = return $ Left $ NumArgs 1 (map expand badArgList)


text:
(function () {
    angular.module('documentation', [

    ]);
})();


text:
package :setup_system do
  requires :create_deployer_user, :system_settings
end

package :system_settings do
  %w[LC_ALL LANG LC_CTYPE].each do |lang|
    runner "sh -c \"echo '#{lang}=en_US.UTF-8' >> /etc/environment\""

    verify do
      @commands << "cat /etc/environment | grep \"#{lang}=en_US.UTF-8\""
    end
  end
end


text:
I need some cash, so I have to find an ATM (Automated Teller Machine).

# Problem

Money withdrawal is under control. Everyone has a personal bank account which is only accessible with a specific credit card and a related code.

For this reason, we cannot interact directly with the "real" object (our bank account). We must interact with another object that will be responsible for the communication with the real object.

# Solution

We could consider an ATM as a proxy whose aim is to verify access to a bank account. Here the Proxy design pattern requires:

  * An abstract representation of a financial entity (abstract class or interface)
  * A concrete bank account which allows some operations
  * A proxy (ATM) which secures these operations and delegates when necessary

![Proxy (classic)](Proxy.png)


text:
/* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
 *******************************************************************************
 * Copyright (C) 2014, International Business Machines Corporation and         *
 * others. All Rights Reserved.                                                *
 *******************************************************************************
 */
package android.icu.dev.test.format;

import org.junit.Test;

import android.icu.dev.test.TestFmwk;
import android.icu.text.DecimalFormat;
import android.icu.text.NumberFormat;
import android.icu.text.ScientificNumberFormatter;
import android.icu.util.ULocale;

/**
 * @author rocketman
 *
 */
public class ScientificNumberFormatterTest extends TestFmwk {
    @Test
    public void TestBasic() {
        ScientificNumberFormatter markup = ScientificNumberFormatter.getMarkupInstance(
                ULocale.ENGLISH, "", "");
        ScientificNumberFormatter superscript = ScientificNumberFormatter.getSuperscriptInstance(ULocale.ENGLISH);
        assertEquals(
                "toMarkupExponentDigits",
                "1.23456×10-78",
                markup.format(1.23456e-78));
        assertEquals(
                "toSuperscriptExponentDigits",
                "1.23456×10⁻⁷⁸",
                superscript.format(1.23456e-78));
    }

    @Test
    public void TestFarsi() {
        ScientificNumberFormatter fmt = ScientificNumberFormatter.getMarkupInstance(
                new ULocale("fa"), "", "");
        assertEquals(
                "",
                "۱٫۲۳۴۵۶×۱۰−۷۸",
                fmt.format(1.23456e-78));
    }

    @Test
    public void TestPlusSignInExponentMarkup() {
        DecimalFormat decfmt = (DecimalFormat) NumberFormat.getScientificInstance(ULocale.ENGLISH);
        decfmt.applyPattern("0.00E+0");
        ScientificNumberFormatter fmt = ScientificNumberFormatter.getMarkupInstance(
                decfmt, "", "");

        assertEquals(
                "",
                "6.02×10+23",
                fmt.format(6.02e23));
    }

    @Test
    public void TestPlusSignInExponentSuperscript() {
        DecimalFormat decfmt = (DecimalFormat) NumberFormat.getScientificInstance(ULocale.ENGLISH);
        decfmt.applyPattern("0.00E+0");
        ScientificNumberFormatter fmt = ScientificNumberFormatter.getSuperscriptInstance(
                decfmt);
        assertEquals(
                "",
                "6.02×10⁺²³",
                fmt.format(6.02e23));
    }

    @Test
    public void TestFixedDecimalMarkup() {
        DecimalFormat decfmt = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH);
        ScientificNumberFormatter fmt = ScientificNumberFormatter.getMarkupInstance(
                decfmt, "", "");
        assertEquals(
                "",
                "123,456",
                fmt.format(123456.0));
    }

    @Test
    public void TestFixedDecimalSuperscript() {
        DecimalFormat decfmt = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH);
        ScientificNumberFormatter fmt = ScientificNumberFormatter.getSuperscriptInstance(decfmt);
        assertEquals(
                "",
                "123,456",
                fmt.format(123456.0));
    }
}


text:
Cacti asp.net mvc extensions
=============

A set of common use extensions, filters and helpers for asp.net MVC

Installation
------------

    Install-Package Cacti.Mvc.Web

To avoid importing namespaces in your views add `Cacti.Mvc.Web` to your Views/Web.config
```xml
<system.web.webPages.razor>
   <namespaces>
      <add namespace="Cacti.Mvc.Web"/>
   </namespaces>
</system.web.webPages.razor>
```
HTML helpers
------------
* DropDownGroupFor
* DescriptionFor
* CleanTextBoxFor

Filters
-------
* AutoRefreshAttribute

Attributes
----------
* MaxFileSizeAttribute

Routes
------
* NotEqual constraint

Extensions
----------
* DateTime (ToUnix, ToJavascript)


text:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace FluentFTP {
	public partial class AsyncFtpClient {

		/// <summary>
		/// Disconnects from the server asynchronously
		/// </summary>
		public async Task Disconnect(CancellationToken token = default(CancellationToken)) {
			if (m_stream != null && m_stream.IsConnected) {
				try {
					if (Config.DisconnectWithQuit) {
						await Execute("QUIT", token);
					}
				}
				catch (Exception ex) {
					LogWithPrefix(FtpTraceLevel.Warn, "AsyncFtpClient.Disconnect(): Exception caught and discarded while closing control connection: " + ex.ToString());
				}
				finally {
					m_stream.Close();
				}
			}
		}

	}
}


text:
<html><head><link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/paper-styles/paper-styles.html">

</head><body><dom-module id="shared-styles">
  <template>
    <style>
      :root {
        --app-evt-red: #da291c;
        --app-unit-base: 8px;

        --app-unit-xs: calc(var(--app-unit-base) * 0.5);
        --app-unit-sm: calc(var(--app-unit-base) * 1);
        --app-unit-md: calc(var(--app-unit-base) * 2);
        --app-unit-lg: calc(var(--app-unit-base) * 4);
        --app-unit-xl: calc(var(--app-unit-base) * 8);

        --app-max-page-width: calc(var(--app-unit-xl) * 12);

        --app-header-color: var(--paper-grey-50);
        --app-drawer-color: var(--paper-grey-800);
        --app-drawer-item-height: 40px;

        --app-image-placeholder-background: var(--paper-grey-200);
        --app-details-background: var(--paper-grey-200);
        --app-chip-color: var(--paper-grey-200);
        --app-property-text-color: var(--paper-grey-700);

        --app-boolean-property-color: var(--paper-blue-grey-500);
        --app-boolean-text-color: var(--app-property-text-color);

        --app-string-property-color: var(--paper-amber-500);
        --app-string-text-color: var(--app-property-text-color);

        --app-number-property-color: var(--paper-cyan-500);
        --app-number-text-color: var(--app-property-text-color);

        --paper-toggle-button-checked-bar-color:  var(--paper-grey-900);
        --paper-toggle-button-checked-button-color:  var(--paper-grey-50);
        --paper-toggle-button-checked-ink-color: var(--paper-grey-50);

        --paper-fab-background: var(--app-evt-red);

        --app-circle: {
          border-radius: 50%;
        };

        --app-code-font: {
          font-family: monospace;
        };

        --app-page: {
          max-width: var(--app-max-page-width);
          margin: var(--app-unit-md) auto;
        };

        --app-list-item: {
          @apply(--layout-horizontal);

          padding: var(--app-unit-xs);
          border-top: 1px solid var(--paper-grey-100);
        };

        --app-layout-flex-25: {
          @apply(--layout-flex);

          width: 25%;
        };

        --app-layout-flex-33: {
          @apply(--layout-flex);

          width: 33.33%;
        };

        --app-layout-flex-50: {
          @apply(--layout-flex);

          width: 50%;
        };

        --app-layout-flex-66: {
          @apply(--layout-flex);

          width: 66.66%;
        };

        --app-layout-fit-drawer: {
          width: 100%;
          height: 100%;

          display: block;
        };

        --app-drawer-dark-theme: {
          color: var(--dark-theme-secondary-color);
          background-color: var(--app-drawer-color);
        };

        --app-muted: {
          color: var(--paper-grey-400);
        }
      }

      paper-material {
        background-color: white;

        margin: var(--app-unit-md);
        padding: var(--app-unit-sm);
        color: var(--paper-grey-700);
        border-radius: 2px;
      }

      app-header {
        @apply(--shadow-elevation-2dp);
        background-color: var(--app-header-color);
      }

      app-drawer-layout {
        transition: all .5s ease;
        transform-origin: bottom;
        overflow: hidden;
        height: 100vh;
        background-color: var(--paper-grey-200);

        @apply(--shadow-elevation-16dp);
      }

      app-drawer > container {
        @apply(--app-layout-fit-drawer);
        @apply(--app-drawer-dark-theme);
        @apply(--shadow-elevation-12dp);

        background-color: var(--app-drawer-color);
      }

      app-drawer > container section {
        margin-bottom: var(--app-unit-sm);
      }

      app-drawer > container section > label {
        font-size: var(--app-unit-sm);
      }

      app-drawer footer {
        width: 100%;
        display: block;
        position: absolute;
        bottom: 140px;
      }

      app-drawer .th-powered-by {

        color: currentColor;
        text-decoration: none;

        @apply(--layout-horizontal);
        @apply(--layout-center);
        @apply(--layout-center-justified);
      }

      app-drawer .th-powered-by img {
        margin-left: var(--app-unit-sm);
      }

      app-header paper-icon-button {
        --paper-icon-button-ink-color: white;
      }

      .header-logo {
        padding: var(--app-unit-md);

        @apply(--layout-vertical);
        @apply(--layout-center);
      }

      .header-logo > img {
        height: var(--app-unit-xl);
        filter: grayscale(100%) brightness(164%);
      }

      .mini-logo {
        width: var(--app-unit-lg);
        height: var(--app-unit-lg);
      }

      .empty-message {
        text-align: center;
      }

      .list-footer {
        text-align: center;
        font-size: var(--app-unit-sm);
      }

      .circle {
        @apply(--app-circle);

        display: inline-block;

        width: var(--app-unit-xl);
        height: var(--app-unit-xl);

        text-align: center;

        color: var(--paper-grey-700);
        background: var(--app-image-placeholder-background);

        font-size: var(--app-unit-md);
        line-height: var(--app-unit-xl);
      }

      h1 {
        margin: 16px 0;

        color: #212121;

        font-size: 22px;
      }

      hr {
        margin: 2px 0;
        height: 1px;

        background-color: var(--dark-theme-text-color);
        opacity: .1;
        border: 0px solid;
      }

      .drawer-item {
        display: block;
        text-decoration: none;

        font-size: 14px;
        line-height: 48px;
        color: var(--dark-theme-secondary-color);

        padding: 0 var(--app-unit-md);

        transition: all .3s ease;
      }

      .drawer-item.iron-selected,
      .drawer-item:hover {
        color: var(--dark-theme-text-color);
        background-color: var(--dark-theme-background-color);
      }

      .drawer-item > iron-icon {
        margin-right: var(--app-unit-md);
      }

      .th-dropdown-content {
        @apply(--shadow-elevation-4dp);
        @apply(--layout-block);

        min-width: 300px;
        background-color: var(--paper-grey-50);
      }

      .th-dropdown-content iron-icon {
        margin-right: var(--app-unit-md);
      }

      .th-entity-image {
        @apply(--app-circle);

        width: var(--app-unit-xl);
        min-width: var(--app-unit-xl);
        height: var(--app-unit-xl);
        background-color: var(--app-image-placeholder-background);
      }

      .th-entity-name {
        @apply(--paper-font-title);
        @apply(--paper-font-common-nowrap);

        font-size: 1.1em;
      }

      .th-entity-id {
        @apply(--paper-font-subhead);
        @apply(--paper-font-common-nowrap);
        @apply(--app-muted);

        font-size: 1em;
      }

      .target-environment {
        @apply(--layout-horizontal);
      }

      .target-environment > span {
        margin-right: var(--app-unit-sm);
      }

      .target-environment > iron-icon {
        @apply(--layout-self-center);
      }

      .paper-item-link {
        color: inherit;
        text-decoration: none;
      }

      .muted {
        color: var(--paper-grey-700);
      }

    </style>
  </template>
</dom-module>
</body></html>


text:
module Workbook
  class Row
    include Workbook::Modules::Cache
    include Enumerable
    extend Forwardable

    attr_accessor :placeholder # The placeholder attribute is used in compares (corresponds to newly created or removed lines (depending which side you're on)
    attr_accessor :format
    attr_reader :cells

    delegate [:first, :last, :pop, :delete_at, :each, :count, :include?, :index, :delete_if, :to_csv, :length, :empty?] => :@cells

    # Initialize a new row
    #
    # @param [Workbook::Row, Array<Workbook::Cell>, Array] cells list of cells to initialize the row with, default is empty
    # @param [Workbook::Table] table a row normally belongs to a table, reference it here
    # @param [Hash] options  Supported options: parse_cells_on_batch_creation (parse cell values during row-initalization, default: false), cell_parse_options (default {}, see Workbook::Modules::TypeParser)
    def initialize cells = [], table = nil, options = {}
      options = options ? {parse_cells_on_batch_creation: false, cell_parse_options: {}, clone_cells: false}.merge(options) : {}
      @cells = []
      add_cells(cells, options)
      self.table = table
    end

    # An internal function used in diffs
    #
    # @return [Boolean] returns true when this row is not an actual row, but a placeholder row to 'compare' against
    def placeholder?
      placeholder ? true : false
    end

    # Returns the table this row belongs to
    #
    # @return [Workbook::Table] the table this row belongs to
    def table
      @table if defined?(@table)
    end

    # Set reference to the table this row belongs to without adding the row to the table
    #
    # @param [Workbook::Table] t the table this row belongs to
    def set_table(t)
      @table = t
    end

    # Set reference to the table this row belongs to and add the row to this table
    #
    # @param [Workbook::Table] t the table this row belongs to
    def table= t
      raise ArgumentError, "table should be a Workbook::Table (you passed a #{t.class})" unless t.is_a?(Workbook::Table) || t.nil?
      if t
        @table = t
        table << self
      end
    end

    # Add row
    # @param [Workbook::Table, Array] row(s) to add
    def push(*args)
      args.each do |arg|
        self.<<(arg)
      end
    end
    alias_method :append, :push

    # Add cell
    # @param [Workbook::Cell, Numeric,String,Time,Date,TrueClass,FalseClass,NilClass] cell or value to add
    def <<(cell)
      @cells << (cell.is_a?(Workbook::Cell) ? cell : Workbook::Cell.new(cell, {row: self}))
    end

    # plus
    # @param [Workbook::Row, Array] row to add
    # @return [Workbook::Row] a new row, not linked to the table
    def +(other)
      Workbook::Row.new(@cells + Row.new(other).cells)
    end

    # concat
    # @param [Workbook::Row, Array] row to add
    # @return [self] self
    def concat(row)
      @cells.concat(Workbook::Row.new(row).cells)
      self
    end

    # Overrides normal Array's []-function with support for symbols that identify a column based on the header-values and / or
    #
    # @example Lookup using fixnum or header value encoded as symbol
    #   row[1] #=> <Cell value="a">
    #   row["A"] #=> <Cell value="a">
    #   row[:a] #=> <Cell value="a">
    #
    # @param [Integer, Symbol, String] index_or_hash that identifies the column (strings are converted to symbols)
    # @return [Workbook::Cell, nil]
    def [](index_or_hash)
      if index_or_hash.is_a? Symbol
        rv = nil
        begin
          rv = to_hash[index_or_hash]
        rescue NoMethodError
        end
        rv
      elsif index_or_hash.is_a?(String) && index_or_hash.match(/^[A-Z]*$/)
        # it looks like a column indicator
        @cells[Workbook::Column.alpha_index_to_number_index(index_or_hash)]
      elsif index_or_hash.is_a? String
        symbolized = Workbook::Cell.new(index_or_hash, {row: self}).to_sym
        self[symbolized]
      elsif index_or_hash
        @cells[index_or_hash]
      end
    end

    # Overrides normal Array's []=-function with support for symbols that identify a column based on the header-values
    #
    # @example Lookup using fixnum or header value encoded as symbol (strings are converted to symbols)
    #   row[1] #=> <Cell value="a">
    #   row[:a] #=> <Cell value="a">
    #
    # @param [Integer, Symbol, String] index_or_hash that identifies the column
    # @param [String, Integer, NilClass, Date, DateTime, Time, Float] value
    # @return [Workbook::Cell, nil]
    def []= index_or_hash, value
      index = index_or_hash
      if index_or_hash.is_a? Symbol
        index = table_header_keys.index(index_or_hash)
      elsif index_or_hash.is_a?(String) && index_or_hash.match(/^[A-Z]*$/)
        # it looks like a column indicator
        index = Workbook::Column.alpha_index_to_number_index(index_or_hash)
      elsif index_or_hash.is_a? String
        symbolized = Workbook::Cell.new(index_or_hash, {row: self}).to_sym
        index = table_header_keys.index(symbolized)
      end

      value_celled = Workbook::Cell.new
      if value.is_a? Workbook::Cell
        value_celled = value
      else
        current_cell = @cells[index]
        if current_cell.is_a? Workbook::Cell
          value_celled = current_cell
        end
        value_celled.value = value
      end
      value_celled.row = self
      @cells[index] = value_celled
    end

    # Returns an array of cells allows you to find cells by a given color, normally a string containing a hex
    #
    # @param [String] color  a CSS-style hex-string
    # @param [Hash] options Option :hash_keys (default true) returns row as an array of symbols
    # @return [Array<Symbol>, Workbook::Row<Workbook::Cell>]
    def find_cells_by_background_color color = :any, options = {}
      options = {hash_keys: true}.merge(options)
      found_cells = @cells.collect { |c| c if c.format.has_background_color?(color) }.compact
      r = Row.new found_cells
      options[:hash_keys] ? r.to_symbols : r
    end

    # Returns true when the row belongs to a table and it is the header row (typically the first row)
    #
    # @return [Boolean]
    def header?
      !table.nil? && (object_id == table_header.object_id)
    end

    # Is this the first row in the table
    #
    # @return [Boolean, NilClass] returns nil if it doesn't belong to a table, false when it isn't the first row of a table and true when it is.
    def first?
      !table.nil? && (object_id == table.first.object_id)
    end

    # Returns true when all the cells in the row have values whose to_s value equals an empty string
    #
    # @return [Boolean]
    def no_values?
      @cells.all? { |c| c.value.to_s == "" }
    end

    # Converts a row to an array of symbol representations of the row content, see also: Workbook::Cell#to_sym
    # @return [Array<Symbol>] returns row as an array of symbols
    def to_symbols
      fetch_cache(:to_symbols) {
        @cells.collect { |c| c.to_sym }
      }
    end

    # Converts the row to an array of Workbook::Cell's
    # @return [Array<Workbook::Cell>] returns row as an array of symbols
    def to_a
      @cells
    end

    def table_header
      table.header
    end

    def table_header_keys
      table_header.to_symbols
    end

    # Returns a hash representation of this row
    #
    # @return [Hash]
    def to_hash
      keys = table_header_keys
      values = @cells
      hash = {}
      keys.each_with_index { |k, i| hash[k] = values[i] }
      hash
    end

    # Quick assessor to the book's template, if it exists
    #
    # @return [Workbook::Template]
    def template
      table&.template
    end

    # Returns a hash representation of this row
    #
    # it differs from #to_hash as it doesn't contain the Workbook's Workbook::Cell-objects,
    # but the actual values contained in these cells
    #
    # @return [Hash]

    def to_hash_with_values
      @hash_with_values = {}
      table_header_keys.each_with_index { |k, i| @hash_with_values[k] = @cells[i]&.value }
      @hash_with_values
    end

    # Compares one row wiht another
    #
    # @param [Workbook::Row] other row to compare against
    # @return [Workbook::Row] a row with the diff result.
    def <=> other
      a = header? ? 0 : 1
      b = other.header? ? 0 : 1
      return (a <=> b) if (a == 0) || (b == 0)
      @cells <=> other.cells
    end

    def == other
      @cells.map(&:value) == other.is_a?(Workbook::Row) ? other.cells.map(&:value) : other
    end

    # The first cell of the row is considered to be the key
    #
    # @return [Workbook::Cell] the key cell
    def key
      first
    end

    # Compact detaches the row from the table
    def compact
      clone.collect { |c| c unless c.nil? }.compact
    end

    # clone the row with together with the cells
    #
    # @return [Workbook::Row] a cloned copy of self with cells
    def clone
      Workbook::Row.new(self, nil, {clone_cells: true})
    end

    # remove all the trailing nil-cells (returning a trimmed clone)
    #
    # @param [Integer] desired_length of the new row
    # @return [Workbook::Row] a trimmed clone of the array
    def trim(desired_length = nil)
      clone.trim!(desired_length)
    end

    # remove all the trailing nil-cells (returning a trimmed self)
    #
    # @param [Integer] desired_length of the new row
    # @return [Workbook::Row] self
    def trim!(desired_length = nil)
      self_count = count - 1
      count.times do |index|
        index = self_count - index
        if desired_length && (index < desired_length)
          break
        elsif desired_length && (index >= desired_length)
          delete_at(index)
        elsif self[index].nil?
          delete_at(index)
        else
          break
        end
      end
      (desired_length - count).times { |a| @cells << Workbook::Cell.new(nil) } if desired_length && ((desired_length - count) > 0)
      self
    end

    private

    # Only to be used on initialization
    # @param [Workbook::Row, Array<Workbook::Cell>, Array] cells list of cells to initialize the row with, default is empty
    # @param [Hash] options  Supported options: parse_cells_on_batch_creation (parse cell values during row-initalization, default: false), cell_parse_options (default {}, see Workbook::Modules::TypeParser)
    def add_cells cells = [], options = {}
      return nil if cells.nil?
      cells.each do |c|
        @cells << (prepare_cell(c, options))
      end
    end

    def prepare_cell cell, options
      if cell.is_a? Workbook::Cell
        cell = cell.clone if options[:clone_cells]
      else
        cell = Workbook::Cell.new(cell, {row: self})
        cell.parse!(options[:cell_parse_options]) if options[:parse_cells_on_batch_creation]
      end

      cell
    end
  end
end


text:
using System.Threading;
using LightBDD.Core.Results;

namespace LightBDD.Framework.Notification.Implementation
{
    internal class ProgressManager
    {
        private readonly object _sync = new object();
        private readonly AsyncLocal<int?> _currentScenarioId = new AsyncLocal<int?>();
        private int _totalScenarios;
        private int _finishedScenarios;
        private int _pendingScenarios;
        private int _failedScenarios;

        public ProgressState GetProgress()
        {
            lock (_sync)
                return new ProgressState(_finishedScenarios, _pendingScenarios, _failedScenarios, _currentScenarioId.Value);
        }

        public void StartNewScenario()
        {
            _currentScenarioId.Value = Interlocked.Increment(ref _totalScenarios);
            lock (_sync)
                ++_pendingScenarios;
        }

        public void CaptureScenarioResult(ExecutionStatus scenarioStatus)
        {
            lock (_sync)
            {
                ++_finishedScenarios;
                if (scenarioStatus == ExecutionStatus.Failed)
                    ++_failedScenarios;
                --_pendingScenarios;
            }
        }

        public void FinishScenario()
        {
            _currentScenarioId.Value = null;
        }
    }
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

# overloading pickle to have it find the PackedDBobj in this module
import pickle

try:
    from cStringIO import StringIO
except ImportError:
    from StringIO import StringIO

renametable = {
        'src.typeclasses.models': 'src.objects.migrations.0019_convert_attrdata',
        'PackedDBobject': 'PackedDBobject',
}

def mapname(name):
    if name in renametable:
        return renametable[name]
    return name

def mapped_load_global(self):
    module = mapname(self.readline()[:-1])
    name = mapname(self.readline()[:-1])
    klass = self.find_class(module, name)
    self.append(klass)

def loads(str):
    file = StringIO(str)
    unpickler = pickle.Unpickler(file)
    unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
    return unpickler.load()

class PackedDBobject(object):
    """
    Attribute helper class.
    A container for storing and easily identifying database objects in
    the database (which doesn't suppport storing db_objects directly).
    """
    def __init__(self, ID, db_model, db_key):
        self.id = ID
        self.db_model = db_model
        self.key = db_key
    def __str__(self):
        return "%s(#%s)" % (self.key, self.id)
    def __unicode__(self):
        return u"%s(#%s)" % (self.key, self.id)

try:
    from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
    from django.contrib.auth.models import User
else:
    User = get_user_model()

user_orm_label = '%s.%s' % (User._meta.app_label, User._meta.object_name)
user_model_label = '%s.%s' % (User._meta.app_label, User._meta.module_name)
user_ptr_name = '%s_ptr' % User._meta.object_name.lower()

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Deleting field 'ObjAttribute.db_mode'

        if not db.dry_run:
            for attr in orm["objects.ObjAttribute"].objects.all():
                # resave attributes
                db_mode = attr.db_mode
                if db_mode and db_mode != 'pickle':
                    # an object. We need to resave this.
                    if db_mode == 'object':
                        val = PackedDBobject(attr.db_value, "objectdb")
                    elif db_mode == 'player':
                        val = PackedDBobject(attr.db_value, "playerdb")
                    elif db_mode == 'script':
                        val = PackedDBobject(attr.db_value, "scriptdb")
                    elif db_mode == 'help':
                        val = PackedDBobject(attr.db_value, "helpentry")
                    else:
                        val = PackedDBobject(attr.db_value, db_mode) # channel, msg
                    attr.value = val

        db.delete_column('objects_objattribute', 'db_mode')

    def backwards(self, orm):

        # Adding field 'ObjAttribute.db_mode'
        db.add_column('objects_objattribute', 'db_mode', self.gf('django.db.models.fields.CharField')(max_length=20, null=True, blank=True), keep_default=False)

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        user_model_label: {
            'Meta': {'object_name': User.__name__, 'db_table': "'%s'" % User._meta.db_table},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'objects.alias': {
            'Meta': {'object_name': 'Alias'},
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'objects.nick': {
            'Meta': {'unique_together': "(('db_nick', 'db_type', 'db_obj'),)", 'object_name': 'Nick'},
            'db_nick': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}),
            'db_real': ('django.db.models.fields.TextField', [], {}),
            'db_type': ('django.db.models.fields.CharField', [], {'default': "'inputline'", 'max_length': '16', 'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'objects.objattribute': {
            'Meta': {'object_name': 'ObjAttribute'},
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']"}),
            'db_value': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'objects.objectdb': {
            'Meta': {'object_name': 'ObjectDB'},
            'db_cmdset_storage': ('django.db.models.fields.TextField', [], {'null': 'True'}),
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_home': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'homes_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'db_location': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations_set'", 'null': 'True', 'to': "orm['objects.ObjectDB']"}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
            'db_player': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['players.PlayerDB']", 'null': 'True', 'blank': 'True'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        'players.playerdb': {
            'Meta': {'object_name': 'PlayerDB'},
            'db_date_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'db_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'db_lock_storage': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
            'db_obj': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['objects.ObjectDB']", 'null': 'True'}),
            'db_permissions': ('django.db.models.fields.CharField', [], {'max_length': '512', 'blank': 'True'}),
            'db_typeclass_path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_orm_label, 'unique': 'True'})
        }
    }

    complete_apps = ['objects']


text:
using System.Linq;
using AutoQueryable.Core.Clauses;

namespace AutoQueryable.Core.Models
{
    public interface IAutoQueryableContext
    {
        dynamic GetAutoQuery<T>(IQueryable<T> query) where T : class;
        IClauseValueManager ClauseValueManager { get; }
        IQueryable<dynamic> TotalCountQuery { get; }
        string QueryString { get; }
    }

}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid cite: userinfo-password-contains-pile-of-poo</title>


text:
namespace RISE
{
	///////////////////////////////////////////////////////////////////////
	// The ValueGenerator is what takes a key type and generates an actual
	// cache item
	///////////////////////////////////////////////////////////////////////
	template<typename Key, typename	Value>
	struct ValueGenerator
	{
		virtual ~ValueGenerator(){}
		virtual Value * Get( const Key& k ) = 0;
		virtual void Return( const Key& k, Value * v ) = 0;
	};

	///////////////////////////////////////////////////////////////////////
	// The MRUCache
	///////////////////////////////////////////////////////////////////////
	template<typename Key, typename Value>
	class MRUCache :
		public ValueGenerator<Key, Value>
	{
		typedef std::pair<Key, Value *> Item;
		static inline bool ItemCompare( const Item& lhs, const Item& rhs )
		{
			return lhs.first < rhs.first;
		}

		struct KeyFind
		{
			const Key& k;
			KeyFind(const Key& k_) : k(k_){}

			inline bool operator()( const Item& rhs ) const
			{
				return rhs.first == k;
			}
		};

		typedef std::list<Item> ItemList;
		ItemList mru;

		ValueGenerator<Key, Value>& gen;
		size_t item_count;

		inline Value * CacheGetAndRemove( const Key& k )
		{
			typename ItemList::iterator it = std::find_if( mru.begin(), mru.end(), KeyFind(k) );
			if( it == mru.end() ) {
				return 0;
			}

			Value * ret = it->second;
			mru.erase(it);
			return ret;
		}

		inline void CacheInsert( const Key& k, Value * v )
		{
			mru.push_front(Item(k, v));
		}

		inline void ControlSize()
		{
			const size_t mru_size = mru.size();
			if(mru_size > item_count)
			{
				size_t to_remove = mru_size - item_count;
				for( ;to_remove > 0; --to_remove )
				{
					Item& item = mru.back();
					gen.Return(item.first, item.second);
					mru.pop_back();
				}
			}
		}

	public:
		MRUCache(ValueGenerator<Key, Value>& gen_, size_t item_count_) :
		gen(gen_), item_count(item_count_)
		{
		}

		virtual ~MRUCache()
		{
			for( typename ItemList::iterator it = mru.begin(); it != mru.end(); ++it ) {
				gen.Return(it->first, it->second);
				it->second = 0;
			}
			mru.clear();
		}

		virtual Value * Get(const Key& k)
		{
			Value * ret = CacheGetAndRemove(k);
			if(!ret) {
				ret = gen.Get(k);
			}
			return ret;
		}

		virtual void Return(const Key& k, Value * v)
		{
			if(!v) {
				return;
			}

			Value * temp = CacheGetAndRemove(k);
			if(temp && temp != v) {
				gen.Return(k, v);
			}

			CacheInsert(k, v);
			ControlSize();
		}
	};
}

#endif //MRUCACHE_


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yue.Common.Repository;
using Yue.Users.Model;
using Dapper;

namespace Yue.Users.Repository
{
    public class UserRepository : BaseRepository, IUserRepository
    {
        public UserRepository(SqlOption option) : base(option) { }

        private static readonly string[] _userColumns = new string[] {
"UserId", "Email", "Name", "State", "CreateBy", "UpdateBy", "CreateAt", "UpdateAt" };

        public User Get(int userId)
        {
            using (IDbConnection connection = OpenConnection())
            {
                var user = connection.Query<User>(
                     string.Format(@"SELECT {0} FROM `users` WHERE `UserId` = @UserId;",
                     SqlHelper.Columns(_userColumns)),
                     new { UserId = userId }).SingleOrDefault();
                return user;
            }
        }

        public User UserByEmail(string email)
        {
            using (IDbConnection connection = OpenConnection())
            {
                var user = connection.Query<User>(
                     string.Format(@"SELECT {0} FROM `users` WHERE `Email` = @Email;",
                     SqlHelper.Columns(_userColumns)),
                     new { Email = email }).SingleOrDefault();
                return user;
            }
        }

        public IEnumerable<User> Users(IEnumerable<int> ids)
        {
            using (IDbConnection connection = OpenConnection())
            {
                var users = connection.Query<User>(
                     string.Format(@"SELECT {0} FROM `users` WHERE `UserId` in @ids;",
                     SqlHelper.Columns(_userColumns)),
                     new { ids = ids });
                return users;
            }
        }
    }
}


text:
<?php

class User extends BaseModel
{
    protected $fillable = ['username', 'name', 'email', 'password'];

    protected $rules = array(
        'name'                  => 'required|alpha|min:2',
        'username'              => 'required|unique:users',
        'email'                 => 'required|email',
        'password'              => 'required|alpha_num|between:6,12|confirmed',
        'password_confirmation' => 'required|alpha_num|between:6,12',
    );
}


text:
<?php

namespace Google\AdsApi\AdWords\v201705\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class CampaignGroupPerformanceTargetOperation extends \Google\AdsApi\AdWords\v201705\cm\Operation
{

    /**
     * @var \Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTarget $operand
     */
    protected $operand = null;

    /**
     * @param string $operator
     * @param string $OperationType
     * @param \Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTarget $operand
     */
    public function __construct($operator = null, $OperationType = null, $operand = null)
    {
      parent::__construct($operator, $OperationType);
      $this->operand = $operand;
    }

    /**
     * @return \Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTarget
     */
    public function getOperand()
    {
      return $this->operand;
    }

    /**
     * @param \Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTarget $operand
     * @return \Google\AdsApi\AdWords\v201705\cm\CampaignGroupPerformanceTargetOperation
     */
    public function setOperand($operand)
    {
      $this->operand = $operand;
      return $this;
    }

}


text:
(function() {
  'use strict';

  angular
    .app
    .directive('ngAutoFocus', autoFocus);

  autoFocus.$inject = ['$timeout'];

  function autoFocus($timeout) {
    return {
      restrict: 'A',
      link: function($scope, $element) {
        $timeout(function() {
          $element[0].focus();
        }, 0);
      }
    };
  }
}());


text:
LOG_FILE="/var/log/cloudera-azure-initialize.log"

# manually set EXECNAME because this file is called from another script and it $0 contains a
# relevant path
EXECNAME="prepare-datanode-disks.sh"

# logs everything to the $LOG_FILE
log() {
  echo "$(date) [${EXECNAME}]: $*" >> "${LOG_FILE}"
}

cat > inputs2.sh << 'END'

mountDriveForLogCloudera()
{
  dirname=/log
  drivename=$1
  mke2fs -F -t ext4 -b 4096 -E lazy_itable_init=1 -O sparse_super,dir_index,extent,has_journal,uninit_bg -m1 $drivename
  mkdir $dirname
  mount -o noatime,barrier=1 -t ext4 $drivename $dirname
  UUID=`sudo lsblk -no UUID $drivename`
  echo "UUID=$UUID   $dirname    ext4   defaults,noatime,discard,barrier=0 0 1" | sudo tee -a /etc/fstab
  mkdir /log/cloudera
  ln -s /log/cloudera /opt/cloudera
}

# Mount the block with difference size as log device
# if minSize = maxSize, just pick minDevice
# if maxSize > secondMax, aka, logdevice is the largest amoung them, mount maxDevice
# else just use minDevice
set_log_device()
{
  maxSize=0
  maxCount=0
  minSize=0
  minDevice=""
  maxDevice=""
  logDevice=""
  # Each line contains an entry like /dev/<device name>
  MOUNTED_VOLUMES=$(df -h | grep -o -E "^/dev/[^[:space:]]*")

  # Each line contains an entry like <device name> (no /dev/ prefix)
  # (This awk script prints the last field of every line with line number
  # greater than 2.)
  ALL_PARTITIONS=$(awk 'FNR > 2 {print $NF}' /proc/partitions)
  COUNTER=0
  for part in $ALL_PARTITIONS; do
    # If this partition does not end with a number (likely a partition of a
    # mounted volume), is not equivalent to the alphabetic portion of another
    # partition with digits at the end (likely a volume that has already been
    # mounted), and is not contained in $MOUNTED_VOLUMES
    if [[ ! ${part} =~ [0-9]$ && ! ${ALL_PARTITIONS} =~ $part[0-9] && $MOUNTED_VOLUMES != *$part* ]];then
      echo ${part}
      if [[ ${COUNTER} == 0 ]]; then
        maxSize=`blockdev --getsize64 "/dev/$part"`
        secMaxSize=${maxSize}
        minSize=`blockdev --getsize64 "/dev/$part"`
        minDevice="/dev/$part"
        maxDevice="/dev/$part"
      else
        # Update max if applicable
        current=`blockdev --getsize64 "/dev/$part"`
        if [[ ${current} -ge ${maxSize} ]]; then
          secMaxSize=${maxSize}
          maxSize=${current}
          maxDevice="/dev/$part"
        fi

        # Update min if applicable
        if [[ ${current} -lt ${minSize} ]]; then
          minSize=${current}
          minDevice="/dev/$part"
        fi
      fi
      COUNTER=$(($COUNTER+1))
    fi
  done
  if [[ ${minDevice} = ${maxDevice} ]]; then
    logDevice=${minDevice}
  elif [[ ${maxSize} -gt ${secMaxSize} ]]; then
    logDevice=${maxDevice}
  else
    logDevice=${minDevice}
  fi
  echo "using logDevice ${logDevice}"
}

prepare_unmounted_volumes()
{
  # Figure out which is log device base on size
  set_log_device

  # Each line contains an entry like /dev/<device name>
  MOUNTED_VOLUMES=$(df -h | grep -o -E "^/dev/[^[:space:]]*")

  # Each line contains an entry like <device name> (no /dev/ prefix)
  # (This awk script prints the last field of every line with line number
  # greater than 2.)
  ALL_PARTITIONS=$(awk 'FNR > 2 {print $NF}' /proc/partitions)
  COUNTER=0
  for part in $ALL_PARTITIONS; do
    # If this partition does not end with a number (likely a partition of a
    # mounted volume), is not equivalent to the alphabetic portion of another
    # partition with digits at the end (likely a volume that has already been
    # mounted), and is not contained in $MOUNTED_VOLUMES, and it is not $logDevice
    if [[ ! ${part} =~ [0-9]$ && ! ${ALL_PARTITIONS} =~ $part[0-9] && $MOUNTED_VOLUMES != *$part* ]];then
      echo ${part}
      if [[ "/dev/$part" = ${logDevice} ]]; then
        mountDriveForLogCloudera "/dev/$part"
      else prepare_disk "/data$COUNTER" "/dev/$part"
           COUNTER=$(($COUNTER+1))
      fi

    fi
  done
  wait # for all the background prepare_disk function calls to complete
}

# This function was lifted from the file prepare_all_disks.sh in the Whirr project
# It's safe to invoke this function in parallel with different arguments because
# the append operation is atomic when the size of the appended string is <1KB. See:
# http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/
prepare_disk()
{
  mount=$1
  device=$2

  FS=ext4
  FS_OPTS="-E lazy_itable_init=1"

  which mkfs.$FS
  # Fall back to ext3
  if [[ $? -ne 0 ]]; then
    FS=ext3
    FS_OPTS=""
  fi

  # is device mounted?
  mount | grep -q "${device}"
  if [ $? == 0 ]; then
    echo "$device is mounted"
  else
    echo "Warning: ERASING CONTENTS OF $device"
    mkfs.$FS -F $FS_OPTS $device -m 0

    # If $FS is ext3 or ext4, then run tune2fs -i 0 -c 0 to disable fsck checks for data volumes

    if [ $FS = "ext3" -o $FS = "ext4" ]; then
    /sbin/tune2fs -i0 -c0 ${device}
    fi

    echo "Mounting $device on $mount"
    if [ ! -e "${mount}" ]; then
      mkdir "${mount}"
    fi
    # gather the UUID for the specific device

    blockid=$(/sbin/blkid|grep ${device}|awk '{print $2}'|awk -F\= '{print $2}'|sed -e"s/\"//g")

    #mount -o defaults,noatime "${device}" "${mount}"

    # Set up the blkid for device entry in /etc/fstab

    echo "UUID=${blockid} $mount $FS defaults,noatime,discard 0 0" >> /etc/fstab
    mount ${mount}

  fi
}

END

log "------- prepare-datanode-disks.sh starting -------"

sudo bash -c "source ./inputs2.sh; prepare_unmounted_volumes"

log "------- prepare-datanode-disks.sh succeeded -------"

# always `exit 0` on success
exit 0


text:
'use strict';

var _ = require('lodash');
var Backbone = require('backbone');
Backbone.$ = global.$ || require('jquery');
require('backbone-relational');
require('backbone-validation');

var Promise = require('bluebird');
var parser = require('./lib/parser');
var url = require('url');

var ignoreAttributeValidation = [
  'createdBy',
  'createdAt',
  'updatedAt',
  'owner',
  'id'
];

/**
 * Hook all waterline anchors; the waterline validators return 'true' when
 * valid; the backbone.validation validators return undefined.
 */
var anchorRules = _.transform(require('anchor/lib/match/rules'), function (rules, rule, name) {
  rules[name] = function (value, attr, model, obj, json) {
    if (_.contains(ignoreAttributeValidation, attr)) return;

    return (rule(value) === true) ? undefined : 'failed "' + name + '" validation';
  };
});

var associationRules = function (ns) {
  return {
    model: function (value, attr, model, obj, json) {
      if (value === null || _.isNumber(value)) return;
      if (!obj instanceof ns._lower[model]) {
        return 'association ('+ attr +') not instance of '+ model;
      }
    },
    collection: function (value, attr, collection, obj, json) {
      if (value === null || _.isNumber(value)) return;
      if (!obj instanceof ns._lower[collection]) {
        return 'association ('+ attr +') not instance of '+ collection;
      }
    }
  };
};

module.exports = {
  /**
   * Return Promise that resolves the API
   * @param url - String the url of the backbonemodels REST endpoint
   * @param ns  - Object namespace object
   */
  create: function (_url, ns) {
    _.isObject(ns) || (ns = { });
    ns.url = url.parse(_url);

    Backbone.Relational.showWarnings = false;
    Backbone.Relational.store.removeModelScope(global);

    _.extend(Backbone.Validation.validators, anchorRules, associationRules(ns));
    _.extend(Backbone.Model.prototype, Backbone.Validation.mixin);

    var BackboneModelCollection = Backbone.Collection.extend({ url: _url });
    var models = new BackboneModelCollection();

    return new Promise(function (resolve, reject) {
      models.fetch({
        success: function (collection, response) {
          var sdk = _.extend({ }, ns, parser.parse(response, ns));
          Backbone.Relational.store.addModelScope(sdk);
          sdk.store = Backbone.Relational.store;
          resolve(sdk);
        },
        error: function (collection, error) {
          reject(error);
        }
      });
    });
  }
};


text:
#include "tensorflow/lite/tools/benchmark/benchmark_model.h"

#include <iostream>
#include <sstream>

#include "tensorflow/lite/profiling/memory_info.h"
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/benchmark/benchmark_utils.h"
#include "tensorflow/lite/tools/benchmark/logging.h"

namespace tflite {
namespace benchmark {
using tensorflow::Stat;

BenchmarkParams BenchmarkModel::DefaultParams() {
  BenchmarkParams params;
  params.AddParam("num_runs", BenchmarkParam::Create<int32_t>(50));
  params.AddParam("min_secs", BenchmarkParam::Create<float>(1.0f));
  params.AddParam("max_secs", BenchmarkParam::Create<float>(150.0f));
  params.AddParam("run_delay", BenchmarkParam::Create<float>(-1.0f));
  params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(1));
  params.AddParam("benchmark_name", BenchmarkParam::Create<std::string>(""));
  params.AddParam("output_prefix", BenchmarkParam::Create<std::string>(""));
  params.AddParam("warmup_runs", BenchmarkParam::Create<int32_t>(1));
  params.AddParam("warmup_min_secs", BenchmarkParam::Create<float>(0.5f));
  return params;
}

BenchmarkModel::BenchmarkModel() : params_(DefaultParams()) {}

void BenchmarkLoggingListener::OnBenchmarkEnd(const BenchmarkResults& results) {
  auto inference_us = results.inference_time_us();
  auto init_us = results.startup_latency_us();
  auto warmup_us = results.warmup_time_us();
  TFLITE_LOG(INFO) << "Average inference timings in us: "
                   << "Warmup: " << warmup_us.avg() << ", "
                   << "Init: " << init_us << ", "
                   << "Inference: " << inference_us.avg();
}

std::vector<Flag> BenchmarkModel::GetFlags() {
  return {
      CreateFlag<int32_t>(
          "num_runs", &params_,
          "expected number of runs, see also min_secs, max_secs"),
      CreateFlag<float>(
          "min_secs", &params_,
          "minimum number of seconds to rerun for, potentially making the "
          "actual number of runs to be greater than num_runs"),
      CreateFlag<float>(
          "max_secs", &params_,
          "maximum number of seconds to rerun for, potentially making the "
          "actual number of runs to be less than num_runs. Note if --max-secs "
          "is exceeded in the middle of a run, the benchmark will continue to "
          "the end of the run but will not start the next run."),
      CreateFlag<float>("run_delay", &params_, "delay between runs in seconds"),
      CreateFlag<int32_t>("num_threads", &params_, "number of threads"),
      CreateFlag<std::string>("benchmark_name", &params_, "benchmark name"),
      CreateFlag<std::string>("output_prefix", &params_,
                              "benchmark output prefix"),
      CreateFlag<int32_t>(
          "warmup_runs", &params_,
          "minimum number of runs performed on initialization, to "
          "allow performance characteristics to settle, see also "
          "warmup_min_secs"),
      CreateFlag<float>(
          "warmup_min_secs", &params_,
          "minimum number of seconds to rerun for, potentially making the "
          "actual number of warm-up runs to be greater than warmup_runs"),
  };
}

void BenchmarkModel::LogParams() {
  TFLITE_LOG(INFO) << "Min num runs: [" << params_.Get<int32_t>("num_runs")
                   << "]";
  TFLITE_LOG(INFO) << "Min runs duration (seconds): ["
                   << params_.Get<float>("min_secs") << "]";
  TFLITE_LOG(INFO) << "Max runs duration (seconds): ["
                   << params_.Get<float>("max_secs") << "]";
  TFLITE_LOG(INFO) << "Inter-run delay (seconds): ["
                   << params_.Get<float>("run_delay") << "]";
  TFLITE_LOG(INFO) << "Num threads: [" << params_.Get<int32_t>("num_threads")
                   << "]";
  TFLITE_LOG(INFO) << "Benchmark name: ["
                   << params_.Get<std::string>("benchmark_name") << "]";
  TFLITE_LOG(INFO) << "Output prefix: ["
                   << params_.Get<std::string>("output_prefix") << "]";
  TFLITE_LOG(INFO) << "Min warmup runs: ["
                   << params_.Get<int32_t>("warmup_runs") << "]";
  TFLITE_LOG(INFO) << "Min warmup runs duration (seconds): ["
                   << params_.Get<float>("warmup_min_secs") << "]";
}

TfLiteStatus BenchmarkModel::PrepareInputData() { return kTfLiteOk; }

TfLiteStatus BenchmarkModel::ResetInputsAndOutputs() { return kTfLiteOk; }

Stat<int64_t> BenchmarkModel::Run(int min_num_times, float min_secs,
                                  float max_secs, RunType run_type,
                                  TfLiteStatus* invoke_status) {
  Stat<int64_t> run_stats;
  TFLITE_LOG(INFO) << "Running benchmark for at least " << min_num_times
                   << " iterations and at least " << min_secs << " seconds but"
                   << " terminate if exceeding " << max_secs << " seconds.";
  int64_t now_us = profiling::time::NowMicros();
  int64_t min_finish_us = now_us + static_cast<int64_t>(min_secs * 1.e6f);
  int64_t max_finish_us = now_us + static_cast<int64_t>(max_secs * 1.e6f);

  *invoke_status = kTfLiteOk;
  for (int run = 0; (run < min_num_times || now_us < min_finish_us) &&
                    now_us <= max_finish_us;
       run++) {
    ResetInputsAndOutputs();
    listeners_.OnSingleRunStart(run_type);
    int64_t start_us = profiling::time::NowMicros();
    TfLiteStatus status = RunImpl();
    int64_t end_us = profiling::time::NowMicros();
    listeners_.OnSingleRunEnd();

    run_stats.UpdateStat(end_us - start_us);
    util::SleepForSeconds(params_.Get<float>("run_delay"));
    now_us = profiling::time::NowMicros();

    if (status != kTfLiteOk) {
      *invoke_status = status;
    }
  }

  std::stringstream stream;
  run_stats.OutputToStream(&stream);
  TFLITE_LOG(INFO) << stream.str() << std::endl;

  return run_stats;
}

TfLiteStatus BenchmarkModel::ValidateParams() { return kTfLiteOk; }

TfLiteStatus BenchmarkModel::Run(int argc, char** argv) {
  TF_LITE_ENSURE_STATUS(ParseFlags(argc, argv));
  return Run();
}

TfLiteStatus BenchmarkModel::Run() {
  TF_LITE_ENSURE_STATUS(ValidateParams());

  LogParams();

  const double model_size_mb = MayGetModelFileSize() / 1e6;
  const auto start_mem_usage = profiling::memory::GetMemoryUsage();
  int64_t initialization_start_us = profiling::time::NowMicros();
  TF_LITE_ENSURE_STATUS(Init());
  const auto init_end_mem_usage = profiling::memory::GetMemoryUsage();
  int64_t initialization_end_us = profiling::time::NowMicros();
  int64_t startup_latency_us = initialization_end_us - initialization_start_us;
  const auto init_mem_usage = init_end_mem_usage - start_mem_usage;

  if (model_size_mb > 0) {
    TFLITE_LOG(INFO) << "The input model file size (MB): " << model_size_mb;
  }
  TFLITE_LOG(INFO) << "Initialized session in " << startup_latency_us / 1e3
                   << "ms.";

  TF_LITE_ENSURE_STATUS(PrepareInputData());

  TfLiteStatus status = kTfLiteOk;
  uint64_t input_bytes = ComputeInputBytes();
  listeners_.OnBenchmarkStart(params_);
  Stat<int64_t> warmup_time_us =
      Run(params_.Get<int32_t>("warmup_runs"),
          params_.Get<float>("warmup_min_secs"), params_.Get<float>("max_secs"),
          WARMUP, &status);
  if (status != kTfLiteOk) {
    return status;
  }

  Stat<int64_t> inference_time_us =
      Run(params_.Get<int32_t>("num_runs"), params_.Get<float>("min_secs"),
          params_.Get<float>("max_secs"), REGULAR, &status);
  const auto overall_mem_usage =
      profiling::memory::GetMemoryUsage() - start_mem_usage;
  listeners_.OnBenchmarkEnd({model_size_mb, startup_latency_us, input_bytes,
                             warmup_time_us, inference_time_us, init_mem_usage,
                             overall_mem_usage});

  TFLITE_LOG(INFO)
      << "Note: as the benchmark tool itself affects memory footprint, the "
         "following is only APPROXIMATE to the actual memory footprint of the "
         "model at runtime. Take the information at your discretion.";
  TFLITE_LOG(INFO) << "Peak memory footprint (MB): init="
                   << init_mem_usage.max_rss_kb / 1024.0
                   << " overall=" << overall_mem_usage.max_rss_kb / 1024.0;

  return status;
}

TfLiteStatus BenchmarkModel::ParseFlags(int* argc, char** argv) {
  auto flag_list = GetFlags();
  const bool parse_result =
      Flags::Parse(argc, const_cast<const char**>(argv), flag_list);
  if (!parse_result) {
    std::string usage = Flags::Usage(argv[0], flag_list);
    TFLITE_LOG(ERROR) << usage;
    return kTfLiteError;
  }
  return kTfLiteOk;
}

}  // namespace benchmark
}  // namespace tflite


text:
<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
      <groupId>org.pmacik</groupId>
      <artifactId>fuse-benchmark-parent</artifactId>
      <version>1.0</version>
      <relativePath>../pom.xml</relativePath>
   </parent>
   <modelVersion>4.0.0</modelVersion>
   <artifactId>fuse-benchmark-camel-jetty</artifactId>
   <packaging>bundle</packaging>
   <properties>
      <server.host>localhost</server.host>
      <server.port>8888</server.port>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.apache.camel</groupId>
         <artifactId>camel-core</artifactId>
      </dependency>
      <dependency>
         <groupId>org.apache.camel</groupId>
         <artifactId>camel-spring</artifactId>
      </dependency>
   </dependencies>
   <build>
      <resources>
         <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
               <include>*.properties</include>
               <include>META-INF/**</include>
               <include>META-INF/spring/camel-context.xml</include>
            </includes>
         </resource>
      </resources>
      <defaultGoal>install</defaultGoal>
      <plugins>
         <plugin>
            <groupId>org.apache.felix</groupId>
            <artifactId>maven-bundle-plugin</artifactId>
            <configuration>
               <instructions>
                  <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                  <Private-Package>org.pmacik.fuse.benchmark.*</Private-Package>
               </instructions>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>