text:
<root xmlns="urn:mixed">
	<mixed>
		<substring>tja</substring>
	</mixed>
</root>

redpajama_set_name: RedPajamaGithub


text:
/// <reference path="../_references.ts"/>

module powerbi {
    export module DataViewAnalysis {
        import ArrayExtensions = jsCommon.ArrayExtensions;
        import QueryProjectionsByRole = powerbi.data.QueryProjectionsByRole;

        export interface ValidateAndReshapeResult {
            dataView?: DataView;
            isValid: boolean;
        }

        export interface RoleKindByQueryRef {
            [queryRef: string]: VisualDataRoleKind;
        }

        /** Reshapes the data view to match the provided schema if possible. If not, returns null */
        export function validateAndReshape(dataView: DataView, dataViewMappings: DataViewMapping[]): ValidateAndReshapeResult {
            if (!dataViewMappings || dataViewMappings.length === 0)
                return { dataView: dataView, isValid: true };

            if (dataView) {
                for (let dataViewMapping of dataViewMappings) {
                    // Keep the original when possible.
                    if (supports(dataView, dataViewMapping))
                        return { dataView: dataView, isValid: true };

                    if (dataViewMapping.categorical && dataView.categorical)
                        return reshapeCategorical(dataView, dataViewMapping);

                    if (dataViewMapping.tree && dataView.tree)
                        return reshapeTree(dataView, dataViewMapping.tree);

                    if (dataViewMapping.single && dataView.single)
                        return reshapeSingle(dataView, dataViewMapping.single);

                    if (dataViewMapping.table && dataView.table)
                        return reshapeTable(dataView, dataViewMapping.table);
                }
            }
            else if (ScriptResultUtil.findScriptResult(dataViewMappings)) {
                // Currently, PBI Service treats R Script Visuals as static images.
                // This causes validation to fail, since in PBI service no DataView is generated, but there are DataViewMappings,
                // to support the PBI Desktop scenario.
                // This code will be removed once PBI Service fully supports R Script Visuals.
                // VSTS: 6217994 - [R Viz] Remove temporary DataViewAnalysis validation workaround of static R Script Visual mappings
                return { dataView: dataView, isValid: true };
            }

            return { isValid: false };
        }

        function reshapeCategorical(dataView: DataView, dataViewMapping: DataViewMapping): ValidateAndReshapeResult {
            debug.assertValue(dataViewMapping, 'dataViewMapping');

            //The functionality that used to compare categorical.values.length to schema.values doesn't apply any more, we don't want to use the same logic for re-shaping.
            let categoryRoleMapping = dataViewMapping.categorical;
            let categorical = dataView.categorical;
            if (!categorical)
                return { isValid: false };

            let rowCount;
            if (categoryRoleMapping.rowCount) {
                rowCount = categoryRoleMapping.rowCount.supported;
                if (rowCount && rowCount.max) {
                    let updated: DataViewCategorical;
                    let categories = categorical.categories;
                    let maxRowCount = rowCount.max;
                    let originalLength = undefined;
                    if (categories) {
                        for (let i = 0, len = categories.length; i < len; i++) {
                            let category = categories[i];
                            originalLength = category.values.length;
                            if (maxRowCount !== undefined && originalLength > maxRowCount) {

                                // Row count too large: Trim it to fit.
                                let updatedCategories = ArrayExtensions.range(category.values, 0, maxRowCount - 1);

                                updated = updated || { categories: [] };
                                updated.categories.push({
                                    source: category.source,
                                    values: updatedCategories
                                });
                            }
                        }
                    }

                    if (categorical.values && categorical.values.length > 0 && maxRowCount) {
                        if (!originalLength)
                            originalLength = categorical.values[0].values.length;

                        if (maxRowCount !== undefined && originalLength > maxRowCount) {
                            updated = updated || {};
                            updated.values = data.DataViewTransform.createValueColumns();

                            for (let i = 0, len = categorical.values.length; i < len; i++) {
                                let column = categorical.values[i],
                                    updatedColumn: DataViewValueColumn = {
                                        source: column.source,
                                        values: ArrayExtensions.range(column.values, 0, maxRowCount - 1)
                                    };

                                if (column.min !== undefined)
                                    updatedColumn.min = column.min;
                                if (column.max !== undefined)
                                    updatedColumn.max = column.max;
                                if (column.subtotal !== undefined)
                                    updatedColumn.subtotal = column.subtotal;

                                updated.values.push(updatedColumn);
                            }
                        }
                    }

                    if (updated) {
                        dataView = {
                            metadata: dataView.metadata,
                            categorical: updated,
                        };
                    }
                }
            }

            if (supportsCategorical(dataView, dataViewMapping))
                return { dataView: dataView, isValid: true };

            return null;
        }

        function reshapeSingle(dataView: DataView, singleRoleMapping: DataViewSingleMapping): ValidateAndReshapeResult {
            debug.assertValue(dataView, 'dataView');
            debug.assertValue(singleRoleMapping, 'singleRoleMapping');

            if (dataView.single)
                return { dataView: dataView, isValid: true };

            return { isValid: false };
        }

        function reshapeTree(dataView: DataView, treeRoleMapping: DataViewTreeMapping): ValidateAndReshapeResult {
            debug.assertValue(dataView, 'dataView');
            debug.assertValue(treeRoleMapping, 'treeRoleMapping');

            // TODO: Need to implement the reshaping of Tree
            let metadata = dataView.metadata;
            if (conformsToRange(countGroups(metadata.columns), treeRoleMapping.depth) /*&& conforms(countMeasures(metadata.columns), treeRoleMapping.aggregates)*/)
                return { dataView: dataView, isValid: true };

            return { isValid: false };
        }

        function reshapeTable(dataView: DataView, tableRoleMapping: DataViewTableMapping): ValidateAndReshapeResult {
            debug.assertValue(dataView, 'dataView');
            debug.assertValue(tableRoleMapping, 'tableRoleMapping');

            if (dataView.table)
                return { dataView: dataView, isValid: true };

            return { isValid: false };
        }

        export function countGroups(columns: DataViewMetadataColumn[]): number {
            let count = 0;

            for (let i = 0, len = columns.length; i < len; i++) {
                if (!columns[i].isMeasure)
                    ++count;
            }

            return count;
        }

        export function countMeasures(columns: DataViewMetadataColumn[]): number {
            let count = 0;

            for (let i = 0, len = columns.length; i < len; i++) {
                if (columns[i].isMeasure)
                    ++count;
            }

            return count;
        }

        /** Indicates whether the dataView conforms to the specified schema. */
        export function supports(dataView: DataView, roleMapping: DataViewMapping, usePreferredDataViewSchema?: boolean): boolean {
            if (!roleMapping || !dataView)
                return false;

            if (roleMapping.scriptResult && !supportsScriptResult(dataView.scriptResult, roleMapping.scriptResult))
                return false;

            if (roleMapping.categorical && !supportsCategorical(dataView, roleMapping.categorical, usePreferredDataViewSchema))
                return false;

            if (roleMapping.tree && !supportsTree(dataView, roleMapping.tree))
                return false;

            if (roleMapping.single && !supportsSingle(dataView.single, roleMapping.single))
                return false;

            if (roleMapping.table && !supportsTable(dataView.table, roleMapping.table, usePreferredDataViewSchema))
                return false;

            return true;
        }

        function supportsCategorical(dataView: DataView, categoryRoleMapping: DataViewCategoricalMapping, usePreferredDataViewSchema?: boolean): boolean {
            debug.assertValue(categoryRoleMapping, 'categoryRoleMapping');

            let dataViewCategorical = dataView.categorical;
            if (!dataViewCategorical)
                return false;

            // TODO: Disabling this implementation isn't right.
            //if (!conforms(countMeasures(dataView.metadata.columns), categoryRoleMapping.values.roles.length))
            //    return false;

            if (categoryRoleMapping.rowCount) {
                let rowCount = categoryRoleMapping.rowCount.supported;
                if (usePreferredDataViewSchema && categoryRoleMapping.rowCount.preferred)
                    rowCount = categoryRoleMapping.rowCount.preferred;

                if (rowCount) {
                    let len: number = 0;
                    if (dataViewCategorical.values && dataViewCategorical.values.length)
                        len = dataViewCategorical.values[0].values.length;
                    else if (dataViewCategorical.categories && dataViewCategorical.categories.length)
                        len = dataViewCategorical.categories[0].values.length;

                    if (!conformsToRange(len, rowCount))
                        return false;
                }
            }

            return true;
        }

        function supportsSingle(dataViewSingle: DataViewSingle, singleRoleMapping: DataViewSingleMapping): boolean {
            debug.assertValue(singleRoleMapping, 'singleRoleMapping');

            if (!dataViewSingle)
                return false;

            return true;
        }

        function supportsTree(dataView: DataView, treeRoleMapping: DataViewTreeMapping): boolean {
            debug.assertValue(treeRoleMapping, 'treeRoleMapping');

            let metadata = dataView.metadata;
            return conformsToRange(countGroups(metadata.columns), treeRoleMapping.depth);
        }

        function supportsTable(dataViewTable: DataViewTable, tableRoleMapping: DataViewTableMapping, usePreferredDataViewSchema?: boolean): boolean {
            debug.assertValue(tableRoleMapping, 'tableRoleMapping');

            if (!dataViewTable)
                return false;

            if (tableRoleMapping.rowCount) {
                let rowCount = tableRoleMapping.rowCount.supported;
                if (usePreferredDataViewSchema && tableRoleMapping.rowCount.preferred)
                    rowCount = tableRoleMapping.rowCount.preferred;

                if (rowCount) {
                    let len: number = 0;
                    if (dataViewTable.rows && dataViewTable.rows.length)
                        len = dataViewTable.rows.length;

                    if (!conformsToRange(len, rowCount))
                        return false;
                }
            }

            return true;
        }

        function supportsScriptResult(dataView: DataViewScriptResultData, scriptResultRoleMapping: DataViewScriptResultMapping): boolean {
            debug.assertValue(scriptResultRoleMapping, 'scriptResultRoleMapping');

            if (!dataView)
                return false;

            if (!dataView.imageBase64)
                return false;

            return true;
        }

        /** Determines whether the value conforms to the range in the role condition */
        export function conformsToRange(value: number, roleCondition: RoleCondition, ignoreMin?: boolean): boolean {
            debug.assertValue(value, 'value');

            if (!roleCondition)
                return value === 0;

            if (!ignoreMin && roleCondition.min !== undefined && roleCondition.min > value)
                return false;

            if (roleCondition.max !== undefined && roleCondition.max < value)
                return false;

            return true;
        }

        /** Determines whether the role conforms to the kind in the roleCondition */
        function conformsToKind(roleCondition: RoleCondition, roleName: string, projections: QueryProjectionsByRole, roleKindByQueryRef: RoleKindByQueryRef): boolean {
            if (!roleCondition || roleCondition.kind === undefined) {
                return true;
            }
            let expectedKind = roleCondition.kind;
            let roleCollection = projections[roleName];
            if (roleCollection) {
                let roleProjections = roleCollection.all();
                for (let roleProjection of roleProjections) {
                    if (roleKindByQueryRef[roleProjection.queryRef] !== expectedKind)
                        return false;
                }
            }
            return true;
        }

