text:
using InterflowFramework.Core.Channel.OutputPoint.Const;
using InterflowFramework.Core.Channel.OutputPoint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InternalFramework.OutputPoint
{
	public class ResponseOutputPoint: BaseOutputPoint
	{
		protected ResponseOutputPoint() {
		}
		protected void Initialize(params Func<object, object>[] actions) {
			actions.All(action => {
				On(OutputPointEvent.OnMessageRecived, message =>
				{
					Response(message, action(message));
				});
				return true;
			});
		}
		public ResponseOutputPoint(params Func<object, object>[] actions)
		{
			Initialize(actions);
		}
		public override void Push(object message)
		{
			Subscriber.Execute(OutputPointEvent.OnMessageRecived, message);
		}
		public virtual void Response(object inputMessage, object responseMessage) {
			var msg = (MessagePackage)inputMessage;
			msg.Object = responseMessage;
			Subscriber.Execute(OutputPointEvent.OnResponse, msg);
		}
	}
}


text:
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.script;

import com.intellij.ide.CliResult;
import com.intellij.lang.LangBundle;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ApplicationStarterBase;
import com.intellij.openapi.diagnostic.DefaultLogger;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.openapi.wm.ex.WindowManagerEx;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author gregsh
 */
final class IdeScriptStarter extends ApplicationStarterBase {
  private static final Logger LOG = Logger.getInstance(IdeScriptStarter.class);

  @Override
  public String getCommandName() {
    return "ideScript";
  }

  @Override
  public String getUsageMessage() {
    String scriptName = ApplicationNamesInfo.getInstance().getScriptName();
    return LangBundle.message("ide.script.starter.usage", scriptName, "ideScript");
  }

  @Override
  protected boolean checkArguments(@NotNull List<String> args) {
    return args.size() > 1;
  }

  @NotNull
  @Override
  protected CompletableFuture<CliResult> processCommand(@NotNull List<String> args,
                                                        @Nullable String currentDirectory) throws Exception {
    List<Path> filePaths = ContainerUtil.map(args.subList(1, args.size()), Paths::get);
    Project project = guessProject();
    CompletableFuture<CliResult> future = new CompletableFuture<>();
    AppExecutorUtil.getAppExecutorService().execute(() -> {
      List<Pair<Path, IdeScriptEngine>> result = IdeStartupScripts.prepareScriptsAndEngines(filePaths);
      IdeStartupScripts.runAllScriptsImpl(project, result, project != null ? LOG : redirectStreamsAndGetLogger(result));
      future.complete(CliResult.OK);
    });
    return future;
  }

  @Nullable
  private static Project guessProject() {
    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    Window recentFocusedWindow = WindowManagerEx.getInstanceEx().getMostRecentFocusedWindow();
    if (recentFocusedWindow instanceof IdeFrame) return ((IdeFrame)recentFocusedWindow).getProject();
    return ContainerUtil.find(openProjects, o -> o.isInitialized() && !o.isDisposed());
  }

  /** @noinspection UseOfSystemOutOrSystemErr*/
  @NotNull
  private static Logger redirectStreamsAndGetLogger(List<Pair<Path, IdeScriptEngine>> result) {
    for (Pair<Path, IdeScriptEngine> pair : result) {
      pair.second.setStdOut(new OutputStreamWriter(System.out, Charset.defaultCharset()));
      pair.second.setStdErr(new OutputStreamWriter(System.err, Charset.defaultCharset()));
      pair.second.setStdIn(new InputStreamReader(System.in, Charset.defaultCharset()));
    }
    return new DefaultLogger(null) {
      @Override
      public void info(String message) {
        System.out.println("INFO: " + message);
      }

      @Override
      public void info(String message, Throwable t) {
        System.out.println("INFO: " + message);
      }
    };
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.ms123.common.camel.components.tabula;

import java.net.URI;
import java.util.Map;

import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;
import static com.jcabi.log.Logger.info;

public class TabulaComponent extends DefaultComponent {

  private static final String TABULA_CONFIG = "tabulaConfig";

  @Override
  protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
    TabulaEndpoint endpoint = new TabulaEndpoint(uri, this, remaining);
    endpoint.setOutputFormat((String)remaining );
    setProperties(endpoint, parameters);
    return endpoint;
  }
}


text:
A far-from-finished game in the Roguelike aesthetic.

Developed with:
* Visual Studio 2015, Community Edition.
* Love (lots)

Third-party sources and assets are not included in this repository.

Depends on:
*SDL 2.0.3


text:
//
// Jupiter: A Ride-Sharing Network Generation and Analysis Application
// Copyright 2017 Pejman Ghorbanzade <pejman@ghorbanzade.com>
// Released under the terms of MIT License
// https://github.com/ghorbanzade/jupiter/blob/master/LICENSE
//

package com.ghorbanzade.jupiter;

import java.util.List;

/**
 *
 *
 * @author Mariam Shahrabifarahani
 */
public interface Filter {

  /**
   *
   *
   * @param customer
   * @param candidate
   * @return
   */
  public boolean pass(Customer customer, Customer candidate);

}


text:
Contributing
============

Thanks for your interest in contributing to ``aioodbc``, there are multiple
ways and places you can contribute.

Reporting an Issue
------------------
If you have found issue with `aioodbc` please do
not hesitate to file an issue on the GitHub_ project. When filing your
issue please make sure you can express the issue with a reproducible test
case.

When reporting an issue we also need as much information about your environment
that you can include. We never know what information will be pertinent when
trying narrow down the issue. Please include at least the following
information:

* Version of `aioodbc` and `python`.
* Version of your ODBC database
* Version of database ODBC driver
* Version of unixODBC_
* Platform you're running on (OS X, Linux, Windows).

Instructions for contributors
-----------------------------

In order to make a clone of the GitHub_ repo: open the link and press the
"Fork" button on the upper-right menu of the web page.

I hope everybody knows how to work with git and github nowadays :)

Work flow is pretty straightforward:

  1. Clone the GitHub_ repo

  2. Make a change

  3. Make sure all tests passed

  4. Commit changes to own aioodbc clone

  5. Make pull request from github page for your clone

Preconditions for running aioodbc test suite
---------------------------------------------

We expect you to use a python virtual environment and docker_ to run
our tests.

There are several ways to make a virtual environment.

If you like to use *virtualenv* please run::

   $ cd aioodbc
   $ virtualenv --python=`which python3.5` venv

For standard python *venv*::

   $ cd aioodbc
   $ python3.5 -m venv venv

For *virtualenvwrapper*::

   $ cd aioodbc
   $ mkvirtualenv --python=`which python3.5` aioodbc

There are other tools like *pyvenv* but you know the rule of thumb
now: create a python3.5 virtual environment and activate it.

After that please install libraries required for development::

   $ pip install -r requirements-dev.txt

We also recommend to install *ipdb* but it's on your own::

   $ pip install ipdb

Congratulations, you are ready to run the test suite

Install database
----------------
You do not need to install any databases, docker_ will pull images and create
containers for you automatically, after the tests, containers will be removed.

Run aioodbc test suite
----------------------

After all the preconditions are met you can run tests typing the next
command::

   $ make test

Or if you want to run only one particular test::

    $ py.test tests/test_connection.py -k test_basic_cursor

The command at first will run the static and style checkers (sorry, we don't
accept pull requests with `pep8` or `pyflakes` errors).

On `flake8` success the tests will be run.

Please take a look on the produced output.

Any extra texts (print statements and so on) should be removed.

Tests coverage
--------------

We are trying hard to have good test coverage; please don't make it worse.

Use::

   $ make cov

to run test suite and collect coverage information. Once the command
has finished check your coverage at the file that appears in the last
line of the output:
``open file:///.../aioodbc/htmlcov/index.html``

Please go to the link and make sure that your code change is covered.

Documentation
-------------

We encourage documentation improvements.

Please before making a Pull Request about documentation changes run::

   $ make doc

Once it finishes it will output the index html page
``open file:///.../aioodbc/docs/_build/html/index.html``.

Go to the link and make sure your doc changes looks good.

The End
-------

After finishing all steps make a GitHub_ Pull Request, thanks.

.. _unixODBC: http://www.unixodbc.org/
.. _GitHub: https://github.com/aio-libs/aioodbc
.. _docker: https://docs.docker.com/engine/installation/


