text:
/**
 * @depend util/core.js
 */
/**
 * Format functions
 *
 * @author Christian Johansen (christian@cjohansen.no)
 * @license BSD
 *
 * Copyright (c) 2010-2014 Christian Johansen
 */
"use strict";

(function (sinon, formatio) {
    function makeApi(sinon) {
        function valueFormatter(value) {
            return "" + value;
        }

        function getFormatioFormatter() {
            var formatter = formatio.configure({
                    quoteStrings: false,
                    limitChildrenCount: 250
                });

            function format() {
                return formatter.ascii.apply(formatter, arguments);
            };

            return format;
        }

        function getNodeFormatter(value) {
            function format(value) {
                return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value;
            };

            try {
                var util = require("util");
            } catch (e) {
                /* Node, but no util module - would be very old, but better safe than sorry */
            }

            return util ? format : valueFormatter;
        }

        var isNode = typeof module !== "undefined" && module.exports && typeof require == "function",
            formatter;

        if (isNode) {
            try {
                formatio = require("formatio");
            } catch (e) {}
        }

        if (formatio) {
            formatter = getFormatioFormatter()
        } else if (isNode) {
            formatter = getNodeFormatter();
        } else {
            formatter = valueFormatter;
        }

        sinon.format = formatter;
        return sinon.format;
    }

    function loadDependencies(require, exports, module) {
        var sinon = require("./util/core");
        module.exports = makeApi(sinon);
    }

    var isNode = typeof module !== "undefined" && module.exports && typeof require == "function";
    var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd;

    if (isAMD) {
        define(loadDependencies);
    } else if (isNode) {
        loadDependencies(require, module.exports, module);
    } else if (!sinon) {
        return;
    } else {
        makeApi(sinon);
    }
}(
    (typeof sinon == "object" && sinon || null),
    (typeof formatio == "object" && formatio)
));


text:
This is a fast and simple [JSON](json.org) library for Java.

## How to use
The important class is Toml.java. It contains public static methods for reading and writing JSON data.
You can read data like this:

```java
//import com.electronwill.json.Json
File file = new File("myFile.json");
FileReader reader = new FileReader(file);
Map<String, Object> jsonObject = Json.readObject(reader);
```

And write data like this:
```java
//import com.electronwill.json.Json
File file = new File("myFile.json");
FileWriter writer = new FileWriter(file);
Map<String, Object> jsonObject = ...//put your data here
boolean humanFriendly = true;//true to indent and space the output, false to compact it
Json.write(jsonObject, writer, humanFriendly);
```

You can also use `JsonReader` and `JsonWriter` directly.

## Data types
The JSON data is mapped to the following java types:

   JSON | Java
------- | -------
Integer | `int` or `long` (it depends on the size)
Decimal | `double`
Boolean | `boolean`
String  | `String`
Array   | `List<Object>`
Object  | `Map<String, Object>`
null    | `null`

## Java version
This library requires Java 7.

redpajama_set_name: RedPajamaGithub


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

import java.io.Serializable;

import org.activiti.engine.IdentityService;

/**
 * Represents a group, used in {@link IdentityService}.
 *
 * @author Tom Baeyens
 */
public interface Group extends Serializable {

  String getId();
  void setId(String id);

  String getName();
  void setName(String name);

  String getType();
  void setType(String string);
}


text:
package us.illyohs.azathoth.fx;

import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;

public class FxHelper {

    /**
     * Binds textures using FML
     */
    public static void bindTextureFML(ResourceLocation texture) {
        FMLClientHandler.instance().getClient().renderEngine.bindTexture(texture);
    }

    /**
     * Binds textures using Minecraft
     */
    public static void bindTextureMC(ResourceLocation texure) {
        Minecraft.getMinecraft().renderEngine.bindTexture(texure);
    }

}


text:
"use strict";

// Subscribes and unsubscribes to push once so that the manifest details are
// stored in service worker storage. After this, subscribe can succeed from
// inside the service worker. This triggers an infobar unless a permission
// decision was previously set.
function subscribeAndUnsubscribePush(registration) {
  return new Promise(function(resolve, reject) {
    // 1. Call subscribe in document context. The manifest details are stored
    // in the service worker storage for later use in a service worker context
    // where there is no manifest.
    registration.pushManager.subscribe().then(function(subscription) {
      // 2. Call unsubscribe so we can subscribe again later inside a
      // service worker.
      return subscription.unsubscribe();
    })
    .then(function(unsubscription_result) {
      resolve();
    })
    .catch(function(e) {
      reject(e);
    });
  });
}

// Registers a service worker and subscribes to push using the given string
// as an applicationServerKey.
function registerAndSubscribePushWithString(test, serverKeyString) {
  return registerAndSubscribePush(test,
      new TextEncoder().encode(serverKeyString));
}

// Subscribes to push with the given application server key. serverKey should be
// a Uint8Array.
function registerAndSubscribePush(test, serverKey) {
  const workerUrl = 'resources/empty_worker.js';
  const workerScope = 'resources/scope/' + location.pathname;
  let swRegistration;

  return service_worker_unregister_and_register(test, workerUrl, workerScope)
      .then(function(serviceWorkerRegistration) {
        swRegistration = serviceWorkerRegistration;
        return wait_for_state(test, swRegistration.installing, 'activated');
      })
  .then(function() {
    if (window.testRunner) {
      testRunner.setPermission('push-messaging', 'granted', location.origin,
          location.origin);
    }
    return swRegistration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: serverKey
    });
  });
}

