text:
///////////////////////////////////////////////////////////////////////////////////////////////////
//This is a boost graph template with bundled property
///////////////////////////////////////////////////////////////////////////////////////////////////
/************************************************************************/
//http://stackoverflow.com/questions/671714/modifying-vertex-properties-in-a-boostgraph
/*   Examples:
struct VertexProperties_graph {
int i;
};

struct EdgeProperties_graph {
};

typedef Graph_bundled<VertexProperties_graph, EdgeProperties_graph> MyGraph;

MyGraph g;

VertexProperties_graph vp;
vp.i = 42;

MyGraph::Vertex v = g.AddVertex(vp);

g.properties(v).i = 23;*/
/************************************************************************/

#ifndef GRAPH_BUNDLED_H_
#define GRAPH_BUNDLED_H_

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/reverse_graph.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/static_assert.hpp>
#include <algorithm> //for std::find_if

using namespace boost;

/* definition of basic boost::graph properties */
enum vertex_properties_t { vertex_properties };
enum edge_properties_t { edge_properties };
//enum graph_properties_t { graph_properties };

namespace boost {
	BOOST_INSTALL_PROPERTY(vertex, properties);
	BOOST_INSTALL_PROPERTY(edge, properties);
	//BOOST_INSTALL_PROPERTY(graph, properties);
}

/* the graph base class template */
template < typename VERTEXPROPERTIES, typename EDGEPROPERTIES >
class Graph_bundled
{
public:
	/* an adjacency_list as we need it */
	/*
	An adjacency_list doesn't have an edge index associated with it, only a vertex index.
	Which is quite logical once you think about how the graph is stored.
	To have an edge index, you need to manually add it to the graph description, and then manually handle it.
	*/
	typedef adjacency_list<
		vecS, // allow parallel edges
		//multisetS, //Specify boost::multisetS as the OutEdgeListS template argument to adjacency_list, this will enable an extra function
		//called edge_range which returns a range of iterators for all the "parallel" edges coming out of u and going into v
		//listS, // doesn't allow parallel edges
		vecS, // vertex container
		bidirectionalS, // directed graph
		/*property<vertex_properties_t, VERTEXPROPERTIES>,*/
		//property<edge_properties_t, EDGEPROPERTIES>

		property<vertex_index_t, std::size_t, property<vertex_properties_t, VERTEXPROPERTIES> >,
		property<edge_index_t, std::size_t, property<edge_properties_t, EDGEPROPERTIES> > //multiple properties
		//edge_index_t is not installed for default, if you want to use get() method to get edge_index, you have to install it explicitly
	> GraphContainer;

	/* a bunch of graph-specific typedefs */
	typedef typename graph_traits<GraphContainer>::vertex_descriptor Vertex;
	typedef std::pair<Vertex, Vertex> VertexPair;
	typedef typename graph_traits<GraphContainer>::edge_descriptor Edge;
	typedef std::pair<Edge, Edge> EdgePair;

	typedef typename graph_traits<GraphContainer>::vertex_iterator vertex_iter;
	typedef typename graph_traits<GraphContainer>::edge_iterator edge_iter;
	typedef typename graph_traits<GraphContainer>::adjacency_iterator adjacency_iter;
	typedef typename graph_traits<GraphContainer>::out_edge_iterator out_edge_iter;

	typedef typename graph_traits<GraphContainer>::degree_size_type degree_t;

	typedef std::pair<adjacency_iter, adjacency_iter> adjacency_vertex_range_t;
	typedef std::pair<out_edge_iter, out_edge_iter> out_edge_range_t;
	typedef std::pair<vertex_iter, vertex_iter> vertex_range_t;
	typedef std::pair<edge_iter, edge_iter> edge_range_t;

	//typedef typename property_map<GraphContainer, edge_index_t>::type edge_index_map_t;

	//typedef for reversed graph
	typedef reverse_graph<GraphContainer> reverse_graph_t;
	typedef typename graph_traits<reverse_graph_t>::vertex_descriptor reverse_vertex_t;
	typedef typename graph_traits<reverse_graph_t>::edge_descriptor reverse_edge_t;

public:
	//visitor for shortest path algotithm, both dijkstra and bellman_ford
	//here we just implement the "edge_relaxed" function so that it could record the edge on the shortest path
	//class my_visitor : public default_bfs_visitor
	//class my_visitor : public dijkstra_visitor<null_visitor>
	class my_visitor : public base_visitor<null_visitor>
	{
	protected:
		//predecessors vector
		std::vector<Vertex>& predecessors;
		//coresponding edges vector of predecessors, edge from current vertex<--predessor coressponds a edge
		std::vector<Edge>& edge_v;

	public:
		template <typename Graph>
		my_visitor(Graph g, std::vector<Vertex>& p, std::vector<Edge>& e_v) :predecessors(p), edge_v(e_v)
		{
			predecessors.resize(num_vertices(g));
			edge_v.resize(num_vertices(g));
		}
	public:
		template <typename Vertex, typename Graph>
		void initialize_vertex(const Vertex &s, const Graph &g) const {}
		template <typename Vertex, typename Graph>
		void discover_vertex(const Vertex &s, const Graph &g) const {}
		template <typename Vertex, typename Graph>
		void examine_vertex(const Vertex &s, const Graph &g) const {}
		template <typename Edge, typename Graph>
		void examine_edge(const Edge &e, const Graph &g) const {}
		//no const statement for this function, gonna change the class itself
		template <typename Edge, typename Graph>
		void edge_relaxed(const Edge &e, const Graph &g)
		{
			auto s = source(e, g);
			auto t = target(e, g);
			//my own way to create predecessor map, or says predecessor vector
			predecessors[t] = s;
			edge_v[t] = e;
			//std::cout << s << "-->" << t << std::endl;

		}
		template <typename Edge, typename Graph>
		void edge_not_relaxed(const Edge &e, const Graph &g) const {}
		template <typename Vertex, typename Graph>
		void finish_vertex(const Vertex &s, const Graph &g) const {}
		//bellman_ford needs this two extra functions
		template <typename Edge, typename Graph>
		void edge_minimized(const Edge &e, const Graph &g) const {}
		template <typename Edge, typename Graph>
		void edge_not_minimized(const Edge &e, const Graph &g) const {}

	};
public:
	//visitor for shortest path algotithm, both dijkstra and bellman_ford
	//here we just implement the "edge_relaxed" function so that it could record the edge on the shortest path
	//class my_visitor : public default_bfs_visitor
	//class my_visitor : public dijkstra_visitor<null_visitor>
	//for reverse graph
	class my_visitor_r : public base_visitor<null_visitor>
	{
	protected:
		//predecessors vector
		std::vector<reverse_vertex_t>& predecessors;
		//coresponding reverse_edge_ts vector of predecessors, reverse_edge_t from current reverse_vertex_t<--predessor coressponds a reverse_edge_t
		std::vector<reverse_edge_t>& reverse_edge_v;

	public:
		template <typename reverse_graph_t>
		my_visitor_r(reverse_graph_t g, std::vector<reverse_vertex_t>& p, std::vector<reverse_edge_t>& e_v) :predecessors(p), reverse_edge_v(e_v)
		{
			predecessors.resize(num_vertices(g));
			reverse_edge_v.resize(num_vertices(g));
		}
	public:
		template <typename reverse_vertex_t, typename reverse_graph_t>
		void initialize_vertex(const reverse_vertex_t &s, const reverse_graph_t &g) const {}
		template <typename reverse_vertex_t, typename reverse_graph_t>
		void discover_vertex(const reverse_vertex_t &s, const reverse_graph_t &g) const {}
		template <typename reverse_vertex_t, typename reverse_graph_t>
		void examine_vertex(const reverse_vertex_t &s, const reverse_graph_t &g) const {}
		template <typename reverse_edge_t, typename reverse_graph_t>
		void examine_edge(const reverse_edge_t &e, const reverse_graph_t &g) const {}
		//no const statement for this function, gonna change the class itself
		template <typename reverse_edge_t, typename reverse_graph_t>
		void edge_relaxed(const reverse_edge_t &e, const reverse_graph_t &g)
		{
			auto s = source(e, g);
			auto t = target(e, g);
			//my own way to create predecessor map, or says predecessor vector
			predecessors[t] = s;
			reverse_edge_v[t] = e;

		}
		template <typename reverse_edge_t, typename reverse_graph_t>
		void edge_not_relaxed(const reverse_edge_t &e, const reverse_graph_t &g) const {}
		template <typename reverse_vertex_t, typename reverse_graph_t>
		void finish_vertex(const reverse_vertex_t &s, const reverse_graph_t &g) const {}
		//bellman_ford needs this two extra functions
		template <typename reverse_edge_t, typename reverse_graph_t>
		void edge_minimized(const reverse_edge_t &e, const reverse_graph_t &g) const {}
		template <typename reverse_edge_t, typename reverse_graph_t>
		void edge_not_minimized(const reverse_edge_t &e, const reverse_graph_t &g) const {}

	};

	/* constructors etc. */
	Graph_bundled() {}

	Graph_bundled(const Graph_bundled& g) : graph(g.graph) {}

	virtual ~Graph_bundled() {}

	/* structure modification methods */
	void Clear()
	{
		graph.clear();
	}

	Vertex AddVertex(const VERTEXPROPERTIES& prop)
	{
		Vertex v = add_vertex(graph);
		properties(v) = prop;
		return v;
	}

	void RemoveVertex(const Vertex& v)
	{
		clear_vertex(v, graph);
		remove_vertex(v, graph);
	}

	Edge AddEdge(const Vertex& v1, const Vertex& v2, const EDGEPROPERTIES& prop_12)
	{
		/* TODO: maybe one wants to check if this edge could be inserted */
		Edge addedEdge = add_edge(v1, v2, graph).first;

		properties(addedEdge) = prop_12;

		return addedEdge;
	}

	EdgePair AddEdge(const Vertex& v1, const Vertex& v2, const EDGEPROPERTIES& prop_12, const EDGEPROPERTIES& prop_21)
	{
		/* TODO: maybe one wants to check if this edge could be inserted */
		Edge addedEdge1 = add_edge(v1, v2, graph).first;
		Edge addedEdge2 = add_edge(v2, v1, graph).first;

		properties(addedEdge1) = prop_12;
		properties(addedEdge2) = prop_21;

		return EdgePair(addedEdge1, addedEdge2);
	}

	/* property access */
	VERTEXPROPERTIES& properties(const Vertex& v)
	{
		typename property_map<GraphContainer, vertex_properties_t>::type param = get(vertex_properties, graph);
		return param[v];
	}

	const VERTEXPROPERTIES& properties(const Vertex& v) const
	{
		typename property_map<GraphContainer, vertex_properties_t>::const_type param = get(vertex_properties, graph);
		return param[v];
	}