        /** Determines the appropriate DataViewMappings for the projections. */
        export function chooseDataViewMappings(projections: QueryProjectionsByRole, mappings: DataViewMapping[], roleKindByQueryRef: RoleKindByQueryRef): DataViewMapping[] {
            debug.assertValue(projections, 'projections');
            debug.assertValue(mappings, 'mappings');

            let supportedMappings: DataViewMapping[] = [];

            for (let i = 0, len = mappings.length; i < len; i++) {
                let mapping = mappings[i],
                    mappingConditions = mapping.conditions;

                if (mappingConditions && mappingConditions.length) {
                    for (let j = 0, jlen = mappingConditions.length; j < jlen; j++) {
                        let condition = mappingConditions[j];
                        if (matchesCondition(projections, condition, roleKindByQueryRef)) {
                            supportedMappings.push(mapping);
                            break;
                        }
                    }
                }
                else {
                    supportedMappings.push(mapping);
                }
            }

            return ArrayExtensions.emptyToNull(supportedMappings);
        }

        function matchesCondition(projections: QueryProjectionsByRole, condition: DataViewMappingCondition, roleKindByQueryRef: RoleKindByQueryRef): boolean {
            debug.assertValue(projections, 'projections');
            debug.assertValue(condition, 'condition');

            let conditionRoles = Object.keys(condition);
            for (let i = 0, len = conditionRoles.length; i < len; i++) {
                let roleName: string = conditionRoles[i],
                    isDrillable = projections[roleName] && projections[roleName].activeProjectionQueryRef != null,
                    roleCondition = condition[roleName];

                let roleCount = getPropertyCount(roleName, projections, isDrillable);
                if (!conformsToRange(roleCount, roleCondition) || !conformsToKind(roleCondition, roleName, projections, roleKindByQueryRef))
                    return false;
            }

            return true;
        }

        export function getPropertyCount(roleName: string, projections: QueryProjectionsByRole, useActiveIfAvailable?: boolean): number {
            debug.assertValue(roleName, 'roleName');
            debug.assertValue(projections, 'projections');

            let projectionsForRole = projections[roleName];
            if (projectionsForRole) {
                if (useActiveIfAvailable)
                    return 1;
                return projectionsForRole.all().length;
            }

            return 0;
        }

        export function hasSameCategoryIdentity(dataView1: DataView, dataView2: DataView): boolean {
            if (dataView1
                && dataView2
                && dataView1.categorical
                && dataView2.categorical) {
                let dv1Categories = dataView1.categorical.categories;
                let dv2Categories = dataView2.categorical.categories;
                if (dv1Categories
                    && dv2Categories
                    && dv1Categories.length === dv2Categories.length) {
                    for (let i = 0, len = dv1Categories.length; i < len; i++) {
                        let dv1Identity = dv1Categories[i].identity;
                        let dv2Identity = dv2Categories[i].identity;

                        let dv1Length = getLengthOptional(dv1Identity);
                        if (dv1Length !== getLengthOptional(dv2Identity))
                            return false;

                        for (let j = 0; j < dv1Length; j++) {
                            if (!DataViewScopeIdentity.equals(dv1Identity[j], dv2Identity[j]))
                                return false;
                        }
                    }

                    return true;
                }
            }

            return false;
        }

        function getLengthOptional(identity: DataViewScopeIdentity[]): number {
            if (identity)
                return identity.length;

            return 0;
        }

        export function areMetadataColumnsEquivalent(column1: DataViewMetadataColumn, column2: DataViewMetadataColumn): boolean {
            if (!column1 && !column2)
                return true;

            if (!column1 || !column2)
                return false;

            if (column1.displayName !== column2.displayName)
                return false;

            if (column1.queryName !== column2.queryName)
                return false;

            if (column1.isMeasure !== column2.isMeasure)
                return false;

            if (column1.type !== column2.type)
                return false;

            if (column1.sort !== column2.sort)
                return false;

            return true;
        }

        /* Returns true if the metadata columns at the same positions in the array are equivalent. */
        export function isMetadataEquivalent(metadata1: DataViewMetadata, metadata2: DataViewMetadata): boolean {
            if (!metadata1 && !metadata2)
                return true;

            if (!metadata1 || !metadata2)
                return false;

            let previousColumnsLength = metadata1.columns.length;
            let newColumnsLength = metadata2.columns.length;

            if (previousColumnsLength !== newColumnsLength)
                return false;

            for (let i: number = 0; i < newColumnsLength; i++) {
                if (!DataViewAnalysis.areMetadataColumnsEquivalent(metadata1.columns[i], metadata2.columns[i]))
                    return false;
            }

            return true;
        }
    }
}


text:
namespace storage {

class QuotaReservationBuffer;

// This class represents a underlying file of a managed FileSystem file.
// The instance keeps alive while at least one consumer keeps an open file
// handle.
// This class is usually manipulated only via OpenFileHandle.
class OpenFileHandleContext : public base::RefCounted<OpenFileHandleContext> {
 public:
  OpenFileHandleContext(const base::FilePath& platform_path,
                        QuotaReservationBuffer* reservation_buffer);

  // Updates the max written offset and returns the amount of growth.
  int64 UpdateMaxWrittenOffset(int64 offset);

  void AddAppendModeWriteAmount(int64 amount);

  const base::FilePath& platform_path() const {
    return platform_path_;
  }

  int64 GetEstimatedFileSize() const;
  int64 GetMaxWrittenOffset() const;

 private:
  friend class base::RefCounted<OpenFileHandleContext>;
  virtual ~OpenFileHandleContext();

  int64 initial_file_size_;
  int64 maximum_written_offset_;
  int64 append_mode_write_amount_;
  base::FilePath platform_path_;

  scoped_refptr<QuotaReservationBuffer> reservation_buffer_;

  base::SequenceChecker sequence_checker_;

  DISALLOW_COPY_AND_ASSIGN(OpenFileHandleContext);
};

}  // namespace storage

#endif  // STORAGE_BROWSER_FILEAPI_OPEN_FILE_HANDLE_CONTEXT_H_


text:
<?xml version='1.0' encoding="UTF-8"?>
<!DOCTYPE preface PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<preface id="preface">
  <title>Preface</title>

  <para>
    Querydsl is a framework which enables the construction of statically
    typed SQL-like queries. Instead of writing queries as inline strings or externalizing them
    into XML files they can be constructed via a fluent API like Querydsl.
  </para>

  <para>
    The benefits of using a fluent API in comparison to simple strings are for example
  </para>

  <itemizedlist>
    <listitem>
      <para>code completion in IDE</para>
    </listitem>
    <listitem>
      <para>almost none syntactically invalid queries allowed</para>
    </listitem>
    <listitem>
      <para>domain types and properties can be referenced safely</para>
    </listitem>
    <listitem>
      <para>adopts better to refactoring changes in domain types</para>
    </listitem>
  </itemizedlist>

  <!-- more -->

</preface>


text:
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Job Sheet</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="/styles/bootstrap.min.css" rel="stylesheet">
    <link href="/styles/bootstrap-responsive.min.css" rel="stylesheet">
    <link href="/styles/font-awesome.min.css" rel="stylesheet">
    <link href="styles/bootstrap-datetimepicker.min.css" rel="stylesheet">

    <link rel="shortcut icon" href="/favicon.ico">

        JEMS

            <sec:authorize access="hasAnyRole('ROLE_ADMIN','ROLE_MANAGER')">

 Dashboard

            </sec:authorize>

 Calendar

            <sec:authorize access="hasAnyRole('ROLE_ADMIN','ROLE_MANAGER','ROLE_OPERATOR')">

 New Event

            </sec:authorize>

 List Events

 Search

            <sec:authorize access="hasRole('ROLE_ADMIN')">

 Settings

            </sec:authorize>

 Report Bug

               <sec:authentication property="principal.username" />

 Logout

<c:if test="${not empty msg}">

    <button type="button" class="close" data-dismiss="alert">×</button>
    ${msg}

</c:if>

Back to Event
<legend>Job Sheet

  <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Action </button>

 Generate PDF

</legend>

      Title
      <spring:eval expression="jemsevent.title" />

      Description
      <spring:eval expression="jemsevent.description" />

      Organization
      <spring:eval expression="jemsevent.organization" />

      Type
      <spring:eval expression="jemsevent.type" />

      Status
      <spring:eval expression="jemsevent.status" />

      Start Date & Time
      <spring:eval expression="jemsevent.startDateTime" />

      End Date & Time
      <spring:eval expression="jemsevent.endDateTime" />

      Location
      <spring:eval expression="jemsevent.location" />

      Number of Drums
      <spring:eval expression="jemsevent.numberDrums" />

      Number of People
      <spring:eval expression="jemsevent.numberPeople" />

      Number of Facilitators
      <spring:eval expression="jemsevent.numberDrummers" />

      Number of Sessions
      <spring:eval expression="jemsevent.numberSessions" />

      Session Duration
      <spring:eval expression="jemsevent.sessionTime" />

      Chairs Required
      <spring:eval expression="jemsevent.chairsRequired" />

      Staff Assigned
      <spring:eval expression="jemsevent.staffAssigned2" />

  <c:choose>
    <c:when test="${jemsevent.useInDocs==0}">

        Client Company
        <spring:eval expression="jemsevent.clientCompany" />

        Client Contact Person
        <spring:eval expression="jemsevent.clientContactPerson" />

        Client Phone
        <spring:eval expression="jemsevent.clientPhone" />

    </c:when>
    <c:otherwise>

        Hiring Agent Company
        <spring:eval expression="jemsevent.hiringAgentCompany" />

        Hiring Agent Contact Person
        <spring:eval expression="jemsevent.hiringAgentContactPerson" />

        Hiring Agent Phone
        <spring:eval expression="jemsevent.hiringAgentPhone" />

    </c:otherwise>
  </c:choose>

      Notes
      <spring:eval expression="jemsevent.notes" />

<legend>Equipment List</legend>

      Item
      Category
      Quantity

<legend>Map</legend>

      GPS Coordinates
      <spring:eval expression="jemsevent.locationLatLong" />

        Map


text:
class Rules {
public:
  using ItemsWithSupportIndex = std::vector<std::pair<Data::BitsType, double>>;

  Rules(const Data&, const double& threshold);
  friend std::ostream& operator<< (std::ostream&, const Rules&);

private:
  ItemsWithSupportIndex itemsWithSuppIndex;
};

#endif // MY_RULES


text:
<?php
require 'includes/header.php';
$requested_page = $_SERVER['REQUEST_URI'];
$basePath = dirname($_SERVER['SCRIPT_NAME']);
if (substr($requested_page, 0, strlen($basePath)) == $basePath) {
    $requested_page = substr($requested_page, strlen($basePath));
}
$requested_page = ltrim($requested_page, '/');
if ($requested_page == 'favicon.ico' || $requested_page == 'favicon.png') {
    die();
}
$stmt = $link->db_exec('SELECT page_title, content FROM pages WHERE url = %1', $requested_page);
if ($link->num_rows($stmt) < 1) {
    redirect(MESSAGE_PAGE_NOT_FOUND.' (Page: '.$requested_page.')', DOMAIN);
}
list($page_title, $content) = $link->fetch_row($stmt);
echo $content;
require 'includes/footer.php';
?>


text:
info = {'name':'nonnegfac',
        'description':'Python Implementations of Nonnegative Matrix Factorization Algorithms',
        'version':'0.1',
        'author':'Jingu Kim',
        'author_email':'jingu.kim@nokia.com',
        'license':'new BSD',
        'packages':['nonnegfac']
        }