text:
package com.effectivejava.util;

public class RegexExercise {
    public static void main(String[] args) {
        final String original = "This is a somehting with an <img src=\"test.png\"/> in it";
        final String expect = "This is a somehting with an image in it";

        final String actual = original.replace("<img[^>]+\\>", "image");
        if (!expect.equals(actual)) {
            System.out.println("Wrong: expected <" + expect + ">, but was <" + actual + ">");
        } else {
            System.out.print("Okay");
        }
    }
}


text:
#ifndef TENSORFLOW_CORE_GRAPPLER_COSTS_VIRTUAL_SCHEDULER_H_
#define TENSORFLOW_CORE_GRAPPLER_COSTS_VIRTUAL_SCHEDULER_H_

#include <list>
#include <memory>
#include <unordered_map>
#include <unordered_set>

#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/step_stats.pb.h"
#include "tensorflow/core/grappler/costs/cost_estimator.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/costs/op_context.h"
#include "tensorflow/core/grappler/costs/virtual_placer.h"
#include "tensorflow/core/grappler/grappler_item.h"

namespace tensorflow {
namespace grappler {

struct NodeState {
  // A node (i.e., an op) takes a set of input:port pairs and produces
  // a set of output ports.

  // Cross references to input and output nodes from graphdef.
  std::vector<std::pair<const NodeDef*, int>> inputs;  // Input, port pairs.
  // List of output nodes (a list of nodes that takes this output port as input)
  // keyed by port_num. Note that port_num -1 is used for control dependency.
  std::unordered_map<int, std::vector<const NodeDef*>> outputs;

  // Info from GraphProperties.
  std::vector<OpInfo::TensorProperties> input_properties;
  std::vector<OpInfo::TensorProperties> output_properties;

  // Canonical device name used within VirtualScheduler.
  string device_name;

  // States updated as scheduling nodes.
  int num_inputs_ready;
  std::unordered_map<int, int> num_outputs_executed;
  Costs::Duration time_ready;
  Costs::Duration time_scheduled;
  Costs::Duration time_finished;
  // Time that all the consumers are executed (hence, no need to keep this
  // output in memory), keyed by port_num.
  std::unordered_map<int, Costs::Duration> time_no_references;

  // Note that a node may have multiple output ports. The length of outputs,
  // num_outputs_executed, and time_no_references should be
  // identical when a NodeState is fully initialized.
  // They should be 1 + output_properties.size() as we add [-1] for control
  // dependency.

  // Node will be ready to be executed at time_ready, scheduled at
  // time_scheduled, and finishes execution at time_finished.
  // Each output port uses up memory space from time_scheduled to its
  // time_no_references.

  // How many times this node has been executed, e.g. in a while loop.
  int num_executed_times;

  NodeState() {
    num_inputs_ready = 0;
    time_ready = Costs::Duration::max();
    time_scheduled = Costs::Duration::max();
    time_finished = Costs::Duration::max();
    num_executed_times = 0;
    // Note that num_outputs_executed and time_no_references are not initialized
    // here, since we don't know the size (i.e., # outputs for this node).
  }
};

struct DeviceState {
  // Nodes executed on this device in execution order.
  std::vector<const NodeDef*> nodes_executed;

  struct NodePairHash {
   public:
    const std::size_t operator()(
        const std::pair<const NodeDef*, int>& element) const {
      return std::hash<const NodeDef*>()(element.first);
    }
  };

  // Nodes currently allocated in memory: set of NodeDef* and port_num pairs
  // so that we can track which output of the node is in memory.
  std::unordered_set<std::pair<const NodeDef*, int>, NodePairHash>
      nodes_in_memory;

  // Nodes allocated in memory persistently: e.g., Variables.
  std::unordered_set<std::pair<const NodeDef*, int>, NodePairHash>
      persistent_nodes;

  // Snapshot of nodes_in_memory, when memory usage is at peak.
  // Same to nodes_in_memory, it's a set of NodeDef* and port_num pairs.
  std::unordered_set<std::pair<const NodeDef*, int>, NodePairHash>
      mem_usage_snapshot_at_peak;

  Costs device_costs;
  std::map<string, Costs> op_to_cost;  // Per-op cost.

  int64 memory_usage;      // Current temporary memory usage
  int64 max_memory_usage;  // Max temporary memory usage

  DeviceState() {
    device_costs = Costs::ZeroCosts();
    device_costs.num_ops_total = 0;
    memory_usage = 0;
    max_memory_usage = 0;
  }

  Costs::Duration GetCurrTime() const { return device_costs.execution_time; }
};

// ReadyNodeManager (abstract class):
// Keeps ready nodes and picks the best one to be scheduled.
class ReadyNodeManager {
 public:
  ReadyNodeManager() {}
  virtual ~ReadyNodeManager() {}
  virtual void Init(
      const std::unordered_map<const NodeDef*, NodeState>* node_state) {}
  virtual void AddNode(const NodeDef* node) = 0;
  virtual const NodeDef* GetCurrNode() = 0;
  virtual void RemoveCurrNode() = 0;
  virtual bool Empty() const = 0;
};

class FIFOManager : public ReadyNodeManager {
 public:
  FIFOManager() : ReadyNodeManager() {}
  ~FIFOManager() override {}
  void Init(const std::unordered_map<const NodeDef*, NodeState>* node_state)
      override {}
  void AddNode(const NodeDef* node) override { nodes_.push_back(node); }
  const NodeDef* GetCurrNode() override {
    CHECK(!nodes_.empty()) << "GetCurrNode(), but there's no ready node";
    return nodes_.front();
  }
  void RemoveCurrNode() override { nodes_.pop_front(); }
  bool Empty() const override { return nodes_.empty(); }

 private:
  std::list<const NodeDef*> nodes_;
};

// The LIFOManager schedules nodes by returning the last one added to the
// scheduler. A node is executed and then its ready outputs are newly added to
// the scheduler, so the LIFOManager will return outputs to a node following
// that node's execution.
class LIFOManager : public ReadyNodeManager {
 public:
  LIFOManager() : ReadyNodeManager() {}
  ~LIFOManager() override {}
  void Init(const std::unordered_map<const NodeDef*, NodeState>* node_state)
      override {}
  void AddNode(const NodeDef* node) override { nodes_.push_back(node); }
  const NodeDef* GetCurrNode() override;
  void RemoveCurrNode() override;
  bool Empty() const override { return nodes_.empty(); }

 private:
  std::list<const NodeDef*> nodes_;
  // Keep track of the current node being executed by saving its position.
  // Necessary because nodes may be added to the end of the list while a node is
  // executing, and we want to remove the correct node (the one that is
  // executing) rather than the new ones being added.
  std::list<const NodeDef*>::iterator curr_pos_ = nodes_.end();
};

// FirstReadyManager picks a node with the minimum time_ready value.
// Behavior is unknown if there are more than one nodes with the minimum
// time_ready value (it depends on C++ STL push_heap and pop_heap).
class FirstReadyManager : public ReadyNodeManager {
 public:
  FirstReadyManager();
  void Init(
      const std::unordered_map<const NodeDef*, NodeState>* node_state) override;
  ~FirstReadyManager() override {}
  void AddNode(const NodeDef* node) override { waiting_queue_.push_back(node); }
  const NodeDef* GetCurrNode() override;
  void RemoveCurrNode() override;
  bool Empty() const override;

 private:
  // Move all the nodes in the waiting_queue_ to nodes_.
  void DrainWaitingQueue();

  // nodes_ is the main queue, where we construct heap, and the front is the
  // current node.
  std::vector<const NodeDef*> nodes_;
  // Newly added nodes are added to waiting_queue_. That way, GetCurrNode(),
  // which returns the front of the nodes_, always returns the same node,
  // even if any of new nodes has time_ready smaller than the current node's.
  std::vector<const NodeDef*> waiting_queue_;
  // Comparator functor for heap; stl heap is max heap, so we use "greater than"
  // functor for keeping the smallest time_ready node at the front of heap.
  std::function<bool(const NodeDef*, const NodeDef*)> greater_;

