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

module.exports = function() {};

module.exports.prototype = {

    configure: function(disallowPaddingNewlinesInBlocks) {
        assert(
            disallowPaddingNewlinesInBlocks === true,
            'disallowPaddingNewlinesInBlocks option requires the value true or should be removed'
        );
    },

    getOptionName: function() {
        return 'disallowPaddingNewlinesInBlocks';
    },

    check: function(file, errors) {
        var lines = file.getLines();
        var tokens = file.getTokens();

        file.iterateNodesByType('BlockStatement', function(node) {
            var openingBracketPos = file.getTokenPosByRangeStart(node.range[0]);
            var openingBracket = tokens[openingBracketPos];
            var startLine = openingBracket.loc.start.line;

            var closingBracketPos = file.getTokenPosByRangeStart(node.range[1] - 1);
            var closingBracket = tokens[closingBracketPos];
            var closingLine = closingBracket.loc.start.line;

            if (startLine === closingLine) {
                return;
            }

            if (lines[startLine] === '') {
                errors.add('Expected no padding newline after opening curly brace', openingBracket.loc.end);
            }

            if (lines[closingLine - 2] === '') {
                errors.add('Expected no padding newline before closing curly brace', closingBracket.loc.start);
            }
        });
    }

};


text:
enum One {
	ONE
};

enum ZeroOne {
	ZERO,
	ONE // error: redefinition of enumerator 'ONE'
};

enum One enum_1(void);
enum ZeroOne enum_2(void);

int main(void) {
	PrintEnum(enum_1());
	PrintEnum(enum_2());

	return 0;
}

enum One enum_1(void) {
	return ONE;
}

enum ZeroOne enum_2(void) {
	return ONE;
}

redpajama_set_name: RedPajamaGithub


text:
#import <IDEKit/IDEViewController.h>

@class NSString;

@interface IDEDebugArea : IDEViewController
{
}

+ (id)createShowRightViewButton;
+ (id)createShowLeftViewButton;
- (void)activateConsole;
- (BOOL)canActivateConsole;
- (void)clearConsole;
- (BOOL)canClearConsole;
@property(readonly) NSString *stateSavingIdentifier;

@end


text:
import ts from 'typescript';

import {ErrorCode, ngErrorCode} from '../../diagnostics';
import {DeclarationNode} from '../../reflection';

import {ReferenceGraph} from './reference_graph';

/**
 * Produce `ts.Diagnostic`s for classes that are visible from exported types (e.g. directives
 * exposed by exported `NgModule`s) that are not themselves exported.
 *
 * This function reconciles two concepts:
 *
 * A class is Exported if it's exported from the main library `entryPoint` file.
 * A class is Visible if, via Angular semantics, a downstream consumer can import an Exported class
 * and be affected by the class in question. For example, an Exported NgModule may expose a
 * directive class to its consumers. Consumers that import the NgModule may have the directive
 * applied to elements in their templates. In this case, the directive is considered Visible.
 *
 * `checkForPrivateExports` attempts to verify that all Visible classes are Exported, and report
 * `ts.Diagnostic`s for those that aren't.
 *
 * @param entryPoint `ts.SourceFile` of the library's entrypoint, which should export the library's
 * public API.
 * @param checker `ts.TypeChecker` for the current program.
 * @param refGraph `ReferenceGraph` tracking the visibility of Angular types.
 * @returns an array of `ts.Diagnostic`s representing errors when visible classes are not exported
 * properly.
 */
export function checkForPrivateExports(
    entryPoint: ts.SourceFile, checker: ts.TypeChecker, refGraph: ReferenceGraph): ts.Diagnostic[] {
  const diagnostics: ts.Diagnostic[] = [];

  // Firstly, compute the exports of the entry point. These are all the Exported classes.
  const topLevelExports = new Set<DeclarationNode>();

  // Do this via `ts.TypeChecker.getExportsOfModule`.
  const moduleSymbol = checker.getSymbolAtLocation(entryPoint);
  if (moduleSymbol === undefined) {
    throw new Error(`Internal error: failed to get symbol for entrypoint`);
  }
  const exportedSymbols = checker.getExportsOfModule(moduleSymbol);

  // Loop through the exported symbols, de-alias if needed, and add them to `topLevelExports`.
  // TODO(alxhub): use proper iteration when build.sh is removed. (#27762)
  exportedSymbols.forEach(symbol => {
    if (symbol.flags & ts.SymbolFlags.Alias) {
      symbol = checker.getAliasedSymbol(symbol);
    }
    const decl = symbol.valueDeclaration;
    if (decl !== undefined) {
      topLevelExports.add(decl);
    }
  });

  // Next, go through each exported class and expand it to the set of classes it makes Visible,
  // using the `ReferenceGraph`. For each Visible class, verify that it's also Exported, and queue
  // an error if it isn't. `checkedSet` ensures only one error is queued per class.
  const checkedSet = new Set<DeclarationNode>();

  // Loop through each Exported class.
  // TODO(alxhub): use proper iteration when the legacy build is removed. (#27762)
  topLevelExports.forEach(mainExport => {
    // Loop through each class made Visible by the Exported class.
    refGraph.transitiveReferencesOf(mainExport).forEach(transitiveReference => {
      // Skip classes which have already been checked.
      if (checkedSet.has(transitiveReference)) {
        return;
      }
      checkedSet.add(transitiveReference);

      // Verify that the Visible class is also Exported.
      if (!topLevelExports.has(transitiveReference)) {
        // This is an error, `mainExport` makes `transitiveReference` Visible, but
        // `transitiveReference` is not Exported from the entrypoint. Construct a diagnostic to
        // give to the user explaining the situation.

        const descriptor = getDescriptorOfDeclaration(transitiveReference);
        const name = getNameOfDeclaration(transitiveReference);

        // Construct the path of visibility, from `mainExport` to `transitiveReference`.
        let visibleVia = 'NgModule exports';
        const transitivePath = refGraph.pathFrom(mainExport, transitiveReference);
        if (transitivePath !== null) {
          visibleVia = transitivePath.map(seg => getNameOfDeclaration(seg)).join(' -> ');
        }

        const diagnostic: ts.Diagnostic = {
          category: ts.DiagnosticCategory.Error,
          code: ngErrorCode(ErrorCode.SYMBOL_NOT_EXPORTED),
          file: transitiveReference.getSourceFile(),
          ...getPosOfDeclaration(transitiveReference),
          messageText: `Unsupported private ${descriptor} ${name}. This ${
              descriptor} is visible to consumers via ${
              visibleVia}, but is not exported from the top-level library entrypoint.`,
        };

        diagnostics.push(diagnostic);
      }
    });
  });

  return diagnostics;
}

function getPosOfDeclaration(decl: DeclarationNode): {start: number, length: number} {
  const node: ts.Node = getIdentifierOfDeclaration(decl) || decl;
  return {
    start: node.getStart(),
    length: node.getEnd() + 1 - node.getStart(),
  };
}

function getIdentifierOfDeclaration(decl: DeclarationNode): ts.Identifier|null {
  if ((ts.isClassDeclaration(decl) || ts.isVariableDeclaration(decl) ||
       ts.isFunctionDeclaration(decl)) &&
      decl.name !== undefined && ts.isIdentifier(decl.name)) {
    return decl.name;
  } else {
    return null;
  }
}

function getNameOfDeclaration(decl: DeclarationNode): string {
  const id = getIdentifierOfDeclaration(decl);
  return id !== null ? id.text : '(unnamed)';
}

function getDescriptorOfDeclaration(decl: DeclarationNode): string {
  switch (decl.kind) {
    case ts.SyntaxKind.ClassDeclaration:
      return 'class';
    case ts.SyntaxKind.FunctionDeclaration:
      return 'function';
    case ts.SyntaxKind.VariableDeclaration:
      return 'variable';
    case ts.SyntaxKind.EnumDeclaration:
      return 'enum';
    default:
      return 'declaration';
  }
}


text:
package com.github.obsidianarch.gvengine.core.input;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

/**
 * The physical device which is bound to an action. (e.g. mouse, keyboard, controller).
 *
 * @author Austin
 * @version 14.08.02
 * @since 14.03.30
 */
public enum InputMedium
{

    /**
     * The input binding is using the keyboard.
     */
    KEYBOARD,
    /**
     * The input binding is using the mouse.
     */
    MOUSE,
    /**
     * The input binding is using a controller.
     */
    CONTROLLER;

    /**
     * @param button
     *         The button's number.
     *
     * @return If the button is pressed for this input medium.
     */
    public boolean isButtonDown( int button )
    {

        switch ( this )
        {

            case KEYBOARD:
                return Keyboard.isKeyDown( button );

            case MOUSE:
                return Mouse.isButtonDown( button );

            case CONTROLLER:
                return false;

            default:
                return false;

        }
    }

}


text:
package org.apache.ambari.server.api.resources;

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

import org.apache.ambari.server.api.services.Request;
import org.apache.ambari.server.api.util.TreeNode;
import org.apache.ambari.server.controller.WidgetResponse;
import org.apache.ambari.server.controller.spi.Resource;

/**
 * Resource Definition for WidgetLayout types.
 */
public class ActiveWidgetLayoutResourceDefinition extends BaseResourceDefinition {

  public ActiveWidgetLayoutResourceDefinition() {
    super(Resource.Type.ActiveWidgetLayout);
  }

  @Override
  public String getPluralName() {
    return "widget_layouts";
  }

  @Override
  public String getSingularName() {
    return "widget_layout";
  }

  @Override
  public List<PostProcessor> getPostProcessors() {
    List<PostProcessor> listProcessors = super.getPostProcessors();
    listProcessors.add(new WidgetLayoutHrefProcessor());

    return listProcessors;
  }

  /**
   * Base resource processor which generates href's.  This is called by the
   * {@link org.apache.ambari.server.api.services.ResultPostProcessor} during post processing of a result.
   */
  private class WidgetLayoutHrefProcessor extends BaseHrefPostProcessor {
    @Override
    public void process(Request request, TreeNode<Resource> resultNode, String href) {
      TreeNode<Resource> parent = resultNode.getParent();

      for (TreeNode<Resource> node : parent.getChildren()) {
        if (node.getObject().getPropertiesMap().get("WidgetLayoutInfo") != null) {
          String layoutId = resultNode.getObject().getPropertyValue("WidgetLayoutInfo/id").toString();
          String clusterName = resultNode.getObject().getPropertyValue("WidgetLayoutInfo/cluster_name").toString();
          String newHref = href.substring(0, href.indexOf("/users") + 1) +
                  "clusters/" + clusterName + "/widget_layouts/" + layoutId;
          resultNode.setProperty("href", newHref);
        }
        if (node.getObject().getPropertiesMap().get("WidgetLayoutInfo") != null &&
                node.getObject().getPropertiesMap().get("WidgetLayoutInfo").get("WidgetInfo") != null) {

          ArrayList widgetsList = (ArrayList) node.getObject().getPropertiesMap().get("WidgetLayoutInfo").get("WidgetInfo");
          for (Object widgetObject : widgetsList) {
            HashMap<String, Object> widgetMap = (HashMap) widgetObject;
            String widgetId = ((WidgetResponse) widgetMap.get("Widget")).getId().toString();
            String clusterName = ((WidgetResponse) widgetMap.get("Widget")).getClusterName().toString();
            String widgetHref = href.substring(0, href.indexOf("/users") + 1) +
                    "clusters/" + clusterName + "/widgets/" + widgetId;
            widgetMap.put("href", widgetHref);
          }
        }
      }
    }
  }
}