	EDGEPROPERTIES& properties(const Edge& v)
	{
		typename property_map<GraphContainer, edge_properties_t>::type param = get(edge_properties, graph);
		return param[v];
	}

	const EDGEPROPERTIES& properties(const Edge& v) const
	{
		typename property_map<GraphContainer, edge_properties_t>::const_type param = get(edge_properties, graph);
		return param[v];
	}

	const EDGEPROPERTIES& properties(const reverse_edge_t& v) const
	{
		//reversed graph
		reverse_graph_t reversed_graph(this->graph);
		typename property_map<reverse_graph_t, edge_properties_t>::const_type param = get(edge_properties, reversed_graph);
		return param[v];
	}

	/* selectors and properties */
	const GraphContainer& getGraph() const
	{
		return graph;
	}

	vertex_range_t getVertices() const
	{
		return vertices(graph);
	}

	std::size_t get_num_vertices() const {
		vertex_range_t vp;
		int count = 0;
		for (vp = vertices(graph); vp.first != vp.second; ++vp.first)
			count++;
		return count;
	}

	edge_range_t getEdges() const
	{
		return edges(graph);
	}

	std::size_t getEdgeCount() const
	{
		return num_edges(graph);
	}

	std::size_t get_num_edges() const {
		edge_range_t ep;
		int count = 0;
		for (ep = edges(graph); ep.first != ep.second; ++ep.first)
			count++;
		return count;
	}

	adjacency_vertex_range_t getAdjacentVertices(const Vertex& v) const
	{
		return adjacent_vertices(v, graph);
	}

	std::size_t getInDegree(const Vertex&v) const {
		return in_degree(v, graph);
	}

	std::size_t getOutDegree(const Vertex&v) const {
		return out_degree(v, graph);
	}

	out_edge_range_t getOutEdges(const Vertex&v) const {
		return out_edges(v, graph);
	}

	std::size_t getVertexCount() const
	{
		return num_vertices(graph);
	}

	std::size_t getVertexDegree(const Vertex& v) const
	{
		return out_degree(v, graph);
	}

	/* operators */
	Graph_bundled& operator=(const Graph_bundled &rhs)
	{
		graph = rhs.graph;
		return *this;
	}

	//find the first edge with specific edge_index
	edge_iter find_edge_with_an_edge_index(size_t x) {
		edge_iter iter_beg, iter_end;
		boost::tie(iter_beg, iter_end) = getEdges();

		//return std::find_if(iter_beg, iter_end, check_x(x));
		for (; iter_beg != iter_end; ++iter_beg) {
			if (properties(*iter_beg).edge_index == x) {
				break;
			}
		}
		return iter_beg;
	}

protected:
	GraphContainer graph;

};

#endif