  // NodeState structure from VirtualScheduler to get time_ready of ready nodes.
  // Not owned by FirstReadyManager.
  const std::unordered_map<const NodeDef*, NodeState>* node_state_;
};

// CompositeNodeManager has a few other NodeManagers: per-device LIFO for normal
// ops (neither _Send nor _Recv) and FirstReadyManagers for _Send ops and _Recv
// ops, and then it chooses FirstReady among the ops chosen from each
// internal NodeManagers. The objective is to maximize producer-consumer
// locality within device, while processing nodes across devices, including
// _Send and _Recv, fairly, in terms of their time_ready.
class CompositeNodeManager : public ReadyNodeManager {
 public:
  CompositeNodeManager();
  ~CompositeNodeManager() override {}

  void Init(
      const std::unordered_map<const NodeDef*, NodeState>* node_state) override;
  void AddNode(const NodeDef* node) override;
  const NodeDef* GetCurrNode() override;
  void RemoveCurrNode() override;
  bool Empty() const override;

 private:
  // Internal ready node managers:
  // LIFO for normal ops to maximize producer consumer locality.
  // One LIFO per device.
  std::unordered_map<string, LIFOManager> ops_lifo_map_;
  // FirstReady for send and recv. Handle send and recv separately ensures that
  // send and recv do not block previously read ops with LIFO schedule.
  FirstReadyManager send_manager_;
  FirstReadyManager recv_manager_;

  // NodeState structure from VirtualScheduler to get time_ready of ready nodes.
  // Not owned by FirstReadyManager.
  const std::unordered_map<const NodeDef*, NodeState>* node_state_;

  // Cached curr node. Set back to nullptr from RemoveCurrNode().
  const NodeDef* curr_node_;
};

// Constructs a ready node manager from the given string.
std::unique_ptr<ReadyNodeManager> ReadyNodeManagerFactory(
    const string& ready_node_manager);

// The virtual scheduler emulates execution of nodes in a graph, considering
// dependencies, device, etc.
class VirtualScheduler {
 public:
  // Does not take ownership of cluster or ready_nodes.
  VirtualScheduler(const bool use_static_shapes,
                   const bool use_aggressive_shape_inference, Cluster* cluster,
                   ReadyNodeManager* ready_nodes);
  // Initializes the scheduler for the specific grappler item.
  // Should be called immediately after the c'tor or when the scheduler will be
  // reused for a new grappler item. All internal states of the scheduler
  // related to the previous grappler item will be reset/cleared.
  //
  // This function should be called at least once after the scheduler is
  // constructed. An uninitialized or failed-to-initialize scheduler will cause
  // undefined behavior.
  Status Init(const GrapplerItem* item);

  OpContext GetCurrNode() const;

  // Returns true if there is any node to be scheduled.
  bool MarkCurrNodeExecuted(const Costs& node_costs);

  // Prints out summary of execution (timing, memory usage, etc.)
  Costs Summary() const;
  // Like the above, but writes detailed stats to RunMetadata.
  // If metadata is nullptr, then just calls and return Summary().
  Costs Summary(RunMetadata* metadata);
  // Generate RunMetadata's step_stats and partition_graphs fields from results
  // of the virtual execution of the graph.
  void GenerateRunMetadata(RunMetadata* metadata);

  // DEPRECATED
  static ReadyNodeManager* ReadyNodeManagerFactory(
      const string& ready_node_manager);

  // Return per device peak memory usage.
  const std::unordered_map<string, int64> GetPeakMemoryUsage() const;

  const std::unordered_map<string, DeviceState>* GetDeviceStates() const {
    return &device_;
  }
  const std::unordered_map<const NodeDef*, NodeState>* GetNodeStates() const {
    return &node_map_;
  }

  void enable_mem_usage_tracking() { track_mem_usage_snapshot_ = true; }

 private:
  // Constants.
  const string kAttrInputSrc = "input_source_";
  const string kAttrSrcDevice = "send_device";
  const string kAttrDstDevice = "recv_device";
  const string kAttrTensorName = "tensor_name";
  const string kChannelDevice = "Channel";

  // Methods called from Init(). Fails if initialize_ is set.
  void MaybeUpdateInputOutput(const NodeDef* node);
  NodeState& GetNodeStateOrCreateIt(const NodeDef* node);
  std::pair<const NodeDef*, const NodeDef*> CreateSendRecv(
      const NodeDef* from, const NodeDef* to, const NodeDef* input_node,
      const string& input_name);
  string DeviceName(const NodeDef* node) const;
  string SanitizedDeviceName(const NodeDef* node) const;
  string ChannelDeviceName(const NodeDef* from, const NodeDef* to) const;

  // Helper methods.
  Costs& FindOrCreateZero(const string& op_name,
                          std::map<string, Costs>* op_cost);
  float Round2(const float x) const;
  bool IsPersistentNode(const NodeDef* node) const;
  bool AddSwitchOutputsToReadyQueue(const NodeDef* node, int curr_iter,
                                    const Costs::Duration& curr_time);
  void AddOutputNodesToReadyQueue(const NodeDef* node,
                                  const Costs::Duration& curr_time);

  // Scheduler states:
  ReadyNodeManager* ready_nodes_;  // Not owned.
  std::unordered_map<const NodeDef*, NodeState> node_map_;
  std::unordered_map<string, DeviceState> device_;

  // Pool of NodeDefs for SendRecv and Identity ops created.
  std::vector<std::unique_ptr<NodeDef>> additional_nodes_;

  // Stats:
  // Op counts with key with input shape.
  // Example key: "[Op=AssignSub, input_shapes=[[7,1,160,160][7,1,160,160]]"
  std::map<string, int> op_counts_;
  // Individual op costs with key with input shape.
  // Integer field for execution time in micro seconds.
  // Boolean field for whether the cost is accurate.
  std::map<string, std::pair<int, bool>> op_costs_;

  Costs graph_costs_;                   // Graph cost.
  std::map<string, Costs> op_to_cost_;  // Per-op cost.

  // Auxiliary data structures for constructing NodeState and DeviceState.
  std::unique_ptr<GraphProperties> graph_properties_;  // Initialized in Init().
  Cluster* cluster_;                                   // Not owned.

  const GrapplerItem* grappler_item_;  // Not owned.
  bool use_static_shapes_;
  bool initialized_;
  bool track_mem_usage_snapshot_;
  const bool use_aggressive_shape_inference_;

  // Whether the input graph includes Switch nodes annotated with output slots
  // information.
  bool switch_outputs_annotated_ = false;

  VirtualPlacer placer_;  // owned.
};

}  // namespace grappler
}  // end namespace tensorflow

#endif  // TENSORFLOW_CORE_GRAPPLER_COSTS_VIRTUAL_SCHEDULER_H_


text:
/**
 *
 * Create a set of Routes
 * Create a set of Things on the Routes
 * Send events for the things at a specified rate
 *
 *
 * David Jennings
 */
package org.jennings.route;

import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author david
 */
public class SendEvents {

    static long numEventsSent;
    static long numIterations;

    final private int STDOUT = 0;
    final private int TCP = 1;
    final private int HTTP = 2;

    final private int TXT = 0;
    final private int JSON = 1;

    final private int DURATIONSSECS = 86400;
    final private int HTTPBATCH = 1000;
    final private int SHOWCNTEVERY = 1000;

    Timer timer;
    int output;
    int fmt;
    int iterations;

//    Routes rts;
    ArrayList<Thing> things = new ArrayList<>();

    private OutputStream os = null;

    private final String USER_AGENT = "Mozilla/5.0";

    private HttpClient httpClient;
    private HttpPost httpPost;

    class CheckCount extends TimerTask {