text:
namespace IdentityBase.Events
{
    /// <summary>
    /// Categories for messenging events
    /// </summary>
    public static class EventCategories
    {
        public const string UserAccount = "UserAccount";
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>cpp-headers: File List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

cpp-headers
    0.1

File List

Here is a list of all files with brief descriptions:

[detail level 12]

 ▼ src

 circular_buffer.h	Fast implementation of a Circular Buffer

 SimpleSet.h	Very basic, light-weight unordered set designed for small data

<address class="footer">
Generated by

 1.8.13
</address>


text:
using System;
using System.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;

namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
    public partial class ScriptBaseClass : MarshalByRefObject
    {
        public IOSSL_Api m_OSSL_Functions;

        public void ApiTypeOSSL(IScriptApi api)
        {
            if (!(api is IOSSL_Api))
                return;

            m_OSSL_Functions = (IOSSL_Api)api;

            Prim = new OSSLPrim(this);
        }

        public void osSetRegionWaterHeight(double height)
        {
            m_OSSL_Functions.osSetRegionWaterHeight(height);
        }

        public void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour)
        {
            m_OSSL_Functions.osSetRegionSunSettings(useEstateSun, sunFixed, sunHour);
        }

        public void osSetEstateSunSettings(bool sunFixed, double sunHour)
        {
            m_OSSL_Functions.osSetEstateSunSettings(sunFixed, sunHour);
        }

        public double osGetCurrentSunHour()
        {
            return m_OSSL_Functions.osGetCurrentSunHour();
        }

        public double osSunGetParam(string param)
        {
            return m_OSSL_Functions.osSunGetParam(param);
        }

        public void osSunSetParam(string param, double value)
        {
            m_OSSL_Functions.osSunSetParam(param, value);
        }

        public string osWindActiveModelPluginName()
        {
            return m_OSSL_Functions.osWindActiveModelPluginName();
        }

// Not yet plugged in as available OSSL functions, so commented out
//        void osWindParamSet(string plugin, string param, float value)
//        {
//            m_OSSL_Functions.osWindParamSet(plugin, param, value);
//        }
//
//        float osWindParamGet(string plugin, string param)
//        {
//            return m_OSSL_Functions.osWindParamGet(plugin, param);
//        }

        public void osParcelJoin(vector pos1, vector pos2)
        {
            m_OSSL_Functions.osParcelJoin(pos1,pos2);
        }

        public void osParcelSubdivide(vector pos1, vector pos2)
        {
            m_OSSL_Functions.osParcelSubdivide(pos1, pos2);
        }

        public void osParcelSetDetails(vector pos, LSL_List rules)
        {
            m_OSSL_Functions.osParcelSetDetails(pos,rules);
        }

        public double osList2Double(LSL_Types.list src, int index)
        {
            return m_OSSL_Functions.osList2Double(src, index);
        }

        public string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams,
                                             int timer)
        {
            return m_OSSL_Functions.osSetDynamicTextureURL(dynamicID, contentType, url, extraParams, timer);
        }

        public string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams,
                                             int timer)
        {
            return m_OSSL_Functions.osSetDynamicTextureData(dynamicID, contentType, data, extraParams, timer);
        }

        public string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams,
                                           int timer, int alpha)
        {
            return m_OSSL_Functions.osSetDynamicTextureURLBlend(dynamicID, contentType, url, extraParams, timer, alpha);
        }

        public string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams,
                                             int timer, int alpha)
        {
            return m_OSSL_Functions.osSetDynamicTextureDataBlend(dynamicID, contentType, data, extraParams, timer, alpha);
        }

        public string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams,
                                           bool blend, int disp, int timer, int alpha, int face)
        {
            return m_OSSL_Functions.osSetDynamicTextureURLBlendFace(dynamicID, contentType, url, extraParams,
                                             blend, disp, timer, alpha, face);
        }

        public string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams,
                                             bool blend, int disp, int timer, int alpha, int face)
        {
            return m_OSSL_Functions.osSetDynamicTextureDataBlendFace(dynamicID, contentType, data, extraParams,
                                             blend, disp, timer, alpha, face);
        }

        public LSL_Float osTerrainGetHeight(int x, int y)
        {
            return m_OSSL_Functions.osTerrainGetHeight(x, y);
        }

        public LSL_Integer osTerrainSetHeight(int x, int y, double val)
        {
            return m_OSSL_Functions.osTerrainSetHeight(x, y, val);
        }

        public void osTerrainFlush()
        {
            m_OSSL_Functions.osTerrainFlush();
        }

        public int osRegionRestart(double seconds)
        {
            return m_OSSL_Functions.osRegionRestart(seconds);
        }

        public void osRegionNotice(string msg)
        {
            m_OSSL_Functions.osRegionNotice(msg);
        }

        public bool osConsoleCommand(string Command)
        {
            return m_OSSL_Functions.osConsoleCommand(Command);
        }

        public void osSetParcelMediaURL(string url)
        {
            m_OSSL_Functions.osSetParcelMediaURL(url);
        }

        public void osSetParcelSIPAddress(string SIPAddress)
        {
            m_OSSL_Functions.osSetParcelSIPAddress(SIPAddress);
        }

        public void osSetPrimFloatOnWater(int floatYN)
        {
            m_OSSL_Functions.osSetPrimFloatOnWater(floatYN);
        }

        // Teleport Functions

        public void osTeleportAgent(string agent, string regionName, vector position, vector lookat)
        {
            m_OSSL_Functions.osTeleportAgent(agent, regionName, position, lookat);
        }

        public void osTeleportAgent(string agent, int regionX, int regionY, vector position, vector lookat)
        {
            m_OSSL_Functions.osTeleportAgent(agent, regionX, regionY, position, lookat);
        }

        public void osTeleportAgent(string agent, vector position, vector lookat)
        {
            m_OSSL_Functions.osTeleportAgent(agent, position, lookat);
        }

        // Avatar info functions
        public string osGetAgentIP(string agent)
        {
            return m_OSSL_Functions.osGetAgentIP(agent);
        }

        public LSL_List osGetAgents()
        {
            return m_OSSL_Functions.osGetAgents();
        }

        // Animation Functions

        public void osAvatarPlayAnimation(string avatar, string animation)
        {
            m_OSSL_Functions.osAvatarPlayAnimation(avatar, animation);
        }

        public void osAvatarStopAnimation(string avatar, string animation)
        {
            m_OSSL_Functions.osAvatarStopAnimation(avatar, animation);
        }

        //Texture Draw functions

        public string osMovePen(string drawList, int x, int y)
        {
            return m_OSSL_Functions.osMovePen(drawList, x, y);
        }

        public string osDrawLine(string drawList, int startX, int startY, int endX, int endY)
        {
            return m_OSSL_Functions.osDrawLine(drawList, startX, startY, endX, endY);
        }

        public string osDrawLine(string drawList, int endX, int endY)
        {
            return m_OSSL_Functions.osDrawLine(drawList, endX, endY);
        }

        public string osDrawText(string drawList, string text)
        {
            return m_OSSL_Functions.osDrawText(drawList, text);
        }

        public string osDrawEllipse(string drawList, int width, int height)
        {
            return m_OSSL_Functions.osDrawEllipse(drawList, width, height);
        }

        public string osDrawRectangle(string drawList, int width, int height)
        {
            return m_OSSL_Functions.osDrawRectangle(drawList, width, height);
        }

        public string osDrawFilledRectangle(string drawList, int width, int height)
        {
            return m_OSSL_Functions.osDrawFilledRectangle(drawList, width, height);
        }

        public string osDrawPolygon(string drawList, LSL_List x, LSL_List y)
        {
            return m_OSSL_Functions.osDrawPolygon(drawList, x, y);
        }

        public string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y)
        {
            return m_OSSL_Functions.osDrawFilledPolygon(drawList, x, y);
        }

        public string osSetFontSize(string drawList, int fontSize)
        {
            return m_OSSL_Functions.osSetFontSize(drawList, fontSize);
        }

        public string osSetFontName(string drawList, string fontName)
        {
            return m_OSSL_Functions.osSetFontName(drawList, fontName);
        }

        public string osSetPenSize(string drawList, int penSize)
        {
            return m_OSSL_Functions.osSetPenSize(drawList, penSize);
        }

        public string osSetPenCap(string drawList, string direction, string type)
        {
            return m_OSSL_Functions.osSetPenCap(drawList, direction, type);
        }

        public string osSetPenColour(string drawList, string colour)
        {
            return m_OSSL_Functions.osSetPenColour(drawList, colour);
        }

        public string osDrawImage(string drawList, int width, int height, string imageUrl)
        {
            return m_OSSL_Functions.osDrawImage(drawList, width, height, imageUrl);
        }

        public vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize)
        {
            return m_OSSL_Functions.osGetDrawStringSize(contentType, text, fontName, fontSize);
        }

        public void osSetStateEvents(int events)
        {
            m_OSSL_Functions.osSetStateEvents(events);
        }

        public string osGetScriptEngineName()
        {
            return m_OSSL_Functions.osGetScriptEngineName();
        }

        public string osGetSimulatorVersion()
        {
           return m_OSSL_Functions.osGetSimulatorVersion();
        }

        public Hashtable osParseJSON(string JSON)
        {
            return m_OSSL_Functions.osParseJSON(JSON);
        }

        public void osMessageObject(key objectUUID,string message)
        {
            m_OSSL_Functions.osMessageObject(objectUUID,message);
        }

        public void osMakeNotecard(string notecardName, LSL_Types.list contents)
        {
            m_OSSL_Functions.osMakeNotecard(notecardName, contents);
        }

        public string osGetNotecardLine(string name, int line)
        {
            return m_OSSL_Functions.osGetNotecardLine(name, line);
        }

        public string osGetNotecard(string name)
        {
            return m_OSSL_Functions.osGetNotecard(name);
        }

        public int osGetNumberOfNotecardLines(string name)
        {
            return m_OSSL_Functions.osGetNumberOfNotecardLines(name);
        }

        public string osAvatarName2Key(string firstname, string lastname)
        {
            return m_OSSL_Functions.osAvatarName2Key(firstname, lastname);
        }

        public string osKey2Name(string id)
        {
            return m_OSSL_Functions.osKey2Name(id);
        }

        public string osGetGridNick()
        {
            return m_OSSL_Functions.osGetGridNick();
        }

        public string osGetGridName()
        {
            return m_OSSL_Functions.osGetGridName();
        }

        public string osGetGridLoginURI()
        {
            return m_OSSL_Functions.osGetGridLoginURI();
        }

        public LSL_String osFormatString(string str, LSL_List strings)
        {
            return m_OSSL_Functions.osFormatString(str, strings);
        }

        public LSL_List osMatchString(string src, string pattern, int start)
        {
            return m_OSSL_Functions.osMatchString(src, pattern, start);
        }

        // Information about data loaded into the region
        public string osLoadedCreationDate()
        {
            return m_OSSL_Functions.osLoadedCreationDate();
        }

        public string osLoadedCreationTime()
        {
            return m_OSSL_Functions.osLoadedCreationTime();
        }

        public string osLoadedCreationID()
        {
            return m_OSSL_Functions.osLoadedCreationID();
        }

        public LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules)
        {
            return m_OSSL_Functions.osGetLinkPrimitiveParams(linknumber, rules);
        }

        public key osNpcCreate(string user, string name, vector position, key cloneFrom)
        {
            return m_OSSL_Functions.osNpcCreate(user, name, position, cloneFrom);
        }

        public void osNpcMoveTo(key npc, vector position)
        {
            m_OSSL_Functions.osNpcMoveTo(npc, position);
        }

        public void osNpcSay(key npc, string message)
        {
            m_OSSL_Functions.osNpcSay(npc, message);
        }

        public void osNpcRemove(key npc)
        {
            m_OSSL_Functions.osNpcRemove(npc);
        }

        public OSSLPrim Prim;

        [Serializable]
        public class OSSLPrim
        {
            internal ScriptBaseClass OSSL;
            public OSSLPrim(ScriptBaseClass bc)
            {
                OSSL = bc;
                Position = new OSSLPrim_Position(this);
                Rotation = new OSSLPrim_Rotation(this);
            }

            public OSSLPrim_Position Position;
            public OSSLPrim_Rotation Rotation;
            private TextStruct _text;
            public TextStruct Text
            {
                get { return _text; }
                set
                {
                    _text = value;
                    OSSL.llSetText(_text.Text, _text.color, _text.alpha);
                }
            }

            [Serializable]
            public struct TextStruct
            {
                public string Text;
                public LSL_Types.Vector3 color;
                public double alpha;
            }
        }

        [Serializable]
        public class OSSLPrim_Position
        {
            private OSSLPrim prim;
            private LSL_Types.Vector3 Position;
            public OSSLPrim_Position(OSSLPrim _prim)
            {
                prim = _prim;
            }
            private void Load()
            {
                Position = prim.OSSL.llGetPos();
            }
            private void Save()
            {
                if (Position.x > ((int)Constants.RegionSize - 1))
                    Position.x = ((int)Constants.RegionSize - 1);
                if (Position.x < 0)
                    Position.x = 0;
                if (Position.y > ((int)Constants.RegionSize - 1))
                    Position.y = ((int)Constants.RegionSize - 1);
                if (Position.y < 0)
                    Position.y = 0;
                if (Position.z > 768)
                    Position.z = 768;
                if (Position.z < 0)
                    Position.z = 0;
                prim.OSSL.llSetPos(Position);
            }

            public double x
            {
                get
                {
                    Load();
                    return Position.x;
                }
                set
                {
                    Load();
                    Position.x = value;
                    Save();
                }
            }
            public double y
            {
                get
                {
                    Load();
                    return Position.y;
                }
                set
                {
                    Load();
                    Position.y = value;
                    Save();
                }
            }
            public double z
            {
                get
                {
                    Load();
                    return Position.z;
                }
                set
                {
                    Load();
                    Position.z = value;
                    Save();
                }
            }
        }

        [Serializable]
        public class OSSLPrim_Rotation
        {
            private OSSLPrim prim;
            private LSL_Types.Quaternion Rotation;
            public OSSLPrim_Rotation(OSSLPrim _prim)
            {
                prim = _prim;
            }
            private void Load()
            {
                Rotation = prim.OSSL.llGetRot();
            }
            private void Save()
            {
                prim.OSSL.llSetRot(Rotation);
            }

            public double x
            {
                get
                {
                    Load();
                    return Rotation.x;
                }
                set
                {
                    Load();
                    Rotation.x = value;
                    Save();
                }
            }
            public double y
            {
                get
                {
                    Load();
                    return Rotation.y;
                }
                set
                {
                    Load();
                    Rotation.y = value;
                    Save();
                }
            }
            public double z
            {
                get
                {
                    Load();
                    return Rotation.z;
                }
                set
                {
                    Load();
                    Rotation.z = value;
                    Save();
                }
            }
            public double s
            {
                get
                {
                    Load();
                    return Rotation.s;
                }
                set
                {
                    Load();
                    Rotation.s = value;
                    Save();
                }
            }
        }

        public key osGetMapTexture()
        {
            return m_OSSL_Functions.osGetMapTexture();
        }

        public key osGetRegionMapTexture(string regionName)
        {
            return m_OSSL_Functions.osGetRegionMapTexture(regionName);
        }

        public LSL_List osGetRegionStats()
        {
            return m_OSSL_Functions.osGetRegionStats();
        }

        /// <summary>
        /// Returns the amount of memory in use by the Simulator Daemon.
        /// Amount in bytes - if >= 4GB, returns 4GB. (LSL is not 64-bit aware)
        /// </summary>
        /// <returns></returns>
        public LSL_Integer osGetSimulatorMemory()
        {
            return m_OSSL_Functions.osGetSimulatorMemory();
        }
        public void osKickAvatar(string FirstName,string SurName,string alert)
        {
            m_OSSL_Functions.osKickAvatar(FirstName, SurName, alert);
        }
        public void osSetSpeed(string UUID, float SpeedModifier)
        {
            m_OSSL_Functions.osSetSpeed(UUID, SpeedModifier);
        }
        public void osCauseDamage(string avatar, double damage)
        {
            m_OSSL_Functions.osCauseDamage(avatar, damage);
        }
        public void osCauseHealing(string avatar, double healing)
        {
            m_OSSL_Functions.osCauseHealing(avatar, healing);
        }
        public LSL_List osGetPrimitiveParams(LSL_Key prim, LSL_List rules)
        {
            return m_OSSL_Functions.osGetPrimitiveParams(prim, rules);
        }
        public void osSetPrimitiveParams(LSL_Key prim, LSL_List rules)
        {
            m_OSSL_Functions.osSetPrimitiveParams(prim, rules);
        }

        public LSL_List osGetAvatarList()
        {
            return m_OSSL_Functions.osGetAvatarList();
        }
    }
}


