text:
#ifndef GRPC_CORE_LIB_CHANNEL_CHANNELZ_H
#define GRPC_CORE_LIB_CHANNEL_CHANNELZ_H

#include <grpc/impl/codegen/port_platform.h>

#include <grpc/grpc.h>

#include "src/core/lib/channel/channel_trace.h"
#include "src/core/lib/gpr/time_precise.h"
#include "src/core/lib/gprpp/inlined_vector.h"
#include "src/core/lib/gprpp/manual_constructor.h"
#include "src/core/lib/gprpp/map.h"
#include "src/core/lib/gprpp/ref_counted.h"
#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/json/json.h"

// Channel arg key for channelz node.
#define GRPC_ARG_CHANNELZ_CHANNEL_NODE "grpc.channelz_channel_node"

// Channel arg key to encode the channelz uuid of the channel's parent.
#define GRPC_ARG_CHANNELZ_PARENT_UUID "grpc.channelz_parent_uuid"

/** This is the default value for whether or not to enable channelz. If
 * GRPC_ARG_ENABLE_CHANNELZ is set, it will override this default value. */
#define GRPC_ENABLE_CHANNELZ_DEFAULT true

/** This is the default value for the maximum amount of memory used by trace
 * events per channel trace node. If
 * GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE is set, it will override
 * this default value. */
#define GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT 1024 * 4

namespace grpc_core {

namespace channelz {

// Helpers for getting and setting GRPC_ARG_CHANNELZ_PARENT_UUID.
grpc_arg MakeParentUuidArg(intptr_t parent_uuid);
intptr_t GetParentUuidFromArgs(const grpc_channel_args& args);

class SocketNode;
class ListenSocketNode;

namespace testing {
class CallCountingHelperPeer;
class ChannelNodePeer;
}  // namespace testing

// base class for all channelz entities
class BaseNode : public RefCounted<BaseNode> {
 public:
  // There are only four high level channelz entities. However, to support
  // GetTopChannelsRequest, we split the Channel entity into two different
  // types. All children of BaseNode must be one of these types.
  enum class EntityType {
    kTopLevelChannel,
    kInternalChannel,
    kSubchannel,
    kServer,
    kSocket,
  };

 protected:
  BaseNode(EntityType type, UniquePtr<char> name);

 public:
  virtual ~BaseNode();

  // All children must implement this function.
  virtual grpc_json* RenderJson() GRPC_ABSTRACT;

  // Renders the json and returns allocated string that must be freed by the
  // caller.
  char* RenderJsonString();

  EntityType type() const { return type_; }
  intptr_t uuid() const { return uuid_; }
  const char* name() const { return name_.get(); }

 private:
  // to allow the ChannelzRegistry to set uuid_ under its lock.
  friend class ChannelzRegistry;
  const EntityType type_;
  intptr_t uuid_;
  UniquePtr<char> name_;
};

// This class is a helper class for channelz entities that deal with Channels,
// Subchannels, and Servers, since those have similar proto definitions.
// This class has the ability to:
//   - track calls_{started,succeeded,failed}
//   - track last_call_started_timestamp
//   - perform rendering of the above items
class CallCountingHelper {
 public:
  CallCountingHelper();

  void RecordCallStarted();
  void RecordCallFailed();
  void RecordCallSucceeded();

  // Common rendering of the call count data and last_call_started_timestamp.
  void PopulateCallCounts(grpc_json* json);

 private:
  // testing peer friend.
  friend class testing::CallCountingHelperPeer;

  // TODO(soheil): add a proper PerCPU helper and use it here.
  struct AtomicCounterData {
    // Define the ctors so that we can use this structure in InlinedVector.
    AtomicCounterData() = default;
    AtomicCounterData(const AtomicCounterData& that)
        : calls_started(that.calls_started.Load(MemoryOrder::RELAXED)),
          calls_succeeded(that.calls_succeeded.Load(MemoryOrder::RELAXED)),
          calls_failed(that.calls_failed.Load(MemoryOrder::RELAXED)),
          last_call_started_cycle(
              that.last_call_started_cycle.Load(MemoryOrder::RELAXED)) {}

    Atomic<intptr_t> calls_started{0};
    Atomic<intptr_t> calls_succeeded{0};
    Atomic<intptr_t> calls_failed{0};
    Atomic<gpr_cycle_counter> last_call_started_cycle{0};
    // Make sure the size is exactly one cache line.
    uint8_t padding[GPR_CACHELINE_SIZE - 3 * sizeof(Atomic<intptr_t>) -
                    sizeof(Atomic<gpr_cycle_counter>)];
  } GPR_ALIGN_STRUCT(GPR_CACHELINE_SIZE);

  struct CounterData {
    intptr_t calls_started = 0;
    intptr_t calls_succeeded = 0;
    intptr_t calls_failed = 0;
    gpr_cycle_counter last_call_started_cycle = 0;
  };

  // collects the sharded data into one CounterData struct.
  void CollectData(CounterData* out);

  // Really zero-sized, but 0-sized arrays are illegal on MSVC.
  InlinedVector<AtomicCounterData, 1> per_cpu_counter_data_storage_;
  size_t num_cores_ = 0;
};

// Handles channelz bookkeeping for channels
class ChannelNode : public BaseNode {
 public:
  ChannelNode(UniquePtr<char> target, size_t channel_tracer_max_nodes,
              intptr_t parent_uuid);

  // Returns the string description of the given connectivity state.
  static const char* GetChannelConnectivityStateChangeString(
      grpc_connectivity_state state);

  intptr_t parent_uuid() const { return parent_uuid_; }

  grpc_json* RenderJson() override;

  // proxy methods to composed classes.
  void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
    trace_.AddTraceEvent(severity, data);
  }
  void AddTraceEventWithReference(ChannelTrace::Severity severity,
                                  const grpc_slice& data,
                                  RefCountedPtr<BaseNode> referenced_channel) {
    trace_.AddTraceEventWithReference(severity, data,
                                      std::move(referenced_channel));
  }
  void RecordCallStarted() { call_counter_.RecordCallStarted(); }
  void RecordCallFailed() { call_counter_.RecordCallFailed(); }
  void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); }

  void SetConnectivityState(grpc_connectivity_state state);

  // TODO(roth): take in a RefCountedPtr to the child channel so we can retrieve
  // the human-readable name.
  void AddChildChannel(intptr_t child_uuid);
  void RemoveChildChannel(intptr_t child_uuid);

  // TODO(roth): take in a RefCountedPtr to the child subchannel so we can
  // retrieve the human-readable name.
  void AddChildSubchannel(intptr_t child_uuid);
  void RemoveChildSubchannel(intptr_t child_uuid);

 private:
  void PopulateChildRefs(grpc_json* json);

  // to allow the channel trace test to access trace_.
  friend class testing::ChannelNodePeer;

  UniquePtr<char> target_;
  CallCountingHelper call_counter_;
  ChannelTrace trace_;
  const intptr_t parent_uuid_;

  // Least significant bit indicates whether the value is set.  Remaining
  // bits are a grpc_connectivity_state value.
  Atomic<int> connectivity_state_{0};

  Mutex child_mu_;  // Guards child maps below.
  // TODO(roth): We don't actually use the values here, only the keys, so
  // these should be sets instead of maps, but we don't currently have a set
  // implementation.  Change this if/when we have one.
  Map<intptr_t, bool> child_channels_;
  Map<intptr_t, bool> child_subchannels_;
};

// Handles channelz bookkeeping for servers
class ServerNode : public BaseNode {
 public:
  ServerNode(grpc_server* server, size_t channel_tracer_max_nodes);

  ~ServerNode() override;

  grpc_json* RenderJson() override;

  char* RenderServerSockets(intptr_t start_socket_id, intptr_t max_results);

  void AddChildSocket(RefCountedPtr<SocketNode> node);

  void RemoveChildSocket(intptr_t child_uuid);

  void AddChildListenSocket(RefCountedPtr<ListenSocketNode> node);

  void RemoveChildListenSocket(intptr_t child_uuid);

  // proxy methods to composed classes.
  void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) {
    trace_.AddTraceEvent(severity, data);
  }
  void AddTraceEventWithReference(ChannelTrace::Severity severity,
                                  const grpc_slice& data,
                                  RefCountedPtr<BaseNode> referenced_channel) {
    trace_.AddTraceEventWithReference(severity, data,
                                      std::move(referenced_channel));
  }
  void RecordCallStarted() { call_counter_.RecordCallStarted(); }
  void RecordCallFailed() { call_counter_.RecordCallFailed(); }
  void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); }

 private:
  CallCountingHelper call_counter_;
  ChannelTrace trace_;
  Mutex child_mu_;  // Guards child maps below.
  Map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_;
  Map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_;
};

// Handles channelz bookkeeping for sockets
class SocketNode : public BaseNode {
 public:
  SocketNode(UniquePtr<char> local, UniquePtr<char> remote,
             UniquePtr<char> name);
  ~SocketNode() override {}

  grpc_json* RenderJson() override;

  void RecordStreamStartedFromLocal();
  void RecordStreamStartedFromRemote();
  void RecordStreamSucceeded() {
    gpr_atm_no_barrier_fetch_add(&streams_succeeded_, static_cast<gpr_atm>(1));
  }
  void RecordStreamFailed() {
    gpr_atm_no_barrier_fetch_add(&streams_failed_, static_cast<gpr_atm>(1));
  }
  void RecordMessagesSent(uint32_t num_sent);
  void RecordMessageReceived();
  void RecordKeepaliveSent() {
    gpr_atm_no_barrier_fetch_add(&keepalives_sent_, static_cast<gpr_atm>(1));
  }

  const char* remote() { return remote_.get(); }

 private:
  gpr_atm streams_started_ = 0;
  gpr_atm streams_succeeded_ = 0;
  gpr_atm streams_failed_ = 0;
  gpr_atm messages_sent_ = 0;
  gpr_atm messages_received_ = 0;
  gpr_atm keepalives_sent_ = 0;
  gpr_atm last_local_stream_created_cycle_ = 0;
  gpr_atm last_remote_stream_created_cycle_ = 0;
  gpr_atm last_message_sent_cycle_ = 0;
  gpr_atm last_message_received_cycle_ = 0;
  UniquePtr<char> local_;
  UniquePtr<char> remote_;
};

// Handles channelz bookkeeping for listen sockets
class ListenSocketNode : public BaseNode {
 public:
  ListenSocketNode(UniquePtr<char> local_addr, UniquePtr<char> name);
  ~ListenSocketNode() override {}

  grpc_json* RenderJson() override;

 private:
  UniquePtr<char> local_addr_;
};

}  // namespace channelz
}  // namespace grpc_core

#endif /* GRPC_CORE_LIB_CHANNEL_CHANNELZ_H */


text:
package asp4j.solver.object;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author hbeck Jun 1, 2013
 */
public class Filter {

    private Set<Class<?>> classes;