if __name__ == '__main__':
    try:
        import numpy
        import scipy
    except ImportError:
        print ('This package requires Numpy (http://www.numpy.org) and Scipy (http://www.scipy.org) installed.')
        print ('Exiting without installation.')
        import sys
        sys.exit(-1)

    from distutils.core import setup
    setup(**info)


text:
/// <reference path="./Definitions/socket.io" />
/// <reference path="./Definitions/node" />

import SocketIO = require("socket.io");
import Pure = require("./Pure");
import Main = require("./Main");
import Util = require("./Util");

class Room extends Pure {
    /**
     * Room is an advanced type of connection: it connects sockets
     * who are in the same room.
     * @param socket
     * @param parent
     */

    constructor(socket: SocketIO.Socket, parent: Main) {
        super(socket, parent);
        this.socket.type = null;

        ["join", "leave", "disconnect"].forEach((method: string) => {
            this.socket.on(method, this[method].bind(this));
        });
    }

    /**
     * Get the clients of the given room
     * @param room
     */

    private getRoomClients(room: string): any[] {
        var clients = this.parent.io.sockets.clients(room);
        var result = [];

        clients.forEach((client: any) => {
            if(this.socket.id !== client.id) {
                result.push({
                    type: client.type,
                    id: client.id
                });
            }
        });
        return result;
    }

    /**
     * Join to a room
     * @param room - Name of the room
     * @param type
     * @param cb
     */

    private join(room: string, type: string, cb: (error: any, clients?: any[]) => void): void {
        room = Util.safeStr(room);
        type = Util.safeStr(type);
        cb = Util.safeCb(cb);

        if(!room) {
            this.log("Invalid room name was used by `" + this.socket.id + "`:", room);
            cb("invalidRoom");
            return;
        }
        if(!type) {
            this.log("Invalid room type was used by `" + this.socket.id + "`:", type);
            cb("invalidType");
            return;
        }

        var clients = this.getRoomClients(room);
        for(var id in clients) {
            if(clients[id].id !== this.socket.id && clients[id].type !== type) {
                this.log("Invalid room type was used by `" + this.socket.id + "`:", type);
                cb("typeError");
                return;
            }
        }

        if(this.socket.room) {
            this.leave();
        }

        this.log("Client `" + this.socket.id + "` was joined room `" + room + "`");
        this.socket.type = type;
        this.socket.join(room);
        cb(null, clients);
    }

    /**
     * Leave the current room
     */

    private leave(): void {
        this.socket.broadcast.to(this.socket.room).emit("remove", this.socket.id);
        this.log("Client `" + this.socket.id + "` was left room `" + this.socket.room + "`");
        this.socket.leave(this.socket.room);
        this.socket.type = null;
    }

    /**
     * Executed when socket was disconnected
     */

    private disconnect(): void {
        this.log("Client `" + this.socket.id + "` was disconnected");
        this.leave();
    }
}

export = Room;


text:
package com.samsung.sec.dexter.executor.cli;

import com.samsung.sec.dexter.core.util.IDexterClient;

import java.io.InputStream;
import java.io.PrintStream;

public interface IAccountHandler {
	void createAccount(String userId, String password);

	void resetPassword(String userId);

	boolean loginOrCreateAccount();

	void setPrintStream(PrintStream out);

	void setInputStream(InputStream in);

	void setDexterClient(IDexterClient client);
}


text:
require "fascicle/version"

module Fascicle
  # Your code goes here...
end


text:
/**
 * Autogenerated by Thrift Compiler (0.9.3)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Thrift;
using Thrift.Collections;
using System.Runtime.Serialization;
using Thrift.Protocol;
using Thrift.Transport;

#if !SILVERLIGHT
[Serializable]
#endif
public partial class TimNode : TBase
{
  private string _key;
  private string _value;

  /// <summary>
  /// 键
  /// </summary>
  public string Key
  {
    get
    {
      return _key;
    }
    set
    {
      __isset.key = true;
      this._key = value;
    }
  }

  /// <summary>
  /// 值
  /// </summary>
  public string Value
  {
    get
    {
      return _value;
    }
    set
    {
      __isset.@value = true;
      this._value = value;
    }
  }

  public Isset __isset;
  #if !SILVERLIGHT
  [Serializable]
  #endif
  public struct Isset {
    public bool key;
    public bool @value;
  }

  public TimNode() {
  }

  public void Read (TProtocol iprot)
  {
    iprot.IncrementRecursionDepth();
    try
    {
      TField field;
      iprot.ReadStructBegin();
      while (true)
      {
        field = iprot.ReadFieldBegin();
        if (field.Type == TType.Stop) {
          break;
        }
        switch (field.ID)
        {
          case 1:
            if (field.Type == TType.String) {
              Key = iprot.ReadString();
            } else {
              TProtocolUtil.Skip(iprot, field.Type);
            }
            break;
          case 2:
            if (field.Type == TType.String) {
              Value = iprot.ReadString();
            } else {
              TProtocolUtil.Skip(iprot, field.Type);
            }
            break;
          default:
            TProtocolUtil.Skip(iprot, field.Type);
            break;
        }
        iprot.ReadFieldEnd();
      }
      iprot.ReadStructEnd();
    }
    finally
    {
      iprot.DecrementRecursionDepth();
    }
  }

  public void Write(TProtocol oprot) {
    oprot.IncrementRecursionDepth();
    try
    {
      TStruct struc = new TStruct("TimNode");
      oprot.WriteStructBegin(struc);
      TField field = new TField();
      if (Key != null && __isset.key) {
        field.Name = "key";
        field.Type = TType.String;
        field.ID = 1;
        oprot.WriteFieldBegin(field);
        oprot.WriteString(Key);
        oprot.WriteFieldEnd();
      }
      if (Value != null && __isset.@value) {
        field.Name = "value";
        field.Type = TType.String;
        field.ID = 2;
        oprot.WriteFieldBegin(field);
        oprot.WriteString(Value);
        oprot.WriteFieldEnd();
      }
      oprot.WriteFieldStop();
      oprot.WriteStructEnd();
    }
    finally
    {
      oprot.DecrementRecursionDepth();
    }
  }

  public override string ToString() {
    StringBuilder __sb = new StringBuilder("TimNode(");
    bool __first = true;
    if (Key != null && __isset.key) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Key: ");
      __sb.Append(Key);
    }
    if (Value != null && __isset.@value) {
      if(!__first) { __sb.Append(", "); }
      __first = false;
      __sb.Append("Value: ");
      __sb.Append(Value);
    }
    __sb.Append(")");
    return __sb.ToString();
  }

}


text:
using System;
using System.Threading.Tasks;
using Windows.Foundation;

namespace PoshWinRT
{
    public class AsyncOperationWrapper<T> : AsyncInfoWrapper<IAsyncOperation<T>>
    {
        public AsyncOperationWrapper(object asyncOperation) : base(asyncOperation) { }

        public object AwaitResult()
        {
            return AwaitResult(-1);
        }

        public object AwaitResult(int millisecondsTimeout)
        {
            var task = _asyncInfo.AsTask();
            task.Wait(millisecondsTimeout);

            if (task.IsCompleted)
            {
                return task.Result;
            }
            else if (task.IsFaulted)
            {
                throw task.Exception;
            }
            else
            {
                throw new TaskCanceledException(task);
            }
        }
    }
}


text:
<!DOCTYPE html>

		<meta charset=utf-8 />
		<title>Sistema Estadístico de Contraste de Hipótesis</title>

		<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.19.custom.css" rel="stylesheet" />
		<link type="text/css" href="css/main.css" rel="stylesheet" />

Sistema Estadístico de Contraste de Hipótesis

					<form name="data">
						Vector de datos X:

						<textarea id="vectorX" class="vector"></textarea>

						Vector de datos Y:

						<textarea id="vectorY" class="vector"></textarea>
					</form>

Comparación de 2 varianzas (σ2) en variables Normales independientes

X: Variable aleatoria continua. Y: Variable aleatoria continua.

Se desea contrastrar las varianzas de 2 poblaciones: σ12 y σ22 usando la proporción entre sus varianzas experimentales (s12y s22), contra una distribución F de Snedecor.

									<input type="radio" id="ht-test-param2-normal-variances-radio-1" name="ht-test-param2-normal-variances-radio" value="eq" checked>

										Bilateral

											H0 ≡ (σ1 = σ2)

											H1 ≡ (σ1 ≠ σ2)

									<input type="radio" id="ht-test-param2-normal-variances-radio-2" name="ht-test-param2-normal-variances-radio" value="le">

										Cola derecha

											H0 ≡ (σ1 ≤ σ2)

											H1 ≡ (σ1 > σ2)

									<input type="radio" id="ht-test-param2-normal-variances-radio-3" name="ht-test-param2-normal-variances-radio" value="ge">

										Cola izquierda

										H0 ≡ (σ1 ≥ σ2)

											H1 ≡ (σ1 < σ2)

								<button id="ht-test-param2-normal-variances-get-button">Obtener Datos Muestrales</button>

								<button id="ht-test-param2-normal-variances-start-button">Calcular</button>

Nivel de Significación (α)

								<input type="text" id="ht-test-param2-normal-variances-alpha" readonly />

								<button id="ht-test-param2-normal-variances-leveldown">
									Disminuir
								</button>
								<button id="ht-test-param2-normal-variances-levelup">
									Aumentar
								</button>

Parámetros de X

							<form name="ht-test-param2-normal-variances">

								Desviación Estándar (sx)

								<input type="text" name="ht-test-param2-normal-variances-sx-input" id="ht-test-param2-normal-variances-sx-input" value="0" />

								Cantidad (nx)

								<input type="text" name="ht-test-param2-normal-variances-nx-input" id="ht-test-param2-normal-variances-nx-input" value="10" />

							</form>

Parámetros de Y

							<form name="ht-test-param2-normal-variances">
								Desviación Estándar (sx)

								<input type="text" name="ht-test-param2-normal-variances-sy-input" id="ht-test-param2-normal-variances-sy-input" value="0" />

								Cantidad (ny)

								<input type="text" name="ht-test-param2-normal-variances-ny-input" id="ht-test-param2-normal-variances-ny-input" value="10" />

							</form>

Comparación X / Y:

									Fexp:

									Valor P:

									Fα:

									Fα/2:

									F1-α/2:

									Interpretación:

					Desarrollado por Gonzalo Díaz Cruz

					© 2012 | Universidad de Santiago de Chile


text:
// MIT License
//
// Copyright (c) 2016 Caring Labs, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "ParticleEmitter.hpp"
#include "ParticleSimulator.hpp"
#include "ParticleNetworkParticle.hpp"

using namespace mf;

//------------------------------------------------------------------------------
// The particle emitter class
//------------------------------------------------------------------------------

ParticleEmitter::ParticleEmitter(const Vec2 & initialPos,
                                 const Vec2 & initialVel,
                                 float massKg,
                                 float initialAngle,
                                 float initialAngularVel,
                                 float momentOfInertia,
                                 float simStartSec,
                                 float simEndSec,
                                 bool isVisible)
: Particle(initialPos, initialVel, massKg, initialAngle, initialAngularVel, momentOfInertia, simStartSec, simEndSec, isVisible)
{
}

ParticleEmitter::~ParticleEmitter()
{
}

//------------------------------------------------------------------------------
// The particle area emitter class
//------------------------------------------------------------------------------

// anonymous namespace for these utilities for generating polygon edges
// these are essentially convenience functions, ultimately only adding the arbitrary
// polygon edges will be used
namespace {
    // sample the edge of the ellipse
    void generateEllipseSamples(float cx, float cy, float a, float b, float phi /*radians*/, size_t nSamples, std::vector<Vec2> & sample)
    {
        const float cos_phi = cosf(phi);
        const float sin_phi = sinf(phi);

        for (size_t i = 0; i < nSamples; ++i) {
            const float t = float(i)/float(nSamples-1);
            const float theta = t*2.0*M_PI;

            const float cos_theta = cosf(theta);
            const float sin_theta = sinf(theta);

            const float x = cx + a * cos_theta * cos_phi - b * sin_theta * sin_phi;
            const float y = cy + a * cos_theta * sin_phi + b * sin_theta * cos_phi;

            sample.push_back(Vec2(x,y));
        }
    }

    // generate edges for polygon intersection test
    void generateEllipseEdges(float cx, float cy, float a, float b, float phi /*radians*/, size_t nSamples, std::vector<Vec2> & edges)
    {
        std::vector<Vec2> sample;
        generateEllipseSamples(cx, cy, a, b, phi, nSamples, sample);

        for (size_t i = 0; i < sample.size()-1; ++i) {
            edges.push_back(sample[i+0]);
            edges.push_back(sample[i+1]);
        }
    }

    void generateRectangleSamples(float cx, float cy, float a, float b, float phi /*radians*/, std::vector<Vec2> & sample)
    {
        const float cos_phi = cosf(phi);
        const float sin_phi = sinf(phi);

        const size_t max = 5;

        const float xaxis[max] = { -a, a, a, -a, -a };
        const float yaxis[max] = { -b, -b, b, b, -b };

        for (size_t i = 0; i < max; ++i) {

            const float a = xaxis[i];
            const float b = yaxis[i];

            const float x = cx + a * cos_phi - b * sin_phi;
            const float y = cy + a * sin_phi + b * cos_phi;
            sample.push_back(Vec2(x,y));
        }
    }

    void generateRectangleEdges(float cx, float cy, float a, float b, float phi /*radians*/, std::vector<Vec2> & edges)
    {
        std::vector<Vec2> sample;
        generateRectangleSamples(cx, cy, a, b, phi, sample);

        for (size_t i = 0; i < sample.size()-1; ++i) {
            edges.push_back(sample[i+0]);
            edges.push_back(sample[i+1]);
        }
    }
} // close anonymous namespace

