text:
#ifndef DRM_FLIP_WORK_H
#define DRM_FLIP_WORK_H

#include <linux/kfifo.h>
#include <linux/spinlock.h>
#include <linux/workqueue.h>

/**
 * DOC: flip utils
 *
 * Util to queue up work to run from work-queue context after flip/vblank.
 * Typically this can be used to defer unref of framebuffer's, cursor
 * bo's, etc until after vblank.  The APIs are all thread-safe.
 * Moreover, drm_flip_work_queue_task and drm_flip_work_queue can be called
 * in atomic context.
 */

struct drm_flip_work;

/*
 * drm_flip_func_t - callback function
 *
 * @work: the flip work
 * @val: value queued via drm_flip_work_queue()
 *
 * Callback function to be called for each of the  queue'd work items after
 * drm_flip_work_commit() is called.
 */
typedef void (*drm_flip_func_t)(struct drm_flip_work *work, void *val);

/**
 * struct drm_flip_task - flip work task
 * @node: list entry element
 * @data: data to pass to work->func
 */
struct drm_flip_task {
	struct list_head node;
	void *data;
};

/**
 * struct drm_flip_work - flip work queue
 * @name: debug name
 * @func: callback fxn called for each committed item
 * @worker: worker which calls @func
 * @queued: queued tasks
 * @commited: commited tasks
 * @lock: lock to access queued and commited lists
 */
struct drm_flip_work {
	const char *name;
	drm_flip_func_t func;
	struct work_struct worker;
	struct list_head queued;
	struct list_head commited;
	spinlock_t lock;
};

struct drm_flip_task *drm_flip_work_allocate_task(void *data, gfp_t flags);
void drm_flip_work_queue_task(struct drm_flip_work *work,
			      struct drm_flip_task *task);
void drm_flip_work_queue(struct drm_flip_work *work, void *val);
void drm_flip_work_commit(struct drm_flip_work *work,
		struct workqueue_struct *wq);
void drm_flip_work_init(struct drm_flip_work *work,
		const char *name, drm_flip_func_t func);
void drm_flip_work_cleanup(struct drm_flip_work *work);

#endif  /* DRM_FLIP_WORK_H */


text:
#ifndef PFC_LIST_H_
#define PFC_LIST_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "pfc_types.h"

typedef struct _PFC_ValueList PFC_ValueList;

PFC_ValueList * PFC_ValueList_New();
void PFC_ValueList_Free(PFC_ValueList * list);
PFC_ValueList * PFC_ValueList_GetFirst(PFC_ValueList * List);
PFC_ValueList * PFC_ValueList_GetLast(PFC_ValueList * List);
void * PFC_ValueList_NextItemValue(PFC_ValueList ** List);
pfc_error PFC_ValueList_AddItem(PFC_ValueList * List, void * Value);
pfc_error PFC_ValueList_RemoveItem(PFC_ValueList * List, void * Value);
void * PFC_ValueList_GetValue(PFC_ValueList * List);
int PFC_ValueList_Count(PFC_ValueList * List);

#ifdef __cplusplus
}
#endif

#endif /* PFC_LIST_H_ */

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

	<ImageView
	    android:id = "@+id/photo"
	    android:layout_width="100dp"
	    android:layout_height="100dp"
	    android:contentDescription="@string/desc" />
	<TextView
	    android:id="@+id/name"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text=""
	    android:textColor="@color/white"
	    android:textSize="16sp" />
	<TextView
	    android:id="@+id/phone"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text=""
	    android:textColor="@color/white"
	    android:textSize="16sp" />
	<TextView
	    android:id="@+id/email"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:text=""
	    android:textColor="@color/white"
	    android:textSize="16sp" />
	<Button
	    android:id="@+id/facebookButton"
	    android:layout_width="100dp"
	    android:layout_height="50dp" />
	<Button
	    android:id="@+id/gmailButton"
	    android:layout_width="100dp"
	    android:layout_height="50dp" />
</LinearLayout>


text:
namespace System.Web.UI {
    using System;
    using System.Collections;

    // Cache TargetControlTypeAttributes to improve performance
    internal static class TargetControlTypeCache {
        // Maps Type (extender control) to Type[] (valid target control types)
        private static readonly Hashtable _targetControlTypeCache = Hashtable.Synchronized(new Hashtable());

        public static Type[] GetTargetControlTypes(Type extenderControlType) {
            Type[] types = (Type[])_targetControlTypeCache[extenderControlType];
            if (types == null) {
                types = GetTargetControlTypesInternal(extenderControlType);
                _targetControlTypeCache[extenderControlType] = types;
            }
            return types;
        }

        private static Type[] GetTargetControlTypesInternal(Type extenderControlType) {
            object[] attrs = extenderControlType.GetCustomAttributes(typeof(TargetControlTypeAttribute), true);
            Type[] types = new Type[attrs.Length];
            for (int i = 0; i < attrs.Length; i++) {
                types[i] = ((TargetControlTypeAttribute)attrs[i]).TargetControlType;
            }
            return types;
        }
    }
}


text:
require 'rspec/core/formatters/helpers'
require 'rspec/core/formatters/base_text_formatter'

module Simulacrum
  module Browserstack
    # The Summary Class is responsible for combining dumped examlpes from one
    # or more other RSpec runs.
    class Summary < RSpec::Core::Formatters::BaseTextFormatter
      # TODO: Rename me, I'm really just a formatter anyway
      # TODO: Also, should this just be an external gem...? Prolly not?
      def initialize(results_set, start_time, end_time)
        super($stdout)
        @results_set = results_set
        @start_time = start_time
        @end_time = end_time
      end

      def dump_commands_to_rerun_failed_examples
        return if failed_examples.empty?
        output.puts
        output.puts('Failed examples:')
        output.puts

        failed_examples.each do |example|
          output.puts(failure_color("simulacrum --browser=#{example.metadata[:browser]} #{RSpec::Core::Metadata::relative_path(example.location)}") + ' ' + detail_color("# #{example.full_description}"))
        end
      end

      def dump_summary
        super(duration, example_count, failure_count, pending_count)
      end

      def failed_examples
        examples.select do |example|
          example.execution_result[:status] == 'failed'
        end
      end

      def pending_examples
        examples.select do |example|
          example.execution_result[:status] == 'pending'
        end
      end

      def duration
        @end_time - @start_time
      end

      def example_count
        summaries.map { |x| x[:example_count] }.reduce(:+)
      end

      def failure_count
        summaries.map { |x| x[:failure_count] }.reduce(:+)
      end

      def pending_count
        summaries.map { |x| x[:pending_count] }.reduce(:+)
      end

      def find_shared_group(example)
      end

      def group_and_parent_groups(example)
      end

      private

      def color_enabled?
        Simulacrum.runner_options.color
      end

      def examples
        dumped_results.map { |result| result[:examples] }.flatten
      end

      def summaries
        dumped_results.map { |result| result[:summary] }.flatten
      end

      def dumped_results
        @dumped_results ||= @results_set.map do |result|
          Marshal.load(result[:results])
        end
      end
    end
  end
end


text:
package com.mit.dstore.entity;

import java.io.Serializable;

public class ScanStoreChridJson implements Serializable {
	/**
	 * 描述
	 *
	 */

	private static final long serialVersionUID = 764322893981L;
	private String UserNeiMa = "";// 职员内码
	private String UserName = "";// 职员名称
	private String UserAccount = "";// 职员账号/编码
	private String GroupID = "";// 集团ID|
	private String SellerID = "";// 店铺ID
	private String SellerName = "";// 店铺名称
	private String SellerBaseInfo = "";// 店铺基本信息
	private String SellerLogo = "";// 店铺logo
	private String SellerAddress = "";// 地址
	private String SellerTel = "";// 电话
	private String Memo = "";
	private String RemainAmount = "";// 可用额度
	private String SellerDesc = "";// 商家描述
	private String SellerCode = "";// 商家编码
	private String GroupCode = "";// 集团编码
	private int CurrencyID=0;

	public String getUserNeiMa() {
		return UserNeiMa;
	}

	public void setUserNeiMa(String userNeiMa) {
		UserNeiMa = userNeiMa;
	}

	public int getCurrencyID() {
		return CurrencyID;
	}

	public void setCurrencyID(int currencyID) {
		CurrencyID = currencyID;
	}

	public String getSellerAddress() {
		return SellerAddress;
	}

	public void setSellerAddress(String sellerAddress) {
		SellerAddress = sellerAddress;
	}

	public String getSellerTel() {
		return SellerTel;
	}

	public void setSellerTel(String sellerTel) {
		SellerTel = sellerTel;
	}

	public String getSellerCode() {
		return SellerCode;
	}

	public void setSellerCode(String sellerCode) {
		SellerCode = sellerCode;
	}

	public String getGroupCode() {
		return GroupCode;
	}

	public void setGroupCode(String groupCode) {
		GroupCode = groupCode;
	}

	public String getMemo() {
		return Memo;
	}

	public void setMemo(String memo) {
		Memo = memo;
	}