    public Filter() {
        this.classes = new HashSet<>();
    }

    public Filter(Class<?> clazz) {
        this.classes = new HashSet<>();
        if (clazz != null) {
            this.classes.add(clazz);
        }
    }

    public Filter(Class<?>... classes) {
        this.classes = new HashSet<>();
        if (classes != null && classes.length>0 ) {
            this.classes.addAll(Arrays.asList(classes));
        }
    }

    public Filter(Collection<Class<?>> classes) {
        this.classes = new HashSet<>();
        if (classes!=null) {
            this.classes.addAll(classes);
        }
    }

    /**
     * test whether given Class is accepted by this filter
     *
     * @param clazz
     * @return
     */
    public boolean accepts(Class<?> clazz) {
        if (clazz==null) {
            return false;
        }
        return classes.contains(clazz);
    }

    public Filter add(Class<?> clazz) {
        this.classes.add(clazz);
        return this;
    }

    public Filter addAll(Collection<Class<?>> classes) {
        for (Class<?> clazz : classes) {
            add(clazz);
        }
        return this;
    }

    public Filter remove(Class<?> clazz) {
        this.classes.remove(clazz);
        return this;
    }

    public Set<Class<?>> getClasses() {
        return classes;
    }

    public void setClasses(Set<Class<?>> classes) {
        this.classes = classes;
        if (this.classes==null) {
            this.classes = new HashSet<>();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Sylius\Component\User\Security;

use Doctrine\ORM\EntityManagerInterface;
use Sylius\Component\User\Security\Generator\GeneratorInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * @author Łukasz Chruściel <lukasz.chrusciel@lakion.com>
 */
class TokenProvider implements TokenProviderInterface
{
    /**
     * @var RepositoryInterface
     */
    private $repository;

    /**
     * @var EntityManagerInterface
     */
    private $manager;

    /**
     * @var GeneratorInterface
     */
    private $generator;

    /**
     * @var int
     */
    private $tokenLength;

    /**
     * @param RepositoryInterface    $repository
     * @param EntityManagerInterface $manager
     * @param GeneratorInterface     $generator
     */
    public function __construct(RepositoryInterface $repository, EntityManagerInterface $manager, GeneratorInterface $generator, $tokenLength)
    {
        $this->repository = $repository;
        $this->manager = $manager;
        $this->generator = $generator;
        $this->tokenLength = $tokenLength;
    }

    /**
     * {@inheritDoc}
     */
    public function generateUniqueToken()
    {
        do {
            $token = $this->generator->generate($this->tokenLength);
        } while ($this->isUsedCode($token));

        return $token;
    }

    /**
     * @param string $token
     *
     * @return Boolean
     */
    protected function isUsedCode($token)
    {
        $this->manager->getFilters()->disable('softdeleteable');

        $isUsed = null !== $this->repository->findOneBy(array('confirmationToken' => $token));

        $this->manager->getFilters()->enable('softdeleteable');

        return $isUsed;
    }
}


text:
"""SignatureDef utility functions implementation."""

from tensorflow.python.keras.saving.utils_v1 import unexported_constants
from tensorflow.python.saved_model import signature_def_utils
from tensorflow.python.saved_model import utils_impl as utils

# LINT.IfChange
def supervised_train_signature_def(
    inputs, loss, predictions=None, metrics=None):
  return _supervised_signature_def(
      unexported_constants.SUPERVISED_TRAIN_METHOD_NAME, inputs, loss=loss,
      predictions=predictions, metrics=metrics)

def supervised_eval_signature_def(
    inputs, loss, predictions=None, metrics=None):
  return _supervised_signature_def(
      unexported_constants.SUPERVISED_EVAL_METHOD_NAME, inputs, loss=loss,
      predictions=predictions, metrics=metrics)

def _supervised_signature_def(
    method_name, inputs, loss=None, predictions=None,
    metrics=None):
  """Creates a signature for training and eval data.

  This function produces signatures that describe the inputs and outputs
  of a supervised process, such as training or evaluation, that
  results in loss, metrics, and the like. Note that this function only requires
  inputs to be not None.

  Args:
    method_name: Method name of the SignatureDef as a string.
    inputs: dict of string to `Tensor`.
    loss: dict of string to `Tensor` representing computed loss.
    predictions: dict of string to `Tensor` representing the output predictions.
    metrics: dict of string to `Tensor` representing metric ops.

  Returns:
    A train- or eval-flavored signature_def.

  Raises:
    ValueError: If inputs or outputs is `None`.
  """
  if inputs is None or not inputs:
    raise ValueError('{} inputs cannot be None or empty.'.format(method_name))

  signature_inputs = {key: utils.build_tensor_info(tensor)
                      for key, tensor in inputs.items()}

  signature_outputs = {}
  for output_set in (loss, predictions, metrics):
    if output_set is not None:
      sig_out = {key: utils.build_tensor_info(tensor)
                 for key, tensor in output_set.items()}
      signature_outputs.update(sig_out)

  signature_def = signature_def_utils.build_signature_def(
      signature_inputs, signature_outputs, method_name)

  return signature_def
# LINT.ThenChange(//tensorflow/python/keras/saving/utils_v1/signature_def_utils.py)


text:
"""
.. _tut-artifact-ssp:

============================
Repairing artifacts with SSP
============================

This tutorial covers the basics of signal-space projection (SSP) and shows
how SSP can be used for artifact repair; extended examples illustrate use
of SSP for environmental noise reduction, and for repair of ocular and
heartbeat artifacts.

We begin as always by importing the necessary Python modules. To save ourselves
from repeatedly typing ``mne.preprocessing`` we'll directly import a handful of
functions from that submodule:
"""

# %%

import os
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.preprocessing import (create_eog_epochs, create_ecg_epochs,
                               compute_proj_ecg, compute_proj_eog)

# %%
# .. note::
#     Before applying SSP (or any artifact repair strategy), be sure to observe
#     the artifacts in your data to make sure you choose the right repair tool.
#     Sometimes the right tool is no tool at all — if the artifacts are small
#     enough you may not even need to repair them to get good analysis results.
#     See :ref:`tut-artifact-overview` for guidance on detecting and
#     visualizing various types of artifact.
#
#
# What is SSP?
# ^^^^^^^^^^^^
#
# Signal-space projection (SSP) :footcite:`UusitaloIlmoniemi1997` is a
# technique for removing noise from EEG
# and MEG signals by :term:`projecting <projector>` the signal onto a
# lower-dimensional subspace. The subspace is chosen by calculating the average
# pattern across sensors when the noise is present, treating that pattern as
# a "direction" in the sensor space, and constructing the subspace to be
# orthogonal to the noise direction (for a detailed walk-through of projection
# see :ref:`tut-projectors-background`).
#
# The most common use of SSP is to remove noise from MEG signals when the noise
# comes from environmental sources (sources outside the subject's body and the
# MEG system, such as the electromagnetic fields from nearby electrical
# equipment) and when that noise is *stationary* (doesn't change much over the
# duration of the recording). However, SSP can also be used to remove
# biological artifacts such as heartbeat (ECG) and eye movement (EOG)
# artifacts. Examples of each of these are given below.
#
#
# Example: Environmental noise reduction from empty-room recordings
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# The :ref:`example data <sample-dataset>` was recorded on a Neuromag system,
# which stores SSP projectors for environmental noise removal in the system
# configuration (so that reasonably clean raw data can be viewed in real-time
# during acquisition). For this reason, all the `~mne.io.Raw` data in
# the example dataset already includes SSP projectors, which are noted in the
# output when loading the data:

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')
# here we crop and resample just for speed
raw = mne.io.read_raw_fif(sample_data_raw_file).crop(0, 60)
raw.load_data().resample(100)

# %%
# The :ref:`example data <sample-dataset>` also includes an "empty room"
# recording taken the same day as the recording of the subject. This will
# provide a more accurate estimate of environmental noise than the projectors
# stored with the system (which are typically generated during annual
# maintenance and tuning). Since we have this subject-specific empty-room
# recording, we'll create our own projectors from it and discard the
# system-provided SSP projectors (saving them first, for later comparison with
# the custom ones):

system_projs = raw.info['projs']
raw.del_proj()
empty_room_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                               'ernoise_raw.fif')
# cropped to 60 sec just for speed
empty_room_raw = mne.io.read_raw_fif(empty_room_file).crop(0, 30)

# %%
# Notice that the empty room recording itself has the system-provided SSP
# projectors in it — we'll remove those from the empty room file too.

empty_room_raw.del_proj()

# %%
# Visualizing the empty-room noise
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Let's take a look at the spectrum of the empty room noise. We can view an
# individual spectrum for each sensor, or an average (with confidence band)
# across sensors:

for average in (False, True):
    empty_room_raw.plot_psd(average=average, dB=False, xscale='log')

# %%
# Creating the empty-room projectors
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# We create the SSP vectors using `~mne.compute_proj_raw`, and control
# the number of projectors with parameters ``n_grad`` and ``n_mag``. Once
# created, the field pattern of the projectors can be easily visualized with
# `~mne.viz.plot_projs_topomap`. We include the parameter
# ``vlim='joint'`` so that the colormap is computed jointly for all projectors
# of a given channel type; this makes it easier to compare their relative
# smoothness. Note that for the function to know the types of channels in a
# projector, you must also provide the corresponding `~mne.Info` object:

empty_room_projs = mne.compute_proj_raw(empty_room_raw, n_grad=3, n_mag=3)
mne.viz.plot_projs_topomap(empty_room_projs, colorbar=True, vlim='joint',
                           info=empty_room_raw.info)

# %%
# Notice that the gradiometer-based projectors seem to reflect problems with
# individual sensor units rather than a global noise source (indeed, planar
# gradiometers are much less sensitive to distant sources). This is the reason
# that the system-provided noise projectors are computed only for
# magnetometers. Comparing the system-provided projectors to the
# subject-specific ones, we can see they are reasonably similar (though in a
# different order) and the left-right component seems to have changed
# polarity.

fig, axs = plt.subplots(2, 3)
for idx, _projs in enumerate([system_projs, empty_room_projs[3:]]):
    mne.viz.plot_projs_topomap(_projs, axes=axs[idx], colorbar=True,
                               vlim='joint', info=empty_room_raw.info)

# %%
# Visualizing how projectors affect the signal
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# We could visualize the different effects these have on the data by applying
# each set of projectors to different copies of the `~mne.io.Raw` object
# using `~mne.io.Raw.apply_proj`. However, the `~mne.io.Raw.plot`
# method has a ``proj`` parameter that allows us to *temporarily* apply
# projectors while plotting, so we can use this to visualize the difference
# without needing to copy the data. Because the projectors are so similar, we
# need to zoom in pretty close on the data to see any differences:

mags = mne.pick_types(raw.info, meg='mag')
for title, projs in [('system', system_projs),
                     ('subject-specific', empty_room_projs[3:])]:
    raw.add_proj(projs, remove_existing=True)
    with mne.viz.use_browser_backend('matplotlib'):
        fig = raw.plot(proj=True, order=mags, duration=1, n_channels=2)
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} projectors'.format(title), size='xx-large', weight='bold')

# %%
# The effect is sometimes easier to see on averaged data. Here we use an
# interactive feature of `mne.Evoked.plot_topomap` to turn projectors on
# and off to see the effect on the data. Of course, the interactivity won't
# work on the tutorial website, but you can download the tutorial and try it
# locally:

events = mne.find_events(raw, stim_channel='STI 014')
event_id = {'auditory/left': 1}

# NOTE: appropriate rejection criteria are highly data-dependent
reject = dict(mag=4000e-15,     # 4000 fT
              grad=4000e-13,    # 4000 fT/cm
              eeg=150e-6,       # 150 µV
              eog=250e-6)       # 250 µV

# time range where we expect to see the auditory N100: 50-150 ms post-stimulus
times = np.linspace(0.05, 0.15, 5)

epochs = mne.Epochs(raw, events, event_id, proj='delayed', reject=reject)
fig = epochs.average().plot_topomap(times, proj='interactive')

# %%
# Plotting the ERP/F using ``evoked.plot()`` or ``evoked.plot_joint()`` with
# and without projectors applied can also be informative, as can plotting with
# ``proj='reconstruct'``, which can reduce the signal bias introduced by
# projections (see :ref:`tut-artifact-ssp-reconstruction` below).
#
# Example: EOG and ECG artifact repair
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# Visualizing the artifacts
# ~~~~~~~~~~~~~~~~~~~~~~~~~
#
# As mentioned in :ref:`the ICA tutorial <tut-artifact-ica>`, an important
# first step is visualizing the artifacts you want to repair. Here they are in
# the raw data:

# pick some channels that clearly show heartbeats and blinks
regexp = r'(MEG [12][45][123]1|EEG 00.)'
artifact_picks = mne.pick_channels_regexp(raw.ch_names, regexp=regexp)
raw.plot(order=artifact_picks, n_channels=len(artifact_picks))

# %%
# Repairing ECG artifacts with SSP
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# MNE-Python provides several functions for detecting and removing heartbeats
# from EEG and MEG data. As we saw in :ref:`tut-artifact-overview`,
# `~mne.preprocessing.create_ecg_epochs` can be used to both detect and
# extract heartbeat artifacts into an `~mne.Epochs` object, which can
# be used to visualize how the heartbeat artifacts manifest across the sensors:

ecg_evoked = create_ecg_epochs(raw).average()
ecg_evoked.plot_joint()

# %%
# Looks like the EEG channels are pretty spread out; let's baseline-correct and
# plot again:

ecg_evoked.apply_baseline((None, None))
ecg_evoked.plot_joint()

# %%
# To compute SSP projectors for the heartbeat artifact, you can use
# `~mne.preprocessing.compute_proj_ecg`, which takes a
# `~mne.io.Raw` object as input and returns the requested number of
# projectors for magnetometers, gradiometers, and EEG channels (default is two
# projectors for each channel type).
# `~mne.preprocessing.compute_proj_ecg` also returns an :term:`events`
# array containing the sample numbers corresponding to the peak of the
# `R wave <https://en.wikipedia.org/wiki/QRS_complex>`__ of each detected
# heartbeat.

projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=1, reject=None)