text:
using System.Collections.Generic;
using OpenQA.Selenium;
using Selenium.WebForms.Infragistics.Inside;

namespace Selenium.WebForms.Infragistics
{
    /// <summary>
    /// WebDataGrid Driver
    /// </summary>
    public class WebDataGridDriver
    {
        /// <summary>
        /// Simple to WebDriver accessor
        /// </summary>
        public IWebDriver Driver { get; }
        /// <summary>
        /// ID of WebDataGrid
        /// </summary>
        public string Id { get; }
        /// <summary>
        /// Simple to IJavaScriptExecutor accessor
        /// </summary>
        public IJavaScriptExecutor Js => (IJavaScriptExecutor)Driver;
        /// <summary>
        /// Grid name of WebDataGrid
        /// </summary>
        protected internal virtual string GridName => WebDataGridJSutility.WebDataGridGridName;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="driver">Drivers to access</param>
        /// <param name="id">ID of WebDataGrid</param>
        public WebDataGridDriver(IWebDriver driver, string id)
        {
            Driver = driver;
            Id = id;
        }

        /// <summary>
        /// Get the active cell element
        /// </summary>
        /// <returns>active cell element</returns>
        public IWebElement GetActiveCellElement()
        {
            var js = new WebDataGridJSutility(this);
            return (IWebElement)Js.ExecuteScript(js.GetGridScript + js.GetActiveCellScript + "return activeCell.get_element();");
        }

        /// <summary>
        /// Get WebDataGridCellDriver
        /// </summary>
        /// <param name="rowIndex">The index of the row</param>
        /// <param name="colIndex">The index of the column</param>
        /// <returns>WebDataGridCellDriver</returns>
        public virtual WebDataGridCellDriver GetCell(int rowIndex, int colIndex) => new WebDataGridCellDriver(this, rowIndex, colIndex);

        /// <summary>
        /// Get WebDataGridCellDriver collection of rows
        /// </summary>
        /// <param name="rowIndex">The index of the row</param>
        /// <returns>WebDataGridCellDriver Collection</returns>
        public IEnumerable<WebDataGridCellDriver> GetCells(int rowIndex)
        {
            var script = new WebDataGridJSutility(this).GetGridScript + $"return {GridName}.get_rows().get_row({rowIndex}).get_cellCount();";
            var count = (long)Js.ExecuteScript(script);
            for (var i = 0; i < count; i++)
            {
                yield return GetCell(rowIndex, i);
            }
        }

        /// <summary>
        /// Number of rows
        /// </summary>
        public long RowCount => (long)Js.ExecuteScript(new WebDataGridJSutility(this).GetGridScript + $"return {GridName}.get_rows().get_length();");

        /// <summary>
        /// Number of columns
        /// </summary>
        public long ColumnCount => (long)Js.ExecuteScript(new WebDataGridJSutility(this).GetGridScript + $"return {GridName}.get_columns().get_length();");

        /// <summary>
        /// Get WebDataGridColumnDriver
        /// </summary>
        /// <param name="columnIndex"></param>
        /// <returns></returns>
        public WebDataGridColumnDriver GetColumn(int columnIndex) => new WebDataGridColumnDriver(this, columnIndex);

        /// <summary>
        /// Get page index
        /// </summary>
        /// <returns></returns>
        public long GetPageIndex() => (long)Js.ExecuteScript($"{new WebDataGridJSutility(this).GetGridScript} return {GridName}.get_behaviors().get_paging().get_pageIndex();") + 1;

        /// <summary>
        /// Set page index
        /// </summary>
        /// <param name="page"></param>
        public void SetPageIndex(int page)
        {
            Js.ExecuteScript($"{new WebDataGridJSutility(this).GetGridScript}{GridName}.get_behaviors().get_paging().set_pageIndex({page - 1});");
        }
    }
}


text:
layout: post
title: Parsing Quantifier {x,y} Following Nothing Considered Harmful
date: '2007-01-02 12:37:00 -0700'
mt_id: 1181
blog_id: 1
post_id: 1181
basename: parsing-quantifier-xy-following-nothing-considered-harmful
categories:
- net-development
---

If you normally do a Regex.Escape(string) in C# to get some text ready for use as a regular expression, be aware that a string like ^Lijit (+http://www.lijit.com/)$ will be escaped like so ^Lijit\ \(+http://www\.lijit\.com/\)$ instead of ^Lijit\ \(\+http://www\.lijit\.com/\)$ as you would expect.

Using that "escaped" regular expression will result in an ArgumentException along the lines of parsing "^Lijit (+http://www.lijit.com/)$" - Quantifier {x,y} following nothing. That message is virtually un-Google-able until now.

The .NET exception occurs, I think, because the parser just doesn't understand the unescaped quantifier being next to an escaped control character. I believe that the escaping misses it because it uses that same parser because the plus sign is definitely one of the characters that the Escape method can handle.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Bombyliospora domingensis var. boninensis Asahina

### Remarks
null


text:
var FILE = require("file"),
    OS = require("os"),
    UTIL = require("narwhal/util"),
    TERM = require("narwhal/term"),
    Jake = require("jake"),
    CLEAN = require("jake/clean").CLEAN,
    CLOBBER = require("jake/clean").CLOBBER,
    base64 = require("base64"),
    ObjectiveJ = require("objective-j"),
    environment = require("objective-j/jake/environment"),
    task = Jake.task;

var Task = Jake.Task,
    filedir = Jake.filedir;