	public String getRemainAmount() {
		return RemainAmount;
	}

	public void setRemainAmount(String remainAmount) {
		RemainAmount = remainAmount;
	}

	public String getUserName() {
		return UserName;
	}

	public void setUserName(String userName) {
		UserName = userName;
	}

	public String getUserAccount() {
		return UserAccount;
	}

	public void setUserAccount(String userAccount) {
		UserAccount = userAccount;
	}

	public String getGroupID() {
		return GroupID;
	}

	public void setGroupID(String groupID) {
		GroupID = groupID;
	}

	public String getSellerID() {
		return SellerID;
	}

	public void setSellerID(String sellerID) {
		SellerID = sellerID;
	}

	public String getSellerName() {
		return SellerName;
	}

	public void setSellerName(String sellerName) {
		SellerName = sellerName;
	}

	public String getSellerBaseInfo() {
		return SellerBaseInfo;
	}

	public void setSellerBaseInfo(String sellerBaseInfo) {
		SellerBaseInfo = sellerBaseInfo;
	}

	public String getSellerLogo() {
		return SellerLogo;
	}

	public void setSellerLogo(String sellerLogo) {
		SellerLogo = sellerLogo;
	}

	public String getSellerDesc() {
		return SellerDesc;
	}

	public void setSellerDesc(String sellerDesc) {
		SellerDesc = sellerDesc;
	}

	@Override
	public String toString() {
		return "ScanStoreChridJson [UserNeiMa=" + UserNeiMa + ", UserName=" + UserName + ", UserAccount=" + UserAccount + ", GroupID=" + GroupID
				+ ", SellerID=" + SellerID + ", SellerName=" + SellerName + ", SellerBaseInfo=" + SellerBaseInfo + ", SellerLogo=" + SellerLogo
				+ ", SellerAddress=" + SellerAddress + ", SellerTel=" + SellerTel + ", Memo=" + Memo + ", RemainAmount=" + RemainAmount
				+ ", SellerDesc=" + SellerDesc + ", SellerCode=" + SellerCode + ", GroupCode=" + GroupCode + ", CurrencyID=" + CurrencyID + "]";
	}

}


text:
// Propagating Cipher - Block Chaining
#ifndef __PCPB__
#define __PCPB__

#include "../common/includes.h"
#include "../Encryptions/SymAlg.h"

class PCPB{
    private:
        SymAlg * algo;
        std::string const_IV;
        uint8_t blocksize;

    public:
        PCPB(SymAlg * instance, const std::string & iv = "");
        std::string encrypt(const std::string & data);
        std::string decrypt(const std::string & data);
};

#endif


text:
"""
Testing for the allusive module
"""

##########################################################################
## Imports
##########################################################################

import unittest

##########################################################################
## Test Cases
##########################################################################

class InitializationTest(unittest.TestCase):

    def test_initialization(self):
        """
        Tests a simple world fact by asserting that 10*10 is 100.
        """
        self.assertEqual(2**3, 8)

    def test_import(self):
        """
        Can import allusive
        """
        try:
            import allusive
        except ImportError:
            self.fail("Unable to import the allusive module!")

    def test_version(self):
        """
        Assert that the version is sane
        """
        import allusive
        self.assertEqual("0.1.0", allusive.get_version())


text:
/* global Arenite:true */
// Arenite is an implementation of the Sandbox and Module patterns. It was designed to,
// unlike most of the existing module libraries, not affect your code making it dependant on the module library itself.
//
// Base of the arenite sandbox object. Creates the base services in the arenite sandbox object.
//
// Using the Namespace and MVP (or MVC) patterns is strongly recommended but not mandatory.
//
// You can create further extensions to the sandbox by providing new services or overriding already imported ones.
//
// There are a few extensions included in this repository and you can read more about them here.
//
// For more information about the mentioned patterns consult the book "Javascript Patterns"
// by Stoyan Stefanov from O'Reilly Media which discusses these patterns in detail.
//
// ## Configuration
// The documentation for the configuration is presented in the website.
Arenite = function (config) {
  //### Arenite.Object
  // Instance of the Sandbox is started with the Arenite.Object module witch gives us access to the extend function used.
  var arenite = Arenite.Object();
  // Add the object and array helper methods to their respective prototypes
  arenite.object.forEach(arenite.object, function (func, name) {
    if (!Object.prototype[name]) {
      Object.defineProperty(Object.prototype, name, {
        writable: true,
        enumerable: false,
        value: function () {
          return func.apply(this, [this].concat([].slice.call(arguments)));
        }
      });
    }
  });

  arenite.object.forEach(arenite.array, function (func, name) {
    if (!Array.prototype[name]) {
      Object.defineProperty(Array.prototype, name, {
        writable: true,
        enumerable: false,
        value: function () {
          return func.apply(this, [this].concat([].slice.call(arguments)));
        }
      });
    }
  });
  //### Arenite.Html
  // Extend the instance with the Arenite.Html extension providing the html helper tooks.
  arenite.fuseWith(Arenite.Html(arenite));
  //### Arenite.Async
  // Extend the instance with the Arenite.Async extension providing the asynchronous tools (Latch Pattern) used by the Loader extension.
  arenite.fuseWith(Arenite.Async(arenite));
  //### Arenite.Url
  // Extend the instance with the Arenite.Url extension which provides functions for analysis of query parameters.
  arenite.fuseWith(Arenite.Url(arenite));
  //### Arenite.DI
  // Extend the instance with the Arenite.DI extension which provides
  // the injector functionality.
  arenite.fuseWith(Arenite.DI(arenite));
  //### Arenite.AnnotationProcessor
  // Extend the instance with the Arenite.AnnotationProcessor extension which provides
  // the parsing and hanlding of annotations.
  arenite.fuseWith(Arenite.AnnotationProcessor(arenite));
  //### Arenite.Context
  // Extend the instance with the Arenite.Context extension which provides
  // the context to manage the instances.
  arenite.fuseWith(Arenite.Context(arenite));
  //### Arenite.Loader
  // Extend the instance with the Arenite.Loader extension which provides
  // the script and resource loading functionality to the sandbox.
  arenite.fuseWith(Arenite.Loader(arenite));
  //### Arenite.Bus
  // Extend the instance with the Arenite.Bus extension which provides
  // an event bus.
  arenite.fuseWith(Arenite.Bus(arenite));
  // Initialize the injector by having it read the configuration object passed into this constructor.
  arenite.di.init(config);
  return arenite;
};