# %%
# The first line of output tells us that
# `~mne.preprocessing.compute_proj_ecg` found three existing projectors
# already in the `~mne.io.Raw` object, and will include those in the
# list of projectors that it returns (appending the new ECG projectors to the
# end of the list). If you don't want that, you can change that behavior with
# the boolean ``no_proj`` parameter. Since we've already run the computation,
# we can just as easily separate out the ECG projectors by indexing the list of
# projectors:

ecg_projs = projs[3:]
print(ecg_projs)

# %%
# Just like with the empty-room projectors, we can visualize the scalp
# distribution:

mne.viz.plot_projs_topomap(ecg_projs, info=raw.info)

# %%
# Moreover, because these projectors were created using epochs chosen
# specifically because they contain time-locked artifacts, we can do a
# joint plot of the projectors and their effect on the time-averaged epochs.
# This figure has three columns:
#
# 1. The left shows the data traces before (black) and after (green)
#    projection. We can see that the ECG artifact is well suppressed by one
#    projector per channel type.
# 2. The center shows the topomaps associated with the projectors, in this case
#    just a single topography for our one projector per channel type.
# 3. The right again shows the data traces (black), but this time with those
#    traces also projected onto the first projector for each channel type (red)
#    plus one surrogate ground truth for an ECG channel (MEG 0111).

# sphinx_gallery_thumbnail_number = 17

# ideally here we would just do `picks_trace='ecg'`, but this dataset did not
# have a dedicated ECG channel recorded, so we just pick a channel that was
# very sensitive to the artifact
fig = mne.viz.plot_projs_joint(ecg_projs, ecg_evoked, picks_trace='MEG 0111')
fig.suptitle('ECG projectors')

# %%
# Since no dedicated ECG sensor channel was detected in the
# `~mne.io.Raw` object, by default
# `~mne.preprocessing.compute_proj_ecg` used the magnetometers to
# estimate the ECG signal (as stated on the third line of output, above). You
# can also supply the ``ch_name`` parameter to restrict which channel to use
# for ECG artifact detection; this is most useful when you had an ECG sensor
# but it is not labeled as such in the `~mne.io.Raw` file.
#
# The next few lines of the output describe the filter used to isolate ECG
# events. The default settings are usually adequate, but the filter can be
# customized via the parameters ``ecg_l_freq``, ``ecg_h_freq``, and
# ``filter_length`` (see the documentation of
# `~mne.preprocessing.compute_proj_ecg` for details).
#
# .. TODO what are the cases where you might need to customize the ECG filter?
#    infants? Heart murmur?
#
# Once the ECG events have been identified,
# `~mne.preprocessing.compute_proj_ecg` will also filter the data
# channels before extracting epochs around each heartbeat, using the parameter
# values given in ``l_freq``, ``h_freq``, ``filter_length``, ``filter_method``,
# and ``iir_params``. Here again, the default parameter values are usually
# adequate.
#
# .. TODO should advice for filtering here be the same as advice for filtering
#    raw data generally? (e.g., keep high-pass very low to avoid peak shifts?
#    what if your raw data is already filtered?)
#
# By default, the filtered epochs will be averaged together
# before the projection is computed; this can be controlled with the boolean
# ``average`` parameter. In general this improves the signal-to-noise (where
# "signal" here is our artifact!) ratio because the artifact temporal waveform
# is fairly similar across epochs and well time locked to the detected events.
#
# To get a sense of how the heartbeat affects the signal at each sensor, you
# can plot the data with and without the ECG projectors:

raw.del_proj()
for title, proj in [('Without', empty_room_projs), ('With', ecg_projs)]:
    raw.add_proj(proj, remove_existing=False)
    with mne.viz.use_browser_backend('matplotlib'):
        fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} ECG projectors'.format(title), size='xx-large',
                 weight='bold')

# %%
# Finally, note that above we passed ``reject=None`` to the
# `~mne.preprocessing.compute_proj_ecg` function, meaning that all
# detected ECG epochs would be used when computing the projectors (regardless
# of signal quality in the data sensors during those epochs). The default
# behavior is to reject epochs based on signal amplitude: epochs with
# peak-to-peak amplitudes exceeding 50 µV in EEG channels, 250 µV in EOG
# channels, 2000 fT/cm in gradiometer channels, or 3000 fT in magnetometer
# channels. You can change these thresholds by passing a dictionary with keys
# ``eeg``, ``eog``, ``mag``, and ``grad`` (though be sure to pass the threshold
# values in volts, teslas, or teslas/meter). Generally, it is a good idea to
# reject such epochs when computing the ECG projectors (since presumably the
# high-amplitude fluctuations in the channels are noise, not reflective of
# brain activity); passing ``reject=None`` above was done simply to avoid the
# dozens of extra lines of output (enumerating which sensor(s) were responsible
# for each rejected epoch) from cluttering up the tutorial.
#
# .. note::
#
#     `~mne.preprocessing.compute_proj_ecg` has a similar parameter
#     ``flat`` for specifying the *minimum* acceptable peak-to-peak amplitude
#     for each channel type.
#
# While `~mne.preprocessing.compute_proj_ecg` conveniently combines
# several operations into a single function, MNE-Python also provides functions
# for performing each part of the process. Specifically:
#
# - `mne.preprocessing.find_ecg_events` for detecting heartbeats in a
#   `~mne.io.Raw` object and returning a corresponding :term:`events`
#   array
#
# - `mne.preprocessing.create_ecg_epochs` for detecting heartbeats in a
#   `~mne.io.Raw` object and returning an `~mne.Epochs` object
#
# - `mne.compute_proj_epochs` for creating projector(s) from any
#   `~mne.Epochs` object
#
# See the documentation of each function for further details.
#
#
# Repairing EOG artifacts with SSP
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Once again let's visualize our artifact before trying to repair it. We've
# seen above the large deflections in frontal EEG channels in the raw data;
# here is how the ocular artifacts manifests across all the sensors:

eog_evoked = create_eog_epochs(raw).average(picks='all')
eog_evoked.apply_baseline((None, None))
eog_evoked.plot_joint()

# %%
# Just like we did with the heartbeat artifact, we can compute SSP projectors
# for the ocular artifact using `~mne.preprocessing.compute_proj_eog`,
# which again takes a `~mne.io.Raw` object as input and returns the
# requested number of projectors for magnetometers, gradiometers, and EEG
# channels (default is two projectors for each channel type). This time, we'll
# pass ``no_proj`` parameter (so we get back only the new EOG projectors, not
# also the existing projectors in the `~mne.io.Raw` object), and we'll
# ignore the events array by assigning it to ``_`` (the conventional way of
# handling unwanted return elements in Python).

eog_projs, _ = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, reject=None,
                                no_proj=True)

# %%
# Just like with the empty-room and ECG projectors, we can visualize the scalp
# distribution:

mne.viz.plot_projs_topomap(eog_projs, info=raw.info)

# %%
# And we can do a joint image:

fig = mne.viz.plot_projs_joint(eog_projs, eog_evoked, 'eog')
fig.suptitle('EOG projectors')

# %%
# And finally, we can make a joint visualization with our EOG evoked. We will
# also make a bad choice here and select *two* EOG projectors for EEG and
# magnetometers, and we will see them show up as noise in the plot. Even though
# the projected time course (left column) looks perhaps okay, problems show
# up in the center (topomaps) and right plots (projection of channel data
# onto the projection vector):
#
# 1. The second magnetometer topomap has a bilateral auditory field pattern.
# 2. The uniformly-scaled projected temporal time course (solid lines) show
#    that, while the first projector trace (red) has a large EOG-like
#    amplitude, the second projector trace (blue-green) is much smaller.
# 3. The re-normalized projected temporal time courses show that the
#    second PCA trace is very noisy relative to the EOG channel data (yellow).