function isImage(/*String*/ aFilename)
{
    return UTIL.has([".png", ".jpg", ".jpeg", ".gif", ".tif", ".tiff"], FILE.extension(aFilename).toLowerCase());
}

function mimeType(/*String*/ aFilename)
{
    return  {
                ".png"  : "image/png",
                ".jpg"  : "image/jpeg",
                ".jpeg" : "image/jpeg",
                ".gif"  : "image/gif",
                ".tif"  : "image/tiff",
                ".tiff" : "image/tiff"
            }[FILE.extension(aFilename).toLowerCase()];
}

function BundleTask(aName, anApplication)
{
    Task.apply(this, arguments);

    this.setEnvironments([environment.Browser, environment.CommonJS]);

    this._author = null;
    this._email = null;
    this._summary = null;

    this._license = null;
    this._sources = null;
    this._resources = null;
    this._spritesResources = true;
    this._identifier = null;
    this._version = 0.1;

    this._compilerFlags = null;
    this._flattensSources = false;
    this._includesNibsAndXibs = false;
    this._preventsNib2Cib = false;

    this._productName = this.name();

    this._buildIntermediatesPath = null;
    this._buildPath = FILE.cwd();

    this._replacedFiles = { };
    this._nib2cibFlags = null;

    this._infoPlistPath = "Info.plist";
    this._principalClass = null;
}

BundleTask.__proto__ = Task;
BundleTask.prototype.__proto__ = Task.prototype;

BundleTask.defineTask = function(/*String*/ aName, /*Function*/ aFunction)
{
    var bundleTask = Task.defineTask.apply(this, [aName]);

    if (aFunction)
        aFunction(bundleTask);

    bundleTask.defineTasks();

    return bundleTask;
}

BundleTask.prototype.setEnvironments = function(environments)
{
    if (arguments.length < 1)
        this._environments = [];

    else if (arguments.length > 1)
        this._environments = Array.prototype.slice.apply(environments);

    else if (typeof environments.slice === "function")
        this._environments = environments.slice();

    else
        this._environments = [environments];
}

BundleTask.prototype.environments = function()
{
    return this._environments;
}

BundleTask.prototype.setAuthor = function(anAuthor)
{
    this._author = anAuthor;
}

BundleTask.prototype.author = function()
{
    return this._author;
}

BundleTask.prototype.setEmail = function(anEmail)
{
    this._email = anEmail;
}

BundleTask.prototype.email = function()
{
    return this._email;
}

BundleTask.prototype.setSummary = function(aSummary)
{
    this._summary = aSummary;
}

BundleTask.prototype.summary = function()
{
    return this._summary;
}

BundleTask.prototype.setIdentifier = function(anIdentifier)
{
    this._identifier = anIdentifier;
}

BundleTask.prototype.identifier = function()
{
    return this._identifier;
}

BundleTask.prototype.setVersion = function(aVersion)
{
    this._version = aVersion;
}

BundleTask.prototype.version = function()
{
    return this._version;
}

BundleTask.prototype.setSources = function(sources, environments)
{
    if (!environments)
        this._sources = sources;
    else
    {
        if (!this._sources)
            this._sources = { };

        // If a single envirnment was passed in...
        if (!Array.isArray(environments))
            environments = [environments];

        environments.forEach(function(anEnvironment)
        {
            this._sources[anEnvironment] = sources;
        }, this);
    }
}

BundleTask.prototype.sources = function()
{
    return this._sources;
}

BundleTask.prototype.setResources = function(resources)
{
    this._resources = resources;
}

BundleTask.prototype.resources = function(resources)
{
    this._resources = resources;
}

BundleTask.prototype.setSpritesResources = function(shouldSpriteResources)
{
    this._spritesResources = shouldSpriteResources;
}

BundleTask.prototype.spritesResources = function()
{
    return this._spritesResources;
}

BundleTask.prototype.setIncludesNibsAndXibs = function(shouldIncludeNibsAndXibs)
{
    this._includesNibsAndXibs = shouldIncludeNibsAndXibs;
}

BundleTask.prototype.includesNibsAndXibs = function()
{
    return this._includesNibsAndXibs;
}

BundleTask.prototype.setPreventsNib2Cib = function(shouldPreventNib2Cib)
{
    this._preventsNib2Cib = shouldPreventNib2Cib;
}

BundleTask.prototype.preventsNib2Cib = function()
{
    return this._preventsNib2Cib;
}

BundleTask.prototype.setProductName = function(aProductName)
{
    this._productName = aProductName;
}

BundleTask.prototype.productName = function()
{
    return this._productName;
}

BundleTask.prototype.setInfoPlistPath = function(anInfoPlistPath)
{
    this._infoPlistPath = anInfoPlistPath;
}

BundleTask.prototype.infoPlistPath = function()
{
    return this._infoPlistPath;
}

BundleTask.prototype.setPrincipalClass = function(aPrincipalClass)
{
    this._principalClass = aPrincipalClass;
}

BundleTask.prototype.principalClass = function()
{
    return this._principalClass;
}

BundleTask.prototype.setCompilerFlags = function(flags)
{
    this._compilerFlags = flags;
}

BundleTask.prototype.compilerFlags = function()
{
    return this._compilerFlags;
}

BundleTask.prototype.setNib2cibFlags = function(flags)
{
    this._nib2cibFlags = flags;
}

BundleTask.prototype.setNib2CibFlags = BundleTask.prototype.setNib2cibFlags;

BundleTask.prototype.nib2cibFlags = function()
{
    return this._nib2cibFlags;
}

BundleTask.prototype.flattensSources = function()
{
    return this._flattensSources;
}

BundleTask.prototype.setFlattensSources = function(/*Boolean*/ shouldFlattenSources)
{
    this._flattensSources = shouldFlattenSources;
}

BundleTask.prototype.setLicense = function(aLicense)
{
    this._license = aLicense;
}

BundleTask.prototype.license = function()
{
    return this._license;
}

BundleTask.prototype.setBuildPath = function(aBuildPath)
{
    this._buildPath = aBuildPath;
}

BundleTask.prototype.buildPath = function()
{
    return this._buildPath;
}

BundleTask.prototype.setBuildIntermediatesPath = function(aBuildPath)
{
    this._buildIntermediatesPath = aBuildPath;
}

BundleTask.prototype.buildIntermediatesPath = function()
{
    return this._buildIntermediatesPath || this.buildPath();
}

BundleTask.prototype.buildProductPath = function()
{
    return FILE.join(this.buildPath(), this.productName());
}

BundleTask.prototype.buildIntermediatesProductPath = function()
{
    return this.buildIntermediatesPath() || FILE.join(this.buildPath(), this.productName() + ".build");
}

BundleTask.prototype.buildProductStaticPathForEnvironment = function(anEnvironment)
{
    return FILE.join(this.buildProductPath(), anEnvironment.name() + ".environment", this.productName() + ".sj");
}

BundleTask.prototype.buildProductMHTMLPathForEnvironment = function(anEnvironment)
{
    return FILE.join(this.buildProductPath(), anEnvironment.name() + ".environment", "MHTMLPaths.txt");
}

BundleTask.prototype.buildProductMHTMLDataPathForEnvironment = function(anEnvironment)
{
    return FILE.join(this.buildProductPath(), anEnvironment.name() + ".environment", "MHTMLData.txt");
}

BundleTask.prototype.buildProductMHTMLTestPathForEnvironment = function(anEnvironment)
{
    return FILE.join(this.buildProductPath(), anEnvironment.name() + ".environment", "MHTMLTest.txt");
}

BundleTask.prototype.buildProductDataURLPathForEnvironment = function(anEnvironment)
{
    return FILE.join(this.buildProductPath(), anEnvironment.name() + ".environment", "dataURLs.txt");
}

BundleTask.prototype.defineTasks = function()
{
    this.defineResourceTasks();
    this.defineSourceTasks();
    this.defineInfoPlistTask();
    this.defineLicenseTask();
    this.defineStaticTask();
    this.defineSpritedImagesTask();

    CLEAN.include(this.buildIntermediatesProductPath());
    CLOBBER.include(this.buildProductPath());
}

BundleTask.prototype.packageType = function()
{
    return 1;
}

BundleTask.prototype.infoPlist = function()
{
    var infoPlistPath = this.infoPlistPath();

    if (infoPlistPath && FILE.exists(infoPlistPath))
        var infoPlist = CFPropertyList.propertyListFromString(FILE.read(infoPlistPath, { charset:"UTF-8" }));
    else
        var infoPlist = new CFMutableDictionary();

    // FIXME: Should all of these unconditionally overwrite?
    infoPlist.setValueForKey("CPBundleInfoDictionaryVersion", 6.0);
    infoPlist.setValueForKey("CPBundleName", this.productName());
    infoPlist.setValueForKey("CPBundleIdentifier", this.identifier());
    infoPlist.setValueForKey("CPBundleVersion", this.version());
    infoPlist.setValueForKey("CPBundlePackageType", this.packageType());
    infoPlist.setValueForKey("CPBundleEnvironments", this.environments().map(function(anEnvironment)
    {
        return anEnvironment.name();
    }));
    infoPlist.setValueForKey("CPBundleExecutable", this.productName() + ".sj");

    var environmentsWithImageSprites = this.environments().filter(
    function(anEnvironment)
    {
        return anEnvironment.spritesImages() && task(this.buildProductDataURLPathForEnvironment(anEnvironment)).prerequisites().filter(isImage).length > 0;
    }, this).map(function(anEnvironment)
    {
        return anEnvironment.name();
    });

    infoPlist.setValueForKey("CPBundleEnvironmentsWithImageSprites", environmentsWithImageSprites);

    var principalClass = this.principalClass();

    if (principalClass)
        infoPlist.setValueForKey("CPPrincipalClass", principalClass);

    return infoPlist;
}

BundleTask.prototype.defineInfoPlistTask = function()
{
    var infoPlistProductPath = FILE.join(this.buildProductPath(), "Info.plist"),
        bundleTask = this;

    filedir (infoPlistProductPath, function()
    {
        FILE.write(infoPlistProductPath, CFPropertyList.stringFromPropertyList(bundleTask.infoPlist(), CFPropertyList.Format280North_v1_0), { charset:"UTF-8" });
    });

    var infoPlistPath = this.infoPlistPath();

    if (infoPlistPath && FILE.exists(infoPlistPath))
        filedir (infoPlistProductPath, [infoPlistPath]);

    // FIXME: ? We do this because adding a .j file should cause Info.plist to be updated.
    // Any better way to handle this? Perhaps this should happen unconditionally.
    this.environments().forEach(function(/*Environment*/ anEnvironment)
    {
        if (!anEnvironment.spritesImages())
            return;

        filedir (infoPlistProductPath, this.buildProductStaticPathForEnvironment(anEnvironment));
    }, this);

    this.enhance([infoPlistProductPath]);
}

BundleTask.License  =   {
                            LGPL_v2_1   : "LGPL_v2_1",
                            MIT         : "MIT"
                        };

var LICENSES_PATH   = FILE.join(FILE.absolute(FILE.dirname(module.path)), "LICENSES"),
    LICENSE_PATHS   =   {
                            "LGPL_v2_1" : FILE.join(LICENSES_PATH, "LGPL-v2.1"),
                            "MIT"       : FILE.join(LICENSES_PATH, "MIT")
                        };