// Runs |command| in the service worker connected to |port|. Returns a promise
// that will be resolved with the response data of the command.
function runCommandInServiceWorker(port, command) {
  return new Promise(function(resolve, reject) {
    port.addEventListener('message', function listener(event) {
      // To make this listener a oneshot, remove it the first time it runs.
      port.removeEventListener('message', listener);

      if (typeof event.data != 'object' || !event.data.command)
        assert_unreached('Invalid message from the service worker');

      assert_equals(event.data.command, command);
      if (event.data.success)
        resolve(event.data);
      else
        reject(new Error(event.data.errorMessage));
    });
    port.postMessage({command: command});
  });
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.psalgs.graph.tsort;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Stack;

/**
 *
 * @author djoshi
 *
 * http://www.geeksforgeeks.org/topological-sorting/
 *
 * Topological Sort ( we use Directed Acyclic Graph )
 *
 *  In Topological sort we print first visited node at last ( we keep it in stack )
 */
public class TopologicalSort {

    int V;
    LinkedList<Integer>[] adj;

    private TopologicalSort(int v) {
        V = v;
        adj = new LinkedList[v];

        for (int i = 0; i < V; i++) {
            adj[i] = new LinkedList<>();
        }
    }

    private void addEdge(int v, int w) {
        adj[v].add(w);
    }

    private void topologicalSort() {
        Stack<Integer> stack = new Stack();

        // Mark all the vertices as not visited
        boolean[] visited = new boolean[V];

        // Call recursive helper function to store Topological sort
        // starting from all vertices one by one
        for (int i = 0; i < V; i++) {
            if (!visited[i]) {
                topologicalSortUtil(i, visited, stack);
            }
        }

        while (!stack.isEmpty()) {
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
    }

    private void topologicalSortUtil(int v, boolean visited[], Stack stack) {
        // Mark the current node as visited.
        visited[v] = true;

        Iterator<Integer> itr = adj[v].iterator();
        while (itr.hasNext()) {
            int i = itr.next();

            if (!visited[i]) {
                topologicalSortUtil(i, visited, stack);
            }
        }
        stack.push(v);
    }

    public static void main(String args[]) {
        TopologicalSort graph = new TopologicalSort(6);
        graph.addEdge(5, 2);
        graph.addEdge(5, 0);
        graph.addEdge(4, 0);
        graph.addEdge(4, 1);
        graph.addEdge(2, 3);
        graph.addEdge(3, 1);
        // Directed Acyclic graph (DAG)

        System.out.println("Following is a Topological sort of the given graph");
        graph.topologicalSort();
    }
}


text:
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

import Page = require('../../../../../base/Page');
import Response = require('../../../../../http/response');
import V2010 = require('../../../V2010');
import { PhoneNumberCapabilities } from '../../../../../interfaces';
import { SerializableClass } from '../../../../../interfaces';

/**
 * Initialize the SharedCostList
 *
 * @param version - Version of the resource
 * @param accountSid - The account_sid
 * @param countryCode - The ISO-3166-1 country code of the country.
 */
declare function SharedCostList(version: V2010, accountSid: string, countryCode: string): SharedCostListInstance;

interface SharedCostListInstance {
  /**
   * Streams SharedCostInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Function to process each record
   */
  each(callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void;
  /**
   * Streams SharedCostInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Function to process each record
   */
  each(opts?: SharedCostListInstanceEachOptions, callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void): void;
  /**
   * Retrieve a single target page of SharedCostInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  getPage(callback?: (error: Error | null, items: SharedCostPage) => any): Promise<SharedCostPage>;
  /**
   * Retrieve a single target page of SharedCostInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param targetUrl - API-generated URL for the requested results page
   * @param callback - Callback to handle list of records
   */
  getPage(targetUrl?: string, callback?: (error: Error | null, items: SharedCostPage) => any): Promise<SharedCostPage>;
  /**
   * Lists SharedCostInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  list(callback?: (error: Error | null, items: SharedCostInstance[]) => any): Promise<SharedCostInstance[]>;
  /**
   * Lists SharedCostInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  list(opts?: SharedCostListInstanceOptions, callback?: (error: Error | null, items: SharedCostInstance[]) => any): Promise<SharedCostInstance[]>;
  /**
   * Retrieve a single page of SharedCostInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param callback - Callback to handle list of records
   */
  page(callback?: (error: Error | null, items: SharedCostPage) => any): Promise<SharedCostPage>;
  /**
   * Retrieve a single page of SharedCostInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @param opts - Options for request
   * @param callback - Callback to handle list of records
   */
  page(opts?: SharedCostListInstancePageOptions, callback?: (error: Error | null, items: SharedCostPage) => any): Promise<SharedCostPage>;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

/**
 * Options to pass to each
 *
 * @property areaCode - The area code of the phone numbers to read
 * @property beta - Whether to read phone numbers new to the Twilio platform
 * @property callback -
 *                         Function to process each record. If this and a positional
 *                         callback are passed, this one will be used
 * @property contains - The pattern on which to match phone numbers
 * @property distance - The search radius, in miles, for a near_ query. (US/Canada only)
 * @property done - Function to be called upon completion of streaming
 * @property excludeAllAddressRequired - Whether to exclude phone numbers that require an Address
 * @property excludeForeignAddressRequired - Whether to exclude phone numbers that require a foreign address
 * @property excludeLocalAddressRequired - Whether to exclude phone numbers that require a local address
 * @property faxEnabled - Whether the phone numbers can receive faxes
 * @property inLata - Limit results to a specific local access and transport area. (US/Canada only)
 * @property inLocality - Limit results to a particular locality
 * @property inPostalCode - Limit results to a particular postal code. (US/Canada only)
 * @property inRateCenter - Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
 * @property inRegion - Limit results to a particular region. (US/Canada only)
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         each() guarantees never to return more than limit.
 *                         Default is no limit
 * @property mmsEnabled - Whether the phone numbers can receive MMS messages
 * @property nearLatLong - Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
 * @property nearNumber - Given a phone number, find a geographically close number within distance miles. (US/Canada only)
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no pageSize is defined but a limit is defined,
 *                         each() will attempt to read the limit with the most efficient
 *                         page size, i.e. min(limit, 1000)
 * @property smsEnabled - Whether the phone numbers can receive text messages
 * @property voiceEnabled - Whether the phone numbers can receive calls.
 */
interface SharedCostListInstanceEachOptions {
  areaCode?: number;
  beta?: boolean;
  callback?: (item: SharedCostInstance, done: (err?: Error) => void) => void;
  contains?: string;
  distance?: number;
  done?: Function;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  limit?: number;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageSize?: number;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

/**
 * Options to pass to list
 *
 * @property areaCode - The area code of the phone numbers to read
 * @property beta - Whether to read phone numbers new to the Twilio platform
 * @property contains - The pattern on which to match phone numbers
 * @property distance - The search radius, in miles, for a near_ query. (US/Canada only)
 * @property excludeAllAddressRequired - Whether to exclude phone numbers that require an Address
 * @property excludeForeignAddressRequired - Whether to exclude phone numbers that require a foreign address
 * @property excludeLocalAddressRequired - Whether to exclude phone numbers that require a local address
 * @property faxEnabled - Whether the phone numbers can receive faxes
 * @property inLata - Limit results to a specific local access and transport area. (US/Canada only)
 * @property inLocality - Limit results to a particular locality
 * @property inPostalCode - Limit results to a particular postal code. (US/Canada only)
 * @property inRateCenter - Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
 * @property inRegion - Limit results to a particular region. (US/Canada only)
 * @property limit -
 *                         Upper limit for the number of records to return.
 *                         list() guarantees never to return more than limit.
 *                         Default is no limit
 * @property mmsEnabled - Whether the phone numbers can receive MMS messages
 * @property nearLatLong - Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
 * @property nearNumber - Given a phone number, find a geographically close number within distance miles. (US/Canada only)
 * @property pageSize -
 *                         Number of records to fetch per request,
 *                         when not set will use the default value of 50 records.
 *                         If no page_size is defined but a limit is defined,
 *                         list() will attempt to read the limit with the most
 *                         efficient page size, i.e. min(limit, 1000)
 * @property smsEnabled - Whether the phone numbers can receive text messages
 * @property voiceEnabled - Whether the phone numbers can receive calls.
 */
interface SharedCostListInstanceOptions {
  areaCode?: number;
  beta?: boolean;
  contains?: string;
  distance?: number;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  limit?: number;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageSize?: number;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

/**
 * Options to pass to page
 *
 * @property areaCode - The area code of the phone numbers to read
 * @property beta - Whether to read phone numbers new to the Twilio platform
 * @property contains - The pattern on which to match phone numbers
 * @property distance - The search radius, in miles, for a near_ query. (US/Canada only)
 * @property excludeAllAddressRequired - Whether to exclude phone numbers that require an Address
 * @property excludeForeignAddressRequired - Whether to exclude phone numbers that require a foreign address
 * @property excludeLocalAddressRequired - Whether to exclude phone numbers that require a local address
 * @property faxEnabled - Whether the phone numbers can receive faxes
 * @property inLata - Limit results to a specific local access and transport area. (US/Canada only)
 * @property inLocality - Limit results to a particular locality
 * @property inPostalCode - Limit results to a particular postal code. (US/Canada only)
 * @property inRateCenter - Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only)
 * @property inRegion - Limit results to a particular region. (US/Canada only)
 * @property mmsEnabled - Whether the phone numbers can receive MMS messages
 * @property nearLatLong - Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only)
 * @property nearNumber - Given a phone number, find a geographically close number within distance miles. (US/Canada only)
 * @property pageNumber - Page Number, this value is simply for client state
 * @property pageSize - Number of records to return, defaults to 50
 * @property pageToken - PageToken provided by the API
 * @property smsEnabled - Whether the phone numbers can receive text messages
 * @property voiceEnabled - Whether the phone numbers can receive calls.
 */
interface SharedCostListInstancePageOptions {
  areaCode?: number;
  beta?: boolean;
  contains?: string;
  distance?: number;
  excludeAllAddressRequired?: boolean;
  excludeForeignAddressRequired?: boolean;
  excludeLocalAddressRequired?: boolean;
  faxEnabled?: boolean;
  inLata?: string;
  inLocality?: string;
  inPostalCode?: string;
  inRateCenter?: string;
  inRegion?: string;
  mmsEnabled?: boolean;
  nearLatLong?: string;
  nearNumber?: string;
  pageNumber?: number;
  pageSize?: number;
  pageToken?: string;
  smsEnabled?: boolean;
  voiceEnabled?: boolean;
}

interface SharedCostPayload extends SharedCostResource, Page.TwilioResponsePayload {
}

interface SharedCostResource {
  address_requirements: string;
  beta: boolean;
  capabilities: PhoneNumberCapabilities;
  friendly_name: string;
  iso_country: string;
  lata: string;
  latitude: number;
  locality: string;
  longitude: number;
  phone_number: string;
  postal_code: string;
  rate_center: string;
  region: string;
}

interface SharedCostSolution {
  accountSid?: string;
  countryCode?: string;
}

declare class SharedCostInstance extends SerializableClass {
  /**
   * Initialize the SharedCostContext
   *
   * @param version - Version of the resource
   * @param payload - The instance payload
   * @param accountSid - The account_sid
   * @param countryCode - The ISO-3166-1 country code of the country.
   */
  constructor(version: V2010, payload: SharedCostPayload, accountSid: string, countryCode: string);

  addressRequirements: string;
  beta: boolean;
  capabilities: PhoneNumberCapabilities;
  friendlyName: string;
  isoCountry: string;
  lata: string;
  latitude: number;
  locality: string;
  longitude: number;
  phoneNumber: string;
  postalCode: string;
  rateCenter: string;
  region: string;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

declare class SharedCostPage extends Page<V2010, SharedCostPayload, SharedCostResource, SharedCostInstance> {
  /**
   * Initialize the SharedCostPage
   *
   * @param version - Version of the resource
   * @param response - Response from the API
   * @param solution - Path solution
   */
  constructor(version: V2010, response: Response<string>, solution: SharedCostSolution);

  /**
   * Build an instance of SharedCostInstance
   *
   * @param payload - Payload response from the API
   */
  getInstance(payload: SharedCostPayload): SharedCostInstance;
  /**
   * Provide a user-friendly representation
   */
  toJSON(): any;
}

export { SharedCostInstance, SharedCostList, SharedCostListInstance, SharedCostListInstanceEachOptions, SharedCostListInstanceOptions, SharedCostListInstancePageOptions, SharedCostPage, SharedCostPayload, SharedCostResource, SharedCostSolution }


text:
var provider={
	'actions':{'giveup':['non', 'laisse tomber', 'oublie'], 'over':['c\'est tout', ' fini']}
}

exports.init=function(config, app)
{
	$('fs').exists(config, function(exists){
		if(!exists)
			$('fs').writeFile(config, '{}', function(error){
				if(error)
					console.log(error);
			});
	});

	commands=$(config);

	var lastCmd=null;

	app.use(function(cmd, context, fileName, callback, next){
		callback(null, 'je n\'ai pas compris, peux-tu m\'apprendre ce que ça veut dire ?');
		context.provider=provider;
		lastCmd=cmd;
		cmd.count=0;
	});

	provider.understand=function(cmd, context){
		cmd.action=this.findInfo(this, 'actions', cmd.text);
		return context.provider==this || typeof(commands[cmd.text])!='undefined';
	};

	provider.process=function(cmd, context, callback, next){
		switch(cmd.action)
		{
			case 'giveup':
				context.provider=null;
				if(lastCmd!=null && lastCmd.count>0 && commands[lastCmd.text] && commands[lastCmd.text].length>0)
				{
					$('fs').writeFile(config, JSON.stringify(commands), function(error)
					{
						callback(error, 'Ok, bien recu');
					});
				}
				else
					callback(null, 'tant pis');
				lastCmd=null;
				return true;
			default:
				if(lastCmd!=null)
				{
					if(lastCmd.count==0)
						commands[lastCmd.text]=[];

					commands[lastCmd.text].push(cmd.text);
					lastCmd.count++;
					callback(null, 'autre chose ?');
				}
				else
				{
					$.eachAsync(commands[cmd.text], function(index, text, next){
						global.eval(text, context, null, function(error, result){
							if(error)
								callback('Error on '+text+'\n'+error);
							else
								next();
						});
					}, function(){
					    callback(null, 'C\'est fait.');
					});
				}
				return true;
		}
	};

	$.language(provider);
};


text:
#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"

#include "geometry/visualization/put_stl.hh"

#include "planning/jet/jet_dynamics.hh"
#include "planning/jet/jet_planner.hh"

// #include "planning/jet/filter_sim.hh"
#include "planning/jet/jet_model.hh"

// TODO CLEANUP
#include "viewer/primitives/camera.hh"
#include "viewer/primitives/image.hh"

#include "estimation/vision/calibration.hh"

#include "util/environment.hh"

#include "eigen.hh"
#include "sophus.hh"

namespace planning {
namespace jet {

constexpr bool SHOW_CAMERA = false;
constexpr bool SHOW_CAMERA_PROJECTION = false;
constexpr bool WRITE_IMAGES = false;
constexpr bool PRINT_STATE = true;
constexpr bool DRAW_VEHICLE = true;
constexpr bool TRACK_VEHICLE = false;
constexpr bool VISUALIZE_TRAJECTORY = false;

namespace {
void setup() {
  const auto view = viewer::get_window3d("Mr. Jet, jets");
  view->set_target_from_world(
      SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
  view->set_continue_time_ms(10);

  const auto background = view->add_primitive<viewer::SimpleGeometry>();
  const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
  background->add_plane({ground});
  background->flip();
}

void put_camera_projection(viewer::SimpleGeometry& geo, const viewer::Camera& cam) {
  const auto proj = cam.get_projection();

  using VPoint = viewer::ViewportPoint;
  const auto bottom_left_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, -1.0)));
  const auto top_left_ray = proj.unproject(VPoint(jcc::Vec2(1.0, -1.0)));
  const auto top_right_ray = proj.unproject(VPoint(jcc::Vec2(1.0, 1.0)));
  const auto bottom_right_ray = proj.unproject(VPoint(jcc::Vec2(-1.0, 1.0)));

  const jcc::Vec4 red(1.0, 0.1, 0.1, 0.8);
  constexpr double length = 5.0;
  const jcc::Vec3 origin = bottom_right_ray(0.0);
  geo.add_line({origin, bottom_left_ray(length), red});
  geo.add_line({origin, top_left_ray(length), red});
  geo.add_line({origin, top_right_ray(length), red});
  geo.add_line({origin, bottom_right_ray(length), red});

  geo.add_line({bottom_left_ray(length), top_left_ray(length), red});
  geo.add_line({top_left_ray(length), top_right_ray(length), red});
  geo.add_line({top_right_ray(length), bottom_right_ray(length), red});
  geo.add_line({bottom_right_ray(length), bottom_left_ray(length), red});
}

/*void draw_fidudical_detections(const cv::Mat localization_camera_image_rgb,
                               const SE3 world_from_opengl_camera,
                               std::shared_ptr<viewer::SimpleGeometry> geo) {
  const auto opengl_camera_from_opencv_camera =
      SE3(SO3::exp(Eigen::Vector3d(M_PI, 0, 0)), Eigen::Vector3d(0, 0, 0)) *
      SE3(SO3::exp(Eigen::Vector3d(0, 0, M_PI / 2 * 0)), Eigen::Vector3d(0, 0, 0));
  const auto world_from_camera =
      world_from_opengl_camera * opengl_camera_from_opencv_camera;
  auto world_from_markers = estimation::vision::get_world_from_marker_centers(
      localization_camera_image_rgb, world_from_camera);

  for (auto const& marker_detection_world_space : world_from_markers) {
    geo->add_line({world_from_opengl_camera.translation(),
                   marker_detection_world_space.world_from_marker.translation(),
                   jcc::Vec4(1.0, 0.1, 0.7, 1), 5.0});
  }
}
*/
}  // namespace

void go() {
  setup();
  const auto view = viewer::get_window3d("Mr. Jet, jets");

  const std::string jet_path = jcc::Environment::asset_path() + "jetcat_p160.stl";
  const auto put_jet = geometry::visualization::create_put_stl(jet_path);

  const auto jet_tree = view->add_primitive<viewer::SceneTree>();
  const auto jet_geo = view->add_primitive<viewer::SimpleGeometry>();
  const auto accum_geo = view->add_primitive<viewer::SimpleGeometry>();

  const auto image_tree = view->add_primitive<viewer::SceneTree>();
  {
    const std::string fiducial_path = jcc::Environment::asset_path() + "fiducial.jpg";
    const cv::Mat fiducial_tag = cv::imread(fiducial_path);
    const auto board_texture_image = std::make_shared<viewer::Image>(fiducial_tag, 1, 1);
    // view->add_primitive(board_texture_image);
    // image_tree->add_primitive("root", SE3(), "fiducial_1",
    // board_texture_image);

    const auto world_from_fiducial =
        SE3(SO3::exp(jcc::Vec3(M_PI / 5, 0.5, 0.0)), jcc::Vec3(0.0, 3.0, 0.0));

    image_tree->add_primitive("root", world_from_fiducial, "fiducial_2",
                              board_texture_image);
    image_tree->add_primitive(
        "root", SE3(SO3::exp(jcc::Vec3(3.14 / 2, 0.0, 0.5)), jcc::Vec3(1.0, 3.0, 1.0)),
        "fiducial_3", board_texture_image);
  }

  const auto camera = std::make_shared<viewer::Camera>();
  view->add_camera(camera);

  const JetModel model;
  if constexpr (DRAW_VEHICLE) {
    model.insert(*jet_tree);
  }

  //
  // Add camera projection to the scene tree
  //

  const SO3 camera_sideways_from_camera_down = SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) *
                                               SO3::exp(jcc::Vec3(0.0, M_PI, 0.0)) *
                                               SO3::exp(jcc::Vec3(0.0, 0, M_PI));
  const SE3 jet_from_camera =
      SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));
  if (SHOW_CAMERA_PROJECTION) {
    const auto camera_geo = std::make_shared<viewer::SimpleGeometry>();
    put_camera_projection(*camera_geo, *camera);
    camera_geo->flush();
    jet_tree->add_primitive("root", jet_from_camera, "camera", camera_geo);
  }

  State jet;
  jet.x = jcc::Vec3(-2.0, -2.0, 7.0);
  jet.w = jcc::Vec3(0.1, -0.1, 0.1);

  jet.R_world_from_body = SO3::exp(jcc::Vec3(0.1, 0.0, 0.0));
  const jcc::Vec3 vel_jet_frame(0.0, 0.0, -0.3);
  jet.v = jet.R_world_from_body * vel_jet_frame;

  jet.throttle_pct = 0.0;

  const jcc::Vec3 final_target(0.5, 0.5, 0.9);

  std::vector<Controls> prev_controls;
  int j = 0;
  while (!view->should_close()) {
    ++j;
    const jcc::Vec3 prev = jet.x;

    //
    // Planning state
    //

    Desires desire;
    desire.target = final_target;
    if (j > 100) {
      desire.target = jcc::Vec3(0, 0, 0);
    } else if (j > 300) {
      desire.target = jcc::Vec3(0, -2, 0);
    } else if (j > 500) {
      desire.target = jcc::Vec3(1, 1, -1);
    } else if (j > 800) {
      desire.target = jcc::Vec3(-2, -6, -1);
    } else if (j > 1000) {
      desire.target = jcc::Vec3(-2, -6, -1);
    } else if (j > 1300) {
      desire.target = jcc::Vec3(3, -6, 3);
    } else if (j > 1600) {
      desire.target = jcc::Vec3(0, 0, 0);
    }

    //
    // Execute planning
    //

    const auto future_states = plan(jet, desire, prev_controls);
    jet = future_states[1].state;

    //
    // Print out first state
    //

    const auto ctrl = future_states[1].control;
    if constexpr (PRINT_STATE) {
      std::cout << j << "..." << std::endl;
      std::cout << "\tq     : " << ctrl.q.transpose() << std::endl;
      std::cout << "\tx     : " << jet.x.transpose() << std::endl;
      std::cout << "\tw     : " << jet.w.transpose() << std::endl;
      std::cout << "\tv     : " << jet.v.transpose() << std::endl;
      std::cout << "\tthrust: " << jet.throttle_pct << std::endl;

      // const Parameters p = get_parameters();
      // const auto kf_state = kf_state_from_xlqr_state(jet, ctrl, p);

      // std::cout << "eps_dot   : " << kf_state.eps_dot.transpose() << std::endl;
      // std::cout << "eps_ddot  : " << kf_state.eps_ddot.transpose() << std::endl;
      // std::cout << "accel_bias: " << kf_state.accel_bias.transpose() << std::endl;
      // std::cout << "gyro_bias : " << kf_state.gyro_bias.transpose() << std::endl;
    }

    //
    // Visualize
    //

    const SE3 world_from_jet = SE3(jet.R_world_from_body, jet.x);

    // put_jet(*jet_geo, world_from_jet);

    // const SO3 camera_sideways_from_camera_down =
    //     SO3::exp(jcc::Vec3(-M_PI / 2, 0.0, 0.0)) * SO3::exp(jcc::Vec3(0.0, M_PI, 0.0))
    //     * SO3::exp(jcc::Vec3(0.0, 0, M_PI));
    // const SE3 jet_from_camera =
    //     SE3(camera_sideways_from_camera_down, jcc::Vec3(0.1, 0.05, 0.1));

    if constexpr (VISUALIZE_TRAJECTORY) {
      for (std::size_t k = 0; k < future_states.size(); ++k) {
        const auto& state = future_states.at(k).state;
        const SE3 world_from_state = SE3(state.R_world_from_body, state.x);
        const double scale =
            static_cast<double>(k) / static_cast<double>(future_states.size());
        jet_geo->add_axes({world_from_state, 1.0 - scale});

        if (k > 1) {
          jet_geo->add_line({future_states.at(k).state.x, future_states.at(k - 1).state.x,
                             jcc::Vec4(0.8, 0.8, 0.1, 0.8), 5.0});
        }
      }
      jet_geo->add_line(
          {world_from_jet.translation(),
           world_from_jet.translation() +
               (world_from_jet.so3() * jcc::Vec3::UnitZ() * jet.throttle_pct * 0.1),
           jcc::Vec4(0.1, 0.9, 0.1, 0.8), 9.0});
      accum_geo->add_line({prev, jet.x, jcc::Vec4(1.0, 0.7, 0.7, 0.7), 5.0});
    }

    if constexpr (TRACK_VEHICLE) {
      const SO3 world_from_target_rot = SO3::exp(jcc::Vec3::UnitX() * M_PI * 0.5);
      const SE3 world_from_target(world_from_target_rot, world_from_jet.translation());
      view->set_target_from_world(world_from_target.inverse());
    } else {
      // view->set_target_from_world(world_from_jet.inverse());
    }

    jet_tree->set_world_from_root(world_from_jet);
    camera->set_world_from_camera(world_from_jet * jet_from_camera);
    accum_geo->flush();

    const cv::Mat camera_image_rgb = camera->extract_image();

    // draw_fidudical_detections(camera_image_rgb, world_from_jet * jet_from_camera,
    //                           jet_geo);

    if (SHOW_CAMERA) {
      cv::imshow("Localization Camera", camera_image_rgb);
      cv::waitKey(1);
    }

    estimation::vision::CalibrationManager calibration_manager;

    if (j % 10 == 0) {
      calibration_manager.add_camera_image(camera_image_rgb);
    }
    if (calibration_manager.num_images_collected() % (200 / 15) == 0 &&
        calibration_manager.num_images_collected() > 0) {
      calibration_manager.calibrate();
    }

    if (WRITE_IMAGES) {
      if (j == 0) {
        std::cout << "Projection: " << std::endl;
        std::cout << camera->get_projection().projection_mat() << std::endl;
      }
      if (j % 1 == 0) {
        std::cout << "-----" << j << std::endl;
        std::cout << camera->get_projection().modelview_mat() << std::endl;
        cv::imwrite("jet_image_" + std::to_string(j) + ".jpg", camera_image_rgb);
      }
    }
    jet_geo->flip();
    view->spin_until_step();
  }

  cv::destroyAllWindows();
}

}  // namespace jet
}  // namespace planning

int main() {
  planning::jet::go();
}


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

import java.util.HashMap;
import java.util.Map;

import rx.Subscriber;

final class SubscriberVault {

    private static long idGenerator;

    private final Map<Long, Subscriber> subscriberMap = new HashMap<Long, Subscriber>();

    <T> long store(Subscriber<T> subscriber) {
        long id = idGenerator++;
        subscriberMap.put(id, subscriber);
        return id;
    }

    public <T> Subscriber<T> get(long key) {
        return subscriberMap.get(key);
    }

    public boolean containsKey(long key) {
        return subscriberMap.containsKey(key);
    }

    public <T> Subscriber<T> remove(long subscriberKey) {
        return subscriberMap.remove(subscriberKey);
    }
}


text:
// this is a local redefinition of nbdkit_error() for use with command-line utilities.

#include "local_nbdkit_error.h"

#include <stdio.h>

void nbdkit_error(const char *fs, ...)
{
    va_list args;

    fprintf(stderr, "ERROR: ");

    va_start(args, fs);
    vfprintf(stderr, fs, args);
    va_end(args);

    fprintf(stderr, "\n");
}


text:
package org.arakhne.afc.math.geometry.d2.afp;

import org.arakhne.afc.math.geometry.d2.Point2D;
import org.arakhne.afc.math.geometry.d2.Tuple2D;
import org.arakhne.afc.math.geometry.d2.UnmodifiablePoint2D;

/** A point that is used for internal computations.
 *
 * @author $Author: sgalland$
 * @version $FullVersion$
 * @mavengroupid $GroupId$
 * @mavenartifactid $ArtifactId$
 * @since 13.0
 */
public class InnerComputationPoint2afp implements Point2D<InnerComputationPoint2afp, InnerComputationVector2afp> {

	private static final long serialVersionUID = 8578192819251519051L;

	private double x;

	private double y;

	/** Construct the point.
	 */
	public InnerComputationPoint2afp() {
		//
	}

	/** Construct the point.
	 * @param x x coordinate
	 * @param y y coordinate
	 */
	public InnerComputationPoint2afp(double x, double y) {
		this.x = x;
		this.y = y;
	}

	@Override
	public InnerComputationGeomFactory getGeomFactory() {
		return InnerComputationGeomFactory.SINGLETON;
	}

	@Override
	public String toString() {
		return Tuple2D.toString(this.x, this.y);
	}

	@Override
	public InnerComputationPoint2afp clone() {
		try {
			return (InnerComputationPoint2afp) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new Error(e);
		}
	}

	@Override
	public double getX() {
		return this.x;
	}

	@Override
	public int ix() {
		return (int) Math.round(this.x);
	}

	@Override
	public void setX(int x) {
		this.x = x;
	}

	@Override
	public void setX(double x) {
		this.x = x;
	}

	@Override
	public double getY() {
		return this.y;
	}

	@Override
	public int iy() {
		return (int) Math.round(this.y);
	}

	@Override
	public void setY(int y) {
		this.y = y;
	}

	@Override
	public void setY(double y) {
		this.y = y;
	}

	@Override
	public UnmodifiablePoint2D<InnerComputationPoint2afp, InnerComputationVector2afp> toUnmodifiable() {
		throw new UnsupportedOperationException();
	}

}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="by.matskevich.calendaroffactory.MainActivity" >

    <item
        android:id="@+id/empty_item"
        android:orderInCategory="10"
        android:title="@string/settings_title"
        android:showAsAction="always"
        android:icon="@drawable/ic_action_overflow">
        <menu>
            <item
                android:id="@+id/action_settings"
                android:orderInCategory="10"
                android:showAsAction="never"
                android:title="@string/action_settings"/>
            <item
                android:id="@+id/action_about"
                android:orderInCategory="20"
                android:showAsAction="never"
                android:title="@string/title_activity_about"/>
        </menu>
    </item>

</menu>


text:
package com.all.core.common.model;

import static com.all.action.ActionType.cm;

import java.util.List;

import com.all.action.ActionType;
import com.all.action.RequestAction;
import com.all.action.ValueAction;
import com.all.shared.model.City;
import com.all.shared.stats.AllStat;

public interface ApplicationActions {

	String REPORT_USER_ACTION_ID = "application.reportUserAction";
	ActionType<ValueAction<Integer>> REPORT_USER_ACTION = cm(REPORT_USER_ACTION_ID);

	String REPORT_USER_STAT_ID = "application.reportUserStat";
	ActionType<ValueAction<AllStat>> REPORT_USER_STAT = cm(REPORT_USER_STAT_ID);

	String CHANGE_LANGUAGE_ID = "application.changeLang";
	ActionType<ValueAction<ApplicationLanguage>> CHANGE_LANGUAGE = cm(CHANGE_LANGUAGE_ID);

	String GET_ALL_CITIES_ID = "application.getAllCities";
	ActionType<RequestAction<Void, List<City>>> GET_ALL_CITIES = cm(GET_ALL_CITIES_ID);

}


text:
define([
  'dojo/_base/lang',
  'dojo/_base/array',
  'dojo/Deferred',
  'dojo/when',
  'dojo/promise/all',
  'jimu/portalUtils',
  'esri/lang',
  'esri/request'
], function(lang, array, Deferred, when, all, portalUtils, esriLang, esriRequest) {
  var mo = {
    map: null,
    layerInfosObj: null,
    appConfig: null,
    _esriLocatorRegExp: /geocode(.){0,3}\.arcgis.com\/arcgis\/rest\/services\/World\/GeocodeServer/g
  };

  mo.setMap = function(map) {
    this.map = map;
  };

  mo.setLayerInfosObj = function(lobj) {
    this.layerInfosObj = lobj;
  };

  mo.setAppConfig = function(apc) {
    this.appConfig = apc;
  };

  mo.getConfigInfo = function(config) {
    if (config && config.sources && config.sources.length > 0) {
      var searchInfo = null;
      if (this.searchLayer(this.map) && config.upgradeFromGeocoder) {
        // back compatibility for config which come from geocoders
        searchInfo = this.map.itemInfo.itemData.applicationProperties.viewing.search;
        var defs = array.map(searchInfo.layers, lang.hitch(this, function(hintText, _layer) {
          _layer.hintText = hintText;
          return this._getQueryTypeGeocoder(_layer);
        }, searchInfo.hintText));
        return all(defs).then(lang.hitch(this, function(results) {
          config.sources = [].concat(results).concat(config.sources);
          return config;
        }));
      } else {
        return config;
      }
    } else {
      return when(this._getSoucesFromPortalAndWebmap())
        .then(lang.hitch(this, function(sources) {
          return {
            "allPlaceholder": "",
            "showInfoWindowOnSelect": true,
            "sources": sources
          };
        }));
    }
  };

  mo._getSoucesFromPortalAndWebmap = function() {
    var defs = [];
    var searchInfo = null;
    if (this.searchLayer(this.map)) {
      searchInfo = this.map.itemInfo.itemData.applicationProperties.viewing.search;
      array.forEach(searchInfo.layers, lang.hitch(this, function(hintText, _layer) {
        _layer.hintText = hintText;
        defs.push(this._getQueryTypeGeocoder(_layer));
      }, searchInfo.hintText));
    } // else do nothing

    return portalUtils.getPortalSelfInfo(this.appConfig.portalUrl)
      .then(lang.hitch(this, function(response) {
        var geocoders = response.helperServices && response.helperServices.geocode;

        if (geocoders && geocoders.length > 0) {
          for (var i = 0, len = geocoders.length; i < len; i++) {
            var geocoder = geocoders[i];
            if (geocoder) {
              defs.push(this._processSingleLine(geocoder));
            }
          }
        }

        return all(defs).then(lang.hitch(this, function(results) {
          var validSources = [];
          for (var i = 0; i < results.length; i++) {
            var geocode = results[i];
            if (!geocode) {
              continue;
            } else if (geocode && geocode.type === 'query') {
              validSources.push(geocode);
            } else {
              var json = {
                name: geocode.name || this._getGeocodeName(geocode.url),
                url: geocode.url,
                singleLineFieldName: geocode.singleLineFieldName,
                placeholder: geocode.placeholder ||
                  geocode.name || this._getGeocodeName(geocode.url),
                maxResults: 6,
                searchInCurrentMapExtent: false,
                type: "locator"
              };
              json.enableLocalSearch = this._isEsriLocator(json.url);
              json.localSearchMinScale = 300000;
              json.localSearchDistance = 50000;

              validSources.push(json);
            }
          }

          return validSources;
        }));
      }));
  };

  mo._getQueryTypeGeocoder = function(item) {
    var layer = this.map.getLayer(item.id);
    var url = null;
    var _layerInfo = null;
    var _layerId = null;

    if (esriLang.isDefined(item.subLayer)) {
      _layerId = item.id + "_" + item.subLayer;
    } else {
      _layerId = item.id;
    }

    var isInMap = this.layerInfosObj.traversal(function(layerInfo) {
      if (layerInfo.id === _layerId) {
        _layerInfo = layerInfo;
        return true;
      }

      return false;
    });

    if (layer && isInMap && _layerInfo) {
      if (esriLang.isDefined(item.subLayer)) {
        url = _layerInfo.url || (layer.url + "/" + item.subLayer);
      } else {
        url = _layerInfo.url || layer.url;
      }

      return {
        name: _layerInfo.title,
        layerId: _layerId,
        url: url,
        placeholder: item.hintText,
        searchFields: [item.field.name],
        displayField: item.field.name,
        exactMatch: item.field.exactMatch || false,
        maxResults: 6,
        searchInCurrentMapExtent: false,
        type: "query"
      };
    } else {
      return null;
    }
  };

  mo._isEsriLocator = function(url) {
    this._esriLocatorRegExp.lastIndex = 0;
    return this._esriLocatorRegExp.test(url);
  };

  mo._processSingleLine = function(geocode) {
    // this._esriLocatorRegExp.lastIndex = 0;
    if (geocode.singleLineFieldName) {
      return geocode;
    } else if (this._isEsriLocator(geocode.url)) {
      geocode.singleLineFieldName = 'SingleLine';
      return geocode;
    } else {
      var def = new Deferred();
      esriRequest({
        url: geocode.url,
        content: {
          f: "json"
        },
        handleAs: "json",
        callbackParamName: "callback"
      }).then(lang.hitch(this, function(response) {
        if (response.singleLineAddressField && response.singleLineAddressField.name) {
          geocode.singleLineFieldName = response.singleLineAddressField.name;
          def.resolve(geocode);
        } else {
          console.warn(geocode.url + "has no singleLineFieldName");
          def.resolve(null);
        }
      }), lang.hitch(this, function(err) {
        console.error(err);
        def.resolve(null);
      }));

      return def.promise;
    }
  };

  mo._getGeocodeName = function(geocodeUrl) {
    if (typeof geocodeUrl !== "string") {
      return "geocoder";
    }
    var strs = geocodeUrl.split('/');
    return strs[strs.length - 2] || "geocoder";
  };

  mo.getGeocoderName = function(url) {
    return this._getGeocodeName(url);
  };

  mo.hasAppSearchInfo = function(map) {
    return map.itemInfo && map.itemInfo.itemData &&
      map.itemInfo.itemData.applicationProperties &&
      map.itemInfo.itemData.applicationProperties.viewing &&
      map.itemInfo.itemData.applicationProperties.viewing.search;
  };

  mo.searchLayer = function(map) {
    if (!this.hasAppSearchInfo(map)) {
      return false;
    }
    var search = map.itemInfo.itemData.applicationProperties.viewing.search;
    if (!search.enabled) {
      return false;
    }
    if (search.layers.length === 0) {
      return false;
    }

    return true;
  };

  return mo;
});


text:
console.log('loaded from static/auth-proxy.js');
window.cloudspongeProxy = (function() {
  var proxyHost = 'https://api.cloudsponge.com/auth';
  var isOAuthPage, queryParams, oauthParams, key;
  var redirecting = false;

  // serializes an object into a query-string
  var serializeParams = function(params) {
    var k, results = [];
    for (k in params) {
      results.push(k + "=" + encodeURIComponent(params[k]));
    }
    return results.join('&');
  }

  // converts the URL string into an object
  var parseParams = function(url) {
    var obj = {};
    url.replace(/([^?=&]+)(=([^&]*))?/g, function($0, $1, $2, $3) {
      return obj[$1] = decodeURIComponent($3);
    });
    return obj;
  }

  // parse the query string
  var queryParams = parseParams(window.location.search);

  // selects just the OAuth-related params out of the query
  oauthParams = {};
  for (key in queryParams) {
    if (key === 'code' || key === 'state' || key === 'error' || key === 'error_code' || key === 'forward') {
      oauthParams[key] = queryParams[key];
    }
  }

  // checks to see if this page actually the necessary received OAuth params
  // and then flings the state and code up to CloudSponge to do the heavy lifting work
  if (oauthParams.state && (oauthParams.code || oauthParams.error || oauthParams.error_code)) {
    redirecting = true;
    window.location = proxyHost + '?' + serializeParams(oauthParams);
  }

  // add the redirect endpoint to any .cs-proxy links on the page
  window.addEventListener('load', function(){
    var i;
    var links = document.getElementsByClassName('cs-force');
    for (i = 0; i < links.length; i++) {
      links[i].href = proxyHost + window.location.search;
    }
  }, false)

  return {
    redirecting: redirecting,
    force: function(){
      window.location = proxyHost + window.location.search;
      return false;
    }
  };
})();


text:
"""runs an executable file with additional enviroment variables which can
   be read from command line or from input file located at same place as
   executable
"""

from optparse import OptionParser
import subprocess
import os
import sys
import logging
import ast
import pprint
import traceback

def add_path_to_env_variable(env, name, value):
    logging.debug("add to '%s': '%s'", name, value)
    if name in env and env[name].strip() != "":
        env[name] += os.pathsep + value
    else:
        env[name] = value

def read_config(directory, warn_if_file_not_existent=True):

    _values = {'PWD'        : os.getcwd(),
               'ENVIRONMENT': ()}

    try:
        _env_file_name = os.path.join(directory, "env_run_variables.txt")

        if not (os.path.dirname(directory).startswith("/usr")
            or directory.endswith("\\asciidoc")
            or directory.endswith("/asciidoc")):
            _values.update( ast.literal_eval(open(_env_file_name).read()) )
        else:
            _values = {}

        if not 'ENVIRONMENT' in _values:
            _values['ENVIRONMENT'] = ()
        if not 'PWD' in _values:
            # [todo] - test for existence
            _values['PWD'] = os.getcwd()

    except IOError, ex:
        if warn_if_file_not_existent:
            logging.warning("could not load environment variable file '%s'. "
                            "error was '%s'",
                            _env_file_name, ex)
    except SyntaxError, ex:
        logging.warning("syntax error in environment variable file. "
                        "error was '%s'", ex)
    except Exception, ex:
        traceback.print_stack()
        logging.error("exception occured in read_config(): '%s'", ex)
        logging.error("args: %s", sys.argv)
    return _values

def write_config(directory, values):

    _env_file_name = os.path.join(directory, "env_run_variables.txt")

    try:
        _serialized_config = pprint.pformat(values) + '\n'
        values = open(_env_file_name, 'w').write(_serialized_config)

    except Exception, ex:
        traceback.print_stack()
        logging.error("could not write environment variable file '%s'. "
                       "error was '%s'",
                       _env_file_name, ex)
        logging.error("args: %s", sys.argv)

def configure_variable(directory, key_value):
    try:

        if not '=' in key_value:
            logging.error("given variable definition '%s' is not valid", key_value)
            return

        pos = key_value.index('=')
        key, value = key_value[:pos], key_value[pos+1:]

        values = read_config(directory, warn_if_file_not_existent=False)

        logging.debug("configure new variable value '%s': '%s'", key, value)

        variable_definitions = set(values['ENVIRONMENT'])
        variable_definitions.add((key, value))
        values['ENVIRONMENT'] = list(variable_definitions)

        write_config(directory, values)

    except Exception, ex:
        traceback.print_stack()
        logging.error("exception occured in configure_variable(): '%s'", ex)
        logging.error("args: %s", sys.argv)

def configure_pwd(directory, pwd):

    try:
        values = read_config(directory, warn_if_file_not_existent=False)

        _pwd = os.path.abspath(pwd)

        logging.debug("configure new pwd = '%s'", _pwd)

        values['PWD'] = _pwd

        write_config(directory, values)

    except Exception, ex:
        traceback.print_stack()
        logging.error("exception occured in configure_pwd(): '%s'", ex)
        logging.error("args: %s", sys.argv)

def replace(variable_to_modify, content):
    for key, value in content.iteritems():
        #logging.warning("HHH %s %s", key, value)
        variable_to_modify = variable_to_modify.replace("$(%s)" % key, value)
    return variable_to_modify

def last_activity(path):
    mtime = 0
    for dirname, dirnames, filenames in os.walk(path):
        for filename in filenames:
            mtime = max(mtime, os.path.getmtime(os.path.join(dirname, filename)))
    return mtime

def guess_configuration_type(variables):
    for conf_variable in ("$(OutDir)", "$(Configuration)"):
        shortest_length = 1000
        base_path = None
        for key, value in variables:
            #logging.warning("aaaaa %s %s", conf_variable, value)
            if not conf_variable in value: continue
            #logging.warning("bbbbb")
            pathname = os.path.abspath(value)
            effective_length = pathname.find(conf_variable)
            if effective_length < shortest_length:
                shortest_length = effective_length
                base_path = pathname[:effective_length]

        if base_path == None: continue

        debug_path = os.path.join(base_path, 'Debug')
        release_path = os.path.join(base_path, 'Release')
        debug_exists = os.path.exists(debug_path)
        release_exists = os.path.exists(release_path)

        if not (debug_exists or release_exists): continue

        if debug_exists and not release_exists:
            return 'Debug'

        if release_exists and not debug_exists:
            return 'Release'

        #logging.warning("cccccc %f %f", last_activity(debug_path), last_activity(release_path))

        if last_activity(debug_path) > last_activity(release_path):
            return 'Debug'
        else:
            return 'Release'

    return None

def run(script_file, args, env):

    _python_exe = sys.executable

    _script_file = os.path.abspath(script_file)

    _env_file_dir = os.path.dirname(_script_file)

    _env_values = read_config(_env_file_dir)

    # for visual studio we guess the last built configuration type
    conf_type = guess_configuration_type(_env_values['ENVIRONMENT'])

    if conf_type:
        env['OutDir'] = conf_type
        env['Configuration'] = conf_type

    #logging.warning("guessed %s", conf_type)
    _env = os.environ.copy()

    _env.update(env)

    for key, value in _env_values['ENVIRONMENT']:
        new_value = replace(value, env)
        #logging.warning("YYY %s %s", value, new_value)
        add_path_to_env_variable(_env, key, new_value)

    # add this files directory, too
    add_path_to_env_variable( _env,
            'PYTHONPATH',
            os.path.dirname(os.path.abspath(__file__)))

    if _script_file.endswith('.py'):
        _args = [_python_exe, _script_file] + args
    else:
        _args = [_script_file] + args

    try:
        #logging.warning("XXX %s", _env['YSBOX_IMPORTER'] if 'YSBOX_IMPORTER' in _env else "---")
        _process = subprocess.Popen(
            _args,
            # stdout=subprocess.PIPE,
            cwd     = _env_values['PWD'],
            env     = _env)

        _process_output = _process.communicate()
        _return_value = _process.returncode
        #print _process_output, _return_value

    except OSError, ex:
        logging.error("could not start process from args='%s', cwd='%s'",
                      _args, _env_values['PWD'])
        logging.error("error was '%s'", ex)
        _return_value = -1

    return _return_value

def add_variable(env, variable):
    if not '=' in variable:
        logging.error("given variable definition '%s' is not valid", variable)
        return
    pos = variable.index('=')
    #logging.warning("VVV '%s'='%s'", variable[:pos],variable[pos+1:])
    env[variable[:pos]] = variable[pos+1:]

if __name__ == "__main__":
    logging.basicConfig(
        format='%(asctime)s [env_run] %(levelname)s %(message)s',
        datefmt="%y%m%d-%H%M%S",
        level=logging.WARNING)

    logging.addLevelName( logging.CRITICAL, '(CRITICAL)' )
    logging.addLevelName( logging.ERROR,    '(EE)' )
    logging.addLevelName( logging.WARNING,  '(WW)' )
    logging.addLevelName( logging.INFO,     '(II)' )
    logging.addLevelName( logging.DEBUG,    '(DD)' )
    logging.addLevelName( logging.NOTSET,   '(NA)' )
    _env = {}
    _config_output_dir = None

    # we don't use OptionParser here because we want to pass all arguments
    # coming after the executable name
    _remaining_args = sys.argv[1:]

    while (len(_remaining_args) > 0
       and _remaining_args[0] in ('-v', '--verbose',
                                  '-p', '--python-executable',
                                  '-e', '--set-env',
                                  '-g', '--get-env',
                                  '--configure-variable',
                                  '--configure-pwd',
                                  '--config-output-dir')):

        if (len(_remaining_args) >= 1
           and _remaining_args[0] in ('-v', '--verbose')):
            # in case a config output directory has been provided we save
            # it for later use
            logging.getLogger().setLevel(logging.DEBUG)
            _remaining_args = _remaining_args[1:]

        if (len(_remaining_args) >= 2
           and _remaining_args[0] in ('--config-output-dir')):
            # in case a config output directory has been provided we save
            # it for later use
            _config_output_dir = _remaining_args[1]
            _remaining_args = _remaining_args[2:]

        if (len(_remaining_args) >= 2
           and _remaining_args[0] in ('-g', '--get-env')):
            if _remaining_args[1] in os.environ:
                print(os.environ[_remaining_args[1]])
            else:
                print("")
            sys.exit(0)

        if (len(_remaining_args) >= 2
           and _remaining_args[0] in ('--configure-variable')):
            if not _config_output_dir:
                logging.error("config output directory not set yet")
                sys.exit(-1)
            configure_variable(_config_output_dir, _remaining_args[1])
            _remaining_args = _remaining_args[2:]

        if (len(_remaining_args) >= 2
           and _remaining_args[0] in ('--configure-pwd')):
            if not _config_output_dir:
                logging.error("config output directory not set yet")
                sys.exit(-1)
            configure_pwd(_config_output_dir, _remaining_args[1])
            _remaining_args = _remaining_args[2:]

        if (len(_remaining_args) >= 2
          and _remaining_args[0] in ('-p', '--python-executable')):
            _python_executable = _remaining_args[1]
            _remaining_args = _remaining_args[2:]

        if (len(_remaining_args) >= 2
          and _remaining_args[0] in ('-e', '--set-env')):
            add_variable(_env,_remaining_args[1])
            _remaining_args = _remaining_args[2:]

    logging.info( "started with %s", str(sys.argv) )

    if len(_remaining_args) == 0:
        if _config_output_dir:
            # in case env_run was called in order to set values
            # everything is ok and we can quit
            sys.exit(0)
        else:
            # otherwise the user forgot something important
            logging.error("no script file given")
            sys.exit(-1)

    _script_file = _remaining_args[0]
    _remaining_args = _remaining_args[1:]

    logging.debug("script file:       '%s'", _script_file)
    logging.debug("config_output_dir: '%s'", _config_output_dir)
    logging.debug("args:              '%s'", _remaining_args)
    logging.debug("env:               '%s'", _env)

    sys.exit(run(_script_file, _remaining_args, _env))