eog_projs_bad, _ = compute_proj_eog(
    raw, n_grad=1, n_mag=2, n_eeg=2, reject=None,
    no_proj=True)
fig = mne.viz.plot_projs_joint(eog_projs_bad, eog_evoked, picks_trace='eog')
fig.suptitle('Too many EOG projectors')

# %%
# Now we repeat the plot from above (with empty room and ECG projectors) and
# compare it to a plot with empty room, ECG, and EOG projectors, to see how
# well the ocular artifacts have been repaired:

for title in ('Without', 'With'):
    if title == 'With':
        raw.add_proj(eog_projs)
    with mne.viz.use_browser_backend('matplotlib'):
        fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
    fig.subplots_adjust(top=0.9)  # make room for title
    fig.suptitle('{} EOG projectors'.format(title), size='xx-large',
                 weight='bold')

# %%
# Notice that the small peaks in the first to magnetometer channels (``MEG
# 1411`` and ``MEG 1421``) that occur at the same time as the large EEG
# deflections have also been removed.
#
#
# Choosing the number of projectors
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# In the examples above, we used 3 projectors (all magnetometer) to capture
# empty room noise, and saw how projectors computed for the gradiometers failed
# to capture *global* patterns (and thus we discarded the gradiometer
# projectors). Then we computed 3 projectors (1 for each channel type) to
# capture the heartbeat artifact, and 3 more to capture the ocular artifact.
# How did we choose these numbers? The short answer is "based on experience" —
# knowing how heartbeat artifacts typically manifest across the sensor array
# allows us to recognize them when we see them, and recognize when additional
# projectors are capturing something else other than a heartbeat artifact (and
# thus may be removing brain signal and should be discarded).
#
# .. _tut-artifact-ssp-reconstruction:
#
# Visualizing SSP sensor-space bias via signal reconstruction
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# .. admonition:: SSP reconstruction
#     :class: sidebar note
#
#     Internally, the reconstruction is performed by effectively using a
#     minimum-norm source localization to a spherical source space with the
#     projections accounted for, and then projecting the source-space data
#     back out to sensor space.
#
# Because SSP performs an orthogonal projection, any spatial component in the
# data that is not perfectly orthogonal to the SSP spatial direction(s) will
# have its overall amplitude reduced by the projection operation. In other
# words, SSP typically introduces some amount of amplitude reduction bias in
# the sensor space data.
#
# When performing source localization of M/EEG data, these projections are
# properly taken into account by being applied not just to the M/EEG data
# but also to the forward solution, and hence SSP should not bias the estimated
# source amplitudes. However, for sensor space analyses, it can be useful to
# visualize the extent to which SSP projection has biased the data. This can be
# explored by using ``proj='reconstruct'`` in evoked plotting functions, for
# example via `evoked.plot() <mne.Evoked.plot>`, here restricted to just
# EEG channels for speed:

evoked_eeg = epochs.average().pick('eeg')
evoked_eeg.del_proj().add_proj(ecg_projs).add_proj(eog_projs)
fig, axes = plt.subplots(1, 3, figsize=(8, 3), squeeze=False)
for ii in range(axes.shape[0]):
    axes[ii, 0].get_shared_y_axes().join(*axes[ii])
for pi, proj in enumerate((False, True, 'reconstruct')):
    evoked_eeg.plot(proj=proj, axes=axes[:, pi], spatial_colors=True)
    if pi == 0:
        for ax in axes[:, pi]:
            parts = ax.get_title().split('(')
            ax.set(ylabel=f'{parts[0]} ({ax.get_ylabel()})\n'
                          f'{parts[1].replace(")", "")}')
    axes[0, pi].set(title=f'proj={proj}')
    for text in list(axes[0, pi].texts):
        text.remove()
plt.setp(axes[1:, :].ravel(), title='')
plt.setp(axes[:, 1:].ravel(), ylabel='')
plt.setp(axes[:-1, :].ravel(), xlabel='')
mne.viz.tight_layout()

# %%
# Note that here the bias in the EEG and magnetometer channels is reduced by
# the reconstruction. This suggests that the application of SSP has slightly
# reduced the amplitude of our signals in sensor space, but that it should not
# bias the amplitudes in source space.
#
# References
# ^^^^^^^^^^
#
# .. footbibliography::


text:
<?php

namespace ANDS\Test;

use ANDS\API\Task\ImportTask;
use ANDS\Repository\DataSourceRepository;
use ANDS\DataSource as DataSource;
use ANDS\DataSourceAttribute;

/**
 * Class TestPopulateImportOptions
 * @package ANDS\Test
 */
class TestScheduleHarvestTask extends UnitTest
{
    /** @test **/
    private $ds_id = 5;
    private $batch_id = "DOESNTMATTER";
    private $harvest_id = 50;
    private $dataSource;
    private $incrementhHarvestMode = "INCREMENTAL";
    private $oldDataSourceadvancedHarvestMode = "";

    /** @test **/
    public function test_it_should_not_change_last_harvest_run_date()
    {

        $task = $this->getScheduleHarvestTask('ErrorWorkflow');

        $this->assertEquals($task->parent()->dataSourceID, "5");
        $this->assertEquals($task->parent()->batchID, "DOESNTMATTER");
        $this->dataSource = DataSourceRepository::getByID($this->ds_id);
        $this->setUpAdvancedHarvestMode($this->incrementhHarvestMode);
        $oldHarvestFrom = $this->dataSource->getDataSourceAttributeValue("last_harvest_run_date");

        $task->run_task();
        $this->assertEquals($oldHarvestFrom, $this->dataSource->getDataSourceAttributeValue("last_harvest_run_date"));
        $this->reSetUpAdvancedHarvestMode();
    }
    /** @test **/
    public function test_it_should_change_last_harvest_run_date()
    {

        $task = $this->getScheduleHarvestTask('default');
        $this->setUpAdvancedHarvestMode($this->incrementhHarvestMode);
        $this->assertEquals($task->parent()->dataSourceID, "5");
        $this->assertEquals($task->parent()->batchID, "DOESNTMATTER");
        $this->dataSource = DataSourceRepository::getByID($this->ds_id);
        $oldHarvestFrom =$this->dataSource->getDataSourceAttributeValue("last_harvest_run_date");

        $task->run_task();
        $this->assertNotEquals($oldHarvestFrom, $this->dataSource->getDataSourceAttributeValue("last_harvest_run_date"));
        $this->reSetUpAdvancedHarvestMode();
    }

    /**
     * Helper
     * Return a ProcessCoreMetadata Task for use each test
     * @return ImportSubTask
     */
    public function getScheduleHarvestTask($pipeline)
    {
        $importTask = new ImportTask();
        //dd($importTask);
        $importTask->init([
            'name' => 'ImportTask',
            'params' => 'ds_id='. $this->ds_id .'&batch_id='.$this->batch_id.'&harvest_id='.$this->harvest_id.'&pipeline='.$pipeline
        ])->setCI($this->ci)->initialiseTask();
        $task = $importTask->getTaskByName("ScheduleHarvest");

        return $task;
    }

    public function setUpAdvancedHarvestMode($newMode)
    {
        $this->oldDataSourceadvancedHarvestMode = $this->dataSource->getDataSourceAttributeValue("advanced_harvest_mode");
        $this->dataSource->setDataSourceAttribute("advanced_harvest_mode", $newMode);

    }

    public function reSetUpAdvancedHarvestMode()
    {
        $this->dataSource->setDataSourceAttribute("advanced_harvest_mode", $this->oldDataSourceadvancedHarvestMode);
    }

}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model frontend\models\Contact */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'user_id')->textInput() ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'email')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'subject')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'body')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'status')->textInput() ?>

    <?= $form->field($model, 'created_at')->textInput() ?>

    <?= $form->field($model, 'updated_at')->textInput() ?>

    <?= $form->field($model, 'deleted')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
package fr.cph.stock.entities.chart;

import java.util.Map;
import java.util.Map.Entry;

/**
 * This class represents an pie chart
 *
 * @author Carl-Philipp Harmant
 *
 */
public class PieChart extends AChart {

	/** Equities **/
	private final Map<String, Double> equities;