ParticleAreaEmitter::ParticleAreaEmitter(const Vec2 & initialPos,
                                         const Vec2 & initialVel,
                                         float massKg,
                                         float initialAngle,
                                         float initialAngularVel,
                                         float momentOfInertia,
                                         float simStartSec,
                                         float simEndSec,
                                         bool isVisible)
: ParticleEmitter(initialPos, initialVel, massKg, initialAngle, initialAngularVel, momentOfInertia, simStartSec, simEndSec, isVisible)
, _particleUpdateKernel(&ParticleNetworkParticle::kernelDefault)
, _simulator(NULL)
, _integralDivisions(60)
, _numParticles(0)
, _initialVelocityFunction(new ConstantInitialVelocity())
, _initialAngleFunction(new ConstantInitialAngleFunction())
, _initialAngularVelocityFunction(new ConstantInitialAngularVelocityFunction())
, _initialTextureCellFunction(new ParticleAreaEmitterInitialTextureAtlasCellFunction())
, _particleSimBeforeParticleInSec(0.0)
, _emissionStartSec(0.0)
, _emissionDurationSec(1.0)
, _areaMin(0.0, 0.0)
, _areaMax(1.0, 1.0)
, _particleDurationSecMin(1.0)
, _particleDurationSecMax(1.0)
, _particleInDurationSecMin(0.1)
, _particleInDurationSecMax(0.1)
, _particleOutDurationSecMin(0.1)
, _particleOutDurationSecMax(0.1)
, _particleMassKgMin(1.0)
, _particleMassKgMax(1.0)
, _particleScalarMin(1.0)
, _particleScalarMax(1.0)
, _particleMomentOfInertiaMin(1.0f)
, _particleMomentOfInertiaMax(1.0f)
, _usePath(false)
, _particleTextureAtlasRows(1)
, _particleTextureAtlasCols(1)
, _particleTextureCellFPSMin(0)
, _particleTextureCellFPSMax(0)
{
    // set default particle color
    _particleColors.push_back(1.0);
    _particleColors.push_back(1.0);
    _particleColors.push_back(1.0);
    _particleColors.push_back(1.0);
}

ParticleAreaEmitter::~ParticleAreaEmitter()
{
}

void
ParticleAreaEmitter::setSimulator(ParticleSimulator * sim)
{
    _simulator = sim;
}

void
ParticleAreaEmitter::setPathCurve(const std::vector<Vec2> & bezier)
{
    CubicBezier2 curve(bezier);
    _pathCurve.setBezier(curve, 128);
}

void
ParticleAreaEmitter::setPathTimingCurve(const std::vector<Vec2> & bezier)
{
    CubicBezier2 curve(bezier);
    _pathTimingCurve.setBezier(curve, 128);
}

void
ParticleAreaEmitter::addEllipticalArea(float cx, float cy, float a, float b, float phi /*radians*/, size_t nSamples)
{
    generateEllipseEdges(cx, cy, a, b, phi, nSamples, _edges);
}

void
ParticleAreaEmitter::addRectangularArea(float cx, float cy, float a, float b, float phi /*radians*/)
{
    generateRectangleEdges(cx, cy, a, b, phi, _edges);
}

void
ParticleAreaEmitter::addPolygonalArea(const std::vector<Vec2> & edges)
{
    std::copy(edges.begin(), edges.end(), std::back_inserter(_edges));
}

void
ParticleAreaEmitter::generateAreaBoundingBox()
{
    assert(_edges.size() > 0);

    // find the boundaries of the dataset
    float xmax = -1000000.0f;
    float ymax = -1000000.0f;
    float xmin =  1000000.0f;
    float ymin =  1000000.0f;

    const size_t size = _edges.size();
    for (size_t i = 0; i < size; ++i) {
        if (_edges[i].x() < xmin) xmin = _edges[i].x();
        if (_edges[i].x() > xmax) xmax = _edges[i].x();
        if (_edges[i].y() < ymin) ymin = _edges[i].y();
        if (_edges[i].y() > ymax) ymax = _edges[i].y();
    }

    _areaMin = Vec2(xmin, ymin);
    _areaMax = Vec2(xmax, ymax);
}

Vec2
ParticleAreaEmitter::generatePositionInArea()
{
    // generate positions, if they are in the polygon, then add them to the position list
    for (size_t i = 0; i < 20; ++i) {

        const float x = _rng.uniform(_areaMin.x(), _areaMax.x());
        const float y = _rng.uniform(_areaMin.y(), _areaMax.y());
        const Vec2 point(x,y);

        const bool ok = pointInPolygon(point, _edges, _areaMin, _areaMax);

        if (ok == true) {
            return point;
        }
    }

    // unable to generate a point!!
    std::cerr << "WARNING: unable to generate enough points!\n";

    return Vec2(0.0, 0.0);
}

Vec2
ParticleAreaEmitter::generatePosition(float sec)
{
    const Vec2 basePosition = generatePositionInArea();

    if (_usePath == false) return basePosition;

    const float s = _pathCurve.arcLength() * _pathTimingCurve.sampleAtPosition(sec);

    return basePosition + _pathCurve.sampleArcLength(s);
}

void
ParticleAreaEmitter::generateColor(float color[4])
{
    const float n = _particleColors.size()/4;

    const int colorIdx = 4 * int(_rng.uniform(0, n-1));

    color[0] = _particleColors[ colorIdx + 0 ];
    color[1] = _particleColors[ colorIdx + 1 ];
    color[2] = _particleColors[ colorIdx + 2 ];
    color[3] = _particleColors[ colorIdx + 3 ];
}

void
ParticleAreaEmitter::setEmissionTimingCurve(const std::vector<Vec2> & bezier)
{
    assert(bezier.size() > 0);

    CubicBezier2 curve(bezier);
    _emissionTimingCurve.setBezier(curve, 128);
    _emissionStartSec = _emissionTimingCurve.firstPoint().x();
    const float emissionEndSec = _emissionTimingCurve.lastPoint().x();
    _emissionDurationSec = emissionEndSec - _emissionStartSec;
}

void
ParticleAreaEmitter::setParticleSimSecBeforeParticleIn(float sec)
{
    _particleSimBeforeParticleInSec = sec;
}

void
ParticleAreaEmitter::setParticleDuration(float minSec, float maxSec)
{
    _particleDurationSecMin = minSec;
    _particleDurationSecMax = maxSec;
}

void
ParticleAreaEmitter::setParticleInDuration(float minSec, float maxSec)
{
    _particleInDurationSecMin = minSec;
    _particleInDurationSecMax = maxSec;
}

void
ParticleAreaEmitter::setParticleOutDuration(float minSec, float maxSec)
{
    _particleOutDurationSecMin = minSec;
    _particleOutDurationSecMax = maxSec;
}

void
ParticleAreaEmitter::setParticleMass(float minKg, float maxKg)
{
    _particleMassKgMin = minKg;
    _particleMassKgMax = maxKg;
}

void
ParticleAreaEmitter::setParticleScalar(float min, float max)
{
    _particleScalarMin = min;
    _particleScalarMax = max;
}

void
ParticleAreaEmitter::setParticleInitialVelocityFunction(ParticleAreaEmitterInitialVelocityFunctionPtr f)
{
    _initialVelocityFunction = f;
}

void
ParticleAreaEmitter::setParticleInitialAngleFunction(ParticleAreaEmitterInitialAngleFunctionPtr f)
{
    _initialAngleFunction = f;
}

void
ParticleAreaEmitter::setParticleInitialAngularVelocityFunction(ParticleAreaEmitterInitialAngularVelocityFunctionPtr f)
{
    _initialAngularVelocityFunction = f;
}

void
ParticleAreaEmitter::setParticleMomentOfInertia(float min, float max)
{
    _particleMomentOfInertiaMin = min;
    _particleMomentOfInertiaMax = max;
}

void
ParticleAreaEmitter::setParticleTextureAtlasCells(int rows, int cols)
{
    _particleTextureAtlasRows = rows;
    _particleTextureAtlasCols = cols;
}

void
ParticleAreaEmitter::setParticleInitialTextureAtlasCellFunction(ParticleAreaEmitterInitialTextureAtlasCellFunctionPtr f)
{
    _initialTextureCellFunction = f;
}

void
ParticleAreaEmitter::setParticleTextureCellFPS(float min, float max)
{
    _particleTextureCellFPSMin = min;
    _particleTextureCellFPSMax = max;
}

void
ParticleAreaEmitter::initialize()
{
    ParticleEmitter::initialize();

    //--------------------------------------------------------------------------
    // setup the pre-conditions for particle generation
    //--------------------------------------------------------------------------

    // generate the bounding box information for the input area so we can efficiently pick random points that fall into that area
    generateAreaBoundingBox();

    // be sure our path information is coherent
    assert(_pathTimingCurve.isEmpty() == _pathCurve.isEmpty());

    // then set the flag for using a path
    if (_pathCurve.isEmpty()) _usePath = false;
    else _usePath = true;

    //--------------------------------------------------------------------------
    // run particle generation
    //--------------------------------------------------------------------------

    generateParticles();
}