        @Override
        public void run() {

            numIterations += 1;

            String postData = ""; // Combine lines and send in groups
            JSONArray jsonArray = new JSONArray();
            JSONObject js = new JSONObject();

            for (Thing t : things) {

                numEventsSent += 1;
                t.setPosition(System.currentTimeMillis());

                String d = ",";

                String line = "";

                switch (fmt) {
                    case TXT:
                        line = t.id + d + t.timestamp + d + t.speed * 1000.0 + d
                                + t.dist + d + t.bearing + d + t.rt.id + d
                                + "\"" + t.location + "\"" + d + t.secsToDep + d
                                + t.gc.getLon() + d + t.gc.getLat();
                        break;
                    case JSON:
                        js = new JSONObject();
                        js.put("id", t.id);
                        js.put("timestamp", t.timestamp);
                        js.put("speed", t.speed * 1000.0);
                        js.put("dist", t.dist);
                        js.put("bearing", t.bearing);
                        js.put("routeid", t.rt.id);
                        js.put("location", t.location);
                        js.put("secsToDep", t.secsToDep);
                        js.put("lon", t.gc.getLon());
                        js.put("lat", t.gc.getLat());
                        line = js.toString();

                }

                switch (output) {
                    case STDOUT:
                        System.out.println(line);
                        break;
                    case TCP:
                        line += "\n";
                        try {
                            os.write(line.getBytes());
                            os.flush();
                            if (numEventsSent % SHOWCNTEVERY == 0) {
                                System.out.println("Total Events Sent: " + numEventsSent);
                            }
                        } catch (Exception e) {
                            //System.out.println("Failed to write to socket");
                        }
                        break;
                    case HTTP:
                        if (fmt == TXT) {
                            postData += line + "\n";
                        } else if (fmt == JSON) {
                            jsonArray.put(js);
                        }

                        if (numEventsSent % HTTPBATCH == 0) {
                            try {
                                if (fmt == TXT) {
                                    postLine(postData);
                                } else if (fmt == JSON) {
                                    postLine(jsonArray.toString());
                                }

                                postData = "";
                                jsonArray = new JSONArray();
                                js = new JSONObject();
                            } catch (Exception e) {
                                System.out.println("Post Failed");
                            }

                        }
                        break;
                    default:
                        System.out.println("Invalid Output");
                }

                if (numIterations >= iterations) {
                    timer.cancel();
                }

            }

        }

    }

    private void postLine(String line) throws Exception {

        StringEntity postingString = new StringEntity(line);

        httpPost.setEntity(postingString);

        if (fmt == TXT) {
            httpPost.setHeader("Content-type", "plain/text");
        } else if (fmt == JSON) {
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse resp = httpClient.execute(httpPost);

        }

        httpPost.releaseConnection();
    }