	/**
	 * Constructor that will construct a chart with the given equities
	 *
	 * @param equities
	 *            the equities
	 */
	public PieChart(final Map<String, Double> equities) {
		this.equities = equities;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see IChart#generate()
	 */
	@Override
	public final void generate() {
		StringBuilder dataTemp = new StringBuilder();
		StringBuilder titleTemp = new StringBuilder();
		StringBuilder drawTemp = new StringBuilder();
		drawTemp.append("[");
		titleTemp.append("var title = [");
		int i = 1;
		for (Entry<String, Double> e : equities.entrySet()) {
			String key = e.getKey();
			Double value = e.getValue();
			if (i != 1) {
				drawTemp.append(",");
				titleTemp.append(",");
			}
			drawTemp.append("{ data : d").append(i);
			drawTemp.append(", label : '").append(key).append("'}");
			titleTemp.append("'").append(key).append("'");
			dataTemp.append("var d").append(i).append(" = [[0,").append(value).append("]];");
			i++;
		}
		setData(dataTemp.toString());
		drawTemp.append("]");
		setDraw(drawTemp.toString());
		titleTemp.append("];");
		setTitle(titleTemp.toString());
	}

	/**
	 * get equities
	 *
	 * @return the equities
	 */
	public final Map<String, Double> getEquities() {
		return equities;
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>São João</logradouro><bairro>Estalagem</bairro><cidade>Viamão</cidade><uf>RS</uf><cep>94425380</cep></feed>


text:
(function () {
    'use strict';
    angular.module('mwApp.memoryWall')
        .factory('memoryWallService', memoryWallService);

    memoryWallService.$inject = ['$resource'];

    function memoryWallService($resource) {
        var service = {
            memoryWall: memoryWall,
            mediaTypes: mediaTypes
        };
        return service;

        function memoryWall(decade) {

          return $resource('/web/app_dev.php/api/memorywalls/:decade',
          { decade: decade },
          {
            query: {
              method: 'GET',
              isArray: true
            }
          });
        }

        function mediaTypes() {
            return $resource('/web/app_dev.php/api/mediatypes', {
                query: {
                    method: 'GET',
                    isArray: true
                }
            });
        }

    }
})();


text:
<?php

namespace Site\Bundle\BackendBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Site\Bundle\BackendBundle\Form\BaseAutoBlocksForm;
use Site\Bundle\BackendBundle\Entity\BaseAutoCarsBlocks;

class AutoBlocksController extends Controller
{
    public function indexAction($id, $block_type, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $qb = $em->createQueryBuilder();
        $qb->select('b')
            ->from('SiteBackendBundle:BaseAutoCarsBlocks','b')
            ->where('b.carId = '.$id.' AND b.blockType = '.$block_type)
            ->orderBy('b.pos', 'ASC');
        $blocks = $qb->getQuery()->getResult();
        return $this->render('SiteBackendBundle:AutoBlocks:index.html.twig', array(
                'blocks' => $blocks,
                'car_id' => $id,
                'block_type' => $block_type,
            ));
    }

    public function addAction($id, $block_type, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $block = new BaseAutoCarsBlocks();

        $form = $this->createForm(new BaseAutoBlocksForm(), $block);

        if ($post = $request->request->all())
        {
            $form->submit($request);
            $block->setCarId($id);
            $block->setBlockType($block_type);
            $em->persist($block);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_cars_blocks_edit', array('id' => $id, 'block_type' => $block_type, 'blockid' => $block->getId())));
        }

        return $this->render('SiteBackendBundle:AutoBlocks:add.html.twig', array(
                'form'   => $form->createView(),
                'id'   => $id,
                'block'   => $block,
            ));
    }

    public function editAction($id, $block_type, $blockid, Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $block = $em->getRepository('SiteBackendBundle:BaseAutoCarsBlocks')->find($blockid);

        $form = $this->createForm(new BaseAutoBlocksForm(), $block);
        $href = $this->getRequest()->headers->get('referer');
        if ($post = $request->request->all())
        {
            $form->submit($request);
            $block->setCarId($id);
            $block->setBlockType($block_type);
            $em->persist($block);
            $em->flush();

            return $this->redirect($this->generateUrl('admin_cars_blocks_edit', array('id' => $id, 'block_type' => $block_type, 'blockid' => $block->getId())));
        }

        return $this->render('SiteBackendBundle:AutoBlocks:edit.html.twig', array(
                'form'   => $form->createView(),
                'id'   => $id,
                'block'   => $block,
                'previous' => $href,
            ));
    }

    public function deleteAction()
    {
        return $this->render('SiteBackendBundle:AutoBlocks:delete.html.twig', array(
                // ...
            ));    }

}


text:
sap.ui.define(["sap/uxap/BlockBase"], function (BlockBase) {
	"use strict";

	return BlockBase.extend("sap/uxap/sample/BlockBaseBlockInBlock/view/blocks/InnerBlock", {
		metadata: {
			/* no additional views provided */
		}
	});
});


text:
package com.bretpatterson.schemagen.graphql.typemappers.java.util;

import com.bretpatterson.schemagen.graphql.IGraphQLObjectMapper;
import com.bretpatterson.schemagen.graphql.annotations.GraphQLTypeMapper;
import com.bretpatterson.schemagen.graphql.typemappers.IGraphQLTypeMapper;
import graphql.Scalars;
import graphql.schema.GraphQLInputType;
import graphql.schema.GraphQLOutputType;

import java.lang.reflect.Type;
import java.util.TimeZone;

/**
 * Maps a TimeZone object into a GraphQLString
 */
@GraphQLTypeMapper(type=TimeZone.class)
public class TimeZoneMapper implements IGraphQLTypeMapper {

	@Override
	public boolean handlesType(IGraphQLObjectMapper graphQLObjectMapper, Type type) {
		return type == TimeZone.class;
	}

	@Override
	public GraphQLOutputType getOutputType(IGraphQLObjectMapper objectMapper, Type type) {
		return Scalars.GraphQLString;
	}

	@Override
	public GraphQLInputType getInputType(IGraphQLObjectMapper objectMapper, Type type) {
		return Scalars.GraphQLString;
	}

}


text:
CPPFLAGS = -c
NVCCFLAGS = --ptxas-options=-v --compiler-options -Wall

# compilers
NVCC = nvcc

###################### main
all: square_array add_arrays

###################### square array
square_array: square_array.cu
	$(NVCC) -o square_array square_array.cu $(NVCCFLAGS)

###################### square array
add_arrays: add_arrays.cu
	$(NVCC) -o add_arrays add_arrays.cu $(NVCCFLAGS)

####################### clean
clean:
	rm square_array add_arrays


text:
function [x, options, flog, pointlog] = cgcarl(f, x, options, gradf, varargin)

% CGCARL Wrapper for Carl Rasmussen's conjugate gradient implemntation.

% OPTIMI

length = options(14);
x = minimize(x', 'gradFuncWrapper', length, f, gradf, varargin{:})';


text:
from __future__ import print_function

from xml.etree import ElementTree as et
import os, sys

def reportfordir(path, reportfilename):
    """
    Usage: python exemplarlistreport.py directorypath reportfile.txt
    Output will be appended to existing reportfile.txt
    """
    with open(reportfilename, mode="a", encoding='utf-8') as ofile:
        chars = ofile.write("\n\nReport for " + path)
        try:
            for file in sorted(os.listdir(path)):
                cf = os.path.join(path, file)
                chars = ofile.write("\n\n" + file)
                r = et.parse(cf).getroot()
                e = set(r.findall(".//exemplarCharacters[@draft='generated']"))
                if len(e) == 0:
                    chars = ofile.write("\nNo generated exemplar lists found")
                    continue
                d = set(r.findall(".//exemplarCharacters[@draft='generated'][@type]"))
                m = list(e-d)
                if len(m) == 0:
                    chars = ofile.write("\nNo generated main exemplar list found")
                    continue
                else:
                    chars = ofile.write("\nGenerated main exemplar list: " + m[0].text)
                a = r.findall(".//exemplarCharacters[@draft='generated'][@type='auxiliary']")
                if len(a) == 0:
                    pass
                    # chars = ofile.write("\nNo generated auxiliary list found")
                else:
                    chars = ofile.write("\nGenerated auxiliary exemplar list: " + a[0].text)
        except OSError:
            chars = ofile.write("\nDirectory not found or empty")

if __name__ == '__main__':
    if len(sys.argv) > 2:
        reportfordir(sys.argv[1], sys.argv[2])
    else:
        print(reportfordir.__doc__)


text:
import Validation from 'ember-stickler/validation';

export default Validation.create({
  validate(value, errors) {
    const REGEX = this.get('format');
    const result = REGEX.test(value);

    if (!result) {
      const message = this.getWithDefault('formatMessage', `A valid format matching ${REGEX} is required`);

      errors.push(message);
    }

    return errors;
  }
});


text:
package com.EverythingBlocks.api;

/** Items that implement this interface can add custom information to the corresponding Everything Block, which will replace vanilla information */
public interface IReplaceEBInformation extends IAddEBInformation { }


text:
#include <stdio.h>
#include "displayIntermediateValues.h"

FILE *intermediateValueFile = 0;
int displayLevel = 0;

void displaySetIntermediateValueFile(FILE *f)
{
    intermediateValueFile = f;
}

void displaySetLevel(int level)
{
    displayLevel = level;
}

void displayBytes(int level, const char *text, const unsigned char *bytes, unsigned int size)
{
    unsigned int i;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<size; i++)
            fprintf(intermediateValueFile, "%02X ", bytes[i]);
        fprintf(intermediateValueFile, "\n");
        fprintf(intermediateValueFile, "\n");
    }
}

void displayBits(int level, const char *text, const unsigned char *data, unsigned int size, int MSBfirst)
{
    unsigned int i, iByte, iBit;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<size; i++) {
            iByte = i/8;
            iBit = i%8;
            if (MSBfirst)
                fprintf(intermediateValueFile, "%d ", ((data[iByte] << iBit) & 0x80) != 0);
            else
                fprintf(intermediateValueFile, "%d ", ((data[iByte] >> iBit) & 0x01) != 0);
        }
        fprintf(intermediateValueFile, "\n");
        fprintf(intermediateValueFile, "\n");
    }
}

void displayStateAsBytes(int level, const char *text, const unsigned char *state, unsigned int width)
{
    displayBytes(level, text, state, width/8);
}

void displayStateAs32bitWords(int level, const char *text, const unsigned int *state)
{
    unsigned int i;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<25; i++) {
            fprintf(intermediateValueFile, "%08X:%08X", (unsigned int)state[2*i+0], (unsigned int)state[2*i+1]);
            if ((i%5) == 4)
                fprintf(intermediateValueFile, "\n");
            else
                fprintf(intermediateValueFile, " ");
        }
    }
}

void displayStateAs64bitLanes(int level, const char *text, void *statePointer)
{
    unsigned int i;
    unsigned long long int *state = statePointer;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<25; i++) {
            fprintf(intermediateValueFile, "%08X", (unsigned int)(state[i] >> 32));
            fprintf(intermediateValueFile, "%08X", (unsigned int)(state[i] & 0xFFFFFFFFULL));
            if ((i%5) == 4)
                fprintf(intermediateValueFile, "\n");
            else
                fprintf(intermediateValueFile, " ");
        }
    }
}

void displayStateAs32bitLanes(int level, const char *text, void *statePointer)
{
    unsigned int i;
    unsigned int *state = statePointer;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<25; i++) {
            fprintf(intermediateValueFile, "%08X", state[i]);
            if ((i%5) == 4)
                fprintf(intermediateValueFile, "\n");
            else
                fprintf(intermediateValueFile, " ");
        }
    }
}

void displayStateAs16bitLanes(int level, const char *text, void *statePointer)
{
    unsigned int i;
    unsigned short *state = statePointer;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<25; i++) {
            fprintf(intermediateValueFile, "%04X ", state[i]);
            if ((i%5) == 4)
                fprintf(intermediateValueFile, "\n");
        }
    }
}

void displayStateAs8bitLanes(int level, const char *text, void *statePointer)
{
    unsigned int i;
    unsigned char *state = statePointer;

    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s:\n", text);
        for(i=0; i<25; i++) {
            fprintf(intermediateValueFile, "%02X ", state[i]);
            if ((i%5) == 4)
                fprintf(intermediateValueFile, "\n");
        }
    }
}

void displayStateAsLanes(int level, const char *text, void *statePointer, unsigned int width)
{
    if (width == 1600)
        displayStateAs64bitLanes(level, text, statePointer);
    if (width == 800)
        displayStateAs32bitLanes(level, text, statePointer);
    if (width == 400)
        displayStateAs16bitLanes(level, text, statePointer);
    if (width == 200)
        displayStateAs8bitLanes(level, text, statePointer);
}

void displayRoundNumber(int level, unsigned int i)
{
    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "\n");
        fprintf(intermediateValueFile, "--- Round %d ---\n", i);
        fprintf(intermediateValueFile, "\n");
    }
}

void displayText(int level, const char *text)
{
    if ((intermediateValueFile) && (level <= displayLevel)) {
        fprintf(intermediateValueFile, "%s", text);
        fprintf(intermediateValueFile, "\n");
        fprintf(intermediateValueFile, "\n");
    }
}


text:
for process in scripts/web-server.js app.js e2eBridge.js; do
    if ! pgrep -f $process > /dev/null; then
        echo "Could not find any process running $process."
        echo "Please start it manually or use scripts/run-all.sh"
        exit 1
    fi