text:
"""Tests for tf.contrib.training.device_setter."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
from tensorflow.contrib.training.python.training import device_setter as device_setter_lib
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import device_setter
from tensorflow.python.training import server_lib

_CLUSTER_SPEC = server_lib.ClusterSpec({
    "ps": ["ps0:2222", "ps1:2222"],
    "worker": ["worker0:2222", "worker1:2222", "worker2:2222"]
})

MockOperation = collections.namedtuple("MockOperation", "name")

class RandomStrategyTest(test.TestCase):

  def testBasic(self):
    ps_strategy = device_setter_lib.RandomStrategy(2, seed=0)
    with ops.device(
        device_setter.replica_device_setter(
            cluster=_CLUSTER_SPEC,
            ps_strategy=ps_strategy)):
      u = variables.Variable(array_ops.zeros([2, 2]))
      v = variables.Variable(array_ops.zeros([2, 1]))
      w = variables.Variable(array_ops.zeros([2, 2]))
      x = variables.Variable(array_ops.zeros([1, 3]))
      a = v + w
      # Randomly distributed with seed 0.
      self.assertDeviceEqual("/job:ps/task:1", u.device)
      self.assertDeviceEqual("/job:ps/task:1", u.initializer.device)
      self.assertDeviceEqual("/job:ps/task:0", v.device)
      self.assertDeviceEqual("/job:ps/task:0", v.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", w.device)
      self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", x.device)
      self.assertDeviceEqual("/job:ps/task:1", x.initializer.device)
      self.assertDeviceEqual("/job:worker", a.device)

  def testHandlesUnicode(self):
    op = MockOperation(u"A unicode \u018e string \xf1")
    ps_strategy = device_setter_lib.RandomStrategy(2, seed=0)
    ps_task = ps_strategy(op)
    self.assertEqual(ps_task, 1)

class GreedyLoadBalancingStrategyTest(test.TestCase):

  def testUniformLoadEqualsRoundRobin(self):

    def _load_fn(unused_op):
      return 1

    with ops.device(
        device_setter.replica_device_setter(
            cluster=_CLUSTER_SPEC,
            ps_strategy=device_setter_lib.GreedyLoadBalancingStrategy(
                2, _load_fn))):
      u = variables.Variable(array_ops.zeros([2, 2]))
      v = variables.Variable(array_ops.zeros([2, 1]))
      w = variables.Variable(array_ops.zeros([2, 2]))
      x = variables.Variable(array_ops.zeros([1, 3]))
      a = v + w
      self.assertDeviceEqual("/job:ps/task:0", u.device)
      self.assertDeviceEqual("/job:ps/task:0", u.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", v.device)
      self.assertDeviceEqual("/job:ps/task:1", v.initializer.device)
      self.assertDeviceEqual("/job:ps/task:0", w.device)
      self.assertDeviceEqual("/job:ps/task:0", w.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", x.device)
      self.assertDeviceEqual("/job:ps/task:1", x.initializer.device)
      self.assertDeviceEqual("/job:worker", a.device)

  def testByteSizeLoadFn(self):
    with ops.device(
        device_setter.replica_device_setter(
            cluster=_CLUSTER_SPEC,
            ps_strategy=device_setter_lib.GreedyLoadBalancingStrategy(
                2, device_setter_lib.byte_size_load_fn))):
      u = variables.VariableV1(array_ops.zeros([2, 2]))
      v = variables.VariableV1(array_ops.zeros([2, 1]))
      w = variables.VariableV1(array_ops.zeros([2, 2]))
      x = variables.VariableV1(array_ops.zeros([1, 3]))
      a = v + w
      self.assertDeviceEqual("/job:ps/task:0", u.device)
      self.assertDeviceEqual("/job:ps/task:0", u.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", v.device)
      self.assertDeviceEqual("/job:ps/task:1", v.initializer.device)
      self.assertDeviceEqual("/job:ps/task:1", w.device)
      self.assertDeviceEqual("/job:ps/task:1", w.initializer.device)
      self.assertDeviceEqual("/job:ps/task:0", x.device)
      self.assertDeviceEqual("/job:ps/task:0", x.initializer.device)
      self.assertDeviceEqual("/job:worker", a.device)

  def testByteSizeLoadFnWithScalar(self):
    with ops.device(
        device_setter.replica_device_setter(
            cluster=_CLUSTER_SPEC,
            ps_strategy=device_setter_lib.GreedyLoadBalancingStrategy(
                2, device_setter_lib.byte_size_load_fn))):
      # Note: we must test the load function as part of the device function
      # instead of passing u.op to the function directly, because the only
      # time that the output Tensor has unknown shape for scalars is during
      # Variable construction.
      u = variables.Variable(0)
      self.assertDeviceEqual("/job:ps/task:0", u.device)
      self.assertDeviceEqual("/job:ps/task:0", u.initializer.device)

if __name__ == "__main__":
  test.main()

redpajama_set_name: RedPajamaGithub


text:
@implementation TYLayoutItem
@synthesize align;
@synthesize rect;
@synthesize view;
@synthesize margin;

- (id)initWithView:(UIView *)aView margin:(CGBorder)aMargin align:(TYLayoutAlign)anAlign {
    self = [super init];
    if (self) {
        view = aView;
        rect = [aView frame];
        margin = aMargin;
        align = anAlign;
    }

    return self;
}

- (id)initWithRect:(CGRect)aRect margin:(CGBorder)aMargin align:(TYLayoutAlign)anAlign {
    self = [super init];
    if (self) {
        rect = aRect;
        margin = aMargin;
        align = anAlign;
    }

    return self;
}

- (CGFloat)getX {
    return rect.origin.x;
}

- (CGFloat)getY {
    return rect.origin.y;
}

- (CGFloat)getHeight {
    return rect.size.height;
}

- (CGFloat)getWidth {
    return rect.size.width;
}

- (CGFloat)getCalculatedHeight {
    return [self getHeight] + [self getVerticalMargin];
}

- (CGFloat)getCalculatedWidth {
    return [self getWidth] + [self getHorizontalMargin];
}

- (CGFloat)getVerticalMargin {
    return margin.top + margin.bottom;
}

- (CGFloat)getHorizontalMargin {
    return margin.left + margin.right;
}

@end


text:
(function (PlayerFramework, undefined) {
    "use strict";

    // MastSchedulerPlugin Errors
    var invalidConstruction = "Invalid construction: MastSchedulerPlugin constructor must be called using the \"new\" operator.";

    // MastSchedulerPlugin Class
    var MastSchedulerPlugin = WinJS.Class.derive(PlayerFramework.PluginBase, function (options) {
        if (!(this instanceof PlayerFramework.Plugins.MastSchedulerPlugin)) {
            throw invalidConstruction;
        }

        this._activeTriggers = [];

        PlayerFramework.PluginBase.call(this, options);
    }, {
        // Public Properties
        source: {
            get: function () {
                return this._source;
            },
            set: function (value) {
                this._source = value;
            }
        },

        activeTriggers: {
            get: function () {
                return this._activeTriggers;
            }
        },

        // Public Methods
        loadAds: function (source) {
            this._mainsail.clear();

            var promise = this._mainsail.loadSource(new Windows.Foundation.Uri(source));

            promise.done(
                function () {
                    PlayerFramework.Utilities.remove(this._activePromises, promise);
                }.bind(this),
                function (e) {
                    PlayerFramework.Utilities.remove(this._activePromises, promise);
                }.bind(this)
            );

            this._activePromises.push(promise);
            return promise;
        },

        cancelActiveTriggers: function () {
            for (var i = 0; i < this._activeTriggers.length; i++) {
                var trigger = this._activeTriggers[i];
                trigger.promise.cancel();
            }

            this._activeTriggers = [];
        },

        // Private Methods
        _setOptions: function (options) {
            PlayerFramework.Utilities.setOptions(this, options, {
                isEnabled: true,
                source: null
            });
        },

        _onLoad: function () {
            this._isStarted = false;
            this._mastAdapter = new Microsoft.PlayerFramework.Js.Advertising.MastAdapter();
            this._mainsail = new Microsoft.Media.Advertising.Mainsail(this._mastAdapter);
        },

        _onUnload: function () {
            this._isStarted = false;
            this._mastAdapter = null;
            this._mainsail.MastInterface = null;
            this._mainsail = null;
        },

        _onActivate: function () {
            this._bindEvent("activatetrigger", this._mainsail, this._onMainsailActivateTrigger);
            this._bindEvent("deactivatetrigger", this._mainsail, this._onMainsailDeactivateTrigger);
            this._bindEvent("canplay", this.mediaPlayer, this._onMediaPlayerCanPlay);
            this._bindEvent("play", this.mediaPlayer, this._onMediaPlayerPlay);
            this._bindEvent("pause", this.mediaPlayer, this._onMediaPlayerPause);
            this._bindEvent("stopped", this.mediaPlayer, this._onMediaPlayerStopped);
            this._bindEvent("seeked", this.mediaPlayer, this._onMediaPlayerSeeked);
            this._bindEvent("loading", this.mediaPlayer, this._onMediaPlayerLoading);
            this._bindEvent("starting", this.mediaPlayer, this._onMediaPlayerStarting);
            this._bindEvent("ending", this.mediaPlayer, this._onMediaPlayerEnding);
            this._bindEvent("timeupdate", this.mediaPlayer, this._onMediaPlayerTimeUpdate);
            this._bindEvent("durationchange", this.mediaPlayer, this._onMediaPlayerDurationChange);
            this._bindEvent("volumechange", this.mediaPlayer, this._onMediaPlayerVolumeChange);
            this._bindEvent("mutedchange", this.mediaPlayer, this._onMediaPlayerMutedChange);
            this._bindEvent("fullscreenchange", this.mediaPlayer, this._onMediaPlayerFullScreenChange);
            this._bindEvent("error", this.mediaPlayer, this._onMediaPlayerError);
            if (this.mediaPlayer.element.onresize !== undefined) {
                this._bindEvent("resize", this.mediaPlayer.element, this._onMediaPlayerResize);
            }
            else { // IE11 no longer supports resize event for arbitrary elements. The best we can do is listen to the window resize event.
                this._bindEvent("resize", window, this._onMediaPlayerResize);
            }
            if (window.PointerEvent) {
                this._bindEvent("pointerover", this.mediaPlayer.element, this._onMediaPlayerMSPointerOver);
            }
            else {
                this._bindEvent("MSPointerOver", this.mediaPlayer.element, this._onMediaPlayerMSPointerOver);
            }

            this._mastAdapter.setContentTitle("");
            this._mastAdapter.setContentUrl(this.mediaPlayer.src);
            this._mastAdapter.setContentBitrate(0);
            this._mastAdapter.setContentWidth(0);
            this._mastAdapter.setContentHeight(0);
            this._mastAdapter.setPosition(0);
            this._mastAdapter.setDuration(0);
            this._mastAdapter.setPlayerWidth(this.mediaPlayer.element.scrollWidth);
            this._mastAdapter.setPlayerHeight(this.mediaPlayer.element.scrollHeight);
            this._mastAdapter.setFullScreen(this.mediaPlayer.isFullScreen);
            this._mastAdapter.setHasAudio(true);
            this._mastAdapter.setHasVideo(true);
            this._mastAdapter.setHasCaptions(this.mediaPlayer.captionTracks && this.mediaPlayer.captionTracks.length > 0);
            this._mastAdapter.setCaptionsActive(!!this.mediaPlayer.currentCaptionTrack);

            return true;
        },

        _onDeactivate: function () {
            this._mastAdapter.invokeEnd();

            this.cancelActiveTriggers();
            this._mainsail.clear();

            this._unbindEvent("activatetrigger", this._mainsail, this._onMainsailActivateTrigger);
            this._unbindEvent("deactivatetrigger", this._mainsail, this._onMainsailDeactivateTrigger);
            this._unbindEvent("canplay", this.mediaPlayer, this._onMediaPlayerCanPlay);
            this._unbindEvent("play", this.mediaPlayer, this._onMediaPlayerPlay);
            this._unbindEvent("pause", this.mediaPlayer, this._onMediaPlayerPause);
            this._unbindEvent("stopped", this.mediaPlayer, this._onMediaPlayerStopped);
            this._unbindEvent("seeked", this.mediaPlayer, this._onMediaPlayerSeeked);
            this._unbindEvent("loading", this.mediaPlayer, this._onMediaPlayerLoading);
            this._unbindEvent("starting", this.mediaPlayer, this._onMediaPlayerStarting);
            this._unbindEvent("ending", this.mediaPlayer, this._onMediaPlayerEnding);
            this._unbindEvent("timeupdate", this.mediaPlayer, this._onMediaPlayerTimeUpdate);
            this._unbindEvent("durationchange", this.mediaPlayer, this._onMediaPlayerDurationChange);
            this._unbindEvent("volumechange", this.mediaPlayer, this._onMediaPlayerVolumeChange);
            this._unbindEvent("mutedchange", this.mediaPlayer, this._onMediaPlayerMutedChange);
            this._unbindEvent("fullscreenchange", this.mediaPlayer, this._onMediaPlayerFullScreenChange);
            this._unbindEvent("error", this.mediaPlayer, this._onMediaPlayerError);
            if (this.mediaPlayer.element.onresize !== undefined) {
                this._unbindEvent("resize", this.mediaPlayer.element, this._onMediaPlayerResize);
            }
            else { // IE11 no longer supports resize event for arbitrary elements. The best we can do is listen to the window resize event.
                this._unbindEvent("resize", window, this._onMediaPlayerResize);
            }
            if (window.PointerEvent) {
                this._unbindEvent("pointerover", this.mediaPlayer.element, this._onMediaPlayerMSPointerOver);
            }
            else {
                this._unbindEvent("MSPointerOver", this.mediaPlayer.element, this._onMediaPlayerMSPointerOver);
            }
        },

        _onUpdate: function () {
            this.cancelActiveTriggers();
            this._mainsail.clear();

            this._mastAdapter.setContentTitle("");
            this._mastAdapter.setContentUrl(this.mediaPlayer.src);
            this._mastAdapter.setContentBitrate(0);
            this._mastAdapter.setContentWidth(0);
            this._mastAdapter.setContentHeight(0);
            this._mastAdapter.setPosition(0);
            this._mastAdapter.setDuration(0);
            this._mastAdapter.setPlayerWidth(this.mediaPlayer.element.scrollWidth);
            this._mastAdapter.setPlayerHeight(this.mediaPlayer.element.scrollHeight);
            this._mastAdapter.setFullScreen(this.mediaPlayer.isFullScreen);
            this._mastAdapter.setHasAudio(true);
            this._mastAdapter.setHasVideo(true);
            this._mastAdapter.setHasCaptions(this.mediaPlayer.captionTracks && this.mediaPlayer.captionTracks.length > 0);
            this._mastAdapter.setCaptionsActive(!!this.mediaPlayer.currentCaptionTrack);
        },

        _onMainsailActivateTrigger: function (e) {
            if (e.trigger.sources.length) {
                var source = e.trigger.sources[0];
                var sourceUri = new Windows.Foundation.Uri(source.uri);
                var remoteSource = new Microsoft.PlayerFramework.Js.Advertising.RemoteAdSource(sourceUri, source.format);
                var promise = this.mediaPlayer.adHandlerPlugin.playAd(remoteSource).then(null, function () { /* swallow */ });
                var trigger = { trigger: e.trigger, promise: promise };

                promise.done(
                    function () {
                        PlayerFramework.Utilities.remove(this._activeTriggers, trigger);
                    }.bind(this)
                );

                this._activeTriggers.push(trigger);
            }
        },

        _onMainsailDeactivateTrigger: function (e) {
            for (var i = 0; i < this._activeTriggers.length; i++) {
                var trigger = this._activeTriggers[i];
                if (trigger === e.trigger) {
                    trigger.promise.cancel();
                    PlayerFramework.Utilities.remove(this._activeTriggers, trigger);
                    return;
                }
            }
        },

        _onMediaPlayerCanPlay: function (e) {
            this._mastAdapter.setContentWidth(this.mediaPlayer.videoWidth);
            this._mastAdapter.setContentHeight(this.mediaPlayer.videoHeight);
        },

        _onMediaPlayerPlay: function (e) {
            this._mastAdapter.invokePlay();
        },

        _onMediaPlayerPause: function (e) {
            this._mastAdapter.invokePause();
        },

        _onMediaPlayerStopped: function (e) {
            this._mastAdapter.invokeStop();
        },

        _onMediaPlayerSeeked: function (e) {
            this._mastAdapter.invokeSeek();
        },

        _onMediaPlayerLoading: function (e) {
            if (this.source) {
                var promise = this.loadAds(this.source);
                e.detail.setPromise(promise);
            }
        },

        _onMediaPlayerStarting: function (e) {
            if (!this._isStarted) {
                this._isStarted = true;
                this._mastAdapter.invokeItemStart();

                if (this.mediaPlayer.allowStartingDeferrals) {
                    var triggerPromises = [];

                    for (var i = 0; i < this._activeTriggers.length; i++) {
                        var trigger = this._activeTriggers[i];
                        triggerPromises.push(trigger.promise);
                    }

                    var promise = WinJS.Promise.join(triggerPromises);

                    promise.done(
                        function () {
                            PlayerFramework.Utilities.remove(this._activePromises, promise);
                        }.bind(this),
                        function (e) {
                            PlayerFramework.Utilities.remove(this._activePromises, promise);
                        }.bind(this)
                    );

                    this._activePromises.push(promise);
                    e.detail.setPromise(promise);
                }
            }
        },

        _onMediaPlayerEnding: function (e) {
            var activeTriggersBeforeEnd = [];
            var activeTriggerPromises = [];

            for (var i = 0; i < this._activeTriggers.length; i++) {
                var trigger = this._activeTriggers[i];
                activeTriggersBeforeEnd.push(trigger);
            }

            this._mastAdapter.invokeItemEnd();

            for (var i = 0; i < this._activeTriggers.length; i++) {
                var trigger = this._activeTriggers[i];
                if (activeTriggersBeforeEnd.indexOf(trigger) === -1) {
                    activeTriggerPromises.push(trigger.promise);
                }
            }

            if (activeTriggerPromises.length) {
                var promise = WinJS.Promise.join(activeTriggerPromises);

                promise.done(
                    function () {
                        PlayerFramework.Utilities.remove(this._activePromises, promise);
                    }.bind(this),
                    function (e) {
                        PlayerFramework.Utilities.remove(this._activePromises, promise);
                    }.bind(this)
                );

                this._activePromises.push(promise);
                e.detail.setPromise(promise);
            }
        },

        _onMediaPlayerTimeUpdate: function (e) {
            if (this._mastAdapter.isPlaying && !this.mediaPlayer.scrubbing) {
                this._mastAdapter.setPosition(this.mediaPlayer.currentTime * 1000);
                this._mainsail.evaluateTriggers();
            }
        },

        _onMediaPlayerDurationChange: function (e) {
            this._mastAdapter.setDuration(this.mediaPlayer.duration * 1000);
        },

        _onMediaPlayerVolumeChange: function (e) {
            this._mastAdapter.invokeVolumeChange();
        },

        _onMediaPlayerMutedChange: function (e) {
            if (this.mediaPlayer.muted) {
                this._mastAdapter.invokeMute();
            }
        },

        _onMediaPlayerFullScreenChange: function (e) {
            this._mastAdapter.invokeFullScreenChange();
        },

        _onMediaPlayerError: function (e) {
            this._mastAdapter.invokeError();
        },

        _onMediaPlayerResize: function (e) {
            this._mastAdapter.invokePlayerSizeChanged();
            this._mastAdapter.setPlayerWidth(this.mediaPlayer.element.scrollWidth);
            this._mastAdapter.setPlayerHeight(this.mediaPlayer.element.scrollHeight);
        },

        _onMediaPlayerMSPointerOver: function (e) {
            this._mastAdapter.invokeMouseOver();
        }
    });

    // MastSchedulerPlugin Mixins
    WinJS.Class.mix(PlayerFramework.MediaPlayer, {
        mastSchedulerPlugin: {
            value: null,
            writable: true,
            configurable: true
        }
    });

    // MastSchedulerPlugin Exports
    WinJS.Namespace.define("PlayerFramework.Plugins", {
        MastSchedulerPlugin: MastSchedulerPlugin
    });

})(PlayerFramework);


text:
package ctxlog_test

import (
	"testing"

	"github.com/corestoreio/csfw/net/ctxlog"
	"github.com/corestoreio/csfw/util/log"
	"github.com/stretchr/testify/assert"
	"golang.org/x/net/context"
)

func TestContext(t *testing.T) {
	l := log.NewStdLogger()
	ctx := context.Background()
	ctx = ctxlog.WithContext(ctx, l)

	haveL := ctxlog.FromContext(ctx)
	assert.Exactly(t, l, haveL)

	haveL2 := ctxlog.FromContext(context.TODO())
	assert.Exactly(t, log.BlackHole{}, haveL2)
}


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

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Far Distance Threshold(m)"/>
    <include android:id="@+id/far_distance_threshold" layout="@layout/increment_decrement" />

    <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@android:color/darker_gray"/>

    <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mid Distance Threshold(m)"/>
    <include android:id="@+id/mid_distance_threshold" layout="@layout/increment_decrement" />

    <Button
        android:id="@+id/done"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Done" />
</LinearLayout>


text:
package br.com.adley.whatsnextseries.holders;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import br.com.adley.whatsnextseries.R;

/**
 * Created by Adley on 28/04/2016.
 * View Holder for List of seasons
 */
public class ListEpisodesViewHolder extends RecyclerView.ViewHolder{
    private TextView mEpisodeNumber;
    private TextView mEpisodeName;
    private ImageView mStillImg;
    private TextView mOverview;
    private TextView mAirDate;

    public TextView getEpisodeNumber() {
        return mEpisodeNumber;
    }

    public TextView getEpisodeName() {
        return mEpisodeName;
    }

    public ImageView getStillImg() {
        return mStillImg;
    }

    public TextView getOverview() {
        return mOverview;
    }

    public TextView getAirDate() {
        return mAirDate;
    }

    public ListEpisodesViewHolder(View view) {
        super(view);
        mEpisodeName = (TextView) view.findViewById(R.id.season_name);
        mEpisodeNumber = (TextView) view.findViewById(R.id.episode_number);
        mAirDate = (TextView) view.findViewById(R.id.air_date_text);
        mOverview = (TextView) view.findViewById(R.id.overview_text);
        mStillImg = (ImageView) view.findViewById(R.id.episode_image);
    }
}


text:
using namespace triagens;
using namespace triagens::basics;
using namespace triagens::arango;
using namespace triagens::rest;
using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                        class GlobalContextMethods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief reload the routing cache
////////////////////////////////////////////////////////////////////////////////

char const* GlobalContextMethods::CodeReloadRouting
  = "require(\"org/arangodb/actions\").reloadRouting()";

////////////////////////////////////////////////////////////////////////////////
/// @brief reload AQL functions
////////////////////////////////////////////////////////////////////////////////

char const* GlobalContextMethods::CodeReloadAql
  = "try { require(\"org/arangodb/aql\").reload(); } catch (err) { }";

////////////////////////////////////////////////////////////////////////////////
/// @brief bootstrap coordinator
////////////////////////////////////////////////////////////////////////////////

char const* GlobalContextMethods::CodeBootstrapCoordinator
  = "require('internal').loadStartup('server/bootstrap/autoload.js').startup();"
    "require('internal').loadStartup('server/bootstrap/routing.js').startup();";

////////////////////////////////////////////////////////////////////////////////
/// @brief warmup the exports
////////////////////////////////////////////////////////////////////////////////

char const* GlobalContextMethods::CodeWarmupExports
  = "require(\"org/arangodb/actions\").warmupExports()";

////////////////////////////////////////////////////////////////////////////////
/// @brief we'll store deprecated config option values in here
////////////////////////////////////////////////////////////////////////////////

static std::string DeprecatedPath;

static bool DeprecatedOption;

// -----------------------------------------------------------------------------
// --SECTION--                                                  class V8GcThread
// -----------------------------------------------------------------------------

namespace {

////////////////////////////////////////////////////////////////////////////////
/// @brief garbage collector
////////////////////////////////////////////////////////////////////////////////

  class V8GcThread : public Thread {
    public:
      V8GcThread (ApplicationV8* applicationV8)
        : Thread("v8-gc"),
          _applicationV8(applicationV8),
          _lastGcStamp(static_cast<uint64_t>(TRI_microtime())) {
      }

    public:

////////////////////////////////////////////////////////////////////////////////
/// @brief collect garbage in an endless loop (main functon of GC thread)
////////////////////////////////////////////////////////////////////////////////

      void run () {
        _applicationV8->collectGarbage();
      }

////////////////////////////////////////////////////////////////////////////////
/// @brief get the timestamp of the last GC
////////////////////////////////////////////////////////////////////////////////

      double getLastGcStamp () {
        return static_cast<double>(_lastGcStamp.load(std::memory_order_acquire));
      }

////////////////////////////////////////////////////////////////////////////////
/// @brief set the global GC timestamp
////////////////////////////////////////////////////////////////////////////////

      void updateGcStamp (double value) {
        _lastGcStamp.store(static_cast<uint64_t>(value), std::memory_order_release);
      }

    private:

      ApplicationV8*        _applicationV8;
      std::atomic<uint64_t> _lastGcStamp;
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   class V8Context
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief adds a global method
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::V8Context::addGlobalContextMethod (string const& method) {
  GlobalContextMethods::MethodType type = GlobalContextMethods::getType(method);

  if (type == GlobalContextMethods::TYPE_UNKNOWN) {
    return false;
  }

  MUTEX_LOCKER(_globalMethodsLock);

  for (size_t i = 0; i < _globalMethods.size(); ++i) {
    if (_globalMethods[i] == type) {
      // action is already registered. no need to register it again
      return true;
    }
  }

  // insert action into vector
  _globalMethods.emplace_back(type);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes all global methods
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::V8Context::handleGlobalContextMethods () {
  vector<GlobalContextMethods::MethodType> copy;

  try {
    // we need to copy the vector of functions so we do not need to hold the
    // lock while we execute them
    // this avoids potential deadlocks when one of the executed functions itself
    // registers a context method

    MUTEX_LOCKER(_globalMethodsLock);
    copy = _globalMethods;
    _globalMethods.clear();
  }
  catch (...) {
    // if we failed, we shouldn't have modified _globalMethods yet, so we can
    // try again on the next invocation
    return;
  }

  for (auto& type : copy) {
    char const* func = GlobalContextMethods::getCode(type);
    // all functions are hard-coded, static const char*s
    TRI_ASSERT(func != nullptr);

    LOG_DEBUG("executing global context methods '%s' for context %d", func, (int) _id);

    TRI_GET_GLOBALS();
    bool allowUseDatabase = v8g->_allowUseDatabase;
    v8g->_allowUseDatabase = true;

    v8::TryCatch tryCatch;

    TRI_ExecuteJavaScriptString(isolate,
                                isolate->GetCurrentContext(),
                                TRI_V8_ASCII_STRING(func),
                                TRI_V8_ASCII_STRING("global context method"),
                                false);

    if (tryCatch.HasCaught()) {
      if (tryCatch.CanContinue()) {
        TRI_LogV8Exception(isolate, &tryCatch);
      }
    }

    v8g->_allowUseDatabase = allowUseDatabase;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the cancelation cleanup
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::V8Context::handleCancelationCleanup () {
  v8::HandleScope scope(isolate);

  LOG_DEBUG("executing cancelation cleanup context %d", (int) _id);

  TRI_ExecuteJavaScriptString(isolate,
                              isolate->GetCurrentContext(),
                              TRI_V8_ASCII_STRING("require('internal').cleanupCancelation();"),
                              TRI_V8_ASCII_STRING("context cleanup method"),
                              false);
}

// -----------------------------------------------------------------------------
// --SECTION--                                               class ApplicationV8
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

ApplicationV8::ApplicationV8 (TRI_server_t* server,
                              triagens::aql::QueryRegistry* queryRegistry,
                              ApplicationScheduler* scheduler,
                              ApplicationDispatcher* dispatcher)
  : ApplicationFeature("V8"),
    _server(server),
    _queryRegistry(queryRegistry),
    _startupPath(),
    _appPath(),
    _devAppPath(),
    _useActions(true),
    _frontendVersionCheck(true),
    _gcInterval(1000),
    _gcFrequency(10.0),
    _v8Options(""),
    _startupLoader(),
    _vocbase(nullptr),
    _nrInstances(0),
    _contexts(),
    _contextCondition(),
    _freeContexts(),
    _dirtyContexts(),
    _busyContexts(),
    _stopping(false),
    _gcThread(nullptr),
    _scheduler(scheduler),
    _dispatcher(dispatcher),
    _definedBooleans(),
    _definedDoubles(),
    _startupFile("server/server.js"),
    _gcFinished(false),
    _platform(nullptr) {

  TRI_ASSERT(_server != nullptr);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

ApplicationV8::~ApplicationV8 () {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief sets the concurrency
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::setConcurrency (size_t n) {
  _nrInstances = n;

  _busyContexts.reserve(n);
  _freeContexts.reserve(n);
  _dirtyContexts.reserve(n);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief sets the database
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::setVocbase (TRI_vocbase_t* vocbase) {
  _vocbase = vocbase;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief enters a context
////////////////////////////////////////////////////////////////////////////////

ApplicationV8::V8Context* ApplicationV8::enterContext (TRI_vocbase_t* vocbase,
                                                       bool allowUseDatabase) {
  v8::Isolate* isolate = nullptr;
  V8Context* context   = nullptr;

  {
    CONDITION_LOCKER(guard, _contextCondition);

    while (_freeContexts.empty() && ! _stopping) {
      LOG_DEBUG("waiting for unused V8 context");

      if (! _dirtyContexts.empty()) {
        // we'll use a dirty context in this case
        auto context = _dirtyContexts.back();
        _freeContexts.emplace_back(context);
        _dirtyContexts.pop_back();
      }
      else {
        auto currentThread = triagens::rest::DispatcherThread::currentDispatcherThread;

        if (currentThread != nullptr) {
          triagens::rest::DispatcherThread::currentDispatcherThread->block();
        }
        guard.wait();
        if (currentThread != nullptr) {
          triagens::rest::DispatcherThread::currentDispatcherThread->unblock();
        }
      }
    }

    // in case we are in the shutdown phase, do not enter a context!
    // the context might have been deleted by the shutdown
    if (_stopping) {
      return nullptr;
    }

    LOG_TRACE("found unused V8 context");
    TRI_ASSERT(! _freeContexts.empty());

    context = _freeContexts.back();
    TRI_ASSERT(context != nullptr);

    isolate = context->isolate;

    _freeContexts.pop_back();
    // should not fail because we reserved enough space beforehand
    _busyContexts.emplace(context);
  }

  // when we get here, we should have a context and an isolate
  TRI_ASSERT(context != nullptr);
  TRI_ASSERT(isolate != nullptr);

  context->_locker = new v8::Locker(isolate);
  context->isolate->Enter();

  v8::HandleScope scope(isolate);
  auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
  localContext->Enter();
  {
    v8::Context::Scope contextScope(localContext);

    TRI_ASSERT(context->_locker->IsLocked(isolate));
    TRI_ASSERT(v8::Locker::IsLocked(isolate));
    TRI_GET_GLOBALS();

    // initialize the context data
    v8g->_query              = nullptr;
    v8g->_vocbase            = vocbase;
    v8g->_allowUseDatabase   = allowUseDatabase;

    TRI_UseVocBase(vocbase);

    LOG_TRACE("entering V8 context %d", (int) context->_id);
    context->handleGlobalContextMethods();
  }

  return context;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief exits a context
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::exitContext (V8Context* context) {
  V8GcThread* gc = dynamic_cast<V8GcThread*>(_gcThread);
  TRI_ASSERT(gc != nullptr);

  LOG_TRACE("leaving V8 context %d", (int) context->_id);
  double lastGc = gc->getLastGcStamp();

  auto isolate = context->isolate;

  TRI_ASSERT(context->_locker->IsLocked(isolate));
  TRI_ASSERT(v8::Locker::IsLocked(isolate));

  // update data for later garbage collection
  TRI_GET_GLOBALS();
  context->_hasActiveExternals = v8g->hasActiveExternals();
  ++context->_numExecutions;

  TRI_ASSERT(v8g->_vocbase != nullptr);
  // release last recently used vocbase
  TRI_ReleaseVocBase(static_cast<TRI_vocbase_t*>(v8g->_vocbase));

  // check for cancelation requests
  bool const canceled = v8g->_canceled;
  v8g->_canceled = false;

  // check if we need to execute global context methods
  bool runGlobal = false;

  {
    MUTEX_LOCKER(context->_globalMethodsLock);
    runGlobal = ! context->_globalMethods.empty();
  }

  // exit the context
  {
    v8::HandleScope scope(isolate);

    // if the execution was canceled, we need to cleanup
    if (canceled) {
      context->handleCancelationCleanup();
    }

    // run global context methods
    if (runGlobal) {
      TRI_ASSERT(context->_locker->IsLocked(isolate));
      TRI_ASSERT(v8::Locker::IsLocked(isolate));

      context->handleGlobalContextMethods();
    }

    // now really exit
    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
    localContext->Exit();
  }
  isolate->Exit();

  delete context->_locker;
  context->_locker = nullptr;

  TRI_ASSERT(! v8::Locker::IsLocked(isolate));

  // reset the context data. garbage collection should be able to run without it
  v8g->_query              = nullptr;
  v8g->_vocbase            = nullptr;
  v8g->_allowUseDatabase   = false;

  LOG_TRACE("returned dirty V8 context");

  // default is false
  bool performGarbageCollection = false;

  // postpone garbage collection for standard contexts
  if (context->_lastGcStamp + _gcFrequency < lastGc) {
    LOG_TRACE("V8 context has reached GC timeout threshold and will be scheduled for GC");
    performGarbageCollection = true;
  }
  else if (context->_numExecutions >= _gcInterval) {
    LOG_TRACE("V8 context has reached maximum number of requests and will be scheduled for GC");
    performGarbageCollection = true;
  }

  {
    CONDITION_LOCKER(guard, _contextCondition);

    if (performGarbageCollection && ! _freeContexts.empty()) {
      // only add the context to the dirty list if there is at least one other free context
      _dirtyContexts.emplace_back(context);
    }
    else {
      _freeContexts.emplace_back(context);
    }

    _busyContexts.erase(context);

    guard.broadcast();
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief adds a global context function to be executed asap
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::addGlobalContextMethod (string const& method) {
  bool result = true;
  size_t nrInstances = _nrInstances;

  try {
    for (size_t i = 0; i < nrInstances; ++i) {
      if (! _contexts[i]->addGlobalContextMethod(method)) {
        result = false;
      }
    }
  }
  catch (...) {
    result = false;
  }

  return result;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs the garbage collection
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::collectGarbage () {
  V8GcThread* gc = dynamic_cast<V8GcThread*>(_gcThread);
  TRI_ASSERT(gc != nullptr);

  // this flag will be set to true if we timed out waiting for a GC signal
  // if set to true, the next cycle will use a reduced wait time so the GC
  // can be performed more early for all dirty contexts. The flag is set
  // to false again once all contexts have been cleaned up and there is nothing
  // more to do
  bool useReducedWait = false;

  // the time we'll wait for a signal
  uint64_t const regularWaitTime = (uint64_t) (_gcFrequency * 1000.0 * 1000.0);

  // the time we'll wait for a signal when the previous wait timed out
  uint64_t const reducedWaitTime = (uint64_t) (_gcFrequency * 1000.0 * 200.0);

  while (_stopping == 0) {
    V8Context* context = nullptr;

    {
      bool gotSignal = false;
      CONDITION_LOCKER(guard, _contextCondition);

      if (_dirtyContexts.empty()) {
        uint64_t waitTime = useReducedWait ? reducedWaitTime : regularWaitTime;

        // we'll wait for a signal or a timeout
        gotSignal = guard.wait(waitTime);

        // use a reduced wait time in the next round because we seem to be idle
        // the reduced wait time will allow to perfom GC for more contexts
        useReducedWait = ! gotSignal;
      }

      if (! _dirtyContexts.empty()) {
        context = _dirtyContexts.back();
        _dirtyContexts.pop_back();
        useReducedWait = false;
      }
      else if (! gotSignal && ! _freeContexts.empty()) {
        // we timed out waiting for a signal, so we have idle time that we can
        // spend on running the GC pro-actively
        // We'll pick one of the free contexts and clean it up
        context = pickFreeContextForGc();

        // there is no context to clean up, probably they all have been cleaned up
        // already. increase the wait time so we don't cycle too much in the GC loop
        // and waste CPU unnecessary
        useReducedWait = (context != nullptr);
      }
      else {
        useReducedWait = false;
      }
    }

    // update last gc time
    double lastGc = TRI_microtime();
    gc->updateGcStamp(lastGc);

    if (context != nullptr) {
      LOG_TRACE("collecting V8 garbage");
      bool hasActiveExternals = false;
      auto isolate = context->isolate;
      TRI_ASSERT(context->_locker == nullptr);
      context->_locker = new v8::Locker(isolate);
      isolate->Enter();
      {
        v8::HandleScope scope(isolate);

        auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);

        localContext->Enter();
        v8::Context::Scope contextScope(localContext);

        TRI_ASSERT(context->_locker->IsLocked(isolate));
        TRI_ASSERT(v8::Locker::IsLocked(isolate));

        TRI_GET_GLOBALS();
        hasActiveExternals = v8g->hasActiveExternals();
        TRI_RunGarbageCollectionV8(isolate, 1.0);

        localContext->Exit();
      }

      isolate->Exit();
      delete context->_locker;
      context->_locker = nullptr;

      // update garbage collection statistics
      context->_hasActiveExternals = hasActiveExternals;
      context->_numExecutions      = 0;
      context->_lastGcStamp        = lastGc;

      {
        CONDITION_LOCKER(guard, _contextCondition);

        _freeContexts.emplace_back(context);
        guard.broadcast();
      }
    }
  }

  _gcFinished = true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief disables actions
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::disableActions () {
  _useActions = false;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief upgrades the database
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::upgradeDatabase (bool skip,
                                     bool perform) {
  LOG_TRACE("starting database init/upgrade");

  // enter context and isolate
  V8Context* context = _contexts[0];

  TRI_ASSERT(context->_locker == nullptr);
  context->_locker = new v8::Locker(context->isolate);
  auto isolate = context->isolate;
  isolate->Enter();
  {
    v8::HandleScope scope(isolate);

    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
    localContext->Enter();
    v8::Context::Scope contextScope(localContext);

    // run upgrade script
    if (! skip) {
      LOG_DEBUG("running database init/upgrade");

      auto unuser(_server->_databasesProtector.use());
      auto theLists = _server->_databasesLists.load();
      for (auto& p : theLists->_databases) {
        TRI_vocbase_t* vocbase = p.second;

        // special check script to be run just once in first thread (not in all)
        // but for all databases
        v8::HandleScope scope(isolate);

        v8::Handle<v8::Object> args = v8::Object::New(isolate);
        args->Set(TRI_V8_ASCII_STRING("upgrade"), v8::Boolean::New(isolate, perform));

        localContext->Global()->Set(TRI_V8_ASCII_STRING("UPGRADE_ARGS"), args);

        bool ok = TRI_UpgradeDatabase(vocbase, &_startupLoader, localContext);

        if (! ok) {
          if (localContext->Global()->Has(TRI_V8_ASCII_STRING("UPGRADE_STARTED"))) {
            localContext->Exit();
            if (perform) {
              LOG_FATAL_AND_EXIT(
                                 "Database '%s' upgrade failed. Please inspect the logs from the upgrade procedure",
                                 vocbase->_name);
            }
            else {
              LOG_FATAL_AND_EXIT(
                                 "Database '%s' needs upgrade. Please start the server with the --upgrade option",
                                 vocbase->_name);
            }
          }
          else {
            LOG_FATAL_AND_EXIT("JavaScript error during server start");
          }

          LOG_DEBUG("database '%s' init/upgrade done", vocbase->_name);
        }
      }
    }

    // finally leave the context. otherwise v8 will crash with assertion failure when we delete
    // the context locker below
    localContext->Exit();
  }

  isolate->Exit();
  delete context->_locker;
  context->_locker = nullptr;

  if (perform) {
    // issue #391: when invoked with --upgrade, the server will not always shut down
    LOG_INFO("database upgrade passed");

    // regular shutdown... wait for all threads to finish

    auto unuser(_server->_databasesProtector.use());
    auto theLists = _server->_databasesLists.load();
    for (auto& p : theLists->_databases) {
      TRI_vocbase_t* vocbase = p.second;

      vocbase->_state = 2;

      int res = TRI_ERROR_NO_ERROR;

      res |= TRI_StopCompactorVocBase(vocbase);
      vocbase->_state = 3;
      res |= TRI_JoinThread(&vocbase->_cleanup);

      if (res != TRI_ERROR_NO_ERROR) {
        LOG_ERROR("unable to join database threads for database '%s'", vocbase->_name);
      }
    }

    LOG_INFO("finished");
    TRI_EXIT_FUNCTION(EXIT_SUCCESS, nullptr);
  }
  else {
    // and return from the context
    LOG_TRACE("finished database init/upgrade");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief runs the version check
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::versionCheck () {
  int result = 1;
  LOG_TRACE("starting version check");

  // enter context and isolate
  V8Context* context = _contexts[0];

  TRI_ASSERT(context->_locker == nullptr);
  context->_locker = new v8::Locker(context->isolate);
  auto isolate = context->isolate;
  isolate->Enter();
  {
    v8::HandleScope scope(isolate);
    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
    localContext->Enter();
    v8::Context::Scope contextScope(localContext);

    // run upgrade script
    LOG_DEBUG("running database version check");

    // can do this without a lock as this is the startup

    auto unuser(_server->_databasesProtector.use());
    auto theLists = _server->_databasesLists.load();
    for (auto& p : theLists->_databases) {
      TRI_vocbase_t* vocbase = p.second;

      // special check script to be run just once in first thread (not in all)
      // but for all databases

      int status = TRI_CheckDatabaseVersion(vocbase, &_startupLoader, localContext);

      if (status < 0) {
        LOG_FATAL_AND_EXIT(
                           "Database version check failed for '%s'. Please inspect the logs from any errors",
                           vocbase->_name);
      }
      else if (status == 3) {
        result = 3;
      }
      else if (status == 2 && result == 1) {
        result = 2;
      }
    }

    // issue #391: when invoked with --upgrade, the server will not always shut down
    localContext->Exit();
  }
  isolate->Exit();
  delete context->_locker;
  context->_locker = nullptr;

  // regular shutdown... wait for all threads to finish

  auto unuser(_server->_databasesProtector.use());
  auto theLists = _server->_databasesLists.load();
  for (auto& p : theLists->_databases) {
    TRI_vocbase_t* vocbase = p.second;

    vocbase->_state = 2;

    int res = TRI_ERROR_NO_ERROR;

    res |= TRI_StopCompactorVocBase(vocbase);
    vocbase->_state = 3;
    res |= TRI_JoinThread(&vocbase->_cleanup);

    if (res != TRI_ERROR_NO_ERROR) {
      LOG_ERROR("unable to join database threads for database '%s'", vocbase->_name);
    }
  }

  if (result == 1) {
    TRI_EXIT_FUNCTION(EXIT_SUCCESS, nullptr);
  }
  else {
    TRI_EXIT_FUNCTION(result, nullptr);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief prepares the server
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::prepareServer () {
  size_t nrInstances = _nrInstances;

  for (size_t i = 0;  i < nrInstances;  ++i) {
    prepareV8Server(i, _startupFile);
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                        ApplicationFeature methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::setupOptions (map<string, basics::ProgramOptionsDescription>& options) {
  options["Javascript Options:help-admin"]
    ("javascript.gc-interval", &_gcInterval, "JavaScript request-based garbage collection interval (each x requests)")
    ("javascript.gc-frequency", &_gcFrequency, "JavaScript time-based garbage collection frequency (each x seconds)")
    ("javascript.app-path", &_appPath, "directory for Foxx applications (normal mode)")
    ("javascript.startup-directory", &_startupPath, "path to the directory containing JavaScript startup scripts")
    ("javascript.v8-options", &_v8Options, "options to pass to v8")
  ;

  options["Hidden Options"]
    ("frontend-version-check", &_frontendVersionCheck, "show new versions in the frontend")
    ("frontend-development-mode", &DeprecatedOption, "only here for compatibility")
    ("javascript.dev-app-path", &_devAppPath, "directory for Foxx applications (development mode)")

    // deprecated options
    ("javascript.action-directory", &DeprecatedPath, "path to the JavaScript action directory (deprecated)")
    ("javascript.modules-path", &DeprecatedPath, "one or more directories separated by semi-colons (deprecated)")
    ("javascript.package-path", &DeprecatedPath, "one or more directories separated by semi-colons (deprecated)")
  ;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::prepare () {

  // check the startup path
  if (_startupPath.empty()) {
    LOG_FATAL_AND_EXIT("no 'javascript.startup-directory' has been supplied, giving up");
  }

  // remove trailing / from path
  _startupPath = StringUtils::rTrim(_startupPath, TRI_DIR_SEPARATOR_STR);

  // dump paths
  {
    vector<string> paths;

    paths.push_back(string("startup '" + _startupPath + "'"));

    if (! _appPath.empty()) {
      paths.push_back(string("application '" + _appPath + "'"));
    }

    if (! _devAppPath.empty()) {
      paths.push_back(string("dev application '" + _devAppPath + "'"));
    }

    LOG_INFO("JavaScript using %s", StringUtils::join(paths, ", ").c_str());
  }

  // check whether app-path was specified
  if (_appPath.empty()) {
    LOG_FATAL_AND_EXIT("no value has been specified for --javascript.app-path.");
  }

  _startupLoader.setDirectory(_startupPath);
  ServerState::instance()->setJavaScriptPath(_startupPath);

  // add v8 options
  if (! _v8Options.empty()) {
    LOG_INFO("using V8 options '%s'", _v8Options.c_str());
    v8::V8::SetFlagsFromString(_v8Options.c_str(), (int) _v8Options.size());
  }

#ifdef TRI_FORCE_ARMV6
  const string forceARMv6 = "--noenable-armv7";
  v8::V8::SetFlagsFromString(forceARMv6.c_str(), (int) forceARMv6.size());
#endif

  // use a minimum of 1 second for GC
  if (_gcFrequency < 1) {
    _gcFrequency = 1;
  }

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::prepare2 () {
  size_t nrInstances = _nrInstances;
  v8::V8::InitializeICU();

  TRI_ASSERT(_platform == nullptr);
  _platform = v8::platform::CreateDefaultPlatform();
  v8::V8::InitializePlatform(_platform);
  v8::V8::Initialize();

  v8::V8::SetArrayBufferAllocator(&_bufferAllocator);

  // setup instances
  {
    CONDITION_LOCKER(guard, _contextCondition);
    _contexts = new V8Context*[nrInstances];
  }

  std::vector<std::thread> threads;
  _ok = true;

  for (size_t i = 0; i < nrInstances;  ++i) {
    threads.push_back(std::thread(&ApplicationV8::prepareV8InstanceInThread,
                                  this,
                                  i,
                                  _useActions));
  }
  for (size_t i = 0; i < nrInstances; ++i) {
    threads[i].join();
  }
  return _ok;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::start () {
  TRI_ASSERT(_gcThread == nullptr);
  _gcThread = new V8GcThread(this);
  _gcThread->start();

  _gcFinished = false;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::close () {
  _stopping = true;
  _contextCondition.broadcast();

  // unregister all tasks
  if (_scheduler != nullptr && _scheduler->scheduler() != nullptr) {
    _scheduler->scheduler()->unregisterUserTasks();
  }

  // wait for all contexts to finish
  CONDITION_LOCKER(guard, _contextCondition);

  for (size_t n = 0;  n < 10 * 5;  ++n) {
    if (_busyContexts.empty()) {
      LOG_DEBUG("no busy V8 contexts");
      break;
    }

    LOG_DEBUG("waiting for %d busy V8 contexts to finish", (int) _busyContexts.size());

    guard.wait(100000);
  }
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::stop () {

  // send all busy contexts a termate signal
  {
    CONDITION_LOCKER(guard, _contextCondition);

    for (auto& it : _busyContexts) {
      LOG_WARNING("sending termination signal to V8 context");
      v8::V8::TerminateExecution(it->isolate);
    }
  }

  // wait for one minute
  {
    CONDITION_LOCKER(guard, _contextCondition);

    for (size_t n = 0;  n < 10 * 60;  ++n) {
      if (_busyContexts.empty()) {
        break;
      }

      guard.wait(100000);
    }
  }

  LOG_DEBUG("Waiting for GC Thread to finish action");

  // wait until garbage collector thread is done
  while (! _gcFinished) {
    usleep(10000);
  }

  LOG_DEBUG("Commanding GC Thread to terminate");
  // stop GC thread
  _gcThread->shutdown();

  // shutdown all instances
  {
    CONDITION_LOCKER(guard, _contextCondition);

    size_t nrInstances = _nrInstances;

    for (size_t i = 0;  i < nrInstances;  ++i) {
      shutdownV8Instance(i);
    }

    delete[] _contexts;
  }

  LOG_DEBUG("Shutting down V8");

  v8::V8::Dispose();
  v8::V8::ShutdownPlatform();

  delete _platform;
  // delete GC thread after all action threads have been stopped
  delete _gcThread;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   private methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief determine which of the free contexts should be picked for the GC
////////////////////////////////////////////////////////////////////////////////

ApplicationV8::V8Context* ApplicationV8::pickFreeContextForGc () {
  int const n = (int) _freeContexts.size();

  if (n == 0) {
    // this is easy...
    return nullptr;
  }

  V8GcThread* gc = dynamic_cast<V8GcThread*>(_gcThread);
  TRI_ASSERT(gc != nullptr);

  V8Context* context = nullptr;

  // we got more than 1 context to clean up, pick the one with the "oldest" GC stamp
  int pickedContextNr = -1; // index of context with lowest GC stamp, -1 means "none"

  for (int i = 0; i < n; ++i) {
    // check if there's actually anything to clean up in the context
    if (_freeContexts[i]->_numExecutions == 0 && ! _freeContexts[i]->_hasActiveExternals) {
      continue;
    }

    // compare last GC stamp
    if (pickedContextNr == -1 ||
        _freeContexts[i]->_lastGcStamp <= _freeContexts[pickedContextNr]->_lastGcStamp) {
      pickedContextNr = i;
    }
  }
  // we now have the context to clean up in pickedContextNr

  if (pickedContextNr == -1) {
    // no context found
    return nullptr;
  }

  // this is the context to clean up
  context = _freeContexts[pickedContextNr];
  TRI_ASSERT(context != nullptr);

  // now compare its last GC timestamp with the last global GC stamp
  if (context->_lastGcStamp + _gcFrequency >= gc->getLastGcStamp()) {
    // no need yet to clean up the context
    return nullptr;
  }

  // we'll pop the context from the vector. the context might be at
  // any position in the vector so we need to move the other elements
  // around
  if (n > 1) {
    for (int i = pickedContextNr; i < n - 1; ++i) {
      _freeContexts[i] = _freeContexts[i + 1];
    }
  }
  _freeContexts.pop_back();

  return context;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief prepares a V8 instance
////////////////////////////////////////////////////////////////////////////////

bool ApplicationV8::prepareV8Instance (size_t i, bool useActions) {
  CONDITION_LOCKER(guard, _contextCondition);

  vector<string> files;

  files.push_back("server/initialize.js");

  v8::Isolate* isolate = v8::Isolate::New();

  V8Context* context = _contexts[i] = new V8Context();

  if (context == nullptr) {
    LOG_FATAL_AND_EXIT("cannot initialize V8 context #%d", (int) i);
  }

  TRI_ASSERT(context->_locker == nullptr);

  // enter a new isolate
  context->_id = i;
  context->isolate = isolate;
  TRI_ASSERT(context->_locker == nullptr);
  context->_locker = new v8::Locker(isolate);
  context->isolate->Enter();

  // create the context
  {
    v8::HandleScope handle_scope(isolate);

    v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);

    v8::Persistent<v8::Context> persistentContext;
    persistentContext.Reset(isolate, v8::Context::New(isolate, 0, global));
    auto localContext = v8::Local<v8::Context>::New(isolate, persistentContext);

    localContext->Enter();
    v8::Context::Scope contextScope(localContext);

    context->_context.Reset(context->isolate, localContext);

    if (context->_context.IsEmpty()) {
      LOG_FATAL_AND_EXIT("cannot initialize V8 engine");
    }

    v8::Handle<v8::Object> globalObj = localContext->Global();
    globalObj->Set(TRI_V8_ASCII_STRING("GLOBAL"), globalObj);
    globalObj->Set(TRI_V8_ASCII_STRING("global"), globalObj);
    globalObj->Set(TRI_V8_ASCII_STRING("root"), globalObj);

    TRI_InitV8VocBridge(isolate, this, localContext, _queryRegistry, _server, _vocbase, &_startupLoader, i);
    TRI_InitV8Queries(isolate, localContext);
    TRI_InitV8UserStructures(isolate, localContext);

    TRI_InitV8Cluster(isolate, localContext);
    if (_dispatcher->dispatcher() != nullptr) {
      // don't initialize dispatcher if there is no scheduler (server started with --no-server option)
      TRI_InitV8Dispatcher(isolate, localContext, _vocbase, _scheduler, _dispatcher, this);
    }

    if (useActions) {
      TRI_InitV8Actions(isolate, localContext, _vocbase, this);
    }

    string modulesPath = _startupPath + TRI_DIR_SEPARATOR_STR + "server" + TRI_DIR_SEPARATOR_STR + "modules;" +
      _startupPath + TRI_DIR_SEPARATOR_STR + "common" + TRI_DIR_SEPARATOR_STR + "modules;" +
      _startupPath + TRI_DIR_SEPARATOR_STR + "node";

    TRI_InitV8Buffer(isolate, localContext);
    TRI_InitV8Conversions(localContext);
    TRI_InitV8Utils(isolate, localContext, _startupPath, modulesPath);
    TRI_InitV8Shell(isolate, localContext);

    {
      v8::HandleScope scope(isolate);

      char const* logfile = TRI_GetFilenameLogging();
      if (logfile != nullptr) {
        TRI_AddGlobalVariableVocbase(isolate, localContext, TRI_V8_ASCII_STRING("LOGFILE_PATH"),        TRI_V8_STRING(logfile));
      }
      else {
        TRI_AddGlobalVariableVocbase(isolate, localContext, TRI_V8_ASCII_STRING("LOGFILE_PATH"),        v8::Null(isolate));
      }
      TRI_AddGlobalVariableVocbase(isolate, localContext,   TRI_V8_ASCII_STRING("APP_PATH"),            TRI_V8_STD_STRING(_appPath));
      TRI_AddGlobalVariableVocbase(isolate, localContext,   TRI_V8_ASCII_STRING("DEV_APP_PATH"),        TRI_V8_STD_STRING(_devAppPath));
      TRI_AddGlobalVariableVocbase(isolate, localContext,   TRI_V8_ASCII_STRING("FE_VERSION_CHECK"),    v8::Boolean::New(isolate, _frontendVersionCheck));

      for (auto j : _definedBooleans) {
        localContext->Global()->ForceSet(TRI_V8_STD_STRING(j.first), v8::Boolean::New(isolate, j.second), v8::ReadOnly);
      }

      for (auto j : _definedDoubles) {
        localContext->Global()->ForceSet(TRI_V8_STD_STRING(j.first), v8::Number::New(isolate, j.second), v8::ReadOnly);
      }
    }

    // load all init files
    for (size_t j = 0;  j < files.size();  ++j) {
      switch (_startupLoader.loadScript(isolate, localContext, files[j])) {
        case JSLoader::eSuccess:
          LOG_TRACE("loaded JavaScript file '%s'", files[j].c_str());
          break;
        case JSLoader::eFailLoad:
          LOG_FATAL_AND_EXIT("cannot load JavaScript file '%s'", files[j].c_str());
          break;
        case JSLoader::eFailExecute:
          LOG_FATAL_AND_EXIT("error during execution of JavaScript file '%s'", files[j].c_str());
          break;
      }
    }

    // and return from the context
    localContext->Exit();
  }
  isolate->Exit();
  delete context->_locker;
  context->_locker = nullptr;

  // some random delay value to add as an initial garbage collection offset
  // this avoids collecting all contexts at the very same time
  double const randomWait = fmod(static_cast<double>(TRI_UInt32Random()), 15.0);

  // initialize garbage collection for context
  context->_numExecutions      = 0;
  context->_hasActiveExternals = true;
  context->_lastGcStamp        = TRI_microtime() + randomWait;

  LOG_TRACE("initialized V8 context #%d", (int) i);

  _freeContexts.emplace_back(context);

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief prepares a V8 instance, multi-threaded version calling the above
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::prepareV8InstanceInThread (size_t i, bool useAction) {
  if (! prepareV8Instance(i, useAction)) {
    _ok = false;
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief prepares the V8 server
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::prepareV8Server (const size_t i, const string& startupFile) {

  // enter context and isolate
  V8Context* context = _contexts[i];

  auto isolate = context->isolate;
  TRI_ASSERT(context->_locker == nullptr);
  context->_locker = new v8::Locker(isolate);
  v8::HandleScope scope(isolate);
  isolate->Enter();
  {
    v8::HandleScope handle_scope(isolate);
    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
    localContext->Enter();
    v8::Context::Scope contextScope(localContext);

    // load server startup file
    switch (_startupLoader.loadScript(isolate, localContext, startupFile)) {
      case JSLoader::eSuccess:
        LOG_TRACE("loaded JavaScript file '%s'", startupFile.c_str());
        break;
      case JSLoader::eFailLoad:
        LOG_FATAL_AND_EXIT("cannot load JavaScript utilities from file '%s'", startupFile.c_str());
        break;
      case JSLoader::eFailExecute:
        LOG_FATAL_AND_EXIT("error during execution of JavaScript utilities from file '%s'", startupFile.c_str());
        break;
    }

    // and return from the context
    localContext->Exit();
  }
  isolate->Exit();
  delete context->_locker;
  context->_locker = nullptr;

  // initialize garbage collection for context
  LOG_TRACE("initialized V8 server #%d", (int) i);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief shut downs a V8 instances
////////////////////////////////////////////////////////////////////////////////

void ApplicationV8::shutdownV8Instance (size_t i) {
  LOG_TRACE("shutting down V8 context #%d", (int) i);

  V8Context* context = _contexts[i];

  auto isolate = context->isolate;
  isolate->Enter();
  TRI_ASSERT(context->_locker == nullptr);
  context->_locker = new v8::Locker(isolate);
  {
    v8::HandleScope scope(isolate);

    auto localContext = v8::Local<v8::Context>::New(isolate, context->_context);
    localContext->Enter();
    v8::Context::Scope contextScope(localContext);
    double availableTime = 30.0;

    if (RUNNING_ON_VALGRIND) {
      availableTime *= 10;
    }

    TRI_RunGarbageCollectionV8(isolate, availableTime);

    TRI_GET_GLOBALS();
    if (v8g != nullptr) {
      if (v8g->_transactionContext != nullptr) {
        delete static_cast<V8TransactionContext*>(v8g->_transactionContext);
        v8g->_transactionContext = nullptr;
      }
      delete v8g;
    }

    localContext->Exit();
  }
  context->_context.Reset();

  isolate->Exit();
  delete context->_locker;
  context->_locker = nullptr;

  isolate->Dispose();

  delete context;

  LOG_TRACE("closed V8 context #%d", (int) i);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
ENT.Type 			= "anim"
ENT.Base 			= "base_wire_entity"

ENT.PrintName		= ""
ENT.Author			= ""
ENT.Contact			= ""
ENT.Purpose			= ""
ENT.Instructions	= ""

ENT.Spawnable			= false
ENT.AdminSpawnable		= false

function ENT:SetEffect( name )
	self:SetNWString( "Effect", name )
end

function ENT:GetEffect( name )
	return self:GetNWString( "Effect" )
end

function ENT:SetOn( boolon )
	self:SetNWBool( "On", boolon, true )
end

function ENT:IsOn( name )
	return self:GetNWBool( "On" )
end

function ENT:SetOffset( v )
	self:SetNWVector( "Offset", v, true )
end

function ENT:GetOffset( name )
	return self:GetNWVector( "Offset" )
end

function ENT:SetPointing(value)
	self:SetNWFloat( "Pointing", value )
end

function ENT:GetPointing()
	return self:GetNWSFloat( "Pointing" )
end


text:
<?php $this->load->view('main/header'); ?>
<link rel="stylesheet" href="<?php echo base_url(); ?>css/jquery-ui.min.css">

<title>Репетиторы Real Language Club. Записаться на занятие. Шаг 3</title>

<?php $this->load->view('student/header_menu'); ?>
<input type="hidden" value="<?php echo $sum; ?>" id="min_sum">

    				ШАГ 1

    			<img src="<?php echo base_url(); ?>img/arrow1.png" alt="arow">

    				ШАГ 2

    			<img src="<?php echo base_url(); ?>img/arrow1.png" alt="arow">

    				ШАГ 3

Шаг 3. Пополните личный счёт на сумму урока.

Окончательный расчёт за урок вы сделаете из личного кабинета после подтверждения заявки репетитором.

        <form action="<?php echo base_url(); ?>index.php/student/makePay" method="post" id="pay_form">
            <input type="hidden" name="go_to" value="student/stepend">
            <input type="hidden" name="repetitor_id" value="<?php echo $repetitor_id; ?>">
            <input type="hidden" name="specialization_id" value="<?php echo $specialization_id; ?>">
            <input type="hidden" name="subject_id" value="<?php echo $subject_id; ?>">
            <input type="hidden" name="about" value="<?php echo $about; ?>">
            <?php foreach ($dates as $date){
                echo '<input type="hidden" name="date[]" value="'.$date.'">';
            }
            ?>

                Сумма $
                <input type="text" placeholder="$" name="sum" id="sum" value="<?php echo $sum; ?>">
                <input type="hidden" name="" value="" id="main_ex">

Выберите способ пополнения:

                <input type="radio"  value="1" checked name="pay_type"  id="card">

                Visa/MasterCard

                <input type="radio" value="2" name="pay_type" id="money">

                ЯндексДеньги

                <input type="radio"  value="3" name="pay_type" id="paypal">

                PayPal

            <input type="submit" value="Пополнить" id="pay">
        </form>

    <?php
    //$receiverEmail = 'evgueny007-facilitator@gmail.com'; //email получателя платежа(на него зарегестрирован paypal аккаунт)
    $receiverEmail = 'evgueny007@gmail.com';
    //$returnUrl = 'https://tutor.reallanguage.club/index.php/admin/getpaypal';
    $returnUrl = 'https://tutor.reallanguage.club/index.php/student/stepend';
    $customData = array ('student_id' => $student['id']);
     ?>
    <form class="" action="https://www.paypal.com/cgi-bin/websc" method="post" id="paypal_form">

        <input type="hidden" name="cmd" value="_xclick" id="cmd">

        <input type="hidden" name="business" value="<?php echo $receiverEmail; ?>">
        <input id="paypalAmmount" type="hidden" name="amount" value="">
        <input type="hidden" name="return" value="<?php echo $returnUrl; ?>">
        <input type="hidden" name="custom" value="<?php echo $student['id']?>"  id="paypal_ex_id">
        <input type="hidden" name="currency_code" value="USD">
        <input type="hidden" name="lc" value="US">
        <input type="hidden" name="bn" value="PP-BuyNowBF">
    </form>
    <form class="hidden" method="POST" action="https://money.yandex.ru/quickpay/confirm.xml"  id="yandex_form">
        <input type="hidden" name="receiver" value="410011776472684">

        <input type="hidden" name="formcomment" value="Сайт Reallanguage.club">
        <input type="hidden" name="short-dest" value="За услуги репетитора">
        <input type="hidden" name="label" value="" id="yandex_ex_id">
        <input type="hidden" name="quickpay-form" value="donate">
        <input type="hidden" name="targets" value="транзакция {order_id}">
        <input type="hidden" name="sum" value="4568.25" data-type="number"  id="yandex_sum">
        <input type="hidden" name="comment" value="">
        <input type="hidden" name="need-fio" value="true">
        <input type="hidden" name="need-email" value="true">
        <input type="hidden" name="need-phone" value="false">
        <input type="hidden" name="need-address" value="false">
        <input type="radio" name="paymentType" value="PC"  id="yandex_mon">Яндекс.Деньгами
        <input type="radio" name="paymentType" value="AC" id="yandex_card">Банковской картой
    </form>

100% гарантия безопасности. Сертификат SSL.
После пополнения, сумма отображается на балансе вашего личного кабинета. Запрос на урок сможете найти в личном кабинете в разделе «Запросы на уроки».

<?php $this->load->view('main/footer'); ?>


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;

namespace Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices
{
    internal struct EmbeddedLanguageInfo
    {
        public readonly int StringLiteralTokenKind;
        public readonly int InterpolatedTextTokenKind;
        public readonly ISyntaxFactsService SyntaxFacts;
        public readonly ISemanticFactsService SemanticFacts;
        public readonly IVirtualCharService VirtualCharService;

        public EmbeddedLanguageInfo(int stringLiteralTokenKind, int interpolatedTextTokenKind, ISyntaxFactsService syntaxFacts, ISemanticFactsService semanticFacts, IVirtualCharService virtualCharService)
        {
            StringLiteralTokenKind = stringLiteralTokenKind;
            InterpolatedTextTokenKind = interpolatedTextTokenKind;
            SyntaxFacts = syntaxFacts;
            SemanticFacts = semanticFacts;
            VirtualCharService = virtualCharService;
        }
    }
}


text:
<?php
	/********************************************************************/
	/*                                                                  */
	/*      Copyright (C) 2004 Arash Dejkam, All Rights Reserved.       */
	/*      http://www.tracewatch.com                                   */
	/*                                                                  */
	/*      Please read the licence file distributed with this          */
	/*      file or the one available at tracewatch.com for             */
	/*      the terms under which you can use or modify this file.      */
	/*                                                                  */
	/********************************************************************/

	class ArdeDbDbErrorWriter {
		private $db;
		private $sub;
		private $tableName;
		private $maxErrors;

		function __construct( $db, $sub, $tableName, $maxErrors ) {
			$this->db = $db;
			$this->sub = $sub;
			$this->tableName = $tableName;
			$this->maxErrors = $maxErrors;
		}

		public function write( $str ) {
			$res = $this->db->query_sub( $this->sub, 'SELECT COUNT(*) FROM', $this->tableName );

			if( !( $r = $this->db->fetchRow( $res ) ) ) throw new ArdeException( "can't get the number of errors in db" );

			if( (int)$r[0] >= $this->maxErrors ) {
				$this->db->query_sub( $this->sub, 'DELETE FROM', $this->tableName,' ORDER BY id LIMIT 1' );
			}

			$this->db->query_sub( $this->sub, 'INSERT INTO', $this->tableName, "VALUES( NULL, ".$this->db->string( $str )." )" );

			return $this->db->lastInsertId();

		}

		public function clear() {
			$this->db->query_sub( $this->sub, 'TRUNCATE', $this->tableName );
		}

		public function getErrorsCount() {
			$res = $this->db->query_sub( $this->sub, 'SELECT COUNT(*) FROM', $this->tableName );
			$r = $this->db->fetchRow( $res );
			return (int)$r[0];
		}

		public function getErrors() {
			$res = $this->db->query_sub( $this->sub, 'SELECT id, '.$this->db->stringResult( 'str' ).' FROM', $this->tableName,' ORDER BY id DESC' );
			$o = array();
			while( $r = $this->db->fetchRow( $res ) ) {
				$o[ (int)$r[0] ] = $r[1];
			}
			return $o;
		}

		public function install( $overwrite ) {
			$this->db->createTable( $this->sub, $this->tableName, '( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, str TEXT CHARACTER SET '.$this->db->getCharset().' COLLATE '.$this->db->getCollation().' )', $overwrite );
		}

		public function uninstall() {
			$this->db->dropTableIfExists( $this->sub, $this->tableName );
		}
	}
?>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>MIPS16bits: MIPS::FileReader Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

MIPS16bits

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

MIPS

FileReader

Public Member Functions |
List of all members

MIPS::FileReader Class Reference

#include <file_reader.hpp>

Public Member Functions

 	FileReader (const char *filename)

 	FileReader (const char *filename, Filter &filter)

 	~FileReader ()

char * 	next ()

void 	rewind ()

bool 	hasNext ()

Detailed Description

Classe responsável por ler o conteúdo de um arquivo e salvá-lo internamente, fazendo com que seja simples para obter as informações do mesmo.

Author

Matheus Nogueira

Constructor & Destructor Documentation

          MIPS::FileReader::FileReader
          (
          const char *
          filename	)

Cria um novo leitor de arquivo.

Parameters

filename	nome do arquivo a ser lido.

          MIPS::FileReader::FileReader
          (
          const char *
          filename,

          Filter &
          filter

          )

Cria um novo leitor de arquivo que filtra determinadas entradas.

Parameters

filename	nome do arquivo a ser lido.

filter	filtro a ser utilizado.

          MIPS::FileReader::~FileReader
          (
          	)

Destroi o leitor de arquivo e o conteúdo do buffer interno.

Member Function Documentation

          bool MIPS::FileReader::hasNext
          (
          	)

Checa se o arquivo ainda tem conteúdo para ser lido.

Returns

booleano que se true, indica que ainda existe linhas a ser lidas.

          char* MIPS::FileReader::next
          (
          	)

Retorna a proxima linha do arquivo.

Returns

proxima linha do arquivo.

          void MIPS::FileReader::rewind
          (
          	)

Retorna o ponteiro da linha atual para o inicio do arquivo.

The documentation for this class was generated from the following file:

include/mips/util/file_reader.hpp

<address class="footer">
Generated by

 1.8.11
</address>


text:
namespace web_app {

// Fake implementation of WebAppProtocolHandlerManager
class FakeWebAppProtocolHandlerManager : public WebAppProtocolHandlerManager {
 public:
  explicit FakeWebAppProtocolHandlerManager(Profile* profile);
  ~FakeWebAppProtocolHandlerManager() override;

  void RegisterProtocolHandler(
      const AppId& app_id,
      const apps::ProtocolHandlerInfo& protocol_handler);

  std::vector<apps::ProtocolHandlerInfo> GetAppProtocolHandlerInfos(
      const std::string& app_id) const override;

 private:
  base::flat_map<AppId, std::vector<apps::ProtocolHandlerInfo>>
      protocol_handlers_;
};

}  // namespace web_app

#endif  // CHROME_BROWSER_WEB_APPLICATIONS_TEST_FAKE_WEB_APP_PROTOCOL_HANDLER_MANAGER_H_