    /*
     where: (default -)
        - http://urlendpoint (http)
        - server:port (tcp) - Use '-' to send to standard output
     what: (default 10:10)
        - numRoutes:numThings -> Create numRoutes and then create numThings using these routes
        - numRoutes:numThings:lllon,lllat,urlon,urlat -> Same as before only limited routes to the bounding box
        - filename:numThings -> Load routes from filename and create numThings using these routes
     how: (default 10:txt)
        - Number of seconds between sending updates
        - Format of things (txt or json)
        - Optional number of iterations (default sends until manually interupted)
     */
    /**
     * Timer contents
     *
     * Compile event(s) and send
     *
     */
    private void send(String where, String what, String how) {

        String parts[];
        String parts2[];

        try {

            parts = how.trim().split(":");
            int rate = Integer.parseInt(parts[0]);
            if (rate < 1) {
                rate = 1;
            }

            fmt = TXT;

            if (parts.length > 1) {
                String fmtRequested = parts[1];
                if (fmtRequested.equalsIgnoreCase("JSON")) {
                    fmt = JSON;
                } else {
                    fmt = TXT;
                }
            }

            iterations = -1;
            if (parts.length > 2) {
                Integer iterationsReq = Integer.parseInt(parts[2]);
                if (iterationsReq > 0) {
                    iterations = iterationsReq;
                }

            }

            numEventsSent = 0;

            Routes rts;
            // Parse where
            parts = where.trim().split(":");

            if (parts[0].equalsIgnoreCase("-")) {
                output = STDOUT;
            } else if (parts[0].equalsIgnoreCase("http")) {
                output = HTTP;
                httpClient = HttpClientBuilder.create().build();

                httpPost = new HttpPost(where);

            } else {
                output = TCP;
                int port = 5565;
                String server = parts[0];

                port = Integer.parseInt(parts[1]);

                Socket skt = new Socket(server, port);
                this.os = skt.getOutputStream();
            }

            parts = what.trim().split(":");
            int numThg = 10;

            // Parse what
            try {
                int numRt = Integer.parseInt(parts[0]);
                numThg = Integer.parseInt(parts[1]);

                if (parts.length == 2) {
                    rts = new Routes();
                    rts.createRandomRoutes(numRt, DURATIONSSECS);
                } else {
                    // bbox provided
                    parts2 = parts[1].split(",");
                    double lllon = Double.parseDouble(parts2[0]);
                    double lllat = Double.parseDouble(parts2[1]);
                    double urlon = Double.parseDouble(parts2[2]);
                    double urlat = Double.parseDouble(parts2[3]);

                    rts = new Routes(lllon, lllat, urlon, urlat);
                    rts.createRandomRoutes(numRt, DURATIONSSECS);

                }

            } catch (NumberFormatException e) {
                // The what is not not a number assume file
                rts = new Routes();
                rts.load(parts[0]);

                if (parts.length == 1) {
                    // Default to 10
                    numThg = 10;
                } else {
                    numThg = Integer.parseInt(parts[1]);
                }

            }

            // Create Things
            Random rnd = new Random();
            int i = 0;
            while (i < numThg) {

                int rndoffset = Math.abs(rnd.nextInt());

                Thing t = new Thing(i, rts.get(i), rndoffset);
                things.add(t);
                i++;

            }

//            System.out.println("HERE");
//
//            System.out.println(rts.rts);
            timer = new Timer();
            timer.schedule(new CheckCount(), 0, rate * 1000);

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public static void main(String[] args) {

        int numArgs = args.length;

        String where = "-";
        //String what = "routesTwoDay1000.json:20";
        String what = "10:20";
        String how = "10:txt";

//        SendEvents t = new SendEvents();
//        t.send(where, what, how);

        if (numArgs == 0) {
            System.err.println("Usage: SendEvents <where> (<what> <how>)");
            System.err.println();
            System.err.println("where: Dash '-' for stdout (default) |  server:port for tcp | url for http");
            System.err.println();
            System.err.println("what: numRandomRoute:numRandomThings:<bounding box> or filename:numberRandomThings");
            System.err.println("     bounding box format: lowerleftlon,lowerleftlat,upperrightlon,upperrightlat");
            System.err.println("     default: 10:20");
            System.err.println();
            System.err.println("how: seconds:format | seconds:format:num");
            System.err.println("     valid formats: json:txt");
            System.err.println("     num: if specified is number of iterations; otherwise output continues until manually interupted (Ctrl-C)");
            System.err.println("     default: 10:txt (output sample every 10 seconds in text format)");

        } else {

            if (numArgs >= 1) {
                where = args[0];
            }

            if (numArgs >= 2) {
                what = args[1];
            }

            if (numArgs >= 3) {
                how = args[2];
            }

            SendEvents t = new SendEvents();
            t.send(where, what, how);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Facebook;
using Microsoft.Phone.Shell;
using System.Windows.Media.Imaging;
using System.IO;

namespace MonsterCam
{
    public partial class Facebook : PhoneApplicationPage
    {
        private FacebookClient client;
        private string token;

        void FaceBookIdentification()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["response_type"] = "token";
            parameters["display"] = "touch";
            parameters["scope"] = "user_photos,publish_stream";
            parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
            parameters["client_id"] = "";

             client = new FacebookClient();
            Uri uri = client.GetLoginUrl(parameters);
            wb.Navigate(uri);
        }

        void updateAccessToken()
        {
            client = new FacebookClient();

            // Affectation de l'access token existant
            client.AccessToken = token;

            client.GetCompleted += (a, e) =>
                {
                    Dispatcher.BeginInvoke(() =>
                        {
                            if (e.Error == null)
                            {
                                if ((string)e.UserState == "exchange_token")
                                {
                                    JsonObject data = (JsonObject)e.GetResultData();

                                    // Enregistrement du nouvel access token
                                    token = (string)data["access_token"];
                                    App.AddOrUpdateValue("token2", token);

                                }
                            }
                            else
                            {
                                wb.Visibility = Visibility.Visible;
                                FaceBookIdentification();

                            }
                        });
                };

            // Préparation de la requête d'échange d'access token
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters["client_id"] = "";
            parameters["client_secret"] = "";
            parameters["grant_type"] = "fb_exchange_token";
            parameters["fb_exchange_token"] = client.AccessToken;

            client.GetAsync("https://graph.facebook.com/oauth/access_token", parameters, "exchange_token");
        }

        public Facebook()
        {
            InitializeComponent();
            if (App.GetValue("token") != null)
            {
                var client = new FacebookClient(App.GetValue("token") as string);
                App.AddOrUpdateValue("token", null);
                Uri uri = client.GetLogoutUrl(new Dictionary<string, object>());
                wb.Navigate(uri);
            }
            token = App.GetValue("token2") as string;
            if (token != null)
            {
                wb.Visibility = Visibility.Collapsed;
                updateAccessToken();
            }
            else
            {
                wb.Visibility = Visibility.Visible;

                FaceBookIdentification();
            }

            ApplicationBar.Buttons.Clear();

            ApplicationBarIconButton appUploadButton = new ApplicationBarIconButton(new Uri("data/appbar.upload.rest.png", UriKind.Relative));
            appUploadButton.Text = "upload";
            appUploadButton.Click += (e, s) =>
            {
                try
                {
                    if (token == null)
                    {
                        wb.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        ApplicationBar.IsVisible = false;
                        Message.IsEnabled = false;
                        var prog = new ProgressIndicator();
                        prog.IsVisible = true;
                        prog.IsIndeterminate = true;
                        prog.Text = "upload...";

                        SystemTray.SetProgressIndicator(this, prog);
                        postimage();
                    }
                }
                catch (Exception)
                {
                }

            };
            ApplicationBar.Buttons.Add(appUploadButton);

            ApplicationBarIconButton appWallButton = new ApplicationBarIconButton(new Uri("data/fb_wall.png", UriKind.Relative));
            appWallButton.Text = "wall";
            appWallButton.Click += (e, s) =>
            {
                try
                {
                    if (token == null)
                    {
                        wb.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        ApplicationBar.IsVisible = false;
                        Message.IsEnabled = false;
                        var prog = new ProgressIndicator();
                        prog.IsVisible = true;
                        prog.IsIndeterminate = true;
                        prog.Text = "upload...";

                        SystemTray.SetProgressIndicator(this, prog);
                        postmessage();
                    }
                }
                catch (Exception)
                {
                }

            };
            ApplicationBar.Buttons.Add(appWallButton);

            var I = (byte[])App.GetValue("image_selected");
            var bmp = new BitmapImage();
            using (MemoryStream stream = new MemoryStream(I))
            {
                bmp.SetSource(stream);
            }
            image.Source = bmp;

        }

        void postmessage()
        {
            var I = (byte[])App.GetValue("image_selected");
            UploadPhoto("me", token, I, true);
        }

        void postimage()
        {
            var I = (byte[])App.GetValue("image_selected");
            UploadPhoto("me", token, I, false);
        }
        public void CreateAlbum(string accessToken, string name/*,EventHandler<FacebookApiEventArgs> ev*/)
        {
            FacebookClient facebookClient = new FacebookClient(accessToken);
            Dictionary<string, object> albumParameters = new Dictionary<string, object>();
            albumParameters.Add("message", "My Album message");
            albumParameters.Add("name", name);
            facebookClient.PostCompleted += (s, ee) =>
                        {
                            JsonObject data = (JsonObject)ee.GetResultData();
                            string id = (string)data["id"];
                            App.AddOrUpdateValue("id", id);
                            Deployment.Current.Dispatcher.BeginInvoke(delegate()
                   {
                       postimage();
                   });
                        };
            facebookClient.PostAsync("/me/albums", albumParameters);

        }

        public void UploadPhoto(string AlbumId, string accessToken, byte[] fileBytes, bool postmesage)
        {
            FacebookClient facebookClient = new FacebookClient(accessToken);

            FacebookMediaObject mediaObject = new FacebookMediaObject
            {
                FileName = Guid.NewGuid() + ".jpg",
                ContentType = "image/jpeg"
            };
            mediaObject.SetValue(fileBytes);
            IDictionary<string, object> upload = new Dictionary<string, object>();
            if (postmesage)
            {
                upload.Add("name", String.Format("MonsterCam {0:yyyyMMdd-HHmmss}.jpg", DateTime.Now));
            }
            else
            {
                upload.Add("name", Message.Text);
            }
            // upload.Add("message", "test sur l'upload d'une photo");
            //upload.Add("caption", "test sur l'upload d'une photo");
            upload.Add("@file.jpg", mediaObject);

            facebookClient.PostCompleted += (s, ee) =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                    {
                        if (ee.Error != null)
                        {
                            MessageBox.Show(ee.Error.Message);
                            NavigationService.GoBack();
                        }

                        else
                        {
                            if (postmesage)
                            {
                                try
                                {
                                    JsonObject data = (JsonObject)ee.GetResultData();
                                    string id = (string)data["id"];
                                    var tmp = new FacebookClient(accessToken);
                                    tmp.GetCompleted += (a, b) =>
                                        {
                                            Deployment.Current.Dispatcher.BeginInvoke(delegate()
                                            {
                                                if (b.Error != null)
                                                {
                                                    MessageBox.Show(ee.Error.Message);
                                                    NavigationService.GoBack();
                                                }
                                                else
                                                {
                                                    try
                                                    {
                                                        JsonObject data2 = (JsonObject)b.GetResultData();
                                                        postMessage(token, (string)data2["source"], (string)data2["link"]);
                                                    }
                                                    catch (Exception exp)
                                                    {
                                                        MessageBox.Show("Facebook error. Check allowed permission");
                                                        NavigationService.GoBack();
                                                    }
                                                }
                                            });

                                        };
                                    tmp.GetAsync(id);
                                }
                                catch (Exception exp)
                                {
                                    MessageBox.Show("Facebook error. Check allowed permission");
                                    NavigationService.GoBack();
                                }
                                // postMessage(token, id);
                            }
                            else
                            {
                                if (App.IsTrial)
                                {
                                    var displayPopup = new CustomDialog("Picture uploaded");

                                    displayPopup.popup.IsOpen = true;
                                    displayPopup.Closed += () =>
                                    {
                                        NavigationService.GoBack();
                                    };
                                }
                                else
                                {
                                    MessageBox.Show("Picture uploaded");
                                    NavigationService.GoBack();
                                }

                            }
                        }

                    });
            };
            facebookClient.PostAsync("/" + AlbumId + "/photos", upload);

        }

        public void postMessage(string accessToken, string name, string link/*,EventHandler<FacebookApiEventArgs> ev*/)
        {
            FacebookClient facebookClient = new FacebookClient(accessToken);
            Dictionary<string, object> albumParameters = new Dictionary<string, object>();

           // albumParameters.Add("caption", "MonsterCam");
            albumParameters.Add("message", Message.Text);

            if (App.IsTrial)
            {
                albumParameters.Add("picture", name);
                albumParameters.Add("link", "http://windowsphone.com/s?appid=8ac6c849-7b2f-4fa4-9be4-7e9d5f3e46a2");
            }
            else
            {
                albumParameters.Add("link", link);
            }
            //  albumParameters.Add("object_attachment", name);
            //albumParameters.Add("attachment", name);

            facebookClient.PostCompleted += (s, ee) =>
            {
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    if (ee.Error != null)
                    {
                        MessageBox.Show(ee.Error.Message);

                    }
                    else
                    {
                        if (App.IsTrial)
                        {
                            var displayPopup = new CustomDialog("Message posted");

                            displayPopup.popup.IsOpen = true;
                            displayPopup.Closed += () =>
                            {
                                NavigationService.GoBack();
                            };
                        }
                        else
                        {
                            MessageBox.Show("Message posted");
                            NavigationService.GoBack();
                        }
                        // MessageBox.Show("Message posted");

                    }

                });
            };
            facebookClient.PostAsync("/me/feed", albumParameters);

        }

        private void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            FacebookOAuthResult result;
            if (client.TryParseOAuthCallbackUrl(e.Uri, out result))
            {
                if (result.IsSuccess)
                {
                    token = result.AccessToken;

                    App.AddOrUpdateValue("token2", token);

                }
                wb.Visibility = Visibility.Collapsed;
            }

        }

        private void wb_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            MessageBox.Show(e.Exception.Message);
            NavigationService.GoBack();
        }
    }
}


text:
Advanced Features
=================

This chapter describes miscellaneous features of :mod:`asynctest` which can be
leveraged in specific use cases.

Controlling time
----------------

Tests running calls to :func:`asyncio.sleep` will take as long as the sum of
all these calls. These calls are frequent when testing for timeouts, for
instance.

In many cases, this will add a useless delay to the execution of the test
suite, and encourage us to deactivate or ignore these tests.