void
ParticleAreaEmitter::generateParticles()
{
    // we do a riemann integral at 1/60th sec width (dx) which is a reasonable granularity
    const size_t max = size_t(_emissionDurationSec * _integralDivisions);

    // the number of fractional particles we carry over from iteration to iteration
    float numPartialParticles = 0.0;

    // the loop to emit particles
    for (size_t i = 0; i < max; ++i) {

        // t goes from 0 to 1
        const float t = float(i)/float(max-1);

        // currentSec is the current time
        const float currentSec = _emissionStartSec + t*_emissionDurationSec;

        // numParticles is the number of particles to emit at currentSec
        // this line should be read as:
        // (fudge factor) + height * width
        // height * width is the area of the 'i'th rectangle for the riemann sum we're doing.
        const float numParticles = numPartialParticles + _emissionTimingCurve.sampleAtPosition(currentSec) * 1.0/float(_integralDivisions);

        // numParticlesToEmit is the integer number of particles we will emit at currentSec
        const size_t numParticlesToEmit = size_t(numParticles);

        // numPartialParticles is the fraction of particles we will carry over to the next iteration
        numPartialParticles = numParticles - numParticlesToEmit;

        // emit particles
        for (size_t j = 0; j < numParticlesToEmit; ++j) {

            const float durationSec = _rng.uniform(_particleDurationSecMin, _particleDurationSecMax);

            //------------------------------------------------------------------
            // particle properties
            const Vec2 particlePos              = generatePosition(currentSec);
            const float particleStartSec        = currentSec - _particleSimBeforeParticleInSec;
            const float particleInSec           = currentSec;
            const float particleInDuration      = _rng.uniform(_particleInDurationSecMin, _particleInDurationSecMax);
            const float particleOutSec          = particleInSec + durationSec;
            const float particleEndSec          = particleOutSec;
            const float particleOutDuration     = _rng.uniform(_particleOutDurationSecMin, _particleOutDurationSecMax);
            const float particleMassKg          = _rng.uniform(_particleMassKgMin, _particleMassKgMax);
            const float particleScalar          = _rng.uniform(_particleScalarMin, _particleScalarMax);
            const Vec2 particleVel              = _initialVelocityFunction->getVelocity(particlePos, particleInSec, durationSec, particleMassKg, particleScalar);
            const float particleMomentOfInertia = _rng.uniform(_particleMomentOfInertiaMin, _particleMomentOfInertiaMax);
            const float particleAngle           = _initialAngleFunction->getAngle(particlePos, particleVel, particleInSec, durationSec,
                                                                                particleMassKg, particleScalar, particleMomentOfInertia);
            const float particleAngularVel      = _initialAngularVelocityFunction->getAnglularVelocity(particlePos, particleVel, particleInSec, durationSec,
                                                                                particleMassKg, particleScalar, particleAngle, particleMomentOfInertia);

            float particleColor[4];
            generateColor(particleColor);

            int particleCellRow = 0, particleCellCol = 0;
            _initialTextureCellFunction->getCell(_particleTextureAtlasRows, _particleTextureAtlasCols, particleCellRow, particleCellCol);

            const float particleFPS = _rng.uniform(_particleTextureCellFPSMin, _particleTextureCellFPSMax);

            //------------------------------------------------------------------
            // construct and setup the particle
            //------------------------------------------------------------------
            ParticleNetworkParticle * particle = new ParticleNetworkParticle(particlePos,
                                                                             particleVel,
                                                                             particleMassKg,
                                                                             particleAngle,
                                                                             particleAngularVel,
                                                                             particleMomentOfInertia,
                                                                             particleStartSec,
                                                                             particleEndSec,
                                                                             true);

            particle->setColor(particleColor[0], particleColor[1], particleColor[2], particleColor[3]);
            particle->setInSec(particleInSec);
            particle->setInDuration(particleInDuration);
            particle->setOutSec(particleOutSec);
            particle->setOutDuration(particleOutDuration);
            particle->setScalar(particleScalar);
            particle->setParticleUpdateKernel(_particleUpdateKernel);
            particle->setTextureAtlasCells(_particleTextureAtlasRows, _particleTextureAtlasCols);
            particle->setTextureCell(particleCellRow, particleCellCol);
            particle->setTextureFPS(particleFPS);

            //------------------------------------------------------------------
            // give particle to the sim
            //------------------------------------------------------------------
            _simulator->addParticle(particle);

        } // end j
    } // end i
}

// MIT License
//
// Copyright (c) 2016 Caring Labs, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.


text:
<BroadcastMonitor>
  <updated>2015-08-07T15:24:01</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T15:23:59</startTime>
    <itemId>1000080586:1243206</itemId>
    <titleId>190154448</titleId>
    <itemCode>JFX1138-0046</itemCode>
    <itemReference>JFX1138-0046</itemReference>
    <titleName>Mad About The Boy</titleName>
    <artistName>Dinah Washington</artistName>
    <albumName></albumName>
    <CategoryCode>737</CategoryCode>
    <CategoryName>JAZZ</CategoryName>
    <itemDuration>164</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T15:21:15</startTime>
    <itemId>1000080586:1243204</itemId>
    <titleId>216041468</titleId>
    <itemCode>MS356</itemCode>
    <itemReference></itemReference>
    <titleName>Jimmy Mack</titleName>
    <artistName>Martha Reeves & The Vandellas</artistName>
    <albumName></albumName>
    <CategoryCode>736</CategoryCode>
    <CategoryName>SOUL</CategoryName>
    <itemDuration>175</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
<?php

namespace Model3\Rest;

use Model3\Request\Request as Model3Request;

class Request extends Model3Request
{
    protected $_method;
    protected $_accepted;

    public function __construct()
    {
        $path = array_keys($_GET);
        $this->_controller = 'Index';
        $this->_action = 'index';
        $this->_params = array();
        $this->_method = strtolower($_SERVER['REQUEST_METHOD']);
        $this->_accepted = isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:'xml';

        if(isset($path[0]))
        {
            $route= $path[0];

            $route= rtrim($path[0], '/');
            $routeParts = preg_split('/\//',$route);

            $idx = 0;
            $this->_component = null;
            $componentes = Model3_Site::getComponentList();
            if(in_array($routeParts[$idx], $componentes))
            {
                $this->_component = $routeParts[$idx];
                $idx++;
            }

            $this->_module = null;
            if(isset($routeParts[$idx]))
            {
                $modulos = Model3_Site::getModuleList();
                if(in_array($routeParts[$idx], $modulos))
                {
                    $this->_module = $routeParts[$idx];
                    $idx++;
                }
            }

            $this->_controller = (isset($routeParts[$idx])&&!empty($routeParts[$idx]))?$routeParts[$idx]:"Index";
            $idx++;
            $this->_action = (isset($routeParts[$idx])&&!empty($routeParts[$idx]))?$routeParts[$idx]:"index";
            $idx++;

            for($cont = 0;$cont < $idx; $cont++)
            {
                array_shift($routeParts);
            }
            $this->_params=$routeParts;
        }
    }
    public function setMethod($method)
    {
        $this->_method = $method;
    }

    public function getMethod()
    {
        return $this->_method;
    }

    public function getApiKey()
    {
        return $this->_action;
    }

    public function getHttpAccept()
    {
        return $this->_accepted;
    }
    public function sendResponse($status = 200, $body = '', $content_type = 'text/html')
    {
        $status_header = 'HTTP/1.1 ' . $status . ' ' . self::getStatusCodeMessage($status);
        // set the status
        header($status_header);
        // set the content type
        header('Content-type: ' . $content_type);

        // pages with body are easy
        if($body != '')
        {
            // send the body
            echo $body;
            exit;
        }
        // we need to create the body if none is passed
        else
        {
            // create some body messages
            $message = '';

            // this is purely optional, but makes the pages a little nicer to read
            // for your users.  Since you won't likely send a lot of different status codes,
            // this also shouldn't be too ponderous to maintain
            switch($status)
            {
                case 401:
                    $message = 'You must be authorized to view this page.';
                    break;
                case 404:
                    $message = 'The requested URL ' . $_SERVER['REQUEST_URI'] . ' was not found.';
                    break;
                case 500:
                    $message = 'The server encountered an error processing your request.';
                    break;
                case 501:
                    $message = 'The requested method is not implemented.';
                    break;
            }

            // servers don't always have a signature turned on (this is an apache directive "ServerSignature On")
            $signature = ($_SERVER['SERVER_SIGNATURE'] == '') ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE'];

            // this should be templatized in a real-world solution
            $body = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

								<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
								<title>' . $status . ' ' . self::getStatusCodeMessage($status) . '</title>

' . self::getStatusCodeMessage($status) . '

' . $message . '

								<address>' . $signature . '</address>

						';

            echo $body;
            exit;
        }
    }

    public static function getStatusCodeMessage($status)
    {
        // these could be stored in a .ini file and loaded
        // via parse_ini_file()... however, this will suffice
        // for an example
        $codes = Array(
                100 => 'Continue',
                101 => 'Switching Protocols',
                200 => 'OK',
                201 => 'Created',
                202 => 'Accepted',
                203 => 'Non-Authoritative Information',
                204 => 'No Content',
                205 => 'Reset Content',
                206 => 'Partial Content',
                300 => 'Multiple Choices',
                301 => 'Moved Permanently',
                302 => 'Found',
                303 => 'See Other',
                304 => 'Not Modified',
                305 => 'Use Proxy',
                306 => '(Unused)',
                307 => 'Temporary Redirect',
                400 => 'Bad Request',
                401 => 'Unauthorized',
                402 => 'Payment Required',
                403 => 'Forbidden',
                404 => 'Not Found',
                405 => 'Method Not Allowed',
                406 => 'Not Acceptable',
                407 => 'Proxy Authentication Required',
                408 => 'Request Timeout',
                409 => 'Conflict',
                410 => 'Gone',
                411 => 'Length Required',
                412 => 'Precondition Failed',
                413 => 'Request Entity Too Large',
                414 => 'Request-URI Too Long',
                415 => 'Unsupported Media Type',
                416 => 'Requested Range Not Satisfiable',
                417 => 'Expectation Failed',
                500 => 'Internal Server Error',
                501 => 'Not Implemented',
                502 => 'Bad Gateway',
                503 => 'Service Unavailable',
                504 => 'Gateway Timeout',
                505 => 'HTTP Version Not Supported'
        );

        return (isset($codes[$status])) ? $codes[$status] : '';
    }
}
?>