BundleTask.prototype.defineLicenseTask = function()
{
    var license = this.license();

    if (!license)
        return;

    var licensePath = LICENSE_PATHS[license];
        licenseProductPath = FILE.join(this.buildProductPath(), "LICENSE");

    filedir (licenseProductPath, [licensePath], function()
    {
        FILE.copy(licensePath, licenseProductPath);
    });

    this.enhance([licenseProductPath]);
}

BundleTask.prototype.resourcesPath = function()
{
    return FILE.join(this.buildProductPath(), "Resources", "");
}

// Don't sprite images larger than 32KB, IE 8 doesn't like it.
BundleTask.isSpritable = function(aResourcePath) {
    return isImage(aResourcePath) && FILE.size(aResourcePath) < 32768 &&
           ("data:" + mimeType(aResourcePath) + ";base64," +
            base64.encode(FILE.read(aResourcePath, "b"))).length < 32768;
}

BundleTask.prototype.defineResourceTask = function(aResourcePath, aDestinationPath)
{
    if (this.spritesResources() && BundleTask.isSpritable(aResourcePath))
    {
        this.environments().forEach(function(/*Environment*/ anEnvironment)
        {
            if (!anEnvironment.spritesImages())
                return;

            var folder = anEnvironment.name() + ".environment",
                spritedDestinationPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Resources", FILE.relative(this.resourcesPath(), aDestinationPath));

            filedir (spritedDestinationPath, function()
            {
                FILE.write(spritedDestinationPath, base64.encode(FILE.read(aResourcePath, "b")), { charset:"UTF-8" });
            });

            filedir (this.buildProductDataURLPathForEnvironment(anEnvironment), [spritedDestinationPath]);
            filedir (this.buildProductMHTMLPathForEnvironment(anEnvironment), [spritedDestinationPath]);
            filedir (this.buildProductMHTMLDataPathForEnvironment(anEnvironment), [spritedDestinationPath]);
            filedir (this.buildProductMHTMLTestPathForEnvironment(anEnvironment), [spritedDestinationPath]);

        }, this);
    }

    var extension = FILE.extension(aResourcePath),
        extensionless = aResourcePath.substr(0, aResourcePath.length - extension.length);
    // NOT:
    // (extname === ".cib" && (FILE.exists(extensionless + '.xib') || FILE.exists(extensionless + '.nib') && !this._preventsNib2Cib) ||
    // (extname === ".xib" || extname === ".nib") && !this.shouldIncludeNibsAndXibs())
    if ((extension !== ".cib" || !FILE.exists(extensionless + ".xib") && !FILE.exists(extensionless + ".nib") || this._preventsNib2Cib) &&
        ((extension !== ".xib" && extension !== ".nib") || this.includesNibsAndXibs()))
    {
        filedir (aDestinationPath, [aResourcePath], function()
        {
            if (FILE.exists(aDestinationPath))
                try { FILE.rmtree(aDestinationPath); } catch (anException) { }

            if (FILE.isDirectory(aResourcePath))
                FILE.copyTree(aResourcePath, aDestinationPath);
            else
                FILE.copy(aResourcePath, aDestinationPath);
        });

        this.enhance([aDestinationPath]);
    }

    if ((extension === ".xib" || extension === ".nib") && !this._preventsNib2Cib)
    {
        var cibDestinationPath = FILE.join(FILE.dirname(aDestinationPath), FILE.basename(aDestinationPath, extension)) + ".cib";

        var nib2cibFlags = this.nib2cibFlags();

        if (!nib2cibFlags)
            nib2cibFlags = "";

        else if (nib2cibFlags.join)
            nib2cibFlags = nib2cibFlags.join(" ");

        filedir (cibDestinationPath, [aResourcePath], function()
        {
            OS.system("nib2cib " + aResourcePath + " "  + cibDestinationPath + " " + nib2cibFlags);
        });

        this.enhance([cibDestinationPath]);
    }
}

function directoryInCommon(filenames)
{
    var aCommonDirectory = null;

    filenames.forEach(function(aFilename)
    {
        var directory = FILE.dirname(aFilename);

        if (directory === ".")
            directory = "";

        // Empty string is an acceptable common directory.
        if (aCommonDirectory === null)
            aCommonDirectory = directory;

        else
        {
            var index = 0,
                count = Math.min(directory.length, aFilename.length);

            for (; index < count && aCommonDirectory.charAt(index) === directory.charAt(index); ++index) ;

            aCommonDirectory = directory.substr(0, index);
        }
    });

    return aCommonDirectory;
}

BundleTask.prototype.defineResourceTasks = function()
{
    if (!this._resources)
        return;

    var resources = [],
        basePath = null;

    // Resolve resources. Consider any file passed in as a resource.
    this._resources.forEach(function(aResourcePath)
    {
        if (FILE.isDirectory(aResourcePath))
        {
            // Add the directory itself as well since it is a legitimate resource as well.
            resources = resources.concat(aResourcePath, FILE.glob(aResourcePath + "/**"));
        }
        else
            resources.push(aResourcePath);
    });

    resources = UTIL.unique(resources);

    if (resources.length <= 0)
        return;

    var basePathLength = directoryInCommon(resources).length,
        resourcesPath = this.resourcesPath();

    resources.forEach(function(aResourcePath)
    {
        this.defineResourceTask(aResourcePath, FILE.join(resourcesPath, aResourcePath.substring(basePathLength)));
    }, this);
}

var RESOURCES_PATH  = FILE.join(FILE.absolute(FILE.dirname(module.path)), "RESOURCES"),
    MHTMLTestPath   = FILE.join(RESOURCES_PATH, "MHTMLTest.txt");

BundleTask.prototype.defineSpritedImagesTask = function()
{
    this.environments().forEach(function(/*Environment*/ anEnvironment)
    {
        if (!anEnvironment.spritesImages())
            return;

        var folder = anEnvironment.name() + ".environment",
            resourcesPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Resources", "");

        var productName = this.productName(),
            dataURLPath = this.buildProductDataURLPathForEnvironment(anEnvironment);

        filedir (dataURLPath, function(aTask)
        {
            var prerequisites = aTask.prerequisites().filter(isImage);

            if (!prerequisites.length)
            {
                if (FILE.exists(dataURLPath))
                    FILE.remove(dataURLPath);

                return;
            }

            TERM.stream.print("Creating data URLs file... \0green(" + dataURLPath +"\0)");

            var dataURLStream = FILE.open(dataURLPath, "w+", { charset:"UTF-8" });

            dataURLStream.write("@STATIC;1.0;");

            prerequisites.forEach(function(aFilename)
            {
                var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename);

                dataURLStream.write("u;" + resourcePath.length + ";" + resourcePath);

                var contents =  "data:" + mimeType(aFilename) +
                                ";base64," + FILE.read(aFilename, "b").decodeToString("UTF-8");

                dataURLStream.write(contents.length + ";" + contents);
            });

            dataURLStream.write("e;");
            dataURLStream.close();
        });

        this.enhance([dataURLPath]);

        var MHTMLPath = this.buildProductMHTMLPathForEnvironment(anEnvironment);

        filedir (MHTMLPath, function(aTask)
        {
            var prerequisites = aTask.prerequisites().filter(isImage);

            if (!prerequisites.length)
            {
                if (FILE.exists(MHTMLPath))
                    FILE.remove(MHTMLPath);

                return;
            }

            TERM.stream.print("Creating MHTML paths file... \0green(" + MHTMLPath +"\0)");

            var MHTMLStream = FILE.open(MHTMLPath, "w+", { charset:"UTF-8" });

            MHTMLStream.write("@STATIC;1.0;");

            prerequisites.forEach(function(aFilename)
            {
                var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename),
                    MHTMLResourcePath = "mhtml:" + FILE.join(folder, "MHTMLData.txt!") + resourcePath;

                MHTMLStream.write("u;" + resourcePath.length + ";" + resourcePath);
                MHTMLStream.write(MHTMLResourcePath.length + ";" + MHTMLResourcePath);
            });

            MHTMLStream.close();
        });

        this.enhance([MHTMLPath]);

        var MHTMLDataPath = this.buildProductMHTMLDataPathForEnvironment(anEnvironment);

        filedir (MHTMLDataPath, function(aTask)
        {
            var prerequisites = aTask.prerequisites().filter(isImage);

            if (!prerequisites.length)
            {
                if (FILE.exists(MHTMLDataPath))
                    FILE.remove(MHTMLDataPath);

                return;
            }

            TERM.stream.print("Creating MHTML images file... \0green(" + MHTMLDataPath +"\0)");

            var MHTMLDataStream = FILE.open(MHTMLDataPath, "w+", { charset:"UTF-8" });

            MHTMLDataStream.write("/*\r\nContent-Type: multipart/related; boundary=\"_ANY_STRING_WILL_DO_AS_A_SEPARATOR\"\r\n\r\n");

            prerequisites.forEach(function(aFilename)
            {
                var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename);

                MHTMLDataStream.write("--_ANY_STRING_WILL_DO_AS_A_SEPARATOR\r\n");
                MHTMLDataStream.write("Content-Location:" + resourcePath + "\r\nContent-Transfer-Encoding:base64\r\n\r\n");
                MHTMLDataStream.write(FILE.read(aFilename, "b").decodeToString("UTF-8"));
                MHTMLDataStream.write("\r\n");
            });

            MHTMLDataStream.write("*/");
            MHTMLDataStream.close();
        });

        this.enhance([MHTMLDataPath]);

        var MHTMLTestDestinationPath = this.buildProductMHTMLTestPathForEnvironment(anEnvironment);

        filedir (MHTMLTestDestinationPath, function(aTask)
        {
            TERM.stream.print("Copying MHTML test file... \0green(" + MHTMLTestDestinationPath +"\0)");

            FILE.copy(MHTMLTestPath, MHTMLTestDestinationPath);
        });

        this.enhance([MHTMLTestDestinationPath]);
    }, this);
}

BundleTask.prototype.defineStaticTask = function()
{
    this.environments().forEach(function(/*Environment*/ anEnvironment)
    {
        var folder = anEnvironment.name() + ".environment",
            sourcesPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Sources", ""),
            resourcesPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Resources", ""),
            staticPath = this.buildProductStaticPathForEnvironment(anEnvironment),
            flattensSources = this.flattensSources(),
            productName = this.productName();

        filedir (staticPath, function(aTask)
        {
            TERM.stream.print("Creating static file... \0green(" + staticPath +"\0)");

            var fileStream = FILE.open(staticPath, "w+", { charset:"UTF-8" });

            fileStream.write("@STATIC;1.0;");

            aTask.prerequisites().forEach(function(aFilename)
            {
                // Our prerequisites will contain directories due to filedir.
                if (!FILE.isFile(aFilename))
                    return;

                var dirname = FILE.dirname(aFilename);

                if (aFilename.indexOf(sourcesPath) === 0)
                {
                    var relativePath = flattensSources ? FILE.basename(aFilename) : FILE.relative(sourcesPath, aFilename);

                    // FIXME: We need to do this for now due to file.read adding newlines in Rhino. Revert when fixed.
                    //fileStream.write(FILE.read(aFilename, "b").decodeToString("UTF-8"));
                    fileStream.write("p;" + relativePath.length + ";" + relativePath);

                    var fileContents = FILE.read(aFilename, "b").decodeToString("UTF-8");

                    fileStream.write("t;" + fileContents.length + ";" + fileContents);
                }

                else if (aFilename.indexOf(resourcesPath) === 0 && !isImage(aFilename))
                {
                    var resourcePath = "Resources/" + FILE.relative(resourcesPath, aFilename);

                    fileStream.write("p;");

                    contents = FILE.read(aFilename, "b").decodeToString("UTF-8");

                    fileStream.write(resourcePath.length + ";" + resourcePath + contents);
                }
            }, this);

            fileStream.write("e;");
            fileStream.close();
        });

        this.enhance([staticPath]);
    }, this);
}