:class:`~asynctest.ClockedTestCase` is a subclass of
:class:`~asynctest.TestCase` which replaces the clock of the loop in a test
with a manually-controlled one. The clock will only advance when calling
:meth:`~asynctest.ClockedTestCase.advance`.

This will not affect the wall clock: functions like :func:`time.time` or
:meth:`datetime.datetime.now` will return the regular date and time of the
system.

.. literalinclude:: examples/tutorial/clock.py
   :pyobject: TestAdvanceTime

This example is pretty self-explanatory: we verified that the clock of the loop
advanced as expected, without awaiting 10 actual seconds and changing the time
of the wall clock.

Internally, :class:`~asynctest.ClockedTestCase` will ensure that the loop is
executed as if time was passing *fast*, instead of jumping the clock to the
target time.

.. literalinclude:: examples/tutorial/clock.py
   :pyobject: TestWithClockAndCallbacks

This example schedules function calls to be executed later by the loop.
Each call will verify that it runs at the expected time.
``@fail_on(active_handles=True)`` ensures that the callbacks have been executed
when the test finishes.

The source code of ``is_time_around()`` can be found in the example file
:doc:`examples/tutorial/clock.py`.

Mocking I/O
-----------

Testing libraries or functions dealing with low-level IO objects may be
complex: these objects are outside of our control, since they are owned by the
kernel. It can be impossible to exactly predict their behavior and simulate
edge-cases, such as the ones happening in a real-world scenario in a large
network.

Even worse, using mocks in place of files will often raise :exc:`OSError`
because these obhjects are not compatible with the features of the system used
by the loop.