text:
(function() {
  var Promise, checkOptions, merge, resolveOptions;

  Promise = require("native-or-bluebird");

  merge = require("deepmerge");

  resolveOptions = function(optionName, service) {
    var i, k, o, _i, _j, _len, _len1, _ref, _ref1;
    o = [];
    if (service.deps[optionName] != null) {
      _ref = service.deps[optionName];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        k = _ref[_i];
        _ref1 = resolveOptions(k, service);
        for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
          i = _ref1[_j];
          if (o.indexOf(i) === -1) {
            o.push(i);
          }
        }
      }
    }
    if (o.indexOf(optionName) === -1) {
      o.push(optionName);
    }
    return o;
  };

  checkOptions = function(requestType, requestPath, service) {
    return new Promise(function(resolve, reject) {
      var i, o, options, res, _i, _j, _len, _len1, _ref, _ref1;
      options = [];
      _ref = service.routes[requestType][requestPath];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        o = _ref[_i];
        _ref1 = resolveOptions(o, service);
        for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
          i = _ref1[_j];
          if (options.indexOf(i) === -1) {
            options.push(i);
          }
        }
      }
      res = {};
      res[requestType] = {};
      res[requestType][requestPath] = options;
      return resolve(res);
    });
  };

  module.exports = function(components) {
    if (components == null) {
      components = [];
    }
    return function(app) {
      return new Promise(function(resolve, reject) {
        return Promise.all(components).then(function(results) {
          var promises, r, requestOptions, requestPath, requestType, requests, routes, service, _i, _len, _ref;
          service = {};
          for (_i = 0, _len = results.length; _i < _len; _i++) {
            r = results[_i];
            service = merge(r, service);
          }
          routes = {};
          promises = [];
          _ref = service.routes;
          for (requestType in _ref) {
            requests = _ref[requestType];
            for (requestPath in requests) {
              requestOptions = requests[requestPath];
              promises.push(checkOptions(requestType, requestPath, service));
            }
          }
          return Promise.all(promises).then(function(reqResults) {
            var rr, _j, _len1;
            for (_j = 0, _len1 = reqResults.length; _j < _len1; _j++) {
              rr = reqResults[_j];
              service.routes = merge(rr, service.routes);
            }
            return resolve(service);
          });
        });
      });
    };
  };

}).call(this);


text:
DGENRPD1 ;ALB/CJM - Veterans with no Application and with a Future Appointment Report; 04/28/2004
 ;;5.3;Registration;**147,568**;Aug 13,1993
 ;
REPORT ;
 N DGENRP
 ;
 ;Control variables used in generating report
 ;DGENRP("BEGIN")=<begining of the date range for appt selection>
 ;DGENRP("END")=<ending date of range>
 ;DGENRP("ALL")=1 means to include all clinics for appt selection
 ;DGENRP("DIVISION",<list of medical center Divisions to include>)=""
 ;DGENRP("CLINIC",<list of clinics to include>)=""
 ;DGENRP("JUSTONCE")=<1 means that if the patient has multiple appts to print only the first, 0 means print all the patient's appts>
 ;
 G:'$$ASKRANGE(.DGENRP) EXIT
 G:'$$LOCATION(.DGENRP) EXIT
 G:'$$JUSTONCE(.DGENRP) EXIT
 ;
 I $$DEVICE() D PRINT^DGENRPD2
EXIT ;
 Q
 ;
DEVICE() ;
 ;Description: allows the user to select a device.
 ;Input: none
 ;
 ;Output:
 ;  Function Value - Returns 0 if the user decides not to print or to
 ;       queue the report, 1 otherwise.
 ;
 N OK
 S OK=1
 S %ZIS="MQ"
 W !,"*** This report requires a 132 column printer. ******"
 D ^%ZIS
 S:POP OK=0
 D:OK&$D(IO("Q"))
 .S ZTRTN="PRINT^DGENRPD2",ZTDESC="Future Appointments with No EnrollmentApplication REPORT",ZTSAVE("DGENRP(")=""
 .D ^%ZTLOAD
 .W !,$S($D(ZTSK):"REQUEST QUEUED TASK="_ZTSK,1:"REQUEST CANCELLED")
 .D HOME^%ZIS
 .S OK=0
 Q OK
 ;
LOCATION(DGENRP) ;
 ;Description: asks the user to select locations of future appointments
 ;
 ;Input: none
 ;Output:
 ;  DGENRP - (pass by reference) used to return selected locations
 ;  Function Value: 0 on failure, 1 on success
 ;
 N DIR,SUCCESS
 S SUCCESS=1
 S DIR("B")="ALL"
 S DIR(0)=$S($P($G(^DG(43,1,"GL")),"^",2):"S^A:All;D:by Division;C:by Clinic",1:"S^A:All;C:by Clinic")
 S DIR("A")="How do you want to select the clinics to appear in the report? "
 S DIR("?")="You have the choice of selecting all clinics, entire divisions, or individual clinics."
 D ^DIR
 I $D(DIRUT) D
 .S SUCCESS=0
 E  D
 .I Y="A" D
 ..S DGENRP("ALL")=1
 .E  D
 ..S DGENRP("ALL")=0
 ..I Y="C" D
 ...S SUCCESS=$$CLINIC(.DGENRP)
 ..E  D
 ...I Y="D" S SUCCESS=$$DIVISION(.DGENRP)
 ;
 Q SUCCESS
 ;
ASKRANGE(DGENRP) ;
 ;Description: Asks the user to enter a date range begining no earlier
 ;than the current date
 ;
 Q:'$$ASKBEGIN(.DGENRP) 0
 Q:'$$ASKEND(.DGENRP) 0
 Q 1
 ;
ASKBEGIN(DGENRP) ;
 ;Description: Asks the user to enter a beginning date.
 ;
 ;Input: none
 ;
 ;Output:
 ;  Function value=1 if user selected a date, 0 otherwise
 ;  DGENRP("BEGIN")=date selected
 ;
 N DIR,X,Y
 S DIR(0)="D^::XO"
 S DIR("A")="Enter beginning date for future appointments for."
 S DIR("B")=$$FMTE^XLFDT($$FMADD^XLFDT(DT,1),"D")
 S DIR("?")="Enter the first day to list appointments."
REPEAT D ^DIR
 Q:$D(DIRUT) 0
 I Y'>DT W !,"Date must be later than today!" G REPEAT
 S DGENRP("BEGIN")=Y
 Q 1
 ;
ASKEND(DGENRP) ;
 ;Description: Asks the user to enter an end date.
 ;
 ;Input:
 ;  DGENRP("BEGIN") - the earliest possible date
 ;
 ;Output:
 ;  Function value=1 if user selected a date, 0 otherwise
 ;  DGENRP("END")=date selected
 ;
 N DIR,X,Y
 S DIR(0)="D^::X"
 S DIR("A")="Enter ending date"
 S DIR("B")=$$FMTE^XLFDT(DGENRP("BEGIN"),"D")
 S DIR("?")="Enter the last day to list appointments for."
AGAIN D ^DIR
 Q:$D(DIRUT) 0
 I (Y<$G(DGENRP("BEGIN"))) W !,"Date must be no earlier than "_DIR("B") G AGAIN
 S DGENRP("END")=Y
 Q 1
 ;
DIVISION(DGENRP) ;
 ;Description: asks divisions to include
 ;
 N DIR,QUIT,SUCCESS
 S SUCCESS=1
 S DIR(0)="PO^40.8:AEM"
 S DIR("A")="Select the medical center divisions to include in the report"
 S DIR("?")="Appointments will not be included in the report for divisions that you do not select."
 S QUIT=0
 F  D  Q:QUIT
 .D ^DIR
 .I $D(DUOUT)!$D(DTOUT) S QUIT=1,SUCCESS=0 Q
 .I ((+Y)'>0) S QUIT=1 Q
 .S DGENRP("DIVISION",+Y)=""
 S:'$O(DGENRP("DIVISION",0)) SUCCESS=0
 Q SUCCESS
 ;
CLINIC(DGENRP) ;
 ;Description: asks clinics to include
 ;
 N DIR,QUIT,SUCCESS
 S SUCCESS=1
 S DIR(0)="PO^44:AEM"
 S DIR("A")="Select the clinics to include in the report"
 S DIR("?")="Appointments will not be included in the report for clinics that you do not select."
 S DIR("S")="I $P(^(0),""^"",3)=""C"""
 S QUIT=0
 F  D  Q:QUIT
 .D ^DIR
 .I $D(DUOUT)!$D(DTOUT) S QUIT=1,SUCCESS=0 Q
 .I ((+Y)'>0) S QUIT=1 Q
 .S DGENRP("CLINIC",+Y)=""
 S:'$O(DGENRP("CLINIC",0)) SUCCESS=0
 Q SUCCESS
 ;
JUSTONCE(DGENRP) ;
 ;Description: Asks wether or not to include only the first appointment
 ;for a patient that has multiple appointments
 ;
 ;Output:
 ;  Function Value: reuturns 1 on success, 0 on failure
 ;  DGENRP("JUSTONCE")=<1 for only earliest, 0 for all>
 ;
 N DIR
 S DGENRP("JUSTONCE")=0
 S DIR(0)="Y"
 S DIR("B")="NO"
 S DIR("A")="For patients with multiple appointments, should only the first be listed"
 D ^DIR
 Q:$D(DIRUT) 0
 I +Y=1 S DGENRP("JUSTONCE")=1
 Q 1


text:
#ifndef ATEMA_CORE_APPLICATION_HPP
#define ATEMA_CORE_APPLICATION_HPP

#include <Atema/Core/Config.hpp>
#include <Atema/Core/NonCopyable.hpp>
#include <Atema/Core/Event.hpp>

#include <queue>

namespace at
{
	class TimeStep;

	class ATEMA_CORE_API Application : public NonCopyable
	{
	public:
		virtual ~Application();

		static Application& instance();

		// Runs the main loop
		void run();

		// Request the application to close after the current loop execution
		void close();

		// Push an event that will be executed on the next loop
		void pushEvent(Event& event);

		// 0 : no limit
		void setFpsLimit(uint32_t fpsLimit);

	protected:
		Application();

		virtual void onEvent(Event& event) = 0;
		virtual void update(TimeStep ms) = 0;

	private:
		void processEvents();

		bool m_close;
		std::queue<Event> m_currentEvents;
		std::queue<Event> m_nextEvents;

		uint32_t m_fpsLimit;
	};
}

#endif


text:
begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails", github: "rails/rails"
  gem "arel", github: "rails/arel"
end

require "action_controller/railtie"

class TestApp < Rails::Application
  config.root = __dir__
  secrets.secret_key_base = "secret_key_base"

  config.logger = Logger.new($stdout)
  Rails.logger  = config.logger

  routes.draw do
    get "/" => "test#index"
  end
end

class TestController < ActionController::Base
  include Rails.application.routes.url_helpers

  def index
    render plain: "Home"
  end
end

require "minitest/autorun"
require "rack/test"

class BugTest < Minitest::Test
  include Rack::Test::Methods

  def test_returns_success
    get "/"
    assert last_response.ok?
  end

  private
    def app
      Rails.application
    end
end


text:
#include <Foundation/Foundation.h>

@interface BlockAsReceiver : NSObject

@end

@implementation BlockAsReceiver

static bool _isAppStartingUp() { return true; }

/* This program would crash if we would specialize NSObject.copy
here because it would become a virtual call without receiver,
as the receiver is the block parameter. Blocks as also objects! */
static void setupTimerOk() {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    dispatch_block_t _timerBlock = [^{
      if (_isAppStartingUp()) {
        return;
      }
    } copy];
  });
}

@end


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>remove (ConstMocker)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