/*global Arenite:true*/
/*jshint evil:true*/
// Utility function to interpret the annotations.
Arenite.AnnotationProcessor = function (arenite) {
  var _processAnnotations = function (text) {
    var regex = /@arenite-instance\s+["']([^"']+)["']\s*(.*);\s*(@arenite-init\s+["']([^"']+)["']\s*(.*);)*\s*(@arenite-start\s+["']([^"']+)["']\s*(.*);)*\s*\*\/\s*([\w.]+)/g;
    var match;
    while ((match = regex.exec(text))) {
      _processAnnotation(match);
    }
  };

  var _processArgAnnotation = function (match) {
    var args = [];
    var split = match.split(',');
    split.forEach(function (arg) {
      var argPair = arg.split(":");
      var argObj = {};
      argObj[argPair[0].trim()] = argPair[0].trim() === 'ref' ? argPair[1].trim() : eval(argPair[1].trim());
      args.push(argObj);
    });
    return args;
  };

  var _processAnnotation = function (match) {
    var instanceName = match[1];
    var namespace = match[9];

    if (!arenite.config.context) {
      arenite.config.context = {instances: {}};
    }

    //instance
    arenite.config.context.instances[instanceName] = {namespace: namespace};
    if (match[2]) {
      arenite.config.context.instances[instanceName].args = _processArgAnnotation(match[2]);
    }

    // init
    if (match[4]) {
      arenite.config.context.instances[instanceName].init = {func: match[4]};
      if (match[5]) {
        arenite.config.context.instances[instanceName].init.args = _processArgAnnotation(match[5]);
      }
    }

    // start
    if (match[7]) {
      var start = {instance: instanceName, func: match[7]};
      if (match[8]) {
        start.args = _processArgAnnotation(match[8]);
      }
      if (!arenite.config.context.start) {
        arenite.config.context.start = [];
      }
      arenite.config.context.start.push(start);
    }
  };

  return {
    annotation: {
      //### annotation.processAnnotations
      // Interpret the annotations specified in a given source.
      //

      // processAnnotations(text)
      //

      //where *text* is the text(source) to be analysed
      processAnnotations: _processAnnotations
    }
  };

};
/*global Arenite:true*/
//Asynchronous tools
Arenite.Async = function (arenite) {
  var _sequencialLatch = function (values, callback, finalCallback) {
    var index = 0;
    var length = values.length;

    var _next = function () {
      if (index < length) {
        callback(values[index], index++);
      } else {
        finalCallback();
      }
    };

    return {
      next: _next
    };
  };

  var _latch = function (times, callback, name) {
    var executions = 0;
    var id = name || new Date().getTime();

    if (arenite.config.debug) {
      window.console.groupCollapsed('Latch: Starting latch "' + id + '" for', times, 'times');
      window.console.trace();
      window.console.groupEnd();
    }

    return {
      countDown: function () {
        executions++;
        if (arenite.config.debug) {
          window.console.log('Latch: Counting down latch "' + id + '" ,', times - executions, 'remaining');
        }
        if (executions === times) {
          if (arenite.config.debug) {
            window.console.log('Latch: Triggering latch "' + id + '"');
          }
          callback(executions);
        }
      },
      countUp: function () {
        executions--;
        if (arenite.config.debug) {
          window.console.log('Latch: Counting up latch "' + id + '" ,', times - executions, 'remaining');
        }
        if (executions === times) {
          if (arenite.config.debug) {
            window.console.log('Latch: Triggering latch "' + id + '"');
          }
          callback(executions);
        }
      }
    };
  };

  return {
    async: {
      //### Sequencial latch.
      //The sequencial latch will synchronously execute the handler
      // with the provided values and execute a callback when all operations are complete.
      //

      // seqLatch(values, handler, callback)
      //

      // Where *values* is an array of values to be passed as parameters to the handler function.
      // The *handler* function must call the next function of the returned object when it
      // finishes the execution.
      // The *callback* is the function that is executed once all the values have been handled.
      seqLatch: _sequencialLatch,
      //### Latch.
      //The latch will execute asynchronous tasks and invoke a callback when all the declared times have been executed
      //

      // latch(times, callback [, name])
      //

      // Where *times* is the initially expected times the latch should wait for to trigger the callback.
      // The *callback* is the function invoked once times reaches 0.
      // The optional **name is if you wish to have a meaningful name in the console logs.
      // This function returns an object with two functions:
      //

      // {
      //   countDown:...
      //   countUp:...
      // }
      //

      // *countDown* will decrease the counter and *CountUp* will increase the counter that is initialized with the times argument.
      // Once the counter hits 0 the callback is invoked.
      latch: _latch
    }
  };
};
/*global Arenite:true*/
Arenite.Bus = function () {
  var bus = {};

  var _subscribe = function (subject, func) {
    if (!bus[subject]) {
      bus[subject] = [];
    }
    bus[subject].push(func);
  };

  var _unsubscribe = function (subject, func) {
    if (bus[subject]) {
      bus[subject].forEach(function (handler, idx) {
        if (handler === func) {
          bus[subject].splice(idx, 1);
        }
      });
    }
  };

  var _publish = function (subject, args) {
    window.console.groupCollapsed("sending event:\"" + subject + "\" with ", args);
    window.console.trace();
    window.console.groupEnd();
    if (bus[subject]) {
      bus[subject].forEach(function (handler) {
        window.setTimeout(function () { //make the calls asynchronous
          handler(args);
        }, 0);
      });
    }
  };

  return {
    bus: {
      subscribe: _subscribe,
      unsubscribe: _unsubscribe,
      publish: _publish
    }
  };
};
/*global Arenite:true*/
// The context(registry) of the instances.
Arenite.Context = function (arenite) {
  var registry = {};
  var factories = {};
  var factory_id = 1;

  var _addInstance = function (name, instance, factory) {
    if (factory) {
      factories[name] = instance;
    } else {
      registry[name] = instance;
    }
  };

  var _removeInstance = function (name) {
    registry.deleteInPath(name);
  };

  var _getInstance = function (name) {
    if (factories.hasOwnProperty(name)) {
      var tempId = '__factory_instance_' + name + '__' + factory_id++;
      var tempContext = {};
      tempContext[tempId] = factories[name].fuseWith({factory: false});
      arenite.di.wire(tempContext);
      var instance = registry[tempId];
      _removeInstance(tempId);
      return instance;
    } else {
      return registry[name];
    }
  };

  /* AMD methods declaration so we can capture the libs that support it */
  window.require = _getInstance;
  window.define = function (name, deps, callback) {
    while (!Array.isArray(deps)) {
      callback = deps;
      deps = typeof name === 'function' || Array.isArray(name) ? name : [];
      name = typeof name === 'string' ? name : undefined;
    }

    var resolvedDeps = [];
    deps.forEach(function (dep) {
      if (dep === 'exports') { //reserved name for Simplified CommonJS wrapper
        resolvedDeps.push({});
      } else if (dep === 'require') { //reserved name for Simplified CommonJS wrapper
        resolvedDeps.push(_getInstance);
      } else {
        resolvedDeps.push(_getInstance(dep));
      }
    });
    var result = callback.apply(window, resolvedDeps);
    if (!name) {
      try {
        throw new Error();
      } catch (e) {
        var reg = /([^\/]+?)(\.min)*\.js[:\d]+\)*$/gm;
        if (reg.exec(e.stack)) {
          var candidates = reg.exec(e.stack);
          if (candidates.length > 1) {
            name = candidates[1];
          }
        }
      }
    }
    if (name) {
      _addInstance(name, result);
    }
  };
  window.define.amd = {
    jQuery: true
  };

  return {
    context: {
      //### context.get
      // Get an registered instance from arenite.
      //

      // get(instance)
      //

      //where *instance* is the name of the instance to be retrieved
      get: _getInstance,
      //### context.add
      // Register an instance in arenite
      //

      // add(name, instance, factory, args)
      //

      //where *name* is the alias by which the instance should be known, *instance* is the actual instance
      // to register or the factory function in case it's a factory, *factory* is a flag stating if a new
      // instance should be generated each time it is requested and *args* is the arguments to use in case
      // the instance is a factory.
      add: _addInstance,
      //### context.remove
      // Removes an instance from the arenite context
      //

      // remove(instance)
      //

      //where *instance* is the name of the instance to be de-registered from arenite.
      remove: _removeInstance
    }
  };
};