done

# Define reasonable set of browsers in case we are running manually from commandline
if [[ -z "$BROWSERS" ]]; then
  BROWSERS="Firefox"
fi

./node_modules/.bin/protractor config/protractor.conf.js | tee tests.out
./node_modules/karma/bin/karma start config/karma-unit.conf.js --single-run --browsers $BROWSERS | tee -a tests.out

cd ../veganaut-backend
NODE_ENV=test npm test | tee -a ../veganaut/tests.out


text:
#pragma once
#ifndef MENU_H
#define MENU_H

#include "Modules/UI/Basic Elements/UI_Element.h"
#include "Modules/UI/Basic Elements/Label.h"
#include "Modules/UI/Basic Elements/List.h"
#include "Modules/UI/Basic Elements/Panel.h"
#include "Modules/UI/Basic Elements/Separator.h"

/** A UI element serving as a menu.
Made to be sub-classed and expanded upon, provides a method for adding menu buttons. */
class Menu : public UI_Element {
public:
	// Public (De)Constructors
	/** Construct a menu.
	@param	engine		reference to the engine to use. */
	explicit Menu(Engine& engine);

	// Public Interface Implementations
	void userAction(ActionState& actionState) override;

	// Public Methods
	/** Retrieve this menu's focus map.
	@return				this menu's focus map. */
	std::shared_ptr<FocusMap> getFocusMap() const noexcept;

protected:
	// Protected Methods
	/** Create a button with the text and callback specified.
	@param	engine		reference to the engine to use.
	@param	buttonText	the text to label the button with.
	@param	callback	the callback to use when the button is pressed. */
	void addButton(Engine& engine, const char* buttonText, const std::function<void()>& callback);

	// Protected Attributes
	std::shared_ptr<Panel> m_backPanel;
	std::shared_ptr<List> m_layout;
	std::shared_ptr<Label> m_title;
	std::shared_ptr<Separator> m_separator;
	std::shared_ptr<FocusMap> m_focusMap;
	std::vector<std::function<void()>> m_selectionCallbacks;
};

#endif // MENU_H


text:
def main():
    info('Jan CO2 laser analysis')
    gosub('jan:WaitForCO2Access')
    gosub('jan:PrepareForCO2Analysis')

    close(name="M", description="Microbone to Getter NP-10H")
    gosub('jan:CO2Analysis')


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [zapposBrain loadItemsBeingMonitored];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    [zapposBrain saveItemsBeingMonitored];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{

}

- (void)applicationWillEnterForeground:(UIApplication *)application
{

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [zapposBrain loadItemsBeingMonitored];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
}

@end


text:
    #pragma warning(push)
    #pragma warning(disable: 4100)
    #pragma warning(disable: 4127)
    #pragma warning(disable: 4231)
    #pragma warning(disable: 4244)
    #pragma warning(disable: 4250)
    #pragma warning(disable: 4251)
    #pragma warning(disable: 4481)
    #pragma warning(disable: 4512)
    #pragma warning(disable: 4702)
    #pragma warning(disable: 4800)
    #pragma warning(disable: 4913)
    #pragma warning(disable: 4996)
#endif


text:
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using UtahOpenSource.Backend.Models;
using UtahOpenSource.DataObjects;
using UtahOpenSource.Backend.Identity;

namespace UtahOpenSource.Backend.Controllers
{
    public class NotificationController : TableController<Notification>
    {
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            UtahOpenSourceContext context = new UtahOpenSourceContext();
            DomainManager = new EntityDomainManager<Notification>(context, Request, true);
        }

        public IQueryable<Notification> GetAllNotification()
        {
            return Query();
        }

        public SingleResult<Notification> GetNotification(string id)
        {
            return Lookup(id);
        }

        [EmployeeAuthorize]
        public Task<Notification> PatchNotification(string id, Delta<Notification> patch)
        {
             return UpdateAsync(id, patch);
        }

        [EmployeeAuthorize]
        public async Task<IHttpActionResult> PostNotification(Notification item)
        {
            Notification current = await InsertAsync(item);
            return CreatedAtRoute("Tables", new { id = current.Id }, current);
        }

        [EmployeeAuthorize]
        public Task DeleteNotification(string id)
        {
             return DeleteAsync(id);
        }
    }
}


text:
from testmorphologyarray import TestMorphologyArray
from testmorphologytree import TestMorphologyTree


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BeeHive.Demo.PrismoEcommerce.Events
{
    public class ProductArrivedBackInStock
    {
        public string ProductId { get; set; }
    }
}


text:
import sys
import math

# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.

n = int(input())  # the number of temperatures to analyse
temps = input()  # the n temperatures expressed as integers ranging from -273 to 5526

# Write an action using print
# To debug: print("Debug messages...", file=sys.stderr)
temps = temps.split()
if len(temps) == 0:
    print ("0")
else:
    result = max(temps)
    for x in temps:
        if abs(int(x)) < abs(int(result)):
            result = x
        elif abs(int(x)) == abs(int(result)) and int(x) > 0:
            result = x

    print(result)


text:
import org.scalatestplus.play._

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class SeleniumSpec extends PlaySpec
  with BaseOneServerPerTest
  with OneBrowserPerTest
  with MyApplicationFactory
  with HtmlUnitFactory {

  "SeleniumSpec" should {

    "work from within a browser" in {

      go to ("http://localhost:" + port)

      pageSource must include("Your new application is ready.")
    }
  }
}


text:
Sometimes is important to cache routes that serve static content to make your web app performs faster and not spend time on re-building a response for clients.

There are two ways to achieve HTTP caching. One is to store the contents per handler on the server-side and the other is by checking some headers and send `304 not modified` in order to let the browser or any compatible client to handle the caching by itself.