# File vendor/plugins/active_scaffold/test/const_mocker.rb, line 10
  def remove
    @const_names.each{|const_name|
      Object.send :remove_const, const_name if Object.const_defined?(const_name)
    }
  end


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

    AudioNetwork.Injector
        .registerFactory('PhysicalLayerCore.ReceiveMulticoreWorker', _ReceiveMulticoreWorker);

    _ReceiveMulticoreWorker.$inject = [
        'PhysicalLayerCore.ReceiveMulticoreWorkerThread',
        'Common.SimplePromiseBuilder'
    ];

    function _ReceiveMulticoreWorker(
        ReceiveMulticoreWorkerThread,
        SimplePromiseBuilder
    ) {
        var ReceiveMulticoreWorker;

        ReceiveMulticoreWorker = function (key) {
            var threadCode, blob, objectUrl;

            if (AudioNetwork.bootConfig.multicoreState === AudioNetwork.MULTICORE_STATE.DISABLED) {
                throw ReceiveMulticoreWorker.MULTICORE_SUPPORT_IS_NOT_ENABLED_EXCEPTION;
            }

            threadCode = ReceiveMulticoreWorkerThread.getJavaScriptCode();
            blob = new Blob(
                [ threadCode ],
                { type: 'application/javascript' }
            );
            objectUrl = URL.createObjectURL(blob);

            this.$$key = key;
            this.$$worker = new Worker(objectUrl);
            this.$$worker.onmessage = this.$$onMessage.bind(this);

            this.$$promise = [];
            this.$$promise.length = ReceiveMulticoreWorker.MESSAGE_TOTAL;

            this.$$sendToThread(ReceiveMulticoreWorker.INITIALIZATION, this.$$key);
        };

        ReceiveMulticoreWorker.MULTICORE_SUPPORT_IS_NOT_ENABLED_EXCEPTION = 'Multicore support is not enabled';
        ReceiveMulticoreWorker.PREVIOUS_PROMISE_NOT_RESOLVED_YET_EXCEPTION = 'Previous promise not resolved yet';

        ReceiveMulticoreWorker.INITIALIZATION = 0;
        ReceiveMulticoreWorker.INITIALIZATION_SUCCESS = 1;
        ReceiveMulticoreWorker.INITIALIZATION_FAIL = 2;
        ReceiveMulticoreWorker.HANDLE_SAMPLE_BLOCK = 3;
        ReceiveMulticoreWorker.HANDLE_SAMPLE_BLOCK_SUCCESS = 4;
        ReceiveMulticoreWorker.HANDLE_SAMPLE_BLOCK_FAIL = 5;
        ReceiveMulticoreWorker.COMPUTE_CRAZY_SINE_SUM = 6;
        ReceiveMulticoreWorker.COMPUTE_CRAZY_SINE_SUM_SUCCESS = 7;
        ReceiveMulticoreWorker.COMPUTE_CRAZY_SINE_SUM_FAIL = 8;

        ReceiveMulticoreWorker.MESSAGE_TOTAL = 9;
        ReceiveMulticoreWorker.MESSAGE_INDEX_SPACING = 3;
        ReceiveMulticoreWorker.MESSAGE_INDEX_OFFSET_SUCCESS = 1;
        ReceiveMulticoreWorker.MESSAGE_INDEX_OFFSET_FAIL = 2;

        ReceiveMulticoreWorker.prototype.destroy = function() {
            if (this.$$worker) {
                this.$$worker.terminate();
                this.$$worker = undefined;
            }
        };

        ReceiveMulticoreWorker.prototype.getInitialization = function() {
            return this.$$promise[ReceiveMulticoreWorker.INITIALIZATION];
        };

        ReceiveMulticoreWorker.prototype.$$onMessage = function(event) {
            var
                data = event.data,
                messageIndex = data.length > 0 ? data[0] : null,
                result = data.length > 1 ? data[1] : null,
                promise,
                i;

            for (i = 0; i < this.$$promise.length; i++) {
                promise = this.$$promise[i];
                if (promise) {
                    switch (messageIndex % ReceiveMulticoreWorker.MESSAGE_INDEX_SPACING) {
                        case ReceiveMulticoreWorker.MESSAGE_INDEX_OFFSET_SUCCESS:
                            promise.resolve(result);
                            break;
                        case ReceiveMulticoreWorker.MESSAGE_INDEX_OFFSET_FAIL:
                            promise.reject(result);
                            break;
                    }
                    this.$$promise[i] = undefined;
                    break;
                }
            }
        };

        ReceiveMulticoreWorker.prototype.$$sendToThread = function (messageIndex, value) {
            if (this.$$promise[messageIndex]) {
                throw ReceiveWorker.PREVIOUS_PROMISE_NOT_RESOLVED_YET_EXCEPTION;
            }
            this.$$promise[messageIndex] = SimplePromiseBuilder.build();
            this.$$worker.postMessage([
                messageIndex,
                value
            ]);

            return this.$$promise[messageIndex];
        };

        ReceiveMulticoreWorker.prototype.computeCrazySineSum = function (value) {
            return this.$$sendToThread(ReceiveMulticoreWorker.COMPUTE_CRAZY_SINE_SUM, value);
        };

        ReceiveMulticoreWorker.prototype.handleSampleBlock = function (value) {
            return this.$$sendToThread(ReceiveMulticoreWorker.HANDLE_SAMPLE_BLOCK, value);
        };

        return ReceiveMulticoreWorker;
    }

})();


text:
* Update to version 3.4.3 (build 4055.4198)

## v1.0.6:

* Update to version 3.2.8

## v1.0.4:

* Add license file
* Update to version 3.2.3
* Ignore failure in file mode changes
* use strings instead of symbols


text:
{% if offers %}

        {% for offer in offers %}

                                    {{ offer.title }}

                                    {{ offer.location }}

                                    {{ offer.started_at|date:'j E Y, G:m'|default:' teraz' }} -
                                    {{ offer.finished_at|date:'j E Y, G:m'|default:' do ustalenia' }}

                        {% if offer.benefits %}

Twoje korzyści

{{ offer.benefits }}

                        {% endif %}
                        {% if offer.requirements %}

Wymagania wobec Ciebie

{{ offer.requirements }}

                        {% endif %}
                        {% if offer.time_commitment %}

Zaangażowanie czasowe

{{ offer.time_commitment }}

                        {% endif %}

Organizator: {{ offer.organization.name }}

        {% endfor %}

{% else %}

Zgłoś się w jednej z dostępnych ofert wolontariatu i zapełnij to miejsce.

{% endif %}


text:
// Test dependencies are required and exposed in common/bootstrap.js
require('../common/bootstrap');

var testDir = __dirname + '/tmp/';
var testFile = 'test_rsa';
var testPath = path.join(testDir, testFile);
var fakeKeyFileData = 'Test Contents';
var pubKey = (`ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDKg4tn+4c1lutKReMLhS8OeoHFC8yej41NUS7OIevSKuHNFEphMztD9L/FA5uAIDrzv1kUixEN5k4mmN3IEXs6oiFlZAQQY2ZSAVrKKNA2B2mR52eqwrIUkDjCiGh78TqRrHTLohl+9bcMebwbchX7zbpUh9ur9Th4n0yDZNhtrEpOWlvg2yxXlJg0h6c8V7145F1jAmpHWuU7cndGJKfzv4OLQTXbEnOvjKWZFLNfPUCTnzzKnFQY2a7MvV66iRRdy/lBahJzDQcNnvXyek+e+6JrWhNAtQm2CrgTFnCnJrut5XL5gzELlr0mAPzmkKAm+7XbFSXaPRbtUqx7QiY1 (unnamed)`).trim();

exports['Tessel.isProvisioned()'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.existsSync = this.sandbox.stub(fs, 'existsSync').returns(true);
    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  isProvisionedTrue: function(test) {
    test.expect(3);

    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;

    Tessel.LOCAL_AUTH_PATH = testPath;
    Tessel.isProvisioned();

    test.equal(this.existsSync.callCount, 2);
    test.equal(this.existsSync.firstCall.args[0], path.join(Tessel.LOCAL_AUTH_PATH, 'id_rsa'));
    test.equal(this.existsSync.lastCall.args[0], path.join(Tessel.LOCAL_AUTH_PATH, 'id_rsa.pub'));

    Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
    test.done();
  },

  isProvisionedFalse: function(test) {
    test.expect(2);

    this.existsSync.returns(false);

    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;

    Tessel.LOCAL_AUTH_PATH = testPath;
    Tessel.isProvisioned();

    test.equal(this.existsSync.callCount, 1);
    test.equal(this.existsSync.firstCall.args[0], path.join(Tessel.LOCAL_AUTH_PATH, 'id_rsa'));

    Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
    test.done();
  },
};

exports['controller.provisionTessel'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.tessel = TesselSimulator();

    this.tessel._rps.on('newListener', (event) => {
      if (event === 'close') {
        setImmediate(() => {
          this.tessel._rps.emit(event);
        });
      }
    });

    this.isProvisioned = this.sandbox.stub(Tessel, 'isProvisioned');
    this.controllerProvisionTessel = this.sandbox.spy(controller, 'provisionTessel');

    this.exec = this.sandbox.stub(cp, 'exec', (command, callback) => {
      callback();
    });

    this.writeFile = this.sandbox.stub(fs, 'writeFile', (file, contents, options, callback) => {
      callback(null, callback);
    });

    this.readFile = this.sandbox.stub(fs, 'readFile', (file, options, callback) => {
      callback(null, pubKey.trim());
    });

    this.provision = this.sandbox.spy(Tessel.prototype, 'provisionTessel');

    this.getName = this.sandbox.stub(Tessel.prototype, 'getName', () => {
      return Promise.resolve('Tessel-1');
    });

    this.getTessel = this.sandbox.stub(Tessel, 'get', () => {
      return Promise.resolve(this.tessel);
    });

    this.warn = this.sandbox.stub(log, 'warn', function() {});
    this.info = this.sandbox.stub(log, 'info', function() {});

    this.closeTesselConnections = this.sandbox.spy(controller, 'closeTesselConnections');

    this.exportKey = this.sandbox.stub(RSA.prototype, 'exportKey', _ => _);
    this.parseKey = this.sandbox.stub(sshpk, 'parseKey', _ => _);
    this.RSA = this.sandbox.stub(global, 'RSA').returns(Object.create(RSA.prototype));

    done();
  },

  tearDown: function(done) {
    this.tessel.mockClose();
    this.tessel._rps.removeAllListeners();
    this.sandbox.restore();
    deleteKeyTestFolder(done);
  },

  completeForced: function(test) {
    test.expect(5);
    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;

    Tessel.LOCAL_AUTH_PATH = testPath;

    // Say it's provisioned to make sure old folder gets deleted
    this.isProvisioned.onFirstCall().returns(true);
    // Make sure to mention that it is not provisioned after folder is deleted
    this.isProvisioned.onSecondCall().returns(false);

    this.controllerProvisionTessel({
        force: true
      })
      .then(() => {
        test.equal(this.exec.callCount, 1);
        test.equal(this.exec.lastCall.args[0], 'rm -r ' + Tessel.LOCAL_AUTH_PATH);
        test.equal(this.provision.callCount, 1);
        test.equal(this.closeTesselConnections.callCount, 1);
        test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
        Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
        test.done();
      });
  },

  completeUnprovisioned: function(test) {
    test.expect(4);
    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;

    Tessel.LOCAL_AUTH_PATH = testPath;

    this.isProvisioned.returns(false);

    this.controllerProvisionTessel().then(() => {
      test.equal(this.exec.callCount, 0);
      test.equal(this.provision.callCount, 1);
      test.equal(this.closeTesselConnections.callCount, 1);
      test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
      Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
      test.done();
    });
  },

  completeUnprovisionedForced: function(test) {
    test.expect(4);
    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;

    Tessel.LOCAL_AUTH_PATH = testPath;

    this.isProvisioned.returns(false);

    this.controllerProvisionTessel({
      force: true
    }).then(() => {
      test.equal(this.exec.callCount, 0);
      test.equal(this.provision.callCount, 1);
      test.equal(this.closeTesselConnections.callCount, 1);
      test.equal(Array.isArray(this.closeTesselConnections.args[0]), true);
      Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
      test.done();
    });
  },

  reportFailure: function(test) {
    test.expect(2);

    this.exec.restore();
    this.exec = this.sandbox.stub(cp, 'exec', function(command, callback) {
      callback('some error');
    });

    this.isProvisioned.returns(true);

    this.controllerProvisionTessel({
      force: true
    }).catch(error => {
      test.equal(error, 'some error');
      test.equal(this.closeTesselConnections.callCount, 0);
      test.done();
    });
  }
};