/*global Arenite:true*/
// Collection of utility functions wire the instances and load the configured resources.
Arenite.DI = function (arenite) {

  var anonymous_id = 1;

  var _resolveFunc = function (execution) {
    var resolvedFunc = execution.func;
    if (typeof execution.func === 'function') {
      resolvedFunc = execution.func;
    } else {
      if (execution.extension) {
        resolvedFunc = arenite[execution.instance].getInPath(execution.func);
      } else {
        resolvedFunc = arenite.context.get(execution.instance).getInPath(execution.func);
      }
    }
    return resolvedFunc;
  };

  var _resolveArgs = function (execution, done, type, stack) {
    execution.args = execution.args || [];
    var failure = false;
    var resolved = [];
    execution.args.forEach(function (arg, idx) {
      if (typeof arg.value !== 'undefined') {
        resolved.push(arg.value);
      } else if (typeof arg.ref !== 'undefined') {
        var ref = arenite.context.get(arg.ref);
        if (ref) {
          resolved.push(ref);
        } else {
          failure = true;
          if (arenite.debug) {
            window.console.log('Arenite: Failed to resolve arg', arg);
          }
        }
      } else if (typeof arg.func !== 'undefined') {
        resolved.push(arg.func);
      } else if (typeof arg.exec !== 'undefined') {
        resolved.push(arg.exec(arenite));
      } else if (typeof arg.instance !== 'undefined') {
        var anonymousContext = {instances: {}};
        var tempId = '__anonymous_temp_instance__' + anonymous_id++;
        anonymousContext.instances[tempId] = arg.instance;
        _loadContext(anonymousContext, stack);
        resolved.push(arenite.context.get(tempId));
        if (type === 'factory') {
          arenite.context.remove(tempId);
        } else {
          execution.args.splice(idx, 1, {ref: tempId});
        }
      }
    });

    if (execution.wait && typeof done === 'function') {
      resolved.push(done);
    }

    return failure ? null : resolved;
  };

  var _execFunction = function (execution, before, done, stack) {
    var resolvedFunc = _resolveFunc(execution);
    if (resolvedFunc) {
      var resolvedArgs = _resolveArgs(execution, done, undefined, stack);
      if (resolvedArgs) {
        if (execution.wait && typeof before === 'function') {
          before();
        }
        resolvedFunc.apply(resolvedFunc, resolvedArgs);
      } else {
        throw 'Unable to resolve arguments for "' + execution.func + '" of instance "' + execution.instance + '"';
      }
    } else {
      throw 'Unknown function "' + execution.func + '" for instance "' + execution.instance + '"';
    }
  };

  var _wire = function (instances, type, stack) {
    if (!instances) {
      return;
    }

    var unresolved = {};

    instances.toKeyArray().forEach(function (instance) {
      if (instances[instance].factory) {
        arenite.context.add(instance, instances[instance], true);
      } else {
        var func = window.getInPath(instances[instance].namespace);
        if (func) {
          var args = _resolveArgs(instances[instance], null, type, [instance]);
          if (args) {
            var actualInstance = func.apply(func, args);
            if (type === 'extension') {
              var wrappedInstance = {};
              wrappedInstance[instance] = actualInstance;
              arenite = arenite.fuseWith(wrappedInstance);
            }
            if (arenite.debug) {
              window.console.log('Arenite: Instance', instance, 'wired');
            }
            arenite.context.add(instance, actualInstance);

          } else {
            unresolved[instance] = instances[instance];
          }
        } else {
          throw 'Unknown function "' + instances[instance].namespace + '"';
        }
      }
    });

    if (unresolved.toKeyArray().length !== instances.toKeyArray().length && unresolved.toKeyArray().length > 0) {
      unresolved.forEach(function (instance, name) {
        var instanceObj = {};
        instanceObj[name] = instance;
        _wire(instanceObj, undefined, stack.concat(name));
      });
    } else {
      if (unresolved.toKeyArray().length !== 0) {
        throw 'Make sure you don\'t have circular dependencies, Unable to resolve the following instances: ' + unresolved.toKeyArray().join(", ") + ' - [' + stack.join(', ') + ']';
      }
    }
  };

  var _init = function (instances, latch, extension) {
    if (!instances) {
      return;
    }
    instances.forEach(function (instance, instanceName) {
      if (instance.init && !instance.factory) {
        if (typeof instance.init === 'string') {
          instance.init = {func: instance.init};
        }
        _execFunction(({
          instance: instanceName,
          extension: extension
        }).fuseWith(instance.init), function () {
          latch.countUp();
        }, function () {
          latch.countDown();
        });
      }
    });
  };

  var _start = function (starts) {
    if (!starts) {
      return;
    }
    if (document.readyState !== 'complete') {
      window.setTimeout(function () {
        _start(starts);
      }, 100);
    } else {
      starts.forEach(function (start) {
        _execFunction(start);
      });
    }
  };

  var _loadContext = function (context, stack) {
    if (arenite.config.debug) {
      window.console.time('Arenite context load');
    }
    if (context) {
      //Starting must wait for the wiring
      var wireLatch = arenite.async.latch(1, function () {
        if (arenite.config.debug) {
          window.console.timeEnd('Arenite context load');
        }
        _start(context.start);
      }, "instances");

      //wiring of instances must wait for the extensions
      var extensionsLatch = arenite.async.latch(1, function () {
        _wire(context.instances, undefined, stack || []);
        _init(context.instances, wireLatch);
        wireLatch.countDown();
      }, "extensions");

      _wire(context.extensions, 'extension', stack || []);
      _init(context.extensions, extensionsLatch, true);
      extensionsLatch.countDown();
    }
  };

  var _loadAsyncDependencies = function (dependencies) {
    var latch = arenite.async.latch(dependencies.async ? dependencies.async.length : 0, function () {
      _loadContext(arenite.config.context);
    }, 'dependencies');
    dependencies.async.forEach(function (dep) {
      arenite.loader.loadScript(dep, latch.countDown);
    });
  };

  var _loadSyncDependencies = function () {
    if (!arenite.config.context || !arenite.config.context.dependencies) {
      return _loadContext(arenite.config.context);
    }

    var dependencies;
    if (!arenite.config.context.dependencies[arenite.config.mode]) {
      dependencies = {sync: [], async: []};
    } else {
      dependencies = arenite.config.context.dependencies[arenite.config.mode];
    }

    var seqLatch = arenite.async.seqLatch(dependencies.sync || [], function (url) {
      arenite.loader.loadScript(url, seqLatch.next);
    }, function () {
      _loadAsyncDependencies(dependencies);
    });
    seqLatch.next();
  };

  var _externalUrl = /^((http:\/\/)|(http:\/\/)|(\/\/)).*$/;
  var _prodModuleVersion = /[\d]+\.[\d]+\.*[\d]*/;
  var _devRepo = '//rawgit.com/{vendor}/{version}/{module}/';
  var _prodRepo = '//cdn.rawgit.com/{vendor}/{version}/{module}/';

  var _fetchModules = function (modules, callback, config) {
    var results = {};
    var moduleKeys = modules.toKeyArray();
    if (moduleKeys.length) {
      var latch = arenite.async.latch(moduleKeys.length, function () {
        modules.forEach(function (module, moduleName) {
          var mode = module.vendor ? 'default' : arenite.config.mode;
          var newDeps = {async: [], sync: []};
          (results[moduleName].module.context.dependencies[mode] || []).forEach(function (dependencies, depType) {
            dependencies.forEach(function (dep) {
              if (typeof dep === 'string') {
                newDeps[depType].push(dep.match(_externalUrl) || !module.vendor ? dep : results[moduleName].path + dep);
              } else {
                newDeps[depType].push(dep.fuseWith({url: dep.url.match(_externalUrl) || !module.vendor ? dep.url : results[moduleName].path + dep.url}));
              }
            });
          });
          delete results[moduleName].module.context.dependencies;

          config.context = config.context || {};
          config.context.dependencies = config.context.dependencies || {
              default: {
                sync: [],
                async: []
              }
            };
          config.context.dependencies[config.mode] = config.context.dependencies[config.mode] || {
              sync: [],
              async: []
            };
          config.context.dependencies.forEach(function (env) {
            env.fuseWith(newDeps);
          });

          config = config.fuseWith(results[moduleName].module);
        });
        callback();
      }, 'modules');
      modules.forEach(function (module, moduleName) {
        var moduleBasePath;
        if (module.vendor) {
          if (arenite.config.repo) {
            moduleBasePath = arenite.config.repo.replace('{vendor}', module.vendor);
          } else if (module.version.match(_prodModuleVersion)) {
            moduleBasePath = _prodRepo.replace('{vendor}', module.vendor);
          } else {
            moduleBasePath = _devRepo.replace('{vendor}', module.vendor);
          }
          moduleBasePath = moduleBasePath.replace('{version}', module.version);
          moduleBasePath = moduleBasePath.replace('{module}', module.module);
        } else {
          moduleBasePath = module.module + '/';
        }

        arenite.loader.loadResource(moduleBasePath + 'module.json', function (xhr) {
          results[moduleName] = {path: moduleBasePath, module: JSON.parse(xhr.responseText)};
          if (results[moduleName].module.imports) {
            _fetchModules(results[moduleName].module.imports, latch.countDown, results[moduleName].module);
          } else {
            latch.countDown();
          }
        });
      });
    } else {
      callback();
    }
  };

  var _loadConfig = function (config, callback) {
    arenite.context.add('arenite', arenite);
    arenite.config = config;
    arenite.config.mode = arenite.config.mode || arenite.url.query().mode || 'default';
    window.console.log('Arenite: Starting in mode', arenite.config.mode);
    if (config.debug) {
      if (typeof config.debug === 'function') {
        config.debug = config.debug(arenite);
      }
    }
    if (config.expose) {
      var exposeName = config.expose;
      if (typeof config.expose === 'function') {
        exposeName = config.expose(arenite);
      }
      if (exposeName) {
        window[exposeName] = arenite;
      }
    }

    if (arenite.config.imports) {
      window.console.log('Arenite: Fetching modules', arenite.config.imports.toKeyArray());
      _fetchModules(JSON.parse(JSON.stringify(arenite.config.imports)), callback, arenite.config);
    } else {
      callback();
    }
  };

  var _boot = function (config) {
    if (arenite.config) {
      _loadSyncDependencies();
    } else {
      _loadConfig(config, _loadSyncDependencies);
    }
  };

  var _wireFactory = function (instances) {
    _wire(instances, 'factory', []);
    _init(instances);
  };

  return {
    di: {
      //### di.init
      // Start arenite with the given configuration
      //

      // init(config)
      //

      //where *config* is the complete configuration with imports
      init: _boot,
      //### di.loadConfig
      // Resolve the imports and merge them into arenite's internal config object
      //

      // loadConfig(config, callback)
      //

      //where *config* is the partial configuration with the imports and *callback* is the callback after
      // the import has extended the config.
      loadConfig: _loadConfig,
      //### di.resolveArgs
      // Resolve the arguments defined in an instance definition AKA execution defined in the arenite configuration format
      //

      // resolveArgs(execution, done)
      //

      //where *execution* is the object describing the execution and *done* is the callback after the execution.
      resolveArgs: _resolveArgs,
      //### di.exec
      // Execute an instance definition AKA execution defined in the arenite configuration format
      //

      // exec(execution, before, done)
      //

      //where *execution* is the object describing the execution, *before* is an optional function to be executed
      // before the actual execution and *done* is the callback after the execution.
      exec: _execFunction,
      //### di.wire
      // Wire a new instance at runtime (used for factories)
      //

      // wire(instanceDefinitions)
      //

      //where *instanceDefinitions* is a list of instance definition objects to be instantiated and initialized.
      wire: _wireFactory
    }
  };
};