BundleTask.prototype.defineSourceTasks = function()
{
    var sources = this.sources();

    if (!sources)
        return;

    var compilerFlags = this.compilerFlags(),
        flattensSources = this.flattensSources();

    if (!compilerFlags)
        compilerFlags = "";

    else if (compilerFlags.join)
        compilerFlags = compilerFlags.join(" ");

    var flattensSources = this.flattensSources();

    this.environments().forEach(function(/*Environment*/ anEnvironment)
    {
        var environmentSources = sources,
            folder = anEnvironment.name() + ".environment",
            sourcesPath = FILE.join(this.buildIntermediatesProductPath(), folder, "Sources", ""),
            staticPath = this.buildProductStaticPathForEnvironment(anEnvironment);

        if (!Array.isArray(environmentSources) && environmentSources.constructor !== Jake.FileList)
        {
            environmentSources = environmentSources[anEnvironment];

            if (!environmentSources)
                return;
        }

        var replacedFiles = [],
            environmentCompilerFlags = anEnvironment.compilerFlags().join(" ") + " " + compilerFlags,
            flattensSources = this.flattensSources(),
            basePath = directoryInCommon(environmentSources),
            basePathLength = basePath.length;

        environmentSources.forEach(function(/*String*/ aFilename)
        {
            if (!FILE.exists(aFilename))
                return;

            var relativePath = aFilename.substring(basePathLength ? basePathLength + 1 : basePathLength),
                compiledEnvironmentSource = FILE.join(sourcesPath, relativePath);

            filedir (compiledEnvironmentSource, [aFilename], function()
            {
                var compile
                // if this file doesn't exist or isn't a .j file, don't preprocess it.
                if (FILE.extension(aFilename) !== ".j")
                {
                    TERM.stream.write("Including [\0blue(" + anEnvironment + "\0)] \0purple(" + aFilename + "\0)").flush();
                    var compiled = FILE.read(aFilename, { charset:"UTF-8" });
                }
                else
                {
                    TERM.stream.write("Compiling [\0blue(" + anEnvironment + "\0)] \0purple(" + aFilename + "\0)").flush();
                    var compiled = require("objective-j/compiler").compile(aFilename, environmentCompilerFlags);
                }

                TERM.stream.print(Array(Math.round(compiled.length / 1024) + 3).join("."));
                FILE.write(compiledEnvironmentSource, compiled, { charset:"UTF-8" });
            });

            filedir (staticPath, [compiledEnvironmentSource]);

            replacedFiles.push(flattensSources ? FILE.basename(aFilename) : relativePath);
        }, this);

        this._replacedFiles[anEnvironment] = replacedFiles;
    }, this);
}

exports.BundleTask = BundleTask;

exports.bundle = function(aName, aFunction)
{
    // No .apply necessary because the parameters aren't variable.
    return BundleTask.defineTask(aName, aFunction);
}


text:
//#define LOG_DEBUG
//#define LOG_DEBUG_VERBOSE

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Type = System.Type;

#if UNITY_EDITOR
using UnityEditor;
using System.IO;
using System.Linq;
#endif

/// <summary>
/// Sets the script exection order to a specific value.
/// </summary>
[System.AttributeUsage(System.AttributeTargets.Class)]
public class ScriptExecutionOrderAttribute : System.Attribute
{
	public readonly int order;
	public ScriptExecutionOrderAttribute(int order)
	{
		this.order = order;
	}
}

/// <summary>
/// Ensures that this script will execute after all scripts of the specified type.
/// Exection order for all scripts in a dependency chain are automatically assigned.
/// This respects order values set by ScriptExecutionOrderAttribute, and will show a warning if that's not possible.
/// </summary>
[System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = true)]
public class ScriptDependencyAttribute : System.Attribute
{
    public readonly Type scriptDependencyType;
    public ScriptDependencyAttribute(Type type)
    {
        this.scriptDependencyType = type;
    }

    public virtual Type[] GetScriptDependencies()
    {
        return new Type[] {scriptDependencyType};
    }
}

#if UNITY_EDITOR
public static class ScriptExecutionOrder
{
    public class Builder : UnityEditor.AssetPostprocessor
    {
        static void OnPostprocessAllAssets (string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            if(importedAssets
                .Concat(movedAssets)
                .Concat(deletedAssets)
                .Any(x=> x.EndsWith(".cs") || x.EndsWith(".js")))
            {
                ScriptExecutionOrder.ProcessAll();
            }
        }
    }

    [UnityEditor.Callbacks.DidReloadScripts]
    static void ProcessAll()
    {
        var types = new string[] {".cs", ".js"};
        var fixedOrders = new Dictionary<UnityEditor.MonoScript, int>();

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
            .Where(s => types.Any(x=>s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
            .ToArray();

        var allScripts = new List<UnityEditor.MonoScript>();
        for(int i=0;i<allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if(!script || script.GetClass()==null) continue;
            int newOrder = 0;
            if(GetFixedOrder(script, out newOrder))
            {
                fixedOrders[script] = newOrder;
            }
            allScripts.Add(script);
        }

        var scriptOrders = new Dictionary<UnityEditor.MonoScript, int>();
        var sortedDeps = SortDependencies(allScripts.ToArray());
        for(int i=0;i<sortedDeps.Count; ++i)
        {
            bool hasFixedOrderItem = false;

            //
            // find out the starting priority for this island
            var currentIsland = sortedDeps[i];

            var newDepOrder = -currentIsland.Length;
            for(int j=0; j<currentIsland.Length; ++j)
            {
                var script = currentIsland[j].script;
                int scriptOrder = 0;
                if(fixedOrders.TryGetValue(script, out scriptOrder))
                {
                    // -j due to sorted items before it
                    newDepOrder = Mathf.Min(scriptOrder-j, newDepOrder);
                    hasFixedOrderItem = true;
                }
            }

            //
            // Don't edit execution order unless there's a fixed order or a dependency
            // This allows the script exection order UI to work normally for these cases
            // instead of forcing them to exection order 0
            if(currentIsland.Length==1 && !hasFixedOrderItem)
            {
                continue;
            }

#if LOG_DEBUG
            Debug.Log("ScriptExectionOrder: Island:"+i+" starts at "+newDepOrder
                +" Scripts:"+string.Join(", ", currentIsland
                    .Select(x=>(fixedOrders.ContainsKey(x.script)
                        ? (x.script.name+"["+fixedOrders[x.script]+"]")
                        : x.script.name)+"("+x.isLeaf+")")
                    .ToArray()));
#endif

            //
            // apply priorities in order
            for(int j=0; j<currentIsland.Length; ++j)
            {
                int scriptFixedOrder = 0;
                var script = currentIsland[j].script;
                var isLeaf = currentIsland[j].isLeaf;
                if(fixedOrders.TryGetValue(script, out scriptFixedOrder))
                {
                    newDepOrder = Mathf.Max(scriptFixedOrder, newDepOrder);
                    if(newDepOrder!=scriptFixedOrder)
                    {
                        Debug.LogWarning("ScriptExectionOrder: "+script.name+" has fixed exection order "+scriptFixedOrder+" but due to ScriptDependency sorting is now at order "+newDepOrder);
                    }
                    fixedOrders.Remove(script);
                }
                else if(fixedOrders.Count==0)
                {
                    newDepOrder = isLeaf && !currentIsland.Skip(j+1).Any(x=>x.isLeaf)
                        ? Mathf.Max(0, newDepOrder)
                        : Mathf.Max(-currentIsland.Length, newDepOrder);
                }

                scriptOrders[script] = newDepOrder;

                // Leaves have no dependencies so the next behaviour can share the same execution order as a leaf
                //
                if(!isLeaf || (isLeaf && !hasFixedOrderItem))
                {
                    ++newDepOrder;
                }
            }
        }

        foreach(var i in scriptOrders)
        {
            var script = i.Key;
            var order = i.Value;
            var currentOrder = UnityEditor.MonoImporter.GetExecutionOrder(script);
            if(order != currentOrder)
            {
                UnityEditor.MonoImporter.SetExecutionOrder(script, order);
            }
        }
    }

    /// <summary>
    /// Sort the scripts by dependencies
    /// </summary>
    static List<IslandItem[]> SortDependencies(UnityEditor.MonoScript[] scriptsToSort)
    {
        var lookup = new Dictionary<Type, UnityEditor.MonoScript>();
        var visited = new HashSet<UnityEditor.MonoScript>();
        var sortedItems = new List<UnityEditor.MonoScript>();
        var connections = new Dictionary<UnityEditor.MonoScript, HashSet<UnityEditor.MonoScript>>();

        // add everything to lookup
        for(int i=0;i<scriptsToSort.Length;++i)
        {
            var script = scriptsToSort[i];
            if(script==null) continue;
            lookup[script.GetClass()] = script;
        }

        // build connection graph
        for (int i = 0; i < scriptsToSort.Length; ++i)
        {
            var script = scriptsToSort[i];
            if(script==null) continue;
            if(!HasDependencies(script)) continue;
            var deps = GetScriptDependencies(scriptsToSort[i]);
            for(int j=0; j < deps.Length; ++j)
            {
                var depType = deps[j];
                if(depType==null) continue;

                MonoScript depScript = null;
                if(!lookup.TryGetValue(depType, out depScript)) continue;

                // forward
                HashSet<UnityEditor.MonoScript> forwardSet = null;
                if (!connections.TryGetValue(script, out forwardSet))
                {
                    connections[script] = forwardSet = new HashSet<MonoScript>();
                }
                forwardSet.Add(depScript);

                // reverse
                HashSet<UnityEditor.MonoScript> reverseSet = null;
                if (!connections.TryGetValue(depScript, out reverseSet))
                {
                    connections[depScript] = reverseSet = new HashSet<MonoScript>();
                }
                reverseSet.Add(script);
            }
        }

        // sort fixed order items first
        for(int i=0;i<scriptsToSort.Length;++i)
        {
            var script = scriptsToSort[i];
            if(script==null || !HasDependencies(script)) continue;
            if(!HasFixedOrder(script)) continue;
            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }

        // non-leaves
        for(int i=0;i<scriptsToSort.Length;++i)
        {
            var script = scriptsToSort[i];
            if(script==null || !HasDependencies(script)) continue;

            HashSet<MonoScript> connectionSet = null;
            if (connections.TryGetValue(script, out connectionSet)
                && GetScriptDependencies(script).Length == connections[script].Count)
            {
                continue;
            }

            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }

        // leaves (any that remain)
        for(int i=0;i<scriptsToSort.Length;++i)
        {
            var script = scriptsToSort[i];
            if(script==null || !HasDependencies(script)) continue;
            SortDependencies_Visit(script, visited, sortedItems, lookup, null, connections);
        }

        //Debug.Log("ScriptExecutionOrder: Sorted dependencies: "+string.Join(", ",sortedItems.Select(x=>x.name).ToArray()));
        return SortDependencies_CreateGraphIslands(sortedItems, connections);
    }

    struct IslandItem
    {
        public UnityEditor.MonoScript script;
        public bool isLeaf;
    }

    /// <summary>
    /// Create graph islands from the non directed dependency graph
    /// </summary>
    static List<IslandItem[]> SortDependencies_CreateGraphIslands(List<UnityEditor.MonoScript> scriptsToSort,
        Dictionary<UnityEditor.MonoScript, HashSet<UnityEditor.MonoScript>> connections)
    {
        var output = new List<IslandItem[]>();
        var remainingSet = new List<UnityEditor.MonoScript>(scriptsToSort);
        var leaves = new HashSet<UnityEditor.MonoScript>();

        while (remainingSet.Any())
        {
            var graphComponentSet = new HashSet<UnityEditor.MonoScript>();
            var openSet = new HashSet<UnityEditor.MonoScript>();
            var current = remainingSet.First();
            while (current != null)
            {
                openSet.Remove(current);
                remainingSet.Remove(current);
                graphComponentSet.Add(current);
                HashSet<UnityEditor.MonoScript> currentConnections = null;
                if (connections.TryGetValue(current, out currentConnections))
                {
                    foreach (var connection in currentConnections)
                    {
                        // leaves are scripts that no other scripts depend on
                        if(GetScriptDependencies(current).Length == currentConnections.Count)
                        {
                            leaves.Add(current);
                        }

                        if (graphComponentSet.Contains(connection))
                            continue;
                        openSet.Add(connection);
                    }
                }
                current = openSet.FirstOrDefault();
            }

            if (graphComponentSet.Count > 0)
            {
                var newIsland = scriptsToSort
                    .Where(graphComponentSet.Contains)
                    .Select(x=> new IslandItem() {script = x, isLeaf = leaves.Contains(x)})
                    .ToArray();
                output.Add(newIsland);
            }
        }

        return output;
    }

    /// <summary>
    /// Visit this script and all dependencies (adding them recursively to the sorted list).
    /// This also builds a connections table that can be used as a nondirected graph of dependencies
    /// </summary>
    static void SortDependencies_Visit( UnityEditor.MonoScript current,
        HashSet<UnityEditor.MonoScript> visited,
        List<UnityEditor.MonoScript> sortedItems,
        Dictionary<Type, UnityEditor.MonoScript> lookup,
        UnityEditor.MonoScript visitedBy,
        Dictionary<UnityEditor.MonoScript, HashSet<UnityEditor.MonoScript>> connections
        )
    {
        if(visited.Add(current))
        {
            //
            // visit all dependencies (adding them recursively to the sorted list) before adding ourselves to the sorted list
            // this ensures that
            // 1. all dependencies are sorted
            // 2. cyclic dependencies can be caught if an item is visited AND it's been added to this list
            var depsRemaining = GetScriptDependencies(current);

            var visitedFrom = current;

            // do deps with fixed orders first
            for(int i=0;i<depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                    true,
                    false);
            }

            // then non-leaves
            for(int i=0;i<depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                    false,
                    false);
            }

            // then any leaves
            for(int i=0;i<depsRemaining.Length; ++i)
            {
                SortDependencies_Visit_VisitDependency(visited, sortedItems, lookup, connections, depsRemaining[i], visitedFrom,
                    false,
                    true);
            }

#if LOG_DEBUG_VERBOSE
            Debug.Log("Sorted "+current.name);
#endif
            sortedItems.Add( current );
        }
        else
        {
            Debug.Assert(sortedItems.Contains(current), "Cyclic dependency found for ScriptDependency "+current.name+" via "+(visitedBy!=null?visitedBy.name:"Unknown")+"!");
        }
    }