Iris provides both server and client caching through its [iris/cache](https://github.com/kataras/iris/tree/master/cache) subpackage which exports the `iris.Cache` and `iris.Cache304` middlewares.

Let's see their outline.

## Cache

`Cache` is a middleware that provides server-side cache functionality to the next handlers, can be used as: `app.Get("/", iris.Cache, aboutHandler)`.

`Cache` accepts one single parameter: the cache expiration duration. If the expiration is invalid value, <=2 seconds, then expiration is taken by the "cache-control's maxage" header

All types of response can be cached, templates, json, text, anything.

Use it for server-side caching, see the `Cache304` for an alternative approach that may be more suited to your needs.

```go
func Cache(expiration time.Duration) Handler
```

For more options and customization use the [kataras/iris/cache.Cache](https://godoc.org/github.com/kataras/iris/cache#Cache) which returns a [structure from which you can add or remove "Rules"](https://godoc.org/github.com/kataras/iris/cache/client#Handler) instead.

## NoCache

`NoCache` is a middleware which overrides the Cache-Control, Pragma and Expires headers in order to disable the cache during the browser's back and forward feature.

A good use of this middleware is on HTML routes; to refresh the page even on "back" and "forward" browser's arrow buttons.

```go
func NoCache(Context)
```

See `StaticCache` for the opposite behavior.

## StaticCache

`StaticCache` returns a middleware for caching static files by sending the "Cache-Control" and "Expires" headers to the client. It accepts a single input parameter, the "cacheDur", a time.Duration that it's used to calculate the expiration.

If "cacheDur" <=0 then it returns the `NoCache` middleware instaed to disable the caching between browser's "back" and "forward" actions.

Usage: `app.Use(iris.StaticCache(24 * time.Hour))` or `app.Use(iris.StaticCache(-1))`.

```go
func StaticCache(cacheDur time.Duration)Handler
```

A middleware, which is a simple Handler, can be called inside another handler as well, example:

```go
 cacheMiddleware := iris.StaticCache(...)

 func(ctx iris.Context){
  cacheMiddleware(ctx)
  [...]
}
```

## Cache304

`Cache304` returns a middleware sends a `StatusNotModified` (304) whenever the "If-Modified-Since" request header (time) is before the time.Now() + expiresEvery (always compared to their UTC values).

Clients that are compatible with the HTTP RCF (all browsers are and tools like postman) will correctly handle the caching.

The only disadvantage of using that instead of server-side caching is that this method will send a 304 status code instead of 200, So, if you use it side by side with other micro services you have to check for that status code as well for a valid response.

Developers are free to extend this method's behavior by watching system directories changes manually and use of the `ctx.WriteWithExpiration` with a "modtime" based on the file modified date, similar to the `HandleDir`(which sends status OK\(200) and browser disk caching instead of 304\).

```go
func Cache304(expiresEvery time.Duration) Handler
```

Examples can be found at: [https://github.com/kataras/iris/tree/master/\_examples/response-writer/cache](https://github.com/kataras/iris/tree/master/_examples/response-writer/cache).

<!-- slide:break-100 -->


text:
#region License

#endregion License

#region Using clause
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Runtime.Remoting.Messaging;

using Sce.PlayStation.Core.Input;

using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

#endregion Using clause

namespace Microsoft.Xna.Framework.GamerServices
{

	public static class Guide
	{
		private static bool isScreenSaverEnabled;
		private static bool isTrialMode;
		private static bool isVisible;
		private static bool simulateTrialMode;
		private static bool isMessageBoxShowing = false;
		private static bool isKeyboardInputShowing = false;

        internal static void Initialise(Game game)
        {
			MonoGameGamerServicesHelper.Initialise(game);
        }

	    delegate string ShowKeyboardInputDelegate(
		 PlayerIndex player,
         string title,
         string description,
         string defaultText,
		 bool usePasswordMode);

		public static string ShowKeyboardInput(
		 PlayerIndex player,
         string title,
         string description,
         string defaultText,
		 bool usePasswordMode)
		{
			throw new NotImplementedException();
			/* TODO Use UISystem etc (See Sample: UI/Overlay and others)
			string result = defaultText;
			if (!isKeyboardInputShowing)
			{
				isKeyboardInputShowing = true;

			}

			isVisible = isKeyboardInputShowing;

		    var alert = new AlertDialog.Builder(Game.Activity);

		    alert.SetTitle(title);
		    alert.SetMessage(description);

		    var input = new EditText(Game.Activity) {Text = defaultText};
		    alert.SetView(input);

		    alert.SetPositiveButton("Ok", (dialog, whichButton) =>
		                                      {
		                                          result = input.Text;
		                                          isVisible = false;
		                                      });

		    alert.SetNegativeButton("Cancel", (dialog, whichButton) =>
		                                          {
		                                              result = null;
                                                      isVisible = false;
                                                  });

            Game.Activity.RunOnUiThread(() => alert.Show());

		    while (isVisible)
		    {
		        Thread.Sleep(1);
		    }

            return result;*/
		}

		public static IAsyncResult BeginShowKeyboardInput (
         PlayerIndex player,
         string title,
         string description,
         string defaultText,
         AsyncCallback callback,
         Object state)
		{
			return BeginShowKeyboardInput(player, title, description, defaultText, callback, state, false );
		}

		public static IAsyncResult BeginShowKeyboardInput (
         PlayerIndex player,
         string title,
         string description,
         string defaultText,
         AsyncCallback callback,
         Object state,
         bool usePasswordMode)
		{
			ShowKeyboardInputDelegate ski = ShowKeyboardInput;

			return ski.BeginInvoke(player, title, description, defaultText, usePasswordMode, callback, ski);
		}

		public static string EndShowKeyboardInput (IAsyncResult result)
		{
			try
			{
				ShowKeyboardInputDelegate ski = (ShowKeyboardInputDelegate)result.AsyncState;

				return ski.EndInvoke(result);
			}
			finally
			{
				isVisible = false;
			}
		}

		delegate Nullable<int> ShowMessageBoxDelegate( string title,
         string text,
         IEnumerable<string> buttons,
         int focusButton,
         MessageBoxIcon icon);

		public static Nullable<int> ShowMessageBox( string title,
         string text,
         IEnumerable<string> buttons,
         int focusButton,
         MessageBoxIcon icon)
		{
			Nullable<int> result = null;

			if ( !isMessageBoxShowing )
			{
				isMessageBoxShowing = true;

				/*UIAlertView alert = new UIAlertView();
				alert.Title = title;
				foreach( string btn in buttons )
				{
					alert.AddButton(btn);
				}
				alert.Message = text;
				alert.Dismissed += delegate(object sender, UIButtonEventArgs e)
								{
									result = e.ButtonIndex;
									isMessageBoxShowing = false;
								};
				alert.Clicked += delegate(object sender, UIButtonEventArgs e)
								{
									result = e.ButtonIndex;
									isMessageBoxShowing = false;
								};

				GetInvokeOnMainThredObj().InvokeOnMainThread(delegate {
       		 		alert.Show();
    			});*/

			}

			isVisible = isMessageBoxShowing;

			return result;
		}

		public static IAsyncResult BeginShowMessageBox(
         PlayerIndex player,
         string title,
         string text,
         IEnumerable<string> buttons,
         int focusButton,
         MessageBoxIcon icon,
         AsyncCallback callback,
         Object state
		)
		{
			ShowMessageBoxDelegate smb = ShowMessageBox;

			return smb.BeginInvoke(title, text, buttons, focusButton, icon, callback, smb);
		}

		public static IAsyncResult BeginShowMessageBox (
         string title,
         string text,
         IEnumerable<string> buttons,
         int focusButton,
         MessageBoxIcon icon,
         AsyncCallback callback,
         Object state
		)
		{
			return BeginShowMessageBox(PlayerIndex.One, title, text, buttons, focusButton, icon, callback, state);
		}

		public static Nullable<int> EndShowMessageBox (IAsyncResult result)
		{
			try
			{
				ShowMessageBoxDelegate smbd = (ShowMessageBoxDelegate)result.AsyncState;

				return smbd.EndInvoke(result);
			}
			finally
			{
				isVisible = false;
			}
		}

		public static void ShowMarketplace (PlayerIndex player )
		{

		}

		public static void Show ()
		{
			ShowSignIn(1, false);
		}

		public static void ShowSignIn (int paneCount, bool onlineOnly)
		{
			if ( paneCount != 1 )
			{
				new ArgumentException("paneCount Can only be 1 on iPhone");
				return;
			}

			MonoGameGamerServicesHelper.ShowSigninSheet();

			if (GamerServicesComponent.LocalNetworkGamer == null)
			{
				GamerServicesComponent.LocalNetworkGamer = new LocalNetworkGamer();
			}
			else
			{
				GamerServicesComponent.LocalNetworkGamer.SignedInGamer.BeginAuthentication(null, null);
			}
		}

		public static void ShowLeaderboard()
		{
			if ( ( Gamer.SignedInGamers.Count > 0 ) && ( Gamer.SignedInGamers[0].IsSignedInToLive ) )
			{

			}
		}

		public static void ShowAchievements()
		{
			if ( ( Gamer.SignedInGamers.Count > 0 ) && ( Gamer.SignedInGamers[0].IsSignedInToLive ) )
			{

			}
		}

		public static void ShowPeerPicker()
		{
			if ( ( Gamer.SignedInGamers.Count > 0 ) && ( Gamer.SignedInGamers[0].IsSignedInToLive ) )
			{

			}
		}

		public static void ShowMatchMaker()
		{
			if ( ( Gamer.SignedInGamers.Count > 0 ) && ( Gamer.SignedInGamers[0].IsSignedInToLive ) )
			{

			}
		}

		public static IAsyncResult BeginShowStorageDeviceSelector( AsyncCallback callback, object state )
		{
			return null;
		}

		public static StorageDevice EndShowStorageDeviceSelector( IAsyncResult result )
		{
			return null;
		}

		#region Properties
		public static bool IsScreenSaverEnabled
		{
			get
			{
				return isScreenSaverEnabled;
			}
			set
			{
				isScreenSaverEnabled = value;
			}
		}

		public static bool IsTrialMode
		{
			get
			{
				return isTrialMode;
			}
			set
			{
				isTrialMode = value;
			}
		}

		public static bool IsVisible
		{
			get
			{
				return isVisible;
			}
			set
			{
				isVisible = value;
			}
		}

		public static bool SimulateTrialMode
		{
			get
			{
				return simulateTrialMode;
			}
			set
			{
				simulateTrialMode = value;
			}
		}

		public static PSSGameWindow Window
		{
			get;
			set;
		}
		#endregion

	}
}


text:
package tw.showang.apiabstrationframework.util;

import android.os.AsyncTask;

public class AsyncManager<BackgroundResult> {

	private boolean mIsAsync = true;
	private AsyncWork<BackgroundResult> mAsyncWork;
	private PostWork<BackgroundResult> mPostWork;

	public AsyncManager<BackgroundResult> setAsync(boolean isAsync) {
		mIsAsync = isAsync;
		return this;
	}

	public AsyncManager<BackgroundResult> background(AsyncWork<BackgroundResult> work) {
		mAsyncWork = work;
		return this;
	}

	public AsyncManager<BackgroundResult> post(PostWork<BackgroundResult> work) {
		mPostWork = work;
		return this;
	}

	public void start() {
		if (mAsyncWork == null) {
			throw new IllegalStateException("Plz init background work before start.");
		}
		if (mIsAsync) {
			doAsync();
		} else {
			doSync();
		}
	}

	private void doSync() {
		BackgroundResult result = mAsyncWork.doInBackground();
		if (mPostWork != null) {
			mPostWork.onPostExecute(result);
		}
	}

	private void doAsync() {
		new AsyncTask<Void, Void, BackgroundResult>() {
			@Override
			protected BackgroundResult doInBackground(Void... params) {
				return mAsyncWork.doInBackground();
			}

			@Override
			protected void onPostExecute(BackgroundResult backgroundResult) {
				super.onPostExecute(backgroundResult);
				if (mPostWork != null) {
					mPostWork.onPostExecute(backgroundResult);
				}
			}
		}.execute();
	}

	public interface AsyncWork<BackgroundResult> {
		BackgroundResult doInBackground();
	}

	public interface PostWork<BackgroundResult> {
		void onPostExecute(BackgroundResult result);
	}
}


text:
var guiLayer : GUILayer;

var arrow : Transform;
var lastDir : Vector3 = Vector3(1,1,1);
var lastY : float;
var sensitivityX = 15.0;
var sensitivityY = 15.0;
var rotationX = 10.0;
var rotationY = 10.0;
var heightBoost : float;
var targetHeight : float;
var gyroTation : Quaternion;

var wr : Quaternion;
private var underwater = false;
var hit : RaycastHit;
var mb : MotionBlur;
var glowEffect : GlowEffect;
var colorEffect : ColorCorrectionEffect;
var worldTime : float = 0;

function Start () {
	Time.timeScale = 1;
	transform.rotation.eulerAngles.x = 270.01;
}

function LateUpdate () {
	if (!Game.Player || !Game.PlayerVeh || !Game.PlayerVeh.ridePos) return;

	//Blur
	if(mb.enabled) {
		mb.blurAmount -= Time.deltaTime * .13;
		if(mb.blurAmount < 0) mb.enabled = false;
	}

	//Audio
	if(Game.Settings.useHypersound == 1) {
		Game.Settings.gameMusic.pitch = Mathf.Clamp(-.5 + Game.Player.GetComponent.<Rigidbody>().velocity.magnitude / 15, .8, 1.5);
	}

	//Cursor Locking
	if(Game.Settings.camMode == 0 || Input.GetButton("Fire2") || (Input.GetButton("Snipe") && !Game.Messaging.chatting)) Cursor.lockState = CursorLockMode.Locked;
	else Cursor.lockState = CursorLockMode.None;

	//Snipe Zooming
	if(Input.GetButton("Snipe") && !Game.Messaging.chatting) {
		if(Camera.main.fieldOfView == 60) Camera.main.fieldOfView = 10;
		Camera.main.fieldOfView += Input.GetAxis("Mouse ScrollWheel") * -1;
		if(Camera.main.fieldOfView > 50) Camera.main.fieldOfView = 50;
		else if(Camera.main.fieldOfView < 1.5) Camera.main.fieldOfView = 1.5;
	}
	else if(Camera.main.fieldOfView != 60) Camera.main.fieldOfView = 60;

	//Green Arrow
	var targetPos : Vector3 = transform.InverseTransformPoint(GetComponent.<Camera>().ScreenToWorldPoint(Vector3(GetComponent.<Camera>().pixelWidth - 30 - 65, 30, GetComponent.<Camera>().nearClipPlane + .05)));
	if(Vector3.Distance(targetPos, arrow.localPosition) < 0.002) arrow.localPosition = Vector3.Lerp(arrow.localPosition, targetPos, Time.deltaTime * .005);
	else arrow.localPosition = targetPos;
    arrow.rotation = Quaternion.Lerp(arrow.rotation, Quaternion.LookRotation((Game.PlayerVeh.isIt || !Game.QuarryVeh ? World.base : Game.QuarryVeh.gameObject.transform).position - Game.Player.transform.position), Time.deltaTime * 15);
	arrow.localScale = Vector3.one * Mathf.Lerp(.03, 1, Camera.main.fieldOfView / 60);

	//Hotkeys
	if(Input.GetKeyDown(KeyCode.Escape) && Game.Settings.camMode == 0) { //Unlock Cursor
		Game.Settings.camMode = 1;
		PlayerPrefs.SetInt("cam", 1);
	}
	if(!Game.Messaging.chatting) {
		if(Input.GetKeyDown(KeyCode.Alpha1)) {
			Game.Settings.camMode = 0;
			PlayerPrefs.SetInt("cam", 0);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha2)) {
			Game.Settings.camMode = 1;
			PlayerPrefs.SetInt("cam", 1);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha3)) {
			Game.Settings.camDist = 0;
			PlayerPrefs.SetFloat("camDist", 0);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha4)) {
			Game.Settings.camDist = 20;
			PlayerPrefs.SetFloat("camDist", 20);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha5)) {
			Game.Settings.camMode = 2;
			PlayerPrefs.SetInt("cam", 2);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha6)) {
			Game.Settings.camMode = 3;
			PlayerPrefs.SetInt("cam", 3);
		}
		else if(Input.GetKeyDown(KeyCode.Alpha7)) {
			Game.Settings.gyroCam = (Game.Settings.gyroCam ? false : true);
			PlayerPrefs.SetInt("gyroCam", (Game.Settings.gyroCam ? 1 : 0));
		}
	}

	//Constants
	var camDist : float = Game.PlayerVeh.camOffset + Game.Settings.camDist;

	//World Entry Effect
	if(worldTime < 7) {
		worldTime = Time.time - Game.Controller.worldLoadTime;
		transform.position = Vector3.Lerp (transform.position, Game.Player.transform.position, Time.deltaTime * 1);
		wr = Quaternion.LookRotation(Game.Player.transform.position - transform.position, Vector3.up);
		if(worldTime > 1) transform.rotation = Quaternion.Slerp(transform.rotation, wr, (Time.deltaTime * .5) * Mathf.Min(1, (worldTime - 1) * .5));
	}

	//Ride
	else if(Game.Settings.camMode == 0 || Input.GetButton("Fire2") || (Input.GetButton("Snipe") &&  !Game.Messaging.chatting)) {
		transform.position = Game.PlayerVeh.ridePos.position;

		if(Input.GetButtonDown("Fire2") || Input.GetKeyDown(KeyCode.Alpha1)) {
			rotationX = 0;
			rotationY = 0;
			if(Game.Settings.gyroCam) {
				gyroTation = Quaternion.Euler(0, Game.PlayerVeh.ridePos.rotation.eulerAngles.y, 0);
			}
		}

		if(Game.Settings.gyroCam) transform.rotation = gyroTation;
		else transform.rotation = Game.PlayerVeh.ridePos.rotation;

		rotationX += Input.GetAxis("Mouse X") * (Input.GetButton("Snipe") ? .5 : 2);
		rotationY += Input.GetAxis("Mouse Y") * (Input.GetButton("Snipe") ? .5 : 2);

		if (rotationX < -360) rotationX += 360;
		else if (rotationX > 360) rotationX -= 360;
 		if (rotationY < -360) rotationY += 360;
		else if (rotationY > 360) rotationY -= 360;

		rotationX = Mathf.Clamp (rotationX, -360, 360);
		if(Game.Settings.gyroCam) rotationY = Mathf.Clamp (rotationY, -100, 100);
		else rotationY = Mathf.Clamp (rotationY, -20, 100);
		transform.localRotation *= Quaternion.AngleAxis (rotationX, Vector3.up);
		transform.localRotation *= Quaternion.AngleAxis (rotationY, Vector3.left);
	}

	//Chase
	else if(Game.Settings.camMode == 1) {

		//Smooth
		if(Game.Settings.camChase == 0) {
			transform.position = Vector3.Lerp(transform.position, (
				Game.Player.transform.position - Vector3.Normalize(Game.Player.transform.position - transform.position) * (camDist) +
				Vector3.one * (Game.PlayerVeh.camSmooth ? 0 : Mathf.Lerp(0, 15, camDist / 30))
				), Time.deltaTime * 3.5);
			transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Game.Player.transform.position - transform.position, (Game.Settings.flightCam ? Game.Player.transform.up : Vector3.up)), Time.deltaTime * 4);
			if(Physics.Linecast(transform.position + Vector3.up * 50, transform.position + Vector3.down * 1, hit, (1 << 8)) && hit.collider.type != TerrainCollider) transform.position.y += 51 - hit.distance;
		}

		//Agile
		else if(Game.Settings.camChase == 1) {
			var dist = Vector3.Distance(Game.Player.transform.position, transform.position);
			if(Game.Player.transform.gameObject.GetComponent.<Rigidbody>() && Game.Player.transform.gameObject.GetComponent.<Rigidbody>().velocity.sqrMagnitude > .1 && Game.Player.transform.gameObject.GetComponent.<Rigidbody>().velocity.normalized.y < .8 && Game.Player.transform.gameObject.GetComponent.<Rigidbody>().velocity.normalized.y > -.8) lastDir = Vector3.Lerp(lastDir,Game.Player.transform.gameObject.GetComponent.<Rigidbody>().velocity.normalized,.1);
			else Vector3.Lerp(lastDir,Vector3(lastDir.x,0,lastDir.z), .1);
			var newPos = (Game.Player.transform.position + lastDir * -(camDist) + Vector3.up * ((camDist) / 3));
			transform.position.y += (Game.Player.transform.position.y - lastY) * Time.deltaTime;
			transform.position = Vector3.Lerp(transform.position, newPos, Time.deltaTime * 4);
			lastY = Game.Player.transform.position.y;
			transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Game.Player.transform.position - transform.position, (Game.Settings.flightCam ? Game.Player.transform.up : Vector3.up)), Time.deltaTime * 4);
			if(Physics.Linecast(transform.position + Vector3.up * 50, transform.position + Vector3.down * 1, hit, (1 << 8)) && hit.collider.type != TerrainCollider) transform.position.y += 51 - hit.distance;
		}

		//Arcade
		else if(Game.Settings.camChase == 2) {
			if(Game.Player.transform.GetComponent.<Rigidbody>().velocity.magnitude > 0) {

				var heightDamping = 3.0;
				var distanceDamping = 10.0;
				var rotationDamping = 3.0;
				wantedRotationAngle = Quaternion.LookRotation(Game.Player.transform.GetComponent.<Rigidbody>().velocity).eulerAngles.y;
				wantedRotationAngle += Input.GetAxis("Horizontal") * Mathf.Lerp(30, 10, camDist / 30);
				wantedHeight = Game.Player.transform.position.y + Mathf.Lerp(.1, 15, camDist / 30) + heightBoost;
				targetHeight = Mathf.Lerp(.5, 3, camDist / 30);

				/*if (Physics.Raycast(transform.position + (Vector3.up * 50), Vector3.down, hit, 51, 1 << 8)) {
					print(50 - hit.distance);
					wantedHeight += (80 - hit.distance);
				}*/

				currentRotationAngle = transform.eulerAngles.y;
				currentHeight = transform.position.y;
				currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
				currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
				currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
				pos = Game.Player.transform.position;
				pos.y += targetHeight; //Look ABOVE the target
				transform.position = pos;
				transform.position -= currentRotation * Vector3.forward * camDist;
				transform.position.y = currentHeight;

				//Terrain Avoidance
				var hit : RaycastHit;
				if (Physics.Raycast(transform.position + (Vector3.up * 49.4), Vector3.down, hit, 50, 1 << 8) && hit.collider.type != TerrainCollider) { //We are under terrain
					Physics.Linecast(transform.position, Game.Player.transform.position + (Vector3.up * currentHeight), hit, (1 << 8)); //Determine how far forward we need to go to be out of it
					transform.position += currentRotation * Vector3.forward * hit.distance;
					heightBoost = hit.distance * .7;
				}
				else heightBoost = 0;

				transform.LookAt (pos);
				//transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(pos - transform.position, (Game.Settings.flightCam ? Game.Player.transform.up : Vector3.up)), Time.deltaTime * 5);
			}
		}

		//Hyper
		/*else if(Game.Settings.camChase == 3) {
			dist = Vector3.Distance(Game.Player.transform.position, transform.position); //Raise when near target
			var wantedPosition = Game.Player.transform.TransformPoint(0, height + (dist < 10 ? 40 - dist * 4 : 0), -distance);
			transform.position = Vector3.Lerp (transform.position, wantedPosition, Time.deltaTime * damping);
			var wantedRotation = Quaternion.LookRotation(Game.Player.transform.position - transform.position, Game.Player.transform.up);
			transform.rotation = Quaternion.Slerp (transform.rotation, wantedRotation, Time.deltaTime * rotationDamping);
		}*/
	}

	//Soar
	else if(Game.Settings.camMode == 2) {
		transform.position = Vector3.Lerp (transform.position, Game.Player.transform.position + (Vector3.up * 40), Time.deltaTime * 0.3);
		wr = Quaternion.LookRotation(Game.Player.transform.position - transform.position, Vector3.up);
		transform.rotation = Quaternion.Slerp (transform.rotation, wr, Time.deltaTime * 2);
	}

	//Spectate
	else if(Game.Settings.camMode == 3) {
		transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Game.Player.transform.position - transform.position), Time.deltaTime * 1.5);
		transform.Translate(Vector3(Input.GetAxis("camX") * Time.deltaTime * 50, Input.GetAxis("camY") * Time.deltaTime * 40, Input.GetAxis("camZ") * Time.deltaTime * 50));
	}

	//Roam
	else if(Game.Settings.camMode == 4) {
		transform.position.x += Input.GetAxis("camX") * Time.deltaTime * 50;
		transform.position.y += Input.GetAxis("camY") * Time.deltaTime * 50;
		transform.position.z += Input.GetAxis("camZ") * Time.deltaTime * 50;
		rotationX += Input.GetAxis("Mouse X") * sensitivityX;
		rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
		//Invoke("Adjust360andClamp", 0);
		transform.localRotation = Quaternion.AngleAxis (rotationX, Vector3.up);
		transform.localRotation *= Quaternion.AngleAxis (rotationY, Vector3.left);
	}
}