/*global Arenite:true*/
// Collection of utility functions to handle html.
Arenite.Html = function (arenite) {

  var _escape = function (text) {
    var span = document.createElement('span');
    span.innerText = text;
    return span.innerHTML;
  };

  var _unescape = function (text) {
    var span = document.createElement('span');
    span.innerHTML = text;
    return span.innerText;
  };

  return {
    html: {
      escape: _escape,
      unescape: _unescape
    }
  };
};
/*global Arenite:true*/
/*jshint evil:true*/
// Collection of utility functions to handle loading resources.
Arenite.Loader = function (arenite) {

  var firefoxOs = navigator.userAgent.indexOf('Firefox') > -1 && navigator.userAgent.indexOf("Mobile") > -1;

  var _createCORSRequest = function (method, url, success, failure) {
    var xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    //xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    //xhr.setRequestHeader("Access-Control-Allow-Origin", window.location.origin);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status % 100 < 4) {
          success();
        } else {
          failure();
        }
      }
    };
    if (arenite.config.withCredentials) {
      xhr.withCredentials = true;
    }
    return xhr;
  };

  var _loadResource = function (url, callback, error) {
    var req = _createCORSRequest('GET', url, function () {
      callback(req);
    }, function () {
      if (typeof error === 'function') {
        error(req);
      }
    });
    req.send();
  };

  var _loadStyleWithTag = function (url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('link');
    script.rel = 'stylesheet';
    script.type = 'text/css';
    if (navigator.appVersion.indexOf("MSIE 9") === -1) { //IE 9 calls the callback twice
      script.onreadystatechange = function () {
        if (this.readyState === 'complete') {
          callback();
        }
      };
    }
    script.onload = callback;
    script.href = url;
    head.appendChild(script);
  };

  var _loadScriptWithTag = function (url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.async = true;
    script.type = 'text/javascript';
    if (navigator.appVersion.indexOf("MSIE 9") === -1) { //IE 9 calls the callback twice
      script.onreadystatechange = function () {
        if (this.readyState === 'complete') {
          callback();
        }
      };
    }
    script.onload = callback;
    script.src = url;
    head.appendChild(script);
  };

  var _loadScriptAsResource = function (url, callback) {
    _loadResource(url, function (req) {
      //analyze the script for "annotation" type configurations
      arenite.annotation.processAnnotations(req.responseText);
      var file_tag = '\n//@ sourceURL=' + window.location.origin + '/' + url + '\n//# sourceURL=' + window.location.origin + '/' + url;
      eval(req.responseText + file_tag);
      callback();
    });
  };

  var _sameOrigin = function (url) {
    var loc = window.location;
    var a = document.createElement('a');
    a.href = url;
    return a.hostname === loc.hostname &&
      a.port === loc.port &&
      a.protocol === loc.protocol;
  };

  var _loadScriptFrom = function (url, callback) {
    var fileExt = url.match(/.*\.(\w+)\?*.*/)[1];
    if (_sameOrigin(url) && !firefoxOs && fileExt === 'js') {
      _loadScriptAsResource(url, callback);
    } else {
      if (fileExt === 'js') {
        _loadScriptWithTag(url, callback);
      } else if (fileExt === 'css') {
        _loadStyleWithTag(url, callback);
      } else {
        throw 'Uknown extension "' + fileExt + '"';
      }
    }
  };

  var _loadScript = function (script, done) {
    if (typeof script === 'string') {
      _loadScriptFrom(script, done);
    } else {
      _loadScriptFrom(script.url, function () {
        script.instances.forEach(function (instance, instanceName) {
          var windowInstance = window[instance];
          if(windowInstance){
            arenite.context.add(instanceName, windowInstance);
          }
          delete window[instance];
        });
        if (typeof done === 'function') {
          done();
        }
      });
    }
  };

  return {
    loader: {
      //### loader.loadResource
      // Load a given resource using ajax.
      //

      // loadResource(url, callback, error)
      //

      //where *url* is the url to fetch from,  *callback* is a function called with the ajax request after
      // it's succesful completion and *error* is an optional callback to handle errors when fetching the resource
      loadResource: _loadResource,
      //### loader.loadScript
      // Load a script. This method will choose the best method to load the script (using tag or ajax) depending on the
      // origin of the script. Additionally it can extract variables exposed in the window object and register them as
      // instances in arenite.
      //

      // loadScript(script, callback)
      //

      //where *script* is either a url string or a structure defining a url and instances to be extracted from
      // the window object into arenite and *callback* is the callback for when the script is loaded.
      loadScript: _loadScript
    }
  };
};