    private static void SortDependencies_Visit_VisitDependency(HashSet<MonoScript> visited, List<MonoScript> sortedItems, Dictionary<Type, MonoScript> lookup,
        Dictionary<MonoScript, HashSet<MonoScript>> connections, Type depType, MonoScript visitedFrom, bool fixedOrderDeps, bool leafDeps)
    {
        if (depType == null) return;

        if (!typeof(ScriptableObject).IsAssignableFrom(depType) &&
            !typeof(MonoBehaviour).IsAssignableFrom(depType))
        {
            return;
        }

        MonoScript depScript = null;
        if (!lookup.TryGetValue(depType, out depScript))
        {
            Debug.LogError("ScriptDependency type " + depType.Name + " not found found for script " + visitedFrom.name +
                "! Check that it exists in a file with the same name as the class");
            return;
        }

        if (fixedOrderDeps && !HasFixedOrder(depScript))
        {
            return;
        }

        HashSet<MonoScript> connectionSet = null;
        if (leafDeps
            && connections.TryGetValue(depScript, out connectionSet)
            && GetScriptDependencies(depScript).Length != connectionSet.Count)
        {
            return;
        }

        if (lookup.TryGetValue(depType, out depScript)/* && !HasFixedOrder(depScript)*/)
        {
            SortDependencies_Visit(depScript, visited, sortedItems, lookup, visitedFrom, connections);
        }
    }

    /// <summary>
    /// Does this script have dependencies?
    /// </summary>
    static bool HasDependencies(UnityEditor.MonoScript script)
    {
        return GetScriptDependencies(script).Length > 0;
    }

    /// <summary>
    /// Does this script have fixed order?
    /// </summary>
    static bool HasFixedOrder(UnityEditor.MonoScript script)
    {
        int output = 0;
        return GetFixedOrder(script, out output);
    }

    /// <summary>
    /// Get the dependencies for a script using the lookup table
    /// </summary>
    private static Dictionary<MonoScript, Type[]> s_dependencyAttributes = new Dictionary<MonoScript, Type[]>();
    static Type[] GetScriptDependencies( UnityEditor.MonoScript script)
    {
        if(script==null) return new Type[0];

        var currentType = script.GetClass();
        if(currentType==null) return new Type[0];

        Type[] output = null;
        if (!s_dependencyAttributes.TryGetValue(script, out output))
        {
            List<Type> types = new List<Type>();

            var attribs = currentType.GetCustomAttributes(typeof(ScriptDependencyAttribute), true);
            for(int i=0;i<attribs.Length;++i)
            {
                var dep = attribs[i] as ScriptDependencyAttribute;
                if(dep==null) continue;
                types.AddRange(dep.GetScriptDependencies()
                    .Where(x=>typeof(ScriptableObject).IsAssignableFrom(x) || typeof(MonoBehaviour).IsAssignableFrom(x))
                    );
            }
            s_dependencyAttributes[script] = output = types.ToArray();
        }
        return output;
    }

    private static Dictionary<MonoScript, int?> s_fixedOrderAttributes = new Dictionary<MonoScript, int?>();
    static bool GetFixedOrder(MonoScript script, out int output)
    {
        output = 0;
        if (script == null) return false;

        int? value = null;

        if (!s_fixedOrderAttributes.TryGetValue(script, out value))
        {
            var order = UnityEditor.MonoImporter.GetExecutionOrder(script);
            output = order;

            var attrib = script.GetClass().GetCustomAttributes(typeof(ScriptExecutionOrderAttribute), true).Cast<ScriptExecutionOrderAttribute>().FirstOrDefault();
            if (attrib == null)
            {
                s_fixedOrderAttributes[script] = null;
            }
            else
            {
                s_fixedOrderAttributes[script] = value = attrib.order;
            }
        }

        if (value.HasValue)
        {
            output = value.Value;
            return true;
        }

        return false;
    }
}
#endif


text:
<!DOCTYPE html>
<html>

  {% include head.html %}

    <body id="page-top" class="index">

    {% include header.html %}
    {% include services.html %}
    {% include portfolio_grid.html %}
    {% include about.html %}
    {% include team.html %}
    {% include clients.html %}
    {% include footer.html %}
    {% include modals.html %}
    {% include js.html %}

    <script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = 'dronephotography';

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function () {
        var s = document.createElement('script'); s.async = true;
        s.type = 'text/javascript';
        s.src = '//' + disqus_shortname + '.disqus.com/count.js';
        (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
    }());
</script>

    </body>
</html>


text:
Date: `r Sys.Date()`

This report covers the analyses used in the ZZZ project (Marcus Mark, PI).

<!--  Set the working directory to the repository's base directory; this assumes the report is nested inside of two directories.-->

<!-- Set the report-wide options, and point to the external code file. -->

<!-- Load 'sourced' R files.  Suppress the output when loading sources. -->

<!-- Load packages, or at least verify they're available on the local machine.  Suppress the output when loading packages. -->

<!-- Load any global functions and variables declared in the R file.  Suppress the output. -->

<!-- Declare any global functions specific to a Rmd output.  Suppress the output. -->

<!-- Load the datasets.   -->

<!-- Tweak the datasets.   -->

# Summary

# Graph on Continuous Time
![](figure-png/graph-continuous-1.png)<!-- -->![](figure-png/graph-continuous-2.png)<!-- -->

# Session Information
For the sake of documentation and reproducibility, the current report was rendered on a system using the following software.

```
Report rendered by Will at 2017-01-16, 15:17 -0600 in 4 seconds.
```

```
R Under development (unstable) (2016-11-29 r71698)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] magrittr_1.5  ggplot2_2.2.0 knitr_1.15.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.8        munsell_0.4.3      colorspace_1.3-1   R6_2.2.0           stringr_1.1.0
 [6] plyr_1.8.4         dplyr_0.5.0        tools_3.4.0        grid_3.4.0         gtable_0.2.0
[11] DBI_0.5-1          ggthemes_3.3.0     htmltools_0.3.5    yaml_2.1.14        lazyeval_0.2.0
[16] rprojroot_1.1      digest_0.6.10      assertthat_0.1     tibble_1.2         readr_1.0.0
[21] RColorBrewer_1.1-2 evaluate_0.10      rmarkdown_1.2      stringi_1.1.2      compiler_3.4.0
[26] scales_0.4.1       backports_1.0.4
```


text:
using ::testing::NiceMock;

namespace {
const char kGuid[] = "broccoli";
const base::FilePath::CharType kDownloadServiceStorageDir[] =
    FILE_PATH_LITERAL("Download Service");
const base::FilePath::CharType kFilesStorageDir[] = FILE_PATH_LITERAL("Files");

// A background download service client used by this test.
class FakeClient : public download::test::MockClient {
 public:
  FakeClient() = default;
  ~FakeClient() override = default;

  void WaitForDownload() {
    run_loop_ = std::make_unique<base::RunLoop>();
    run_loop_->Run();
  }

  const download::CompletionInfo* completion_info() const {
    return completion_info_.get();
  }

  const absl::optional<FailureReason>& failure_reason() const {
    return failure_reason_;
  }

 private:
  // download::test::MockClient overrides.
  void OnServiceInitialized(
      bool state_lost,
      const std::vector<download::DownloadMetaData>& downloads) override {
    metadata_ = downloads;
  }