function OnPreRender () {

	if(Game.Settings.fogColor == Color.clear) return;	//Game has just initialized - don't start adding effects yet...

	if (transform.position.y < Game.Settings.lavaAlt || Physics.Raycast(transform.position + (Vector3.up * 200), Vector3.up * -1, 200, 1 << 4)) {
		RenderSettings.fogColor = World.seaFogColor;
		RenderSettings.fogDensity = Game.Settings.lavaFog;
		glowEffect.enabled = (Game.Settings.renderLevel > 2);
		glowEffect.glowTint = World.seaGlowColor;
		Camera.main.clearFlags = CameraClearFlags.SolidColor;
	}
	else {
		RenderSettings.fogColor = Game.Settings.fogColor;
		RenderSettings.fogDensity = Game.Settings.worldFog;
		glowEffect.enabled = false;
		Camera.main.clearFlags = (Camera.main.farClipPlane > 2000 ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor);
	}

	colorEffect.enabled = glowEffect.enabled;
	Camera.main.backgroundColor = RenderSettings.fogColor;

}


text:
import { ClientCommand } from './clientCommand';
import { BaseCommand } from './baseCommand';

module.exports = class EditProject extends ClientCommand {
    static create(): BaseCommand {
        return new EditProject();
    }

    constructor() {
        super('Open Salesforce', 'open-sfdc');
        this.async = false;
        this.body.args.ui = true;
    }
}