/*global Arenite:true*/
// Collection of utility functions to handle objects.
// This is an integral part for the usage of the Namespace pattern since this provides the ability to, for example,
// retrieve the functions by namespace.
Arenite.Object = function () {

  var _navigateToBeforeLast = function (object, path) {
    if (!object) {
      return;
    }

    var split = path.split(".");
    var last = split.splice(split.length - 1, 1);

    var result = object;
    split.forEach(function (pathEl) {
      if (!result) {
        return;
      }
      if (!result[pathEl]) {
        result[pathEl] = {};
      }
      result = result[pathEl];
    });
    return {object: result, path: last};
  };

  var _getInObject = function (object, path) {
    if (!object) {
      return;
    }

    var split = path.split(".");
    var result = object;
    split.forEach(function (pathEl) {
      if (!result) {
        return;
      }
      result = result[pathEl];
    });
    return result;
  };

  var _setInObject = function (object, path, element) {
    var beforeLast = _navigateToBeforeLast(object, path);
    if (beforeLast && beforeLast.object) {
      beforeLast.object[beforeLast.path] = element;
      return beforeLast.object[beforeLast.path];
    }
  };

  var _deleteInObject = function (object, path) {
    var beforeLast = _navigateToBeforeLast(object, path);
    if (beforeLast && beforeLast.object) {
      delete beforeLast.object[beforeLast.path];
    }
  };

  var _extend = function (source, target) {
    for (var f in target) {
      if (target.hasOwnProperty(f)) {
        if (source[f] && typeof source[f] === 'object') {
          if (source[f].constructor === Array && target[f] && target[f].constructor === Array) {
            source[f] = _uniq(source[f].concat(target[f]));
          } else {
            _extend(source[f], target[f]);
          }
        } else {
          source[f] = target[f];
        }
      }
    }
    return source;
  };

  var _keys = function (obj) {
    var keys = [], key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        keys.push(key);
      }
    }
    return keys;
  };

  var _contains = function (obj, key) {
    if (obj.length) {
      var result = false;
      obj.forEach(function (_key) {
        result = result || _key === key;
      });
      return result;
    } else {
      for (var _key in obj) {
        if (obj.hasOwnProperty(_key)) {
          if (_key === key) {
            return true;
          }
        }
      }
    }
    return false;
  };

  var _uniq = function (arr) {
    var result = [];
    arr.forEach(function (el) {
      if (result.indexOf(el) < 0) {
        result.push(el);
      }
    });
    return result;
  };

  var _merge = function (arr1, arr2) {
    return _uniq(arr1.concat(arr2));
  };

  var _extract = function (obj, prop) {
    var result = [];
    for (var _key in obj) {
      if (obj.hasOwnProperty(_key)) {
        result.push(obj[_key][prop]);
      }
    }
    return result;
  };

  var _obj = function (arr, key) {
    var obj = {};
    arr.forEach(function (elem) {
      obj[_getInObject(elem, key)] = elem;
    });
    return obj;
  };

  var _forEach = function (obj, func) {
    var key;
    for (key in obj) {
      if (obj.hasOwnProperty(key)) {
        func(obj[key], key);
      }
    }
  };

  var _array = function (obj) {
    var arr = [];
    _forEach(obj, function (el) {
      arr.push(el);
    });
    return arr;
  };

  var _filter = function (obj, keys) {
    var filtered = {};
    keys.forEach(function (key) {
      if (obj.hasOwnProperty(key)) {
        filtered[key] = obj[key];
      }
    });
    return filtered;
  };

  var _find = function (obj, func) {
    var isArray = Array.isArray(obj);
    var match;
    _forEach(obj, function (val, key) {
      if (!match && func(val, key)) {
        if (isArray) {
          match = val;
        } else {
          match = {};
          match[key] = val;
        }
      }
    });
    return match;
  };

  var _findBy = function (obj, key, val) {
    return _find(obj, function (elem) {
      return (key ? _getInObject(elem, key) : elem) === val;
    });
  };

  var _findAll = function (obj, func) {
    var isArray = Array.isArray(obj);
    var matches = isArray ? [] : {};
    _forEach(obj, function (val, key) {
      if (func(val, key)) {
        if (isArray) {
          matches.push(val);
        } else {
          matches[key] = val;
        }
      }
    });
    return matches;
  };

  var _findAllBy = function (obj, key, val) {
    return _findAll(obj, function (elem) {
      return (key ? _getInObject(elem, key) : elem) === val;
    });
  };

  var _collect = function (obj, func) {
    var isArray = Array.isArray(obj);
    var collection = isArray ? [] : {};
    _forEach(obj, function (val, key) {
      var result = func(val, key);
      if (result !== undefined) {
        if (isArray) {
          collection.push(result);
        } else {
          collection[key] = result;
        }
      }
    });
    return collection;
  };

  var _collectBy = function (obj, key) {
    return obj.collectWhere(function (elem) {
      return _getInObject(elem, key);
    });
  };

  return {
    object: {
      //### object.getFromPath
      // Retrieves a property from an object. The property is expressed as a string, denoting a path.
      //

      // getFromPath(object, path)
      //

      //where *object* is the target object and *path* is the path of the value to be fetched.
      getInPath: _getInObject,
      //### object.setInPath
      // Sets a property in an object. The property is expressed as a string, denoting a path.
      //

      // setInPath(object, path, value)
      //

      //where *object* is the target object,
      // *path* is the path of the value and *value* the value to be set at the given path.
      setInPath: _setInObject,
      //### object.deleteInPath
      // Removes a property from an object. The property is expressed as a string, denoting a path.
      //

      // deleteInPath(object, path)
      //

      //where *object* is the target object and *path* is the path of the value to be deleted.
      deleteInPath: _deleteInObject,
      //### object.fuseWith
      // Fuse merges objects. The second object will "override" properties also existing in the first.
      //

      // fuseWith(object, other)
      //

      //where *object* is the object to be merged and extended by *other*.
      fuseWith: _extend,
      //### object.keysOf
      //Returns all the properties available to an object in the form of an array.
      //

      // keysOf(object)
      //

      //where *object* is the object from which the properties will be extracted.
      toKeyArray: _keys,
      //### object.forEach
      //Iterates through the object the equivalent to the way forEach works for arrays.
      //

      // forEach(object, func(elem, key))
      //

      //where *object* is the object to iterate. *func(elem, key)* is the function called for each element and receives the element and its key.
      forEach: _forEach,
      //### object.containsKey
      // Determines if a key exists in an object:
      //

      // containsKey(object, key)
      //

      //where *object* is the object to test for the presence of key and *key* is the property/element to be tested.
      containsKey: _contains,
      //### object.toArray
      // Transforms the object to an array using the values for each key:
      //

      // toArray(object)
      //

      //where *object* is the object to be transformed into the array.
      toArray: _array,
      //### object.filterWith
      // Returns a filtered version of the object:
      //

      // filterWith(object, keys)
      //

      //where *object* is the object to be filtered and *keys* an array of keys to maintain.
      filterWith: _filter,
      //### object.findWhere
      // Find the first occurence of a matching element
      //

      // findWhere(object, func(elem, key))
      //

      //where *object* is the object to iterate. *func(elem, key)* is the function called for each element and receives the element and its key.
      //The element is considered to be a match if the result of the function is not undefined.
      findWhere: _find,
      //### object.findBy
      // Find the first occurence of a matching object
      //

      // findBy(object, property, value)
      //

      //where *object* is the object to iterate. *property* the property of the object to be used in the comparison. *property* the property value for the element to be considered a match.
      findBy: _findBy,
      //### object.findAllWhere
      // Find all occurences of a matching object
      //

      // findWhere(object, func(elem, idx))
      //

      //where *object* is the object to iterate. *func(elem, key)* is the function called for each element and receives the element and its key.
      //The element is considered to be a match if the result of the function is not undefined.
      findAllWhere: _findAll,
      //### object.findAllBy
      // Find all occurences of a matching object
      //

      // findAllBy(object, property, value)
      //

      //where *object* is the object to iterate. *property* the property of the object to be used in the comparison. *property* the property value for the element to be considered a match.
      findAllBy: _findAllBy,
      //### object.collectWhere
      // Collect objects for occurences of a matching object
      //

      // collectWhere(object, func(elem, idx))
      //

      //where *object* is the object to iterate. *func(elem, key)* is the function called for each element and receives the element and its key.
      //The resulting object will contain all elements returned by the function (where the result is not undefined).
      collectWhere: _collect,
      //### object.collectBy
      // Collect sub objects
      //

      // findWhere(object, property)
      //

      //where *object* is the array to iterate. *property* is the object path to be collected.
      collectBy: _collectBy
    },
    array: {
      //### array.containsElement
      // Determines if a element is present in an array:
      //

      // containsElement(object, key)
      //

      //where *object* is the object to test for the presence of key and *key* is the property/element to be tested.
      containsElement: _contains,
      //### array.filterUnique
      // Filters an array returning a new one with the unique values.
      //

      // filterUnique(array)
      //

      //where *array* is the array to be stripped o duplicate values
      filterUnique: _uniq,
      //### array.mergeWith
      // Merges two arrays returning a new one with the unique values.
      //

      // mergeWith(arr1, arr2)
      //

      //where *arr1* and *arr2* are the arrays to be merged
      mergeWith: _merge,
      //### array.toArrayOf
      // Extract an array composed of a specified property of the subobjects of a given object
      //

      // toArrayOf(object, property)
      //

      //where *object* is the object whose members will be analysed *property* the property to be extracted from those members
      toArrayOf: _extract,
      //### array.toObject
      // Extract an object indexed by a given key
      //

      // toObject(array, property)
      //

      //where *array* is the array whose members will be analysed *property* the property of each element to be turned into the key of that element in the resulting object
      toObject: _obj,
      //### array.findWhere
      // Find the first occurence of a matching object
      //

      // findWhere(array, func(elem, idx))
      //

      //where *array* is the array to iterate. *func(elem, idx)* is the function called for each element and receives the element and its index.
      //The element is considered to be a match if the result of the function is not undefined.
      findWhere: _find,
      //### array.findBy
      // Find the first occurence of a matching object
      //

      // findBy(array, property, value)
      //

      //where *array* is the array to iterate. *property* the property of the object to be used in the comparison. *property* the property value for the element to be considered a match.
      findBy: _findBy,
      //### array.findAllWhere
      // Find all occurences of a matching object
      //

      // findWhere(array, func(elem, idx))
      //

      //where *array* is the array to iterate. *func(elem, idx)* is the function called for each element and receives the element and its index.
      //The element is considered to be a match if the result of the function is not undefined.
      findAllWhere: _findAll,
      //### array.findAllBy
      // Find all occurences of a matching object
      //

      // findAllBy(array, property, value)
      //

      //where *array* is the array to iterate. *property* the property of the object to be used in the comparison. *property* the property value for the element to be considered a match.
      findAllBy: _findAllBy,
      //### array.collectWhere
      // Collect objects in array
      //

      // collectWhere(array, func(elem, idx))
      //

      //where *array* is the array to iterate. *func(elem, idx)* is the function called for each element and receives the element and its index.
      //The resulting array will contain all elements returned by the function (where the result is not undefined).
      collectWhere: _collect,
      //### array.collectBy
      // Collect sub objects
      //

      // findWhere(array, property)
      //

      //where *array* is the array to iterate. *property* is the object path to be collected.
      collectBy: _collectBy
    }
  };
};

/*global Arenite:true*/
//Utility function for interpreting url query parameters
Arenite.Url = function () {
  var query_string;

  var _query = function (force) {
    if (!query_string || force) {
      query_string = {};
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (typeof query_string[pair[0]] === "undefined") {
          query_string[pair[0]] = pair[1];
        } else if (typeof query_string[pair[0]] === "string") {
          query_string[pair[0]] = [query_string[pair[0]], pair[1]];
        } else {
          query_string[pair[0]].push(pair[1]);
        }
      }
    }
    return query_string;
  };

  return {
    url: {
      //### url.query
      // Fetches the query parameters for the current url and returns them in an object.
      // Variables will be keys in the object and the values are either the value for the variable or an array of
      //values in the case where a variable is defined more than once.
      query: _query
    }
  };
};


text:
package com.squareframework.web;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import com.squareframework.web.config.SSOConfig;
import com.squareframework.web.config.UserConfig;
import com.squareframework.web.config.WebConfig;

public class WebContext {

	private static ThreadLocal<WebContext> instance = new ThreadLocal<WebContext>();

	private ServletContext context;

	private HttpServletRequest request;

	private WebConfig webConfig;

	private SSOConfig SSOConfig;

	private UserConfig userConfig;

	public WebContext(ServletContext context, HttpServletRequest request) {
		this.context = context;
		this.request = request;
		this.webConfig = (WebConfig) context.getAttribute(WebConfig.class.getName());
		this.SSOConfig = (SSOConfig) context.getAttribute(SSOConfig.class.getName());
	}

	public static ThreadLocal<WebContext> getInstance() {
		return instance;
	}