:mod:`asynctest` provides special mocks which can be used in place of actual
file-like objects. They are supported by the loop provided by
:class:`~asynctest.TestCase` if the loop uses a standard implementation with a
selector (Window's Proactor loop or uvloop are not supported).

These mocks are configured with a spec matching common file-like objects.

=================================== ========================================
  Mock                               ``spec``
=================================== ========================================
 :class:`~asynctest.FileMock`        a file object, implements ``fileno()``
 :class:`~asynctest.SocketMock`      :class:`socket.socket`
 :class:`~asynctest.SSLSocketMock`   :class:`ssl.SSLSocket`
=================================== ========================================

We can use :func:`asynctest.isfilemock()` to differenciate mocks from regular
objects.

As of :mod:`asynctest` 0.12, these mocks don't provide other features, and must
be configured to return expected values for calls to methods like ``read()`` or
``recv()``.

When configured, we still need to force the loop to detect that I/O is possible
on these mock files.

This is done with :func:`~asynctest.set_read_ready()` and
:func:`~asynctest.set_write_ready()`.

.. literalinclude:: examples/tutorial/mocking_io.py
   :pyobject: TestMockASocket

In this example, we configure a socket mock to simulate a simple
request-response scenario with a TCP (stream) socket. Some data is available to
read on the socket once a request has been written. ``recv_side_effect()``
makes as if the data is received in several packets, but it has no impact on
the high level :class:`~asyncio.StreamReader`.

It's common that while a read operation blocks until data is available, a write
is often successful. Thus, we didn't bother simulating the case where the
congestion control would block the write operation.

Testing with event loop policies
--------------------------------

Advanced users may not be able to use the loop provided by
:class:`~asyncio.TestCase` because they use a customized event loop policy (see
:py:ref:`asyncio-policies`). It is often the case when using an alternative
implementation (like `uvloop <https://uvloop.readthedocs.io/>`_) or if the
tests are integrated within a framework hidding the scheduling and management
of the loop.

It is possible to force the :class:`~asynctest.TestCase` to use the loop
provided by the policy by setting the class attribute
:attr:`~asynctest.TestCase.use_default_loop`.

Conversely, authors of libraries may not want to assume which loop they should
use and let users explicitly pass the loop as argument to a function call. For
instance, most of the high-level functions of :py:mod:`asyncio` (see
:py:ref:`asyncio-streams`, for instance) allow the caller to specify the loop
to use if it needs this kind of flexibility.

:attr:`~asynctest.TestCase.forbid_get_event_loop` forbids the use of
:meth:`asyncio.get_event_loop`. An exception is raised if the method is
called while a test is running. It helps developers to ensure they don't rely
on the default loop this their library.

.. note::

   The behavior of :meth:`asyncio.get_event_loop()` changed over time.
   Explicitly passing the loop is not the recommended practice anymore.


text:
package org.apereo.cas.support.oauth.web;

import org.apereo.cas.support.oauth.OAuthConstants;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * This is {@link OAuth20HandlerInterceptorAdapter}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class OAuth20HandlerInterceptorAdapter extends HandlerInterceptorAdapter {
    /** Access token interceptor. */
    protected final HandlerInterceptorAdapter requiresAuthenticationAccessTokenInterceptor;

    /** Authorization interceptor. */
    protected final HandlerInterceptorAdapter requiresAuthenticationAuthorizeInterceptor;

    public OAuth20HandlerInterceptorAdapter(final HandlerInterceptorAdapter requiresAuthenticationAccessTokenInterceptor,
                                            final HandlerInterceptorAdapter requiresAuthenticationAuthorizeInterceptor) {
        this.requiresAuthenticationAccessTokenInterceptor = requiresAuthenticationAccessTokenInterceptor;
        this.requiresAuthenticationAuthorizeInterceptor = requiresAuthenticationAuthorizeInterceptor;
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response,
                             final Object handler) throws Exception {
        if (isAccessTokenRequestRequest(request.getRequestURI())) {
            return requiresAuthenticationAccessTokenInterceptor.preHandle(request, response, handler);
        }

        if (isAuthorizationRequest(request.getRequestURI())) {
            return requiresAuthenticationAuthorizeInterceptor.preHandle(request, response, handler);
        }
        return true;
    }

    /**
     * Is access token request request.
     *
     * @param requestPath the request path
     * @return the boolean
     */
    protected boolean isAccessTokenRequestRequest(final String requestPath) {
        return doesUriMatchPattern(requestPath, OAuthConstants.ACCESS_TOKEN_URL);
    }

    /**
     * Is authorization request.
     *
     * @param requestPath the request path
     * @return the boolean
     */
    protected boolean isAuthorizationRequest(final String requestPath) {
        return doesUriMatchPattern(requestPath, OAuthConstants.AUTHORIZE_URL);
    }

    /**
     * Does uri match pattern.
     *
     * @param requestPath the request path
     * @param patternUrl  the pattern
     * @return the boolean
     */
    protected boolean doesUriMatchPattern(final String requestPath, final String patternUrl) {
        final Pattern pattern = Pattern.compile('/' + patternUrl + "(/)*$");
        return pattern.matcher(requestPath).find();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class edu.wpi.first.wpilibj.networktables2.type.NetworkTableEntryType (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2013-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
edu.wpi.first.wpilibj.networktables2.type.NetworkTableEntryType

Packages that use NetworkTableEntryType

edu.wpi.first.wpilibj.networktables2

edu.wpi.first.wpilibj.networktables2.type

Uses of NetworkTableEntryType in edu.wpi.first.wpilibj.networktables2

Methods in edu.wpi.first.wpilibj.networktables2 that return NetworkTableEntryType

 NetworkTableEntryType
NetworkTableEntry.getType()

Methods in edu.wpi.first.wpilibj.networktables2 with parameters of type NetworkTableEntryType

 void
NetworkTableEntry.forcePut(char newSequenceNumber,
         NetworkTableEntryType type,
         Object newValue)

          force a value and new sequence number upon an entry, Will also set the type of the entry

 void
AbstractNetworkTableEntryStore.putOutgoing(String name,
            NetworkTableEntryType type,
            Object value)

          Stores the given value under the given name and queues it for
 transmission to the server.

 void
NetworkTableNode.putValue(String name,
         NetworkTableEntryType type,
         Object value)

          Put a value with a specific network table type

Constructors in edu.wpi.first.wpilibj.networktables2 with parameters of type NetworkTableEntryType

NetworkTableEntry(char id,
                  String name,
                  char sequenceNumber,
                  NetworkTableEntryType type,
                  Object value)

          Create a new entry with the given id, name, sequence number, type and value

NetworkTableEntry(String name,
                  NetworkTableEntryType type,
                  Object value)

          Create a new entry with the given name, type, value, an unknown id and a sequence number of 0

TableKeyExistsWithDifferentTypeException(String existingKey,
                                         NetworkTableEntryType existingType)

          Creates a new TableKeyExistsWithDifferentTypeException

TableKeyExistsWithDifferentTypeException(String existingKey,
                                         NetworkTableEntryType existingType,
                                         String message)

Uses of NetworkTableEntryType in edu.wpi.first.wpilibj.networktables2.type

Subclasses of NetworkTableEntryType in edu.wpi.first.wpilibj.networktables2.type

 class
ArrayEntryType

 class
ComplexEntryType

Fields in edu.wpi.first.wpilibj.networktables2.type declared as NetworkTableEntryType

static NetworkTableEntryType
DefaultEntryTypes.BOOLEAN

          a boolean entry type

static NetworkTableEntryType
DefaultEntryTypes.DOUBLE

          a double floating point type

static NetworkTableEntryType
DefaultEntryTypes.STRING

          a string type

Methods in edu.wpi.first.wpilibj.networktables2.type that return NetworkTableEntryType

 NetworkTableEntryType
NetworkTableEntryTypeManager.getType(byte id)

Constructors in edu.wpi.first.wpilibj.networktables2.type with parameters of type NetworkTableEntryType

ArrayEntryType(byte id,
               NetworkTableEntryType elementType,
               Class externalArrayType)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

"For updated information see the Java FRC site"


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <artifactId>pollKAT-Server</artifactId>
    <packaging>war</packaging>
    <groupId>pollKATgroup</groupId>
    <version>1.0-SNAPSHOT</version>

    <url>http://www.ninjaframework.org</url>

    <properties>
        <ninja.version>5.1.0</ninja.version>
        <jetty.version>9.2.10.v20150310</jetty.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>1.3.1</version>
                <executions>
                    <execution>
                        <id>enforce-banned-dependencies</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <bannedDependencies>
                                    <excludes>
                                        <exclude>commons-logging</exclude>
                                    </excludes>
                                </bannedDependencies>
                            </rules>
                            <fail>true</fail>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.version}</version>
                <configuration>
                    <contextPath>/</contextPath>
                    <stopKey>stop</stopKey>
                    <stopPort>8889</stopPort>
                    <scanIntervalSeconds>1</scanIntervalSeconds>
                    <reload>automatic</reload>
                    <scanTargetPatterns>
                        <scanTargetPattern>
                            <directory>target/classes</directory>
                            <includes>
                                <include>**/*</include>
                            </includes>
                            <excludes>
                                <exclude>**/*.ftl.html</exclude>
                                <exclude>assets/**</exclude>
                            </excludes>
                        </scanTargetPattern>
                    </scanTargetPatterns>
                    <systemProperties>
                        <systemProperty>
                            <name>ninja.mode</name>
                            <value>dev</value>
                        </systemProperty>
                    </systemProperties>
                </configuration>
            </plugin>
            <!-- Allows you to run Ninja via the SuperDevMode. -->
            <!-- run "mvn ninja:run" on the command line for the best -->
            <!-- development experience. -->
            <plugin>
                <groupId>org.ninjaframework</groupId>
                <artifactId>ninja-maven-plugin</artifactId>
                <version>${ninja.version}</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                    <archive>
                        <manifest>
                            <mainClass>ninja.standalone.NinjaJetty</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*</include>
                </includes>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>tinymce-jquery</artifactId>
            <version>4.0.16</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.182</version>
        </dependency>
        <!-- If you want to deploy to a war please -->
        <!-- comment ninja-standalone dependency and  -->
        <!-- uncomment the dependency for ninja-servlet -->
        <!--
        <dependency>
            <groupId>org.ninjaframework</groupId>
            <artifactId>ninja-servlet</artifactId>
            <version>${ninja.version}</version>
        </dependency>
        -->
        <dependency>
            <groupId>org.ninjaframework</groupId>
            <artifactId>ninja-standalone</artifactId>
            <version>${ninja.version}</version>
        </dependency>
        <dependency>
            <groupId>org.ninjaframework</groupId>
            <artifactId>ninja-test-utilities</artifactId>
            <version>${ninja.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
        </dependency>
       <dependency>
	<groupId>org.xerial</groupId>
	<artifactId>sqlite-jdbc</artifactId>
	<version>3.8.7</version>
</dependency>

    </dependencies>
</project>


text:
require "rich"

if Object.const_defined?("Rich")

  Rich.setup do |config|

    # Customize ckeditor by adding configuration to config.editor (you can use any ckeditor config directive)
    # Look at the Rich source for default settings. These settings can also be overridden per editor instance.
    # Example: config.editor[:skin] = 'office2003' # ill advice, but you get the idea
    # Example: config.editor[:startupOutlineBlocks] = false

    config.image_styles = {
      :large => "500x500",
      :thumb => "100x100#"
    }

    # config.allowed_styles = :all # this is the default - show all styles
    # config.allowed_styles = [ :large, :original ]
    # config.allowed_styles = [ :large, :thumb ]

    config.default_style = :large

    #config.authentication_method = :authenticate_admin_user!

  end

  # activate Rich
  Rich.insert
end


text:
/*  Getting the new tags to behave */
article, aside, audio, canvas, command, datalist, details, embed, figcaption, figure, footer, header, hgroup, keygen, meter, nav, output, progress, section, source, video {display:block}
mark, rp, rt, ruby, summary, time {display:inline}
/*  Global properties */
html {width:100%}
body {font-family: Arial, Helvetica, sans-serif;font-size:100%;color:#696969;min-width:1080px;background:#f2f2f2}
.ic, .ic a {border:0;float:right;background:#fff;color:#f00;width:50%;line-height:10px;font-size:10px;margin:-220% 0 0 0;overflow:hidden;padding:0}
.bg-1 {width:100%;padding:20px 0 18px;background:url(../images/bg1-tail.gif) center bottom repeat-x #f2f2f2}
.bg-2 {width:100%;padding:37px 0 46px;background:#fff}
.main {width:900px;padding:0;margin:0 auto;font-size:0.875em;line-height:1.428em}
a {color:#c53005;outline:none}
a:hover {text-decoration:none}
.col-1, .col-2 {float:left}
.wrapper {width:100%;overflow:hidden}
.extra-wrap {overflow:hidden}
p {margin-bottom:18px}
.p1 {margin-bottom:8px}
.p2 {margin-bottom:15px}
.p3 {margin-bottom:30px}
.p4 {margin-bottom:40px}
.p5 {margin-bottom:50px}
.fleft {float:left}
.fright {float:right}
.alignright {text-align:right}
.aligncenter {text-align:center}
.frame {padding:1px;border:1px solid #e5e5e5;background:#fff}
/* boxes */
.margin-bot {margin-bottom:35px}
.indent {padding:0 0 0px 30px}
.indent2 {padding-left:50px}
.indent-bot {margin-bottom:20px}
.img-indent-bot {margin-bottom:25px}
.img-indent {float:left;margin:0 32px 0px 0}
.img-indent2 {float:left;margin:0 28px 0px 0}
.img-indent3 {float:left;margin:0 18px 0px 0}
.img-indent4 {float:left;margin:0 20px 0px 0}
.prev-indent-bot {margin-bottom:10px}
.buttons a:hover {cursor:pointer}
.menu li a, .news-list li a, .link, .link-1, .button, .logo {text-decoration:none}
/* header */
header {min-height:271px;width:100%;position:relative;z-index:2;background:url(../images/header-bg1.jpg) center bottom no-repeat}
.row-top {padding-top:13px;height:139px;width:100%;background:url(../images/row-top-tail.png) center 13px repeat}
.row-bot {width:100%;text-align:center;padding-top:27px;overflow:hidden}
h1 {padding:31px 0 0 0;position:relative;float:left}
.logo {display:block;width:313px;height:68px;text-indent:-5000px;background:url(../images/logo.png) 0 0 no-repeat}
.slog-1 {display:block;font-size:80px;line-height:1.2em;color:#fff;letter-spacing:-4px;margin:0 0 -26px -5px}
.slog-2 {display:block;font-size:80px;line-height:1.2em;color:#fff;letter-spacing:-4px;margin:0 0 -26px -5px}
.slog-3 {display:block;font-size:80px;line-height:1.2em;color:#fff;letter-spacing:-4px;margin-left:-5px}
/*  main menu  */
.menu {float:right;padding-top:53px}
.menu li {float:left;position:relative;padding-left:37px}
.menu li a {display:inline-block;font-size:19px;line-height:1.21em;color:#000}
.menu li a.active, .menu li a:hover {color:#c53005}
/* content */
#content {width:100%;padding:0;position:relative;z-index:1}
h3 {font-size:30px;line-height:1.2em;color:#000;letter-spacing:-1px}
h4 {font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;font-size:19px;line-height:1.21em;font-style:normal;font-weight:normal;color:#8c8c8c}
.title-1 {display:block;font-size:25px;line-height:1.2em;margin-bottom:-5px;color:#000}
.title-2 {display:block;font-size:25px;line-height:1.2em;margin-bottom:17px;color:#000}
.title-3 {display:block;font-size:23px;line-height:1.217em;margin-bottom:10px;color:#000}
.news-title {display:inline-block;font-size:49px;line-height:1.2em;color:#fff;letter-spacing:-2px;margin-left:-5px}
.border-bot {width:100%;padding-bottom:15px;background:url(../images/pic-2.gif) 0 bottom repeat-x}
.box-1 {width:177px;padding:12px 32px 20px 0;text-align:center;background:url(../images/pic-1.gif) right top repeat-y}
.box-2 {width:241px;padding:12px 0 20px 0;text-align:center;background:url(../images/pic-1.gif) right top repeat-y}
.box-3 {width:175px;padding:12px 0 20px 32px;text-align:center}
.button {display:inline-block;font-size:14px;line-height:24px;min-width:71px;padding:7px 5px;color:#696969;text-align:center;border:1px solid #c2c2c2;background:url(../images/button-tail.gif) 0 0 repeat-x #eee;border-radius:6px;-moz-border-radius:6px;-webkit-border-radius:6px}
.button:hover {color:#fff;background:#696969}
.news-list {float:right}
.news-list li {float:left;padding-left:24px}
.news-list li a {display:inline-block;font-size:49px;line-height:1.2em;color:#edae89;letter-spacing:-2px}
.news-list li a.active,
.news-list li a:hover {color:#fff}
.link:hover {text-decoration:underline}
.link-1 {color:#696969}
.link-1:hover {color:#c53005}
.tdate-1 {display:block;padding-top:10px;margin-bottom:5px}
.tdate-2 {display:block;font-family:"Palatino Linotype", "Book Antiqua", Palatino, serif;font-size:18px;line-height:1.22em;font-style:italic;font-weight:normal;color:#8c8c8c}
dl span {float:left;width:91px}
/*  contact form  */
#contact-form {display:block}
#contact-form label {display:block;height:30px;overflow:hidden}
#contact-form input {width:219px;font-size:12px;color:#696969;padding:1px 10px;margin:0;font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;border:1px solid #ccc;background:#fff}
#contact-form textarea {height:230px;overflow:auto;width:459px;font-size:12px;color:#696969;padding:10px;margin:0;font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;border:1px solid #ccc;background:none}
.text-form {float:left;display:block;font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;font-size:14px;width:96px;line-height:1.7em;color:#696969}
.buttons {padding-top:8px;text-align:right}
.buttons a {margin-left:16px}
/* footer */
footer {width:100%;padding:35px 0 50px;background:url(../images/footer-tail.gif) left top repeat-x #f2f2f2}
footer .main {font-size:0.8125em;line-height:1.538em}
.phone-numb {display:block;font-size:19px;line-height:1.2em;color:#818181;margin-bottom:10px}
.phone-numb strong {color:#000}
.social-title {display:block;font-size:19px;line-height:1.2em;color:#000;margin-bottom:16px}
.list-services li {float:left;padding:0 7px 0 0}
.list-services li a {display:block;width:33px;height:33px;background-image:url(../images/social-icon.png);background-repeat:no-repeat}
.list-services li a.item-1 {background-position:0 top}
.list-services li a.item-2 {background-position:-33px top}
.list-services li a.item-3 {background-position:-66px top}
.list-services li a.item-4 {background-position:-99px top}
.list-services li a.item-5 {background-position:-132px top}
.list-services li a.item-1:hover {background-position:0 bottom}
.list-services li a.item-2:hover {background-position:-33px bottom}
.list-services li a.item-3:hover {background-position:-66px bottom}
.list-services li a.item-4:hover {background-position:-99px bottom}
.list-services li a.item-5:hover {background-position:-132px bottom}

.required {
	border:solid 2px red;
	background:#ffc;
}

.alert {
	color:blue;
}

.bgtext {
  color: black;
  float:right;
}

/* Form */

.form {
	width: 770px;
	padding:10px;
	list-style:none;
}

.form label {
	display:block;
	font-size: 9pt;
}

.input,
 input {
	margin-top:3px;
	margin-bottom:5px;
	background: white;
}

.button {
	background:#eee;
	font-size:12pt;
}

/* Targeted elements */

#chatpane
{
	height:300px;
	width:600px;
	float: left;
	color:Black;
	overflow:auto;
	border:solid 3px #eef;
	padding:4px;
	margin-bottom:4px;
	margin-right:10px;
}

#chatbuffer
{
 	width:560px;
	font-size: 18px;
	font-family:"Times New Roman", Times, serif;
	font-style:italic;
	padding: 5px;
}

#userpane
{
	height:298px;
	width:117px;
	float: right;
	color:Black;
	overflow:auto;
	border:solid 3px #eef;
	padding:5px;
	margin-bottom:4px;
}

#userlist
{
	width:100px;
}

#chatpane ul,
#userpane ul
{
	margin:0px;
	padding:0px;
	list-style:none;
}

#stats,
#charcount
{
	font-size:8pt;
	padding:3px;
	border:solid 2px white;

	margin:1px;
	display:inline;
}

#archivelink
{
	font-size:8pt;
	padding:3px;
	border:solid 2px white;
	margin:1px;
	display:inline;
}

#footer {
	border-top: solid 2px #ccc;
	margin-top:20px;
	padding:5px;
	text-align:center;
}

.servermsg
{
	color:Red;
}

.actionmsg
{
	color:Blue;
}

.mytext
{
	width:50%;
	margin-bottom:10px;
}

.clear
{
	clear:both;
}

#login {
	position: relative;
	top: 35%;
}
#actions {
	padding-top: 20px;
}

.chatimg {
	float: right;
	padding: 5px;
}

.cb {
	clear: both;
	background: #eee;
	height: 70px;
	padding: 5px;
	-moz-border-radius: 15px;
	border-radius: 15px;
	margin: 5px;
}
.cb-smile {
	clear: both;
	background: #eee;
	height: 105px;
	padding: 5px;
	-moz-border-radius: 15px;
	border-radius: 15px;
	margin: 5px;
}
.cb-error {
	clear: both;
	background: #fff;
	height: 15px;
	padding: 5px;
	-moz-border-radius: 15px;
	border-radius: 15px;
	margin: 5px;
}


text:
/**
 * Base classes for electronic billing.
 *
 * @author The eFaps Team
 */
package org.efaps.esjp.electronicbilling;


text:
<?php

namespace Drupal\aggregator;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;

/**
 * Provides HTML routes for the feed entity type.
 */
class FeedHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
    $route = parent::getCanonicalRoute($entity_type);
    $route->setDefault('_title_controller', '\Drupal\aggregator\Controller\AggregatorController::feedTitle');

    return $route;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditFormRoute(EntityTypeInterface $entity_type) {
    $route = parent::getEditFormRoute($entity_type);

    $route->setDefault('_title', 'Configure');

    return $route;
  }

}


text:
/**
 * Created by jason on 16/3/14.
 */

module.exports = function(){

    var mongoose = require('mongoose');

    mongoose.connect('mongodb://localhost:27017/crudusers');

    var db = mongoose.connection;

    db.on('error',function(error){

        console.log('connection error: ' + error.message);

    })

    db.once('open',function(){

        console.log('Connection successfull!!!');
    })

}


text:
<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Tees;

/**
 * TeesSearch represents the model behind the search form about `app\models\Tees`.
 */
class TeesSearch extends Tees
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'course_id'], 'integer'],
            [['name', 'color'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Tees::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'course_id' => $this->course_id,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'color', $this->color]);

        return $dataProvider;
    }
}