  void OnDownloadSucceeded(
      const std::string& guid,
      const download::CompletionInfo& completion_info) override {
    download_guid_ = guid;
    completion_info_ =
        std::make_unique<download::CompletionInfo>(completion_info);
    DCHECK(run_loop_);
    run_loop_->Quit();
  }

  void OnDownloadFailed(const std::string& guid,
                        const download::CompletionInfo& completion_info,
                        FailureReason reason) override {
    download_guid_ = guid;
    completion_info_ =
        std::make_unique<download::CompletionInfo>(completion_info);
    DCHECK(run_loop_);
    run_loop_->Quit();
    failure_reason_ = reason;
  }

  std::unique_ptr<base::RunLoop> run_loop_;
  std::vector<download::DownloadMetaData> metadata_;
  std::string download_guid_;
  std::unique_ptr<download::CompletionInfo> completion_info_;
  absl::optional<FailureReason> failure_reason_;
};

}  // namespace

// Browsertest-like integration unit test to verify the whole background
// download service. This is not a EG test since background download service
// doesn't have UI. Not in anonymous namespace due to friend class of
// BackgroundDownloadServiceFactory.
class BackgroundDownloadServiceTest
    : public download::test::BackgroundDownloadTestBase {
 protected:
  BackgroundDownloadServiceTest() = default;
  ~BackgroundDownloadServiceTest() override = default;

  void SetUp() override {
    download::test::BackgroundDownloadTestBase::SetUp();
    TestChromeBrowserState::Builder builder;
    browser_state_ = builder.Build();

    // Create a random file in root dir and an unknown file in downoad dir.
    ASSERT_TRUE(base::CreateTemporaryFileInDir(browser_state_->GetStatePath(),
                                               &temp_file_path_));
    auto download_dir = browser_state_->GetStatePath()
                            .Append(kDownloadServiceStorageDir)
                            .Append(kFilesStorageDir);
    base::CreateDirectoryAndGetError(download_dir, nullptr);
    ASSERT_TRUE(base::CreateTemporaryFileInDir(download_dir,
                                               &temp_file_path_to_delete_));

    // Inject a fake client through SetTestingFactory.
    BackgroundDownloadServiceFactory* factory =
        BackgroundDownloadServiceFactory::GetInstance();
    factory->SetTestingFactory(
        browser_state_.get(),
        base::BindLambdaForTesting([&](web::BrowserState* browser_state) {
          auto fake_client = std::make_unique<NiceMock<FakeClient>>();
          fake_client_ = fake_client.get();
          auto clients = std::make_unique<download::DownloadClientMap>();
          clients->emplace(download::DownloadClient::TEST,
                           std::move(fake_client));
          return factory->BuildServiceWithClients(browser_state,
                                                  std::move(clients));
        }));
    service_ = BackgroundDownloadServiceFactory::GetForBrowserState(
        browser_state_.get());
  }

  // Download a file from embedded test server. Use different |relative_url| for
  // different http responses.
  void Download(const std::string& relative_url) {
    download::DownloadParams params;
    params.guid = kGuid;
    params.client = download::DownloadClient::TEST;
    params.request_params.method = "GET";
    params.request_params.url = server_.GetURL(relative_url);
    service_->StartDownload(std::move(params));
  }

  FakeClient* client() { return fake_client_; }
  const base::FilePath& temp_file_path() const { return temp_file_path_; }
  const base::FilePath& temp_file_path_to_delete() const {
    return temp_file_path_to_delete_;
  }

 private:
  std::unique_ptr<ChromeBrowserState> browser_state_;
  download::BackgroundDownloadService* service_;
  FakeClient* fake_client_;
  base::FilePath temp_file_path_;
  base::FilePath temp_file_path_to_delete_;
};

// Verifies download can be finished.
TEST_F(BackgroundDownloadServiceTest, DownloadComplete) {
  Download("/test");
  client()->WaitForDownload();
  std::string content;
  ASSERT_TRUE(
      base::ReadFileToString(client()->completion_info()->path, &content));
  EXPECT_EQ(BackgroundDownloadTestBase::kDefaultResponseContent, content);
}

// Verifies download will fail when the server returns http 404 status code.
TEST_F(BackgroundDownloadServiceTest, DownloadFailed) {
  Download("/notfound");
  client()->WaitForDownload();
  EXPECT_TRUE(client()->failure_reason().has_value());
  EXPECT_EQ(FakeClient::FailureReason::UNKNOWN, client()->failure_reason());
}

// Verifies that unknown files under download directory will be deleted.
TEST_F(BackgroundDownloadServiceTest, FileCleanUp) {
  // Make sure the service is initialized.
  Download("/notfound");
  client()->WaitForDownload();

  EXPECT_TRUE(base::PathExists(temp_file_path()))
      << "Files under browser state directory should not be deleted.";
  EXPECT_FALSE(base::PathExists(temp_file_path_to_delete()))
      << "Unknown files under download files directory should be deleted.";
}


text:
using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Text;

using Poderosa.Util;
using Poderosa.Util.Collections;
using Poderosa.Plugins;
//using Poderosa.UI;
using Poderosa.Commands;

namespace Poderosa.Forms {
    //ƒƒCƒ"ƒƒjƒ…[
    //  ƒ}ƒ‹ƒ`ƒEƒBƒ"ƒhƒE'ª‰Â"\'Å' 'é'̂ŁAMainMenuItem'̃cƒŠ['̓AƒvƒŠƒP[ƒVƒ‡ƒ"'Å—Bˆê(WindowManager'ª•Û—L)'µA
    //  Windows.Formsƒx[ƒX'̃ƒjƒ…[€–Ú'Í•K—v'ɉž'¶'Ä'»'Ì"s"xì¬'³'ê'邱'Æ'É'ˆÓ'·'é
    internal class MainWindowMenu {
        private TypedSequentialTable<string, MainMenuItem> _idToMenu;
        private MainMenuItem _fileMenu;
        private MainMenuItem _editMenu;
        private MainMenuItem _consoleMenu;
        private MainMenuItem _toolMenu;
        private MainMenuItem _windowMenu;
        private MainMenuItem _pluginMenu;
        private MainMenuItem _helpMenu;

        //'¼'©'çŽQÆ'³'ê'郁ƒjƒ…[ƒOƒ‹[ƒv
        private SplitMenuGroup _splitMenuGroup;

        public MainWindowMenu() {
            _idToMenu = new TypedSequentialTable<string, MainMenuItem>();

            _fileMenu = CreateMainMenu("Menu.File", "org.poderosa.menu.file");
            _editMenu = CreateMainMenu("Menu.Edit", "org.poderosa.menu.edit");
            _consoleMenu = CreateMainMenu("Menu.Console", "org.poderosa.menu.console");
            _toolMenu = CreateMainMenu("Menu.Tool", "org.poderosa.menu.tool");
            _windowMenu = CreateMainMenu("Menu.Window", "org.poderosa.menu.window");
            _pluginMenu = CreateMainMenu("Menu.Plugin", "org.poderosa.menu.plugin");
            _helpMenu = CreateMainMenu("Menu.Help", "org.poderosa.menu.help");

            _splitMenuGroup = new SplitMenuGroup();
#if !UNITTEST
            _windowMenu.ExtensionPoint.RegisterExtension(_splitMenuGroup);
            _windowMenu.ExtensionPoint.RegisterExtension(new CloseAllMenuGroup(_splitMenuGroup));
            _windowMenu.ExtensionPoint.RegisterExtension(new SetTabRowCountMenuGroup(_splitMenuGroup));
            _windowMenu.ExtensionPoint.RegisterExtension(new DocActivationMenuGroup());
            _fileMenu.ExtensionPoint.RegisterExtension(new NewWindowMenuGroup());
            _fileMenu.ExtensionPoint.RegisterExtension(new QuitMenuGroup());
            _editMenu.ExtensionPoint.RegisterExtension(new CopyGroup());
            _editMenu.ExtensionPoint.RegisterExtension(new PasteGroup());
            _consoleMenu.ExtensionPoint.RegisterExtension(new CloseDocumentGroup());
            _pluginMenu.ExtensionPoint.RegisterExtension(new DefaultPluginMenuGroup());
            _helpMenu.ExtensionPoint.RegisterExtension(new DefaultHelpMenuGroup());
#endif
        }
        private MainMenuItem CreateMainMenu(string text_id, string extension_point_name) {
            StringResource str = CoreUtil.Strings;
            MainMenuItem item = new MainMenuItem(text_id, extension_point_name, _idToMenu.Count);
            _idToMenu.Add(extension_point_name, item);
            return item;
        }

        public void FullBuild(MenuStrip mainmenu, ICommandTarget target) {
            foreach (Pair<string, MainMenuItem> p in _idToMenu.Pairs) {
                mainmenu.Items.Add(MenuUtil.CreateMenuItem(p.Second, target));
            }
        }

        public SplitMenuGroup SplitMenuGroup {
            get {
                return _splitMenuGroup;
            }
        }

        public MainMenuItem FindMainMenuItem(string extension_point_name) {
            return _idToMenu[extension_point_name];
        }

    }

    internal class MainMenuItem : IPoderosaMenuFolder {
        private List<IPoderosaMenuGroup> _children;
        private bool _created;
        private int _index;
        private string _text;
        private IExtensionPoint _extensionPoint;

        public MainMenuItem(string text, string extension_point_name, int index) {
            _children = new List<IPoderosaMenuGroup>();
            _index = index;
            _text = text;
            _extensionPoint = WindowManagerPlugin.Instance.PoderosaWorld.PluginManager.CreateExtensionPoint(extension_point_name, typeof(IPoderosaMenuGroup), WindowManagerPlugin.Instance);
            _created = false;
        }

        public void Create() {
            if (_created)
                return;

            _children.Clear();
            IPoderosaMenuGroup[] me = (IPoderosaMenuGroup[])_extensionPoint.GetExtensions();

            //ƒ\[ƒg'µ'ăRƒŒƒNƒVƒ‡ƒ"'ɒljÁ
            foreach (IPoderosaMenuGroup g in PositionDesignationSorter.SortItems(me)) {
                _children.Add(g);
            }

            _created = true;
        }

        public IPoderosaMenuGroup[] ChildGroups {
            get {
                return _children.ToArray();
            }
        }

        public string Text {
            get {
                return CoreUtil.Strings.GetString(_text);
            }
        }
        public int Index {
            get {
                return _index;
            }
        }
        public IExtensionPoint ExtensionPoint {
            get {
                return _extensionPoint;
            }
        }

        public bool IsEnabled(ICommandTarget target) {
            return true;
        }
        public bool IsChecked(ICommandTarget target) {
            return false;
        }
        public IAdaptable GetAdapter(Type adapter) {
            return WindowManagerPlugin.Instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter);
        }
    }

    internal class DefaultMenuItemGroup : IPoderosaMenuGroup {
        private List<IPoderosaMenu> _children;

        public DefaultMenuItemGroup() {
            _children = new List<IPoderosaMenu>();
        }

        public IPoderosaMenu[] ChildMenus {
            get {
                return _children.ToArray();
            }
        }

        public bool IsVolatileContent {
            get {
                return false;
            }
        }
        public bool ShowSeparator {
            get {
                return true;
            }
        }

        public IAdaptable GetAdapter(Type adapter) {
            return WindowManagerPlugin.Instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter);
        }
    }

}