	public static void setInstance(ThreadLocal<WebContext> instance) {
		WebContext.instance = instance;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public WebConfig getWebConfig() {
		return webConfig;
	}

	public void setWebConfig(WebConfig webConfig) {
		this.webConfig = webConfig;
	}

	public SSOConfig getSSOConfig() {
		return SSOConfig;
	}

	public void setSSOConfig(SSOConfig sSOConfig) {
		SSOConfig = sSOConfig;
	}

	public UserConfig getUserConfig() {
		return userConfig;
	}

	public void setUserConfig(UserConfig userConfig) {
		this.userConfig = userConfig;
	}

	public static WebContext getCurrentInstance() {
		 return instance.get();
	}

	public static void setCurrentInstance(WebContext context) {
		if (context == null) {
			instance.remove();
		} else {
			instance.set(context);
		}
	}

}


text:
from .control import *

# Little demo on how it could be used.
if __name__ == '__main__':
    a = I2PController()
    print(a.get_network_settings())
    vals = a.get_router_info()
    print(''.join([
        'You are running i2p version ', str(vals['i2p.router.version']), '. ',
        'It has been up for ', str(vals['i2p.router.uptime']), 'ms. ',
        'Your router knows ', str(vals['i2p.router.netdb.knownpeers']),' peers.'
        ]))


text:
const _ = require('@sailshq/lodash');
const field = require('../../../siteMapPriorityField.js');
const arrange = require('../../../arrangeFields.js');

module.exports = {
  improve: 'apostrophe-pieces',
  beforeConstruct: function(self, options) {
    var exclude = [
      // These piece types never have pieces pages or URLs ordinarily.
      // If they do in your project, you can add the field yourself
      // and it will be honored, see the source
      'apostrophe-global', 'apostrophe-users', 'apostrophe-tags', 'apostrophe-groups', 'apostrophe-images', 'apostrophe-files'
    ];
    if (_.contains(exclude, self.__meta.name) && (options.sitemap !== true)) {
      return;
    }
    if (options.sitemap !== false) {
      options.addFields = [
        _.clone(field)
      ].concat(options.addFields || []);
      options.arrangeFields = [
        _.clone(arrange)
      ].concat(options.arrangeFields || []);
    }
  },
  afterConstruct: function(self) {
    self.on('apostrophe:modulesReady', 'adjustSchemaForSiteMapPriority', function() {
      const siteMap = self.apos.modules['apostrophe-site-map'];
      if (siteMap.options.noPriority === true) {
        self.schema = self.schema.filter(item => item.name !== 'siteMapPriority');
      }
    });
  }
};


text:
import os
import argparse
import textwrap

import scona as scn
from scona.scripts.useful_functions import read_in_data, \
    write_out_measures

# =============================================================================
# FUNCTIONS
# =============================================================================

def setup_argparser():
    '''
    Code to read in arguments from the command line
    Also allows you to change some settings
    '''
    # Build a basic parser.
    help_text = (('Generate a graph as a fixed cost from a non-thresholded\n')
                 + ('matrix and return global and nodal measures.'))

    sign_off = 'Author: Kirstie Whitaker <kw401@cam.ac.uk>'

    parser = argparse.ArgumentParser(
        description=help_text,
        epilog=sign_off,
        formatter_class=argparse.RawTextHelpFormatter)

    # Now add the arguments
    parser.add_argument(
        dest='corr_mat_file',
        type=str,
        metavar='corr_mat_file',
        help=textwrap.dedent(('Text file (tab or space delimited) that \
contains the unthresholded\n') + ('matrix with no column or row labels.')))

    parser.add_argument(
        dest='names_file',
        type=str,
        metavar='names_file',
        help=textwrap.dedent(('Text file that contains the names of each \
region, in the same\n') + ('order as the correlation matrix. One region \
name on each line.')))

    parser.add_argument(
        dest='centroids_file',
        type=str,
        metavar='centroids_file',
        help=textwrap.dedent(('Text file that contains the x, y, z \
coordinates of each region,\n') + ('in the same order as the correlation \
matrix. One set of three\n') + ('coordinates, tab or space delimited, on each \
line.')))

    parser.add_argument(
        dest='output_dir',
        type=str,
        metavar='output_dir',
        help=textwrap.dedent(('Location in which to save global and nodal \
measures.')))

    parser.add_argument(
        '-c', '--cost',
        type=float,
        metavar='cost',
        help=textwrap.dedent(('Cost at which to threshold the matrix.\n') +
                             ('  Default: 10.0')),
        default=10.0)

    parser.add_argument(
        '-n', '--n_rand',
        type=int,
        metavar='n_rand',
        help=textwrap.dedent(('Number of random graphs to generate to compare \
with real network.\n') + ('  Default: 1000')),
        default=1000)

    parser.add_argument(
        '-s', '--seed', '--random_seed',
        type=int,
        metavar='seed',
        help=textwrap.dedent(('Set a random seed to pass to the random graph \
creator.\n') + ('  Default: None')),
        default=None)

    arguments = parser.parse_args()

    return arguments, parser

def network_analysis_from_corrmat(corr_mat_file,
                                  names_file,
                                  centroids_file,
                                  output_dir,
                                  cost=10,
                                  n_rand=1000,
                                  edge_swap_seed=None):
    '''
    This is the big function!
    It reads in the correlation matrix, thresholds it at the given cost
    (incorporating a minimum spanning tree), creates a networkx graph,
    calculates global and nodal measures (including random comparisons
    for the global measures) and writes them out to csv files.
    '''
    # Read in the data
    M, names, a, centroids = read_in_data(
                                corr_mat_file,
                                names_file,
                                centroids_file=centroids_file,
                                data_as_df=False)

    corrmat = os.path.basename(corr_mat_file).strip('.txt')

    # Initialise graph
    B = scn.BrainNetwork(
        network=M,
        parcellation=names,
        centroids=centroids)
    # Threshold graph
    G = B.threshold(cost)
    # Calculate the modules
    G.partition()
    # Calculate distance and hemispheric attributes
    G.calculate_spatial_measures()
    # Get the nodal measures
    # (note that this takes a bit of time because the participation coefficient
    # takes a while)
    G.calculate_nodal_measures()
    nodal_df = G.report_nodal_measures()
    nodal_name = 'NodalMeasures_{}_cost{:03.0f}.csv'.format(corrmat, cost)
    # FILL possibly wise to remove certain cols here (centroids)
    # Save your nodal measures
    write_out_measures(
        nodal_df, output_dir, nodal_name, first_columns=['name'])

    # Create setup for comparing real_graph against random graphs
    # name your graph G after the corrmat it was created from
    bundle = scn.GraphBundle([G], [corrmat])
    # Get the global measures
    # (note that this takes a bit of time because you're generating random
    # graphs)
    bundle.create_random_graphs(corrmat, n_rand, seed=edge_swap_seed)
    # Add the small world coefficient to global measures
    small_world = bundle.report_small_world(corrmat)
    for gname, G in bundle.items():
        G.graph['global_measures'].update(
            {"sw coeff against " + corrmat: small_world[gname]})
    global_df = bundle.report_global_measures()
    global_name = 'GlobalMeasures_{}_cost{:03.0f}.csv'.format(corrmat, cost)
    # Write out the global measures
    write_out_measures(
        global_df, output_dir, global_name, first_columns=[corrmat])

    # Get the rich club coefficients
    rc_df = bundle.report_rich_club()
    rc_name = 'rich_club_{}_cost{:03.0f}.csv'.format(corrmat, cost)
    # Write out the rich club coefficients
    write_out_measures(
        rc_df, output_dir, rc_name, first_columns=['degree', corrmat])

if __name__ == "__main__":

    # Read in the command line arguments
    arg, parser = setup_argparser()

    # Now run the main function :)
    network_analysis_from_corrmat(
                                arg.corr_mat_file,
                                arg.names_file,
                                arg.centroids_file,
                                arg.output_dir,
                                cost=arg.cost,
                                n_rand=arg.n_rand,
                                edge_swap_seed=arg.seed)

# =============================================================================
# Wooo! All done :)
# =============================================================================


text:
using AutoMapper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using ZKWeb.Cache;
using ZKWeb.Localize;
using ZKWeb.MVVMPlugins.MVVM.Common.Base.src.Application.Dtos;
using ZKWeb.MVVMPlugins.MVVM.Common.Base.src.Application.Extensions;
using ZKWeb.MVVMPlugins.MVVM.Common.Base.src.Application.Services.Bases;
using ZKWeb.MVVMPlugins.MVVM.Common.Base.src.Application.Services.Structs;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Application.Dtos;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Components.ActionFilters;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Components.GenericConfigs;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Domain.Entities.Interfaces;
using ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Domain.Services;
using ZKWeb.MVVMPlugins.MVVM.Common.TaskScheduler.src.Application.Dtos;
using ZKWeb.MVVMPlugins.MVVM.Common.TaskScheduler.src.Domain.Entities;
using ZKWeb.Plugin;
using ZKWebStandard.Ioc;
using ZKWebStandard.Utils;

namespace ZKWeb.MVVMPlugins.MVVM.Common.Organization.src.Application.Services
{
    /// <summary>
    /// 网站管理服务
    /// </summary>
    [ExportMany, SingletonReuse, Description("网站管理服务")]
    public class WebsiteManageService : ApplicationServiceBase
    {
        private IList<ICacheCleaner> _cacheCleaners;
        private PluginManager _pluginManager;
        private GenericConfigManager _configManager;

        public WebsiteManageService(
            IEnumerable<ICacheCleaner> cacheCleaners,
            PluginManager pluginManager,
            GenericConfigManager configManager)
        {
            _cacheCleaners = cacheCleaners.ToList();
            _pluginManager = pluginManager;
            _configManager = configManager;
        }