exports['Tessel.prototype.provisionTessel'] = {

  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();

    this.provision = this.sandbox.spy(Tessel.prototype, 'provisionTessel');
    this.warn = this.sandbox.stub(log, 'warn', function() {});
    this.info = this.sandbox.stub(log, 'info', function() {});
    this.setupLocal = this.sandbox.spy(provision, 'setupLocal');
    this.fileExists = this.sandbox.spy(commands, 'ensureFileExists');
    this.appendStdinToFile = this.sandbox.spy(commands, 'appendStdinToFile');

    this.exportKey = this.sandbox.stub(RSA.prototype, 'exportKey', _ => _);
    this.parseKey = this.sandbox.stub(sshpk, 'parseKey', _ => _);
    this.RSA = this.sandbox.stub(global, 'RSA').returns(Object.create(RSA.prototype));

    this.writeFile = this.sandbox.stub(fs, 'writeFile', (dirname, contents, options, callback) => {
      callback(null);
    });
    this.ensureDir = this.sandbox.stub(fs, 'ensureDir', (dirname, callback) => {
      callback(null);
    });

    this.tessel = TesselSimulator();

    deleteKeyTestFolder();

    done();
  },

  tearDown: function(done) {
    this.tessel.mockClose();
    this.sandbox.restore();
    deleteKeyTestFolder(done);
  },

  alreadyAuthedError: function(test) {
    test.expect(1);

    this.setupLocal.restore();

    this.setupLocal = this.sandbox.stub(provision, 'setupLocal', function() {
      return Promise.resolve();
    });
    this.authTessel = this.sandbox.stub(provision, 'authTessel', function() {
      return Promise.reject(new provision.AlreadyAuthenticatedError());
    });

    this.tessel.provisionTessel()
      .then(() => {
        test.equal(this.info.lastCall.args[0], 'Tessel is already authenticated with this computer.');
        test.done();
      })
      .catch(() => {
        test.ok(false, 'The AlreadyAuthenticatedError will resolve, not reject.');
        test.done();
      });

  },

  requestFromLANTessel: function(test) {
    test.expect(2);
    // Set the connectionType to LAN so it will fail
    this.tessel = new TesselSimulator({
      type: 'LAN'
    });

    // Attempt to provision
    this.tessel.provisionTessel()
      // If an error is not thrown, this test failed
      .then(() => {
        test.ok(false, 'provisionTessel should not have been successful');
        test.done();
      })
      // If the error was thrown, continue to the next test
      .catch((err) => {
        test.equal(err !== undefined, true);
        // Ensure we never tried to set up local keys
        test.equal(this.setupLocal.callCount, 0);
        this.tessel = new TesselSimulator();
        // Finish the test
        test.done();
      });
  },

  keysCreatedCorrectPermissions: function(test) {
    test.expect(3);

    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;
    Tessel.LOCAL_AUTH_PATH = testPath;

    // Attempt to set up local keys
    provision.setupLocal( /* intentionally empty */ )
      .then(() => {
        // Make sure we wrote both keys
        test.equal(this.writeFile.callCount, 2);

        // Permissions should be 0600 (decimal 384)
        // (owner can read and write)
        test.equal(this.writeFile.firstCall.args[2].mode, 384);
        test.equal(this.writeFile.lastCall.args[2].mode, 384);

        Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
        // End the test
        test.done();
      })
      .catch(() => {
        test.ok(false, 'Key write failed.');
        test.done();
      });
  },

  noPreviousLocalKeys: function(test) {
    test.expect(1);

    this.isProvisioned = this.sandbox.stub(Tessel, 'isProvisioned').returns(false);

    // Attempt to set up local keys
    provision.setupLocal(testPath)
      .then(() => {
        // Make sure we wrote both keys
        test.equal(this.writeFile.callCount, 2);
        test.done();
      })
      .catch(() => {
        test.ok(false, 'Key write failed.');
        test.done();
      });
  },

  fallbackKeyPath: function(test) {
    test.expect(4);

    this.isProvisioned = this.sandbox.stub(Tessel, 'isProvisioned').returns(false);

    var tesselAuthPath = Tessel.LOCAL_AUTH_PATH;
    Tessel.LOCAL_AUTH_PATH = testPath;

    // Attempt to set up local keys
    provision.setupLocal( /* intentionally empty */ )
      .then(() => {
        // Make sure we wrote both keys
        test.equal(this.writeFile.callCount, 2);
        test.equal(path.dirname(this.writeFile.firstCall.args[0]), testPath);
        test.equal(path.dirname(this.writeFile.lastCall.args[0]), testPath);

        // Ensure that key ends with a newline
        var publicKey = this.writeFile.firstCall.args[1];
        test.equal(publicKey[publicKey.length - 1], '\n');

        Tessel.LOCAL_AUTH_PATH = tesselAuthPath;
        this.isProvisioned.restore();
        // End the test
        test.done();
      })
      .catch(() => {
        test.ok(false, 'Key write failed.');
        test.done();
      });
  },

  keyAlreadyInRemoteAuth: function(test) {
    test.expect(3);

    this.writeFile.restore();

    createTestKeys(error => {
      if (error) {
        test.ok(false, `createTestKeys failed: ${error.toString()}`);
        test.done();
      } else {
        provision.authTessel(this.tessel, testPath)
          .then(() => {
            test.ok(false, 'Authorize did not return fail even though remote Tessel already listed user key.');
            test.done();
          })
          .catch(error => {
            test.equal(error !== undefined, true);
            // We should have checked that the remote file exists
            test.equal(this.fileExists.callCount, 1);
            // We should not have tried to write anything to the file
            test.equal(this.appendStdinToFile.callCount, 0);

            test.done();
          });

        // Emit close for ensuring remote file exists
        setTimeout(() => {
          this.tessel._rps.emit('close');
          // Write out fake key file data
          setTimeout(() => {
            this.tessel._rps.stdout.push(fakeKeyFileData);
            // Finish key file data process
            setTimeout(() => {
              this.tessel._rps.emit('close');
            }, 10);
          }, 10);
        }, 10);
      }
    });
  },

  deviceReadyForProvision: function(test) {
    test.expect(3);

    this.writeFile.restore();

    createTestKeys(error => {
      if (error) {
        test.ok(false, `createTestKeys failed: ${error.toString()}`);
        test.done();
      } else {
        // Attempt to authorize the remote Tessel by writing the SSH keys
        provision.authTessel(this.tessel, testPath)
          .then(() => {
            // We should have checked that the remote file exists
            test.equal(this.fileExists.callCount, 1);
            // We should not have tried to write anything to the file
            test.equal(this.appendStdinToFile.callCount, 1);
            // Ensure the proper key was provided to the authorized_keys file
            test.done();
          })
          .catch(function unexpectedRoute() {
            test.ok(false, 'Provision did not copy keys to remote device when it should have.');
            test.done();
          });

        // Emit close for ensuring remote file exists
        setTimeout(() => {
          this.tessel._rps.emit('close');
          // Write out no keys so it's forced to write a new one
          setTimeout(() => {
            this.tessel._rps.stdout.push('');
            // Finish key file read back process
            setTimeout(() => {
              this.tessel._rps.emit('close');
              // Ensure the fake key file data was sent to stdin
              this.tessel._rps.on('stdin', function(data) {
                test.equal(data.toString(), fakeKeyFileData);
              });
              // Finish key copy process
              setTimeout(() => {
                this.tessel._rps.emit('close');
              }, 1);
            }, 1);
          }, 1);
        }, 1);
      }
    });
  }
};
exports['provision.setDefaultKey'] = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    this.warn = this.sandbox.stub(log, 'warn', function() {});
    this.info = this.sandbox.stub(log, 'info', function() {});
    this.basic = this.sandbox.stub(log, 'basic', function() {});

    done();
  },

  tearDown: function(done) {
    this.sandbox.restore();
    done();
  },

  // setDefaultKey should reject with an error if no path was provided
  failNoKey: function(test) {
    test.expect(1);

    provision.setDefaultKey()
      .then(function noCall() {
        // This test should throw an error. Fail if it didn't
        test.ok(false, 'provision.setDefaultKey should not have been successful');
        test.done();
      })
      .catch(function doCall(err) {
        test.ok(err, 'Returned error is undefined');
        test.done();
      });
  },

  // setDefaultKey should reject with an error if a non-string was provided
  failWrongType: function(test) {
    test.expect(1);

    provision.setDefaultKey(path.parse('~/.tessel/id_rsa'))
      .then(function noCall() {
        // This test should throw an error. Fail if it didn't
        test.ok(false, 'provision.setDefaultKey should not have been successful');
        test.done();
      })
      .catch(function doCall(err) {
        test.ok(err, 'Returned error is undefined');
        test.done();
      });
  },

  // setDefaultKey should reject with an error if a non-existent file was provided
  failNoFiles: function(test) {
    test.expect(1);
    provision.setDefaultKey('./no_files_here')
      .then(function noCall() {
        // This test should throw an error. Fail if it didn't
        test.ok(false, 'provision.setDefaultKey should not have been successful');
        test.done();
      })
      .catch(function doCall(err) {
        test.ok(err, 'Returned error is undefined');
        test.done();
      });
  },

  successfulSetting: function(test) {
    test.expect(1);

    var key = path.join(__dirname, './real_file_i_promise');
    var privateKeyPath = path.join(__dirname, './real_file_i_promise');
    var publicKeyPath = path.join(__dirname, './real_file_i_promise' + '.pub');
    fs.writeFileSync(privateKeyPath, 'test_contents');
    fs.writeFileSync(publicKeyPath, 'test_contents');
    provision.setDefaultKey(key)
      .then(function doCall() {
        test.equal(Tessel.LOCAL_AUTH_KEY, key);
        fs.unlinkSync(privateKeyPath);
        fs.unlinkSync(publicKeyPath);
        test.done();
      })
      .catch(function noCall() {
        // This test should not throw an error. Fail if it did
        test.ok(false, 'provision.setDefaultKey should have been successful');
        test.done();
      });
  }
};

function createTestKeys(callback) {
  // Create the test folder
  createKeyTestFolder(function createKeys(err) {
    if (err) {
      if (typeof callback === 'function') {
        callback(err);
      }
      return;
    }
    // Create fake keys
    async.parallel([
      (next) => fs.writeFile(testPath + '.pub', fakeKeyFileData, next), (next) => fs.writeFile(testPath, fakeKeyFileData, next),
    ], callback);
  });
}

function createKeyTestFolder(callback) {
  mkdirp(testDir, callback);
}

function deleteKeyTestFolder(callback) {
  if (!callback) {
    callback = function() {};
  }
  fs.remove(testDir, callback);
}