        [Description("清理缓存")]
        [CheckPrivilege(typeof(ICanUseAdminPanel))]
        public ActionResponseDto ClearCache()
        {
            foreach (var cleaner in _cacheCleaners)
            {
                cleaner.ClearCache();
            }
            GC.Collect();
            return ActionResponseDto.CreateSuccess("Clear Cache Successfully");
        }

        [Description("获取网站信息")]
        [CheckPrivilege(typeof(ICanUseAdminPanel))]
        public WebsiteInfoOutputDto GetWebsiteInfo()
        {
            var websiteInfo = new WebsiteInfoOutputDto();
            websiteInfo.ZKWebVersion = ZKWeb.Application.Version.ToString();
            websiteInfo.ZKWebFullVersion = ZKWeb.Application.FullVersion.ToString();
            websiteInfo.MemoryUsage = FileUtils.GetSizeDisplayName(SystemUtils.GetUsedMemoryBytes());
            foreach (var plugin in _pluginManager.Plugins)
            {
                websiteInfo.Plugins.Add(new PluginInfoOutputDto()
                {
                    DirectoryName = plugin.DirectoryName(),
                    Name = new T(plugin.Name),
                    Version = plugin.VersionObject().ToString(),
                    FullVersion = plugin.Version,
                    Description = new T(plugin.Description)
                });
            }
            return websiteInfo;
        }

        [Description("获取网站信息")]
        [CheckPrivilege(typeof(ICanUseAdminPanel))]
        public WebsiteSettingsDto GetWebsiteSettings()
        {
            var settings = _configManager.GetData<WebsiteSettings>();
            var dto = Mapper.Map<WebsiteSettingsDto>(settings);
            return dto;
        }

        [Description("保存网站信息")]
        [CheckPrivilege(typeof(IAmAdmin), "Settings:WebsiteSettings")]
        public ActionResponseDto SaveWebsiteSettings(WebsiteSettingsDto dto)
        {
            var settings = Mapper.Map<WebsiteSettings>(dto);
            _configManager.PutData(settings);
            return ActionResponseDto.CreateSuccess("Saved Successfully");
        }

        [Description("搜索定时任务")]
        [CheckPrivilege(typeof(IAmAdmin), "ScheduledTask:View")]
        public GridSearchResponseDto SearchScheduledTasks(GridSearchRequestDto request)
        {
            return request.BuildResponse<ScheduledTask, string>()
                .FilterKeywordWith(t => t.Id)
                .ToResponse<ScheduledTaskOutputDto>();
        }

        [Description("搜索定时任务记录")]
        [CheckPrivilege(typeof(IAmAdmin), "ScheduledTask:View")]
        public GridSearchResponseDto SearchScheduledTaskLogs(GridSearchRequestDto request)
        {
            return request.BuildResponse<ScheduledTaskLog, Guid>()
                .FilterKeywordWith(t => t.Task.Id)
                .FilterKeywordWith(t => t.Error)
                .FilterColumnWith(
                    nameof(ScheduledTaskLogOutputDto.TaskId),
                    (c, q) => q.Where(t => t.Task.Id.Contains((string)c.Value)))
                .ToResponse<ScheduledTaskLogOutputDto>();
        }

        [Description("获取当前的Api函数信息")]
        public string GetApiMethodInfo()
        {
            var info = Context.GetApiMethodInfo();
            return info.Name;
        }
    }
}


text:
struct IFTTTTransform3DTranslate
{
    CGFloat tx, ty, tz;
};

typedef struct IFTTTTransform3DTranslate IFTTTTransform3DTranslate;

struct IFTTTTransform3DScale
{
    CGFloat sx, sy, sz;
};

typedef struct IFTTTTransform3DScale IFTTTTransform3DScale;

struct IFTTTTransform3DRotate
{
    CGFloat angle;
    CGFloat x, y, z;
};

typedef struct IFTTTTransform3DRotate IFTTTTransform3DRotate;

@interface IFTTTTransform3D : NSObject

@property (nonatomic, assign) CGFloat m34;
@property (nonatomic, assign) IFTTTTransform3DScale scale;
@property (nonatomic, assign) IFTTTTransform3DRotate rotate;
@property (nonatomic, assign) IFTTTTransform3DTranslate translate;

+ (instancetype)transformWithM34:(CGFloat)m34;

- (id)initWithM34:(CGFloat)m34;

@end

@interface IFTTTTransform3DAnimation : IFTTTAnimation
@end


text:
from glance.common import wsgi
from glance.registry.api.v2 import rpc

def init(mapper):
    rpc_resource = rpc.create_resource()
    mapper.connect("/rpc", controller=rpc_resource,
                   conditions=dict(method=["POST"]),
                   action="__call__")

class API(wsgi.Router):
    """WSGI entry point for all Registry requests."""

    def __init__(self, mapper):
        mapper = mapper or wsgi.APIMapper()

        init(mapper)

        super(API, self).__init__(mapper)


text:
package gnu.xml.xpath;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.namespace.QName;
import org.w3c.dom.Node;

/**
 * The concat function returns the concatenation of its arguments.
 *
 * @author Chris Burdess
 */
final class ConcatFunction
  extends Expr
{

  final List args;

  ConcatFunction(List args)
  {
    this.args = args;
  }

  public Object evaluate(Node context, int pos, int len)
  {
    StringBuffer buf = new StringBuffer();
    for (Iterator i = args.iterator(); i.hasNext(); )
      {
        Expr arg = (Expr) i.next();
        Object val = arg.evaluate(context, pos, len);
        buf.append(_string(context, val));
      }
    return buf.toString();
  }

  public Expr clone(Object context)
  {
    int len = args.size();
    List args2 = new ArrayList(len);
    for (int i = 0; i < len; i++)
      {
        args2.add(((Expr) args.get(i)).clone(context));
      }
    return new ConcatFunction(args2);
  }

  public boolean references(QName var)
  {
    for (Iterator i = args.iterator(); i.hasNext(); )
      {
        if (((Expr) i.next()).references(var))
          {
            return true;
          }
      }
    return false;
  }

  public String toString()
  {
    StringBuffer buf = new StringBuffer("concat(");
    int len = args.size();
    for (int i = 0; i < len; i++)
      {
        if (i > 0)
          {
            buf.append(',');
          }
        buf.append(args.get(i));
      }
    buf.append(')');
    return buf.toString();
  }

}


text:
package ch.softshake.arquillian.lab03;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.persistence.UsingDataSet;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import java.math.BigDecimal;
import java.util.Collection;

import static org.fest.assertions.Assertions.assertThat;

@RunWith(Arquillian.class)
public class BeerServiceTest
{

   @Deployment
   public static Archive<?> createDeployment()
   {
      return ShrinkWrap.create(JavaArchive.class, "test.jar")
                       .addClasses(Beer.class, BeerService.class,
                             BeerRepository.class, JpaBeerRepository.class)
                       .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
                       .addAsManifestResource("test-persistence.xml", "persistence.xml")
                       .addPackages(true, "org.fest");
   }

   @Inject
   private BeerService beerService;

   @Test
   @UsingDataSet("beers.yml")
   public void should_find_all_beers() throws Exception
   {
      // when
      final Collection<Beer> beers = beerService.findAll();

      // then
      assertThat(beers).hasSize(2);
   }

}


text:
<form action="" method="get" class="form--inline">

            Text
            <input id="text" type="text" class="input" name="text">

            Static

email@domain.com

            Select
            <select id="select" class="input" name="select">
                <option value="1">Option 1</option>
                <option value="2">Option 2</option>
                <option value="3">Option 3</option>
                <option value="4">Option 4</option>
                <option value="5">Option 5</option>
                <option value="6">Option 6</option>
            </select>

            <input id="checkbox-1" type="checkbox" name="checkbox[]">Checkbox 1
            <input id="checkbox-2" type="checkbox" name="checkbox[]">Checkbox 2
            <input id="checkbox-3" type="checkbox" name="checkbox[]">Checkbox 3

            <input id="radio-1" type="radio" name="radio"> Radio 1
            <input id="radio-2" type="radio" name="radio"> Radio 2
            <input id="radio-3" type="radio" name="radio"> Radio 3

            <button type="submit" class="button is-success">Submit</button>
            <button type="reset" class="button">Reset</button>

</form>

<input type="text" class="input" value="Input">
<select class="input"><option>Select</option></select>
<button type="Button" class="button">Button</button>
Anchor
<input type="submit" class="button" value="Submit">


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    android:baselineAligned="false"
    android:divider="?android:attr/dividerHorizontal"
    android:orientation="horizontal"
    android:showDividers="middle"
    tools:context=".activity.MovieListActivity">

    <!--
    This layout is a two-pane layout for the Movies
    master/detail flow.

    -->

    <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/movie_list"
        android:name="com.itweeti.isse.popmovies.MovieListFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        app:layoutManager="LinearLayoutManager"
        tools:context=".activity.MovieListActivity"
        tools:listitem="@layout/movie_list_content"
        android:layout_weight="3" />

    <FrameLayout
        android:id="@+id/movie_detail_container"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

</LinearLayout>