text:
.. _stereo_gui:

stereo_gui
----------

The ``stereo_gui`` program is a GUI frontend to ``stereo``, and has the
same command-line options. It can display the input images side-by-side
(and in other ways, as detailed later). One can zoom in by dragging the
mouse from upper-left to lower-right, and zoom out via the reverse
motion.

By pressing the ``Control`` key while dragging the mouse, regions can be
selected in the input images, and then stereo can be run on these
regions from the menu via Run\ :math:`\rightarrow`\ Stereo. The
``stereo`` command that is invoked (with appropriately populated
parameter values for ``--left-image-crop-win`` and
``--right-image-crop-win`` for the selected regions) will be displayed
on screen, and can be re-run on a more powerful machine/cluster without
GUI access.

Additional navigation options are using the mouse wheel or the +/- keys
to zoom, and the arrow keys to pan (one should first click to bring into
focus the desired image before using any keys).

.. figure:: ../images/stereo_gui.jpg
   :name: asp_gui_fig
   :alt: stereo_gui.

   An illustration of stereo_gui. The ``stereo`` command will be run on
   the regions selected by red rectangles.

Usage::

     ISIS> stereo_gui [options] <images> [<cameras>] output_file_prefix

Use as an Image Viewer
~~~~~~~~~~~~~~~~~~~~~~

This program can be also used as a general-purpose image viewer, case in
which no stereo options or camera information is necessary. It can
display arbitrarily large images with integer, floating-point, or RGB
pixels, including ISIS .cub files and DEMs. It handles large images by
building on disk pyramids of increasingly coarser subsampled images and
displaying the subsampled versions that are appropriate for the current
level of zoom.

The images can be shown either side-by-side, as tiles on a grid (using
``--grid-cols integer``), or on top of each other (using
``--single-window``), with a dialog to choose among them. In the last
usage scenario, the option ``--use-georef`` will overlay the images
correctly if georeference information is present. It is possible to
switch among these modes once the GUI has been open, from the GUI View
menu.

When the images are shown side-by-side, the GUI can zoom in all images
to the same region, for easier comparison among them.

When the images are in a single window, an individual image can be
turned on or off via a checkbox. Clicking on an image's name will zoom
to it and display it on top of other images. By right-clicking the list
of images, other operations can be performed, such as deleting an image
from the view, etc.

``stereo_gui`` can show hillshaded DEMs, either via the ``--hillshade``
option, or by choosing from the GUI View menu the ``Hillshaded images``
option.

This program can also display the output of the ASP ``colormap`` tool
(:numref:`colormap`).

When clicking on a pixel, the pixel indices and value will be printed on
screen. When selecting a region by pressing the ``Control`` key while
dragging the mouse, its bounds will be displayed on screen. If the image
is geo-referenced, the extent of the region in projected coordinates and
in the longitude-latitude domain will be shown as well.

The program can also save a screenshot to disk in the BMP or XPM format.

Other Functionality
~~~~~~~~~~~~~~~~~~~

View/create/move/delete/save interest point matches, GCP, and VWIP files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

``stereo_gui`` can be used to view interest point matches (``*.match``
files), such as generated by ``ipmatch``, ``bundle_adjust``, or
``stereo``. It can also manually create and delete matches (useful in
situations when automatic interest point matching is unreliable due to
large changes in illumination). Interest point matches can be created or
deleted with the right-mouse click. To move interest points, right click
on a panel and check "Move match point". While this is checked you can
move interest points by clicking and dragging them within the panel.
Uncheck "Move match point" to stop moving interest points.

The match file to load can be specified via ``--match-file``. It may
also be auto-detected if ``stereo_gui`` was invoked like ``stereo``,
with an output prefix (auto-detection works only when images are not
map-projected and alignment is homography or affine epipolar). Match
files can be created with the ``ipmatch`` tool or by using
``stereo_pprc``.

When working with N images, N-1 match files are needed to describe all
of the interest points. For image i, the match file must contain the
matches from image i-1 or from image 0. You can provide these match
files to ``stereo_gui`` by conforming to its naming convention
(prefix-fname1__fname2.match) or by selecting them from the GUI when
prompted. All match files must describe the same set of interest points,
the tool will check the positions of loaded points and discard any that
do not correspond to the already loaded points. If one of the match
files fails to load or does not contain enough matching points, the
missing points will be added to an arbitrary position and flagged as
invalid. You must either validate these points by manually moving them
to the correct position or else delete them.

This tool can show the interest points from a GCP file (but cannot edit
them with this interface, creating such points is described later in
this section). The ``--gcp-file`` option is used.

The ``stereo_gui`` program can also display ``.vwip`` files. Those are
interest points created by ``ipfind``, ``bundle_adjust``, or ``stereo``,
before they are matched across images. One should specify as many such
files as images when launching this program.

.. _creatinggcp:

Creating GCP with a georeferenced image and a DEM
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

There exist situations when one has one or more images for which
the camera files are either inaccurate or, for Pinhole camera models,
just the intrinsics may be known. Given a DEM of the area, and
optionally a georeferenced image, it is possible to create GCP files
(:numref:`bagcp`) that can later be used with ``bundle_adjust`` to
either improve the alignment of these cameras to the DEM, or create
new Pinhole cameras from scratch (the latter is shown in
:numref:`imagecorners`).

One starts by opening these desired images and the georeferenced image
in the GUI, in this order (hence the georeferenced image is the last).
If no georeferenced image exists, one can use the given DEM instead (and
it can be hillshaded after loading to easier identify features).

Next, a feature is identified and manually added as an interest point in
all open images, using the right-click menu, and this process is
repeated a few times. Thus created interest points can also be moved
around by right-clicking to turn on this mode, and then dragging them
with the mouse (this can be slow).

If the input images and the georeferenced image are very similar
visually, one can also try to automatically detect interest point
matches in them using ``ipfind``/``ipmatch`` and load the .match files
as described in the earlier section on creating interest points.

When you are finished creating interest points, use the "IP
matches"->"Write GCP file" menu item to generate a ground control point
file containing the selected points. You will be prompted for the
reference DEM and for the desired output file name, unless this DEM was
already specified via ``--dem-file`` upon launch and the GCP file was
already specified via ``--gcp-file``. The last image, that is the
reference, is only used to find the positions on the ground, which in
turn are used to find the heights for the GCPs from the DEM. The
selected interest points from the reference image are not saved to the
GCP file.

.. _mapip:

Creating interest point matches using map-projected images
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To make it easier to create interest point matches in situations when
the images are very different or taken from very diverse perspectives,
they can be first mapproject onto a DEM, as then the images look a lot
more similar. Then interest points are created among the map-projected
images, when this process is more likely to succeed, and they are
transferred to the original images.

Here is an example. Given three images A.tif, B.tif, and C.tif, and a
DEM named dem.tif, mapproject them onto this DEM, obtaining the images
A.map.tif, B.map.tif, and C.map.tif. Note that one should not use
``--bundle-adjust-prefix`` in mapprojection.

Then bundle adjustment is invoked as follows, during which the transfer
of interest points happens::

      bundle_adjust A.tif B.tif C.tif <cameras> run/run \
      --mapprojected-data 'A.map.tif B.map.tif C.map.tif dem.tif' --min-matches 0

If the mapprojected images are still too different for interest point
matching among them to succeed, one can try to bring in more images that
are intermediate in appearance or illumination between the existing
ones, hence bridging the gap. Alternatively, interest point matching can
be done manually in the GUI as follows::

     stereo_gui A.map.tif B.map.tif C.map.tif run/run

Interest points can be picked by right-clicking on the same feature in
each image, from left to right, then repeating this process for a
different feature, etc. They can be saved to disk from the menu, and the
above bundle adjustment command can be invoked.

One can then run::

     stereo_gui A.tif B.tif C.tif run/run

and turn on viewing of interest point matches to study if they were
"unmapped" to the right locations.

Polygon editing
^^^^^^^^^^^^^^^

``stereo_gui`` is able to draw and edit polygonal shapes on top of
georeferenced images, and load/save them as shape files (*.shp). This
functionality can be accessed by turning on polygon editing from the
*Vector Layer* menu, and then right-clicking with the mouse to access
the various functions. Subsequently, one can use ``gdal_rasterize`` to
keep or exclude the portion of a given image/DEM that is within or
outside the selected polygon.

Shadow threshold
^^^^^^^^^^^^^^^^

``stereo_gui`` can be used to find the shadow threshold for each
of a given set of images (useful for shape-from-shading, see
:numref:`sfs`). This can be done by turning on from the menu the
``Shadow threshold detection`` mode, and then clicking on pixels
in the shadow. The largest of the chosen pixel values will be set
to the shadow threshold for each image and printed to the screen.
To see the images with the pixels below the shadow threshold
highlighted, select from the menu the ``View shadow-thresholded
images`` option.

Somewhat related to this, if the viewer is invoked with
``--nodata-value double``, it will display any pixels (presumably in the
background) with values less than or equal to this as transparent.

Listed below are the options specific to ``stereo_gui``. It will accept
all other ``stereo`` options as well.

Command line options for ``stereo_gui``:

-h, --help  Display this help message.

--grid-cols <integer (default: 1)>
    Display images as tiles on a grid with this many columns.

--window-size <integer integer (default: 1200 800)>
    The width and height of the GUI window in pixels.

-w, --single-window
    Show all images in the same window (with a dialog to choose
    among them) rather than next to each other.

--use-georef
    Plot the images in the projected coordinate system given by
    the image georeferences.

--nodata-value <double (default: NaN)>
    Pixels with values less than or equal to this number are treated
    as no-data and displayed as transparent. This overrides the
    no-data values from input images.

--hillshade
    Interpret the input images as DEMs and hillshade them.

--hillshade-azimuth
    The azimuth value when showing hillshaded images.

--hillshade-elevation
    The elevation value when showing hillshaded images.

--view-matches
    Locate and display the interest point matches.

--match-file
    Display this match file instead of looking one up based on
    existing conventions (implies ``--view-matches``).

--gcp-file
    Display the GCP pixel coordinates for this GCP file (implies
    ``--view-matches``).  Also save here GCP if created from the
    GUI.

--dem-file
    Use this DEM when creating GCP from images.

--hide-all
    Start with all images turned off (if all images are in the same
    window, useful with a large number of images).

--delete-temporary-files-on-exit
    Delete any subsampled and other files created by the GUI when exiting.

--create-image-pyramids-only
    Without starting the GUI, build multi-resolution pyramids for
    the inputs, to be able to load them fast later.


text:
project.name = "examples"
project.bindir = "."

-- Package ----------------------------------------------------------------------------------

example_checkin = newpackage()

example_checkin.name = "example_checkin"
example_checkin.kind = "exe"
example_checkin.language = "c++"
example_checkin.configs = { "Debug", "Release" }

if (windows) then
   table.insert(example_checkin.defines, "WIN32") -- Needed to fix something on Windows.
end

-- Include and library search paths, system dependent (I don't assume a directory structure)

example_checkin.includepaths = {
-- for more boost awesomeness
"../cpp-netlib/",
"../include",

-- alter this as required to point to a relatively recent
-- version of boost (I've been testing against 1.44, but 1.42
-- might work as well)
"/usr/local/include/boost"

}

example_checkin.libpaths = {
"/usr/local/lib",
"../build/debug"
}

-- Libraries to link to ---------------------------------------------------------------------

example_checkin.links = {
"pthread",
"boost_system",
"boost_regex",
"boost_program_options",
"ssl",
"foursquarepp_d"

}

-- pkg-configable stuff ---------------------------------------------------------------------

if (linux) then
example_checkin.buildoptions = {
"-Winvalid-pch"
}

example_checkin.linkoptions = {
}
end

-- Files ------------------------------------------------------------------------------------

example_checkin.files = {
"./example_checkin.cpp",
}

example_getcheckins = newpackage()

example_getcheckins.name = "example_getcheckins"
example_getcheckins.kind = "exe"
example_getcheckins.language = "c++"
example_getcheckins.configs = { "Debug", "Release" }

if (windows) then
   table.insert(example_getcheckins.defines, "WIN32") -- Needed to fix something on Windows.
end

-- Include and library search paths, system dependent (I don't assume a directory structure)

example_getcheckins.includepaths = {
-- for more boost awesomeness
"../cpp-netlib/",
"../include",

-- alter this as required to point to a relatively recent
-- version of boost (I've been testing against 1.44, but 1.42
-- might work as well)
"/usr/local/include/boost"

}

example_getcheckins.libpaths = {
"/usr/local/lib",
"../build/debug"
}

-- Libraries to link to ---------------------------------------------------------------------

example_getcheckins.links = {
"pthread",
"boost_system",
"boost_regex",
"boost_program_options",
"ssl",
"foursquarepp_d"

}

-- pkg-configable stuff ---------------------------------------------------------------------

if (linux) then
example_getcheckins.buildoptions = {
"-Winvalid-pch"
}

example_getcheckins.linkoptions = {
}
end

-- Files ------------------------------------------------------------------------------------

example_getcheckins.files = {
"./example_getcheckins.cpp",
}

-- Debug configuration ----------------------------------------------------------------------

--debug = example_client.config["Debug"]
--debug.defines = { "DEBUG", "_DEBUG" }
--debug.objdir = "obj/debug"
--debug.target = "./" .. example_client.name .. "_d"

--debug.buildoptions = { "-g" }

-- Release configuration --------------------------------------------------------------------

--release = example_client.config["Release"]
--release.objdir = "obj/release"
--release.target = "release/" .. example_client.name

redpajama_set_name: RedPajamaGithub


text:
package io.github.markbernard.jnotepad;

import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;

/**
 * @author Mark Bernard
 */
public class ResourceCleanup {
    /**
     * Close a reader safely.
     *
     * @param reader
     */
    public static final void close(Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                //cannot do anything
            }
        }
    }

    /**
     * Close a writer safely.
     *
     * @param writer
     */
    public static final void close(Writer writer) {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                //cannot do anything
            }
        }
    }

    /**
     * Close a outputstream safely.
     *
     * @param out
     */
    public static final void close(OutputStream out) {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                //cannot do anything
            }
        }
    }

    /**
     * Close a outputstream safely.
     *
     * @param file
     */
    public static final void close(RandomAccessFile file) {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                //cannot do anything
            }
        }
    }
}


text:
<?php

namespace Springy;

class DBWhere extends DBExpression
{
    private $where = '';
    private $values = [];

    public function __construct()
    {
        $this->where = '';
    }

    public function add(DBExpression $filtro, $conf = self::COND_AND)
    {
        $this->where .= (!empty($this->where) ? ' ' . $conf . ' ' : '') . '(' . $filtro . ')';

        $valores = $filtro->getValue(); // o método pode retornar NULL, sendo assim, po PHP o considera não setado gerando um E_NOTICE

        if (isset($valores)) {
            if (is_array($valores)) {
                foreach ($valores as $valor) {
                    $this->values[] = $valor;
                }
            } else {
                $this->values[] = $valores;
            }
        }
    }

    public function getValue()
    {
        return $this->values;
    }

    public function __toString()
    {
        return $this->where;
    }
}


text:
`juniper_iron` changelog
========================

All user visible changes to `juniper_iron` crate will be documented in this file. This project uses [Semantic Versioning 2.0.0].

## master

### BC Breaks

- Switched to 0.16 version of [`juniper` crate].

## Previous releases

See [old CHANGELOG](/../../blob/juniper_iron-v0.7.6/juniper_iron/CHANGELOG.md).

[`juniper` crate]: https://docs.rs/juniper
[Semantic Versioning 2.0.0]: https://semver.org


text:
package info.naiv.lab.java.jmt.infrastructure.annotation.test;

import info.naiv.lab.java.jmt.infrastructure.annotation.OptionalService;

/**
 *
 * @author enlo
 */
@OptionalService(dependOn = {"org.springframework.context.ApplicationContext"})
public class OptionalTestClass2 {

}


text:
      You

      {{ user.settings.email.email }}

      updated
      removed
      the {{ logItem.data.update.id | bgPolicyIdStringConversion }} policy
      on the wallet "{{ label }}"

                The new limit was {{ amountInQuestion | bgBitcoinFormat:'name':null:null:'unlimited' }}

              The address "{{ addressInQuestion }}" was {{ verb === 'Add' ? 'added' : 'removed' }}

      requested a change to the {{ logItem.data.update.id | bgPolicyIdStringConversion }} policy
      on the wallet "{{ label }}"

                The proposed limit was {{ amountInQuestion | bgBitcoinFormat:'name':null:null:'unlimited' }}

              The proposed address to {{ verb.toLowerCase() }} was "{{ addressInQuestion }}"

This policy change required approval.

Approval ID: {{ logItem.data.pendingApproval }}

IP Address: {{ logItem.ip }}

{{ logItem.prettyDate }}


text:
<?php

namespace yii\imperavi;

use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\web\AssetBundle;

/**
 * Imperavi Redactor Widget For Yii2 class file.
 *
 * @property array $plugins
 * @property \yii\web\AssetBundle $assetBundle Imperavi Redactor asset bundle
 *
 * @author Veaceslav Medvedev <slavcopost@gmail.com>
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Alexander Yaremchuk <alwex10@gmail.com>
 *
 * @version 2.0.1
 *
 * @link https://github.com/asofter/yii2-imperavi-redactor
 * @link http://imperavi.com/redactor
 * @license https://github.com/asofter/yii2-imperavi-redactor/blob/master/LICENSE.md
 */
class Widget extends \yii\base\Widget
{
    /**
     * @var array the options for the Imperavi Redactor.
     * Please refer to the corresponding [Imperavi Web page](http://imperavi.com/redactor/docs/)  for possible options.
     */
    public $options = [];

    /**
     * @var array the html options.
     */
    public $htmlOptions = [];

    /**
     * @var array plugins that you want to use
     */
    public $plugins = [];

    /*
     * @var object model for active text area
     */
    public $model = null;

    /*
     * @var string selector for init js scripts
     */
    protected $selector = null;

    /*
     * @var string name of textarea tag or name of attribute
     */
    public $attribute = null;

    /*
     * @var string value for text area (without model)
     */
    public $value = '';

    /**
     * @var \yii\web\AssetBundle|null Imperavi Redactor Asset bundle
     */
    protected $_assetBundle = null;

    /**
     * Initializes the widget.
     * If you override this method, make sure you call the parent implementation first.
     */
    public function init()
    {
        parent::init();
        if (!isset($this->htmlOptions['id'])) {
            $this->htmlOptions['id'] = $this->getId();
        }
    }

    /**
     * Renders the widget.
     */
    public function run()
    {
        $this->selector = '#' . $this->htmlOptions['id'];

        if (!is_null($this->model)) {
            echo Html::activeTextarea($this->model, $this->attribute, $this->htmlOptions);
        } else {
            echo Html::textarea($this->attribute, $this->value, $this->htmlOptions);
        }

        $this->registerRedactorAsset();
        $this->registerClientScript();
    }

    /**
     * Registers Imperavi Redactor asset bundle
     */
    protected function registerRedactorAsset()
    {
        $this->_assetBundle = ImperaviRedactorAsset::register($this->getView());
    }

    /**
     * Returns current asset bundle
     * @return \yii\web\AssetBundle current asset bundle for Redactor
     */
    protected function getAssetBundle()
    {
        if (!($this->_assetBundle instanceof AssetBundle)) {
            $this->registerRedactorAsset();
        }

        return $this->_assetBundle;
    }

    /**
     * Registers Imperavi Redactor JS
     */
    protected function registerClientScript()
    {
        $view = $this->getView();

        /*
         * Language fix
         * @author <https://github.com/sim2github>
         */
        if (!isset($this->options['lang']) || empty($this->options['lang'])) {
            $this->options['lang'] = strtolower(substr(Yii::$app->language, 0, 2));
        }

        // Kudos to yiidoc/yii2-redactor for this solution
        $this->assetBundle->js[] = 'lang/' . $this->options['lang'] . '.js';

        // Insert plugins in options
        if (!empty($this->plugins)) {
            $this->options['plugins'] = $this->plugins;

            foreach ($this->options['plugins'] as $plugin) {
                $this->registerPlugin($plugin);
            }
        }

        $options = empty($this->options) ? '' : Json::encode($this->options);
        $js = "jQuery('" . $this->selector . "').redactor($options);";
        $view->registerJs($js);
    }

    /**
     * Registers a specific Imperavi plugin and the related events
     * @param string $name the name of the Imperavi plugin
     */
    protected function registerPlugin($name)
    {
        $asset = "yii\\imperavi\\" . ucfirst($name) . "ImperaviRedactorPluginAsset";
        // check exists file before register (it may be custom plugin with not standard file placement)
        $sourcePath = Yii::$app->vendorPath . '/asofter/yii2-imperavi-redactor/' . str_replace('\\', '/', $asset) . '.php';
        if (is_file($sourcePath)) {
            $asset::register($this->getView());
        }
    }
}


text:
#include "paddle/fluid/platform/profiler/event_python.h"

#include "paddle/fluid/platform/profiler/chrometracing_logger.h"
#include "paddle/fluid/platform/profiler/dump/deserialization_reader.h"
#include "paddle/fluid/platform/profiler/dump/serialization_logger.h"
#include "paddle/fluid/platform/profiler/extra_info.h"

namespace paddle {
namespace platform {

HostPythonNode::~HostPythonNode() {
  // delete all runtime or device nodes and recursive delete children
  for (auto it = children_node_ptrs.begin(); it != children_node_ptrs.end();
       ++it) {
    delete *it;
  }
  for (auto it = runtime_node_ptrs.begin(); it != runtime_node_ptrs.end();
       ++it) {
    delete *it;
  }
  for (auto it = device_node_ptrs.begin(); it != device_node_ptrs.end(); ++it) {
    delete *it;
  }
  for (auto it = mem_node_ptrs.begin(); it != mem_node_ptrs.end(); ++it) {
    delete *it;
  }
}

HostPythonNode* ProfilerResult::CopyTree(HostTraceEventNode* root) {
  // Copy and transfer EventNode in NodeTree to PythonNode
  if (root == nullptr) {
    return nullptr;
  }
  // copy HostTraceEventNode and its children
  HostPythonNode* host_python_node = new HostPythonNode();
  host_python_node->name = root->Name();
  host_python_node->type = root->Type();
  host_python_node->start_ns = root->StartNs();
  host_python_node->end_ns = root->EndNs();
  host_python_node->process_id = root->ProcessId();
  host_python_node->thread_id = root->ThreadId();
  for (auto it = root->GetChildren().begin(); it != root->GetChildren().end();
       ++it) {
    host_python_node->children_node_ptrs.push_back(CopyTree(*it));
  }
  // copy its CudaRuntimeTraceEventNode
  for (auto runtimenode = root->GetRuntimeTraceEventNodes().begin();
       runtimenode != root->GetRuntimeTraceEventNodes().end();
       ++runtimenode) {
    HostPythonNode* runtime_python_node = new HostPythonNode();
    runtime_python_node->name = (*runtimenode)->Name();
    runtime_python_node->type = (*runtimenode)->Type();
    runtime_python_node->start_ns = (*runtimenode)->StartNs();
    runtime_python_node->end_ns = (*runtimenode)->EndNs();
    runtime_python_node->process_id = (*runtimenode)->ProcessId();
    runtime_python_node->thread_id = (*runtimenode)->ThreadId();
    runtime_python_node->correlation_id = (*runtimenode)->CorrelationId();
    host_python_node->runtime_node_ptrs.push_back(runtime_python_node);
    // copy DeviceTraceEventNode
    for (auto devicenode = (*runtimenode)->GetDeviceTraceEventNodes().begin();
         devicenode != (*runtimenode)->GetDeviceTraceEventNodes().end();
         ++devicenode) {
      DevicePythonNode* device_python_node = new DevicePythonNode();
      device_python_node->name = (*devicenode)->Name();
      device_python_node->type = (*devicenode)->Type();
      device_python_node->start_ns = (*devicenode)->StartNs();
      device_python_node->end_ns = (*devicenode)->EndNs();
      device_python_node->device_id = (*devicenode)->DeviceId();
      device_python_node->context_id = (*devicenode)->ContextId();
      device_python_node->stream_id = (*devicenode)->StreamId();
      device_python_node->correlation_id = (*devicenode)->CorrelationId();
      if (device_python_node->type == TracerEventType::Kernel) {
        KernelEventInfo kernel_info = (*devicenode)->KernelInfo();
        device_python_node->block_x = kernel_info.block_x;
        device_python_node->block_y = kernel_info.block_y;
        device_python_node->block_z = kernel_info.block_z;
        device_python_node->grid_x = kernel_info.grid_x;
        device_python_node->grid_y = kernel_info.grid_y;
        device_python_node->grid_z = kernel_info.grid_z;
        device_python_node->shared_memory = kernel_info.dynamic_shared_memory +
                                            kernel_info.static_shared_memory;
        device_python_node->registers_per_thread =
            kernel_info.registers_per_thread;
        device_python_node->blocks_per_sm = kernel_info.blocks_per_sm;
        device_python_node->warps_per_sm = kernel_info.warps_per_sm;
        device_python_node->occupancy = kernel_info.occupancy;
      } else if (device_python_node->type == TracerEventType::Memcpy) {
        MemcpyEventInfo memcpy_info = (*devicenode)->MemcpyInfo();
        device_python_node->num_bytes = memcpy_info.num_bytes;
      } else if (device_python_node->type == TracerEventType::Memset) {
        MemsetEventInfo memset_info = (*devicenode)->MemsetInfo();
        device_python_node->num_bytes = memset_info.num_bytes;
        device_python_node->value = memset_info.value;
      }
      runtime_python_node->device_node_ptrs.push_back(device_python_node);
    }
  }
  // copy MemTraceEventNode
  for (auto memnode = root->GetMemTraceEventNodes().begin();
       memnode != root->GetMemTraceEventNodes().end();
       memnode++) {
    MemPythonNode* mem_python_node = new MemPythonNode();
    mem_python_node->timestamp_ns = (*memnode)->TimeStampNs();
    mem_python_node->addr = (*memnode)->Addr();
    mem_python_node->type = (*memnode)->Type();
    mem_python_node->process_id = (*memnode)->ProcessId();
    mem_python_node->thread_id = (*memnode)->ThreadId();
    mem_python_node->increase_bytes = (*memnode)->IncreaseBytes();
    mem_python_node->place = (*memnode)->Place();
    mem_python_node->current_allocated = (*memnode)->CurrentAllocated();
    mem_python_node->current_reserved = (*memnode)->CurrentReserved();
    mem_python_node->peak_allocated = (*memnode)->PeakAllocated();
    mem_python_node->peak_reserved = (*memnode)->PeakReserved();
    host_python_node->mem_node_ptrs.push_back(mem_python_node);
  }
  // copy OperatorSupplementEventNode's information if exists
  OperatorSupplementEventNode* op_supplement_node =
      root->GetOperatorSupplementEventNode();
  if (op_supplement_node != nullptr) {
    host_python_node->input_shapes = op_supplement_node->InputShapes();
    host_python_node->dtypes = op_supplement_node->Dtypes();
    host_python_node->callstack = op_supplement_node->CallStack();
    host_python_node->attributes = op_supplement_node->Attributes();
    host_python_node->op_id = op_supplement_node->OpId();
  }
  return host_python_node;
}

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
ProfilerResult::ProfilerResult(
    std::unique_ptr<NodeTrees> tree,
    const ExtraInfo& extra_info,
    const std::map<uint32_t, gpuDeviceProp> device_property_map)
    : tree_(tree.release()),
      extra_info_(extra_info),
      device_property_map_(device_property_map) {
  if (tree_ != nullptr) {
    std::map<uint64_t, HostTraceEventNode*> nodetrees = tree_->GetNodeTrees();
    for (auto it = nodetrees.begin(); it != nodetrees.end(); ++it) {
      thread_event_trees_map_[it->first] = CopyTree(it->second);
    }
  }
}
#endif

ProfilerResult::ProfilerResult(std::unique_ptr<NodeTrees> tree,
                               const ExtraInfo& extra_info)
    : tree_(tree.release()), extra_info_(extra_info) {
  if (tree_ != nullptr) {
    std::map<uint64_t, HostTraceEventNode*> nodetrees = tree_->GetNodeTrees();
    for (auto it = nodetrees.begin(); it != nodetrees.end(); ++it) {
      thread_event_trees_map_[it->first] = CopyTree(it->second);
    }
  }
}

ProfilerResult::~ProfilerResult() {
  // delete all root nodes
  for (auto it = thread_event_trees_map_.begin();
       it != thread_event_trees_map_.end();
       ++it) {
    delete it->second;
  }
}

void ProfilerResult::Save(const std::string& file_name,
                          const std::string format) {
  if (format == std::string("json")) {
    ChromeTracingLogger logger(file_name);
    logger.LogMetaInfo(version_, span_indx_);
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    logger.LogDeviceProperty(device_property_map_);
#endif
    tree_->LogMe(&logger);
    logger.LogExtraInfo(GetExtraInfo());
  } else if (format == std::string("pb")) {
    SerializationLogger logger(file_name);
    logger.LogMetaInfo(version_, span_indx_);
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
    logger.LogDeviceProperty(device_property_map_);
#endif
    tree_->LogMe(&logger);
    logger.LogExtraInfo(GetExtraInfo());
  }
  return;
}

std::unique_ptr<ProfilerResult> LoadProfilerResult(std::string filename) {
  DeserializationReader reader(filename);
  std::unique_ptr<ProfilerResult> result = reader.Parse();
  return result;
}

}  // namespace platform
}  // namespace paddle


text:
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace AWSLambdaPGPDocker
{
    public class PgpDockerCryptoService : ICryptoService
    {
        private const string Root = "/tmp";
        private readonly string RecipientPublicKeyFile = $"{Root}/RecipientPublicKey.pgp";
        private readonly string SenderPrivateKeyFile = $"{Root}/PrivateKey.pgp";
        private readonly string OriginalFile = $"{Root}/Original.csv";
        private readonly string OutputFileName = $"{Root}/PGP.csv";
        private readonly ILogger<PgpDockerCryptoService> logger;

        public PgpSettings PgpSettings { get; }

        public PgpDockerCryptoService(
            IOptions<PgpSettings> pgpSettings,
            ILogger<PgpDockerCryptoService> logger)
        {
            PgpSettings = pgpSettings.Value;
            this.logger = logger;
        }

        public async Task<byte[]> Convert(byte[] fileContent)
        {
            await SaveCertsToDisk();
            await ImportCertificatesIntoPgp();
            return await PgpEncryptAndSign(fileContent);
        }

        private async Task<byte[]> PgpEncryptAndSign(byte[] fileContent)
        {
            logger.LogInformation("Starting PGP EncryptAndSign File Contents");
            var senderUserId = PgpSettings.SenderUserId;
            var recipientUserId = PgpSettings.RecipientUserId;
            var passphrase = PgpSettings.SenderPassphrase;

            await System.IO.File.WriteAllBytesAsync(OriginalFile, fileContent);
            await RunGpgExternalProcess(
                $"--no-tty --trust-model always --batch --passphrase {passphrase} --recipient {recipientUserId} --encrypt --sign --local-user {senderUserId} --armor -o {OutputFileName} {OriginalFile}");
            return await System.IO.File.ReadAllBytesAsync(OutputFileName);
        }

        private async Task ImportCertificatesIntoPgp()
        {
            logger.LogInformation("Importing Certificates into pgp keyring");
            string passphrase = PgpSettings.SenderPassphrase;

            await RunGpgExternalProcess( // Import Private Key into Key Ring
                $"--passphrase \"{passphrase}\" --import {SenderPrivateKeyFile}");
            await RunGpgExternalProcess( // Import Public Key into Key Ring
                $"--import {RecipientPublicKeyFile}");
            logger.LogInformation("Imported Certificates into pgp keyring");
        }

        private async Task RunGpgExternalProcess(string arguments)
        {
            using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
            {
                string result = "";
                proc.StartInfo.FileName = "gpg";
                proc.StartInfo.Arguments = $"--homedir \"{Root}/\" {arguments}";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.Start();

                result += await proc.StandardOutput.ReadToEndAsync();
                result += await proc.StandardError.ReadToEndAsync();
                proc.WaitForExit();
                logger.LogInformation($"GPG External Process - {result}");
            }
        }

        private async Task SaveCertsToDisk()
        {
            logger.LogInformation("Saving GPG Certificates Locally");
            string recipientPublicKey = PgpSettings.RecipientPublicKey.Base64Decode();
            string senderPrivateKey = PgpSettings.SenderPrivateKey.Base64Decode();
            await System.IO.File.WriteAllTextAsync(RecipientPublicKeyFile, recipientPublicKey);
            await System.IO.File.WriteAllTextAsync(SenderPrivateKeyFile, senderPrivateKey);
            logger.LogInformation("Saved GPG Certificates Locally");
        }
    }

    public class PgpSettings
    {
        public string SenderUserId { get; set; }
        public string RecipientUserId { get; set; }
        public string RecipientPublicKey { get; set; }
        public string SenderPrivateKey { get; set; }
        public string SenderPassphrase { get; set; }
    }
}


text:
#include <asm/blackfin.h>
#include <asm/cplbinit.h>

/* Invalidate the Entire Data cache by
 * clearing DMC[1:0] bits
 */
void blackfin_invalidate_entire_dcache(void)
{
	u32 dmem = bfin_read_DMEM_CONTROL();
	bfin_write_DMEM_CONTROL(dmem & ~0xc);
	SSYNC();
	bfin_write_DMEM_CONTROL(dmem);
	SSYNC();
}

/* Invalidate the Entire Instruction cache by
 * clearing IMC bit
 */
void blackfin_invalidate_entire_icache(void)
{
	u32 imem = bfin_read_IMEM_CONTROL();
	bfin_write_IMEM_CONTROL(imem & ~0x4);
	SSYNC();
	bfin_write_IMEM_CONTROL(imem);
	SSYNC();
}

#if defined(CONFIG_BFIN_ICACHE) || defined(CONFIG_BFIN_DCACHE)

static void
bfin_cache_init(struct cplb_entry *cplb_tbl, unsigned long cplb_addr,
                unsigned long cplb_data, unsigned long mem_control,
                unsigned long mem_mask)
{
	int i;
#ifdef CONFIG_L1_PARITY_CHECK
	u32 ctrl;

	if (cplb_addr == DCPLB_ADDR0) {
		ctrl = bfin_read32(mem_control) | (1 << RDCHK);
		CSYNC();
		bfin_write32(mem_control, ctrl);
		SSYNC();
	}
#endif

	for (i = 0; i < MAX_CPLBS; i++) {
		bfin_write32(cplb_addr + i * 4, cplb_tbl[i].addr);
		bfin_write32(cplb_data + i * 4, cplb_tbl[i].data);
	}

	_enable_cplb(mem_control, mem_mask);
}

#ifdef CONFIG_BFIN_ICACHE
void bfin_icache_init(struct cplb_entry *icplb_tbl)
{
	bfin_cache_init(icplb_tbl, ICPLB_ADDR0, ICPLB_DATA0, IMEM_CONTROL,
		(IMC | ENICPLB));
}
#endif

#ifdef CONFIG_BFIN_DCACHE
void bfin_dcache_init(struct cplb_entry *dcplb_tbl)
{
	/*
	 *  Anomaly notes:
	 *  05000287 - We implement workaround #2 - Change the DMEM_CONTROL
	 *  register, so that the port preferences for DAG0 and DAG1 are set
	 *  to port B
	 */
	bfin_cache_init(dcplb_tbl, DCPLB_ADDR0, DCPLB_DATA0, DMEM_CONTROL,
		(DMEM_CNTR | PORT_PREF0 | (ANOMALY_05000287 ? PORT_PREF1 : 0)));
}
#endif

#endif


text:
This is a framework for exchanging data with Crestron systems using the xsig protocol.
It is currently in an early state of development, but has working methods for changing
Crestron digital, analog, or serial signals into Python objects holding the corresponding
boolean, integer, or string object and xsig index.

The module has the start of an asynchronous server that allows TCP connections on a port
and processes signals received from a connected Crestron system.


text:
'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
	function($scope, $http, $location, Authentication) {
		$scope.authentication = Authentication;

		// If user is signed in then redirect back home
		if ($scope.authentication.user) $location.path('/');

		$scope.signup = function() {
            if($scope.credentials.password != $scope.credentials.passwordConfirm) {
                $scope.error = 'Les deux mots de passe doivent être identique';
                return;
            }
            if(true !== $scope.credentials.termsConditions) {
                $scope.error = 'L\'inscription n\'est possible que si vous acceptez les conditions d\'utilisation.';
                return;
            }
			$http.post('/auth/signup', $scope.credentials).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.authentication.user = response;

				// And redirect to the index page
				$location.path('/');
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		$scope.signin = function() {
			$http.post('/auth/signin', $scope.credentials).success(function(response) {
				// If successful we assign the response to the global user model
				$scope.authentication.user = response;

				// And redirect to the index page
				$location.path('/');
			}).error(function(response) {
				$scope.error = response.message;
			});
		};
	}
]);


text:
This README outlines the details of collaborating on this Ember addon.

## Installation

* `git clone` this repository
* `npm install`
* `bower install`

## Usage

    `import Ember from 'ember'`
    `import PublicMixin from '../mixins/public'`

    IndexController = Ember.Controller.extend PublicMixin,

      init:(etc...)->
        @_super etc
        @Signal 'public', 'Foo'
        @Signal 'private', 'Foo'
        @Signal 'foobar', 'Foo', 'Coffee'
        return

      'public':
        Foo:->
          console.log '1'
          return

      'private':
        Foo:->
          console.log '2'
          return

      'foobar':
        Foo:(name)->
          console.log '2', name
          return

    `export default IndexController`


text:
module("CSS Transformations", {
    setup : function() {
        stop();
        var that = this;
        this.cb = function(e) {
            ok(true, "Scene loaded");
            that.doc = document.getElementById("xml3dframe").contentDocument;
            start();
        };
        loadDocument("scenes/css-transforms.html"+window.location.search, this.cb);
    },
    teardown : function() {
        var v = document.getElementById("xml3dframe");
        v.removeEventListener("load", this.cb, true);
    }
});

test("Static Transforms", 3, function() {
    var xTest = this.doc.getElementById("xml3dTest"),
        glTest = getContextForXml3DElement(xTest), hTest = getHandler(xTest);
    var self = this;

    var testStep = 0;
    function onFrameDrawn(){
        if(testStep == 0){
            if( XML3DUnit.getPixelValue(glTest, 200, 100)[0] == 0) {
                ok(false, "Nothing rendered at all");
                return;
            }

            XML3DUnit.loadSceneTestImages(self.doc, "xml3dReference", "xml3dTest", function(refImage, testImage){
                QUnit.imageEqual(refImage, testImage, "CSS-Tranform Render matches");
                testStep++;

                start();
            });
        }
    }

    xTest.addEventListener("framedrawn", onFrameDrawn);

    this.doc.getElementById("rootGroup").visible = true;
    hTest.draw();

    stop();
});


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".activities.LibraryActivity"
    tools:ignore="AlwaysShowAction">
    <item
        android:id="@+id/groups_flat"
        android:title="@string/groups_flat"/>
    <item
        android:id="@+id/groups_by_artist"
        android:title="@string/groups_by_artist"/>
    <item
        android:id="@+id/groups_by_dl_date"
        android:title="@string/groups_by_dl_date"/>
    <item
        android:id="@+id/groups_custom"
        android:title="@string/groups_custom"/>
</menu>


text:
package org.sagebionetworks.evaluation.dbo;

import static org.junit.jupiter.api.Assertions.*;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Date;
import java.util.Optional;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.repo.model.AuthorizationConstants;
import org.sagebionetworks.repo.model.dbo.DBOBasicDao;
import org.sagebionetworks.repo.model.jdo.KeyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
class EvaluationRoundDBOTest {
	@Autowired
	private DBOBasicDao dboBasicDao;

	Long id;
	Long evaluationId;

	@BeforeEach
	void setUp() {
		id = 12345L;
		evaluationId = 9098770L;

		EvaluationDBO eval = new EvaluationDBO();
		eval.setId(evaluationId);
		eval.seteTag("eeeeeeeeeeeeeeeeeeeeee");
		eval.setName("ffffffffffffffffffffff");
		eval.setOwnerId(AuthorizationConstants.BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId());
		eval.setCreatedOn(System.currentTimeMillis());
		eval.setDescription("my description".getBytes());
		eval.setContentSource(KeyFactory.ROOT_ID);

		dboBasicDao.createNew(eval);
	}

	@AfterEach
	void tearDown() {
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("id", evaluationId);
		dboBasicDao.deleteObjectByPrimaryKey(EvaluationDBO.class, params);
	}

	@Test
	public void testCRUD(){
		EvaluationRoundDBO evaluationRoundDBO = new EvaluationRoundDBO();
		evaluationRoundDBO.setEtag("eeeeetag");
		evaluationRoundDBO.setId(id);
		evaluationRoundDBO.setEvaluationId(evaluationId);
		evaluationRoundDBO.setLimitsJson(null);
		Instant now = Instant.now();
		evaluationRoundDBO.setRoundStart(Timestamp.from(now));
		evaluationRoundDBO.setRoundEnd(Timestamp.from(now.plusSeconds(43 )));

		//create
		EvaluationRoundDBO created = dboBasicDao.createNew(evaluationRoundDBO);
		assertEquals(evaluationRoundDBO, created);

		//retrieve
		MapSqlParameterSource params = new MapSqlParameterSource();
		params.addValue("id", id);
		EvaluationRoundDBO retrieved = dboBasicDao.getObjectByPrimaryKey(EvaluationRoundDBO.class, params);
		assertEquals(evaluationRoundDBO, retrieved);

		//update
		evaluationRoundDBO.setLimitsJson("[{\"limitType\": \"TOTAL\", \"maximumSubmissions\": 23}]");
		boolean wasUpdated = dboBasicDao.update(evaluationRoundDBO);
		assertTrue(wasUpdated);
		EvaluationRoundDBO updated = dboBasicDao.getObjectByPrimaryKey(EvaluationRoundDBO.class, params);
		assertEquals(evaluationRoundDBO, updated);

		//delete
		boolean wasDeleted = dboBasicDao.deleteObjectByPrimaryKey(EvaluationRoundDBO.class,  params);
		assertTrue(wasDeleted);

		Optional<EvaluationRoundDBO> notExists = dboBasicDao.getObjectByPrimaryKeyIfExists(EvaluationRoundDBO.class, params);
		assertFalse(notExists.isPresent());
	}
}


text:
require 'rumale/validation'
require 'rumale/evaluation_measure/accuracy'

module Rumale
  module Base
    # Module for all classifiers in Rumale.
    module Classifier
      include Validation

      # An abstract method for fitting a model.
      def fit
        raise NotImplementedError, "#{__method__} has to be implemented in #{self.class}."
      end

      # An abstract method for predicting labels.
      def predict
        raise NotImplementedError, "#{__method__} has to be implemented in #{self.class}."
      end

      # Calculate the mean accuracy of the given testing data.
      #
      # @param x [Numo::DFloat] (shape: [n_samples, n_features]) Testing data.
      # @param y [Numo::Int32] (shape: [n_samples]) True labels for testing data.
      # @return [Float] Mean accuracy
      def score(x, y)
        x = check_convert_sample_array(x)
        y = check_convert_label_array(y)
        check_sample_label_size(x, y)
        evaluator = Rumale::EvaluationMeasure::Accuracy.new
        evaluator.score(y, predict(x))
      end
    end
  end
end


text:
<ion-view view-title="{{ 'mm.courses.mycourses' | translate }}">
    <ion-nav-buttons side="secondary">

    </ion-nav-buttons>
    <ion-content padding="true" mm-state-class>

        <ion-refresher pulling-text="{{ 'mm.core.pulltorefresh' | translate }}" ng-if="coursesLoaded" on-refresh="refreshCourses()">
        </ion-refresher>
        <mm-loading hide-until="coursesLoaded">

 5">

                    <input type="text" placeholder="{{ 'mm.courses.filtermycourses' | translate}}" ng-model="filter.filterText">

<mm-format-text watch="true">{{course.fullname}}</mm-format-text>

                            <mm-format-text class="mm-content-with-float" watch="true" shorten="40%" expand-on-click="true">{{course.summary}}</mm-format-text>

                         {{title | translate}}

                    <ion-spinner></ion-spinner>

{{ 'mm.courses.nocourses' | translate }}

{{ 'mm.courses.searchcoursesadvice' | translate }}

        </mm-loading>
    </ion-content>
</ion-view>


text:
package org.javaz.copse.model.helper;

import org.javaz.copse.model.iface.*;
import org.javaz.copse.model.beans.*;
import org.javaz.jdbc.util.StringMapPair;

import org.javaz.jdbc.base.*;
import java.util.*;
import java.sql.*;
import java.io.Serializable;

public class GroupHelper extends AbstractMapConvertibleHelper<GroupI> {

    public static final String UPDATE_SCRIPT = "update %s set code = ?"
                + " , comments = ?"
                + " , enabled = ?"
                + " , parent_group_id = ?"
                + " , title = ?"
                + "  where id = ?";

    public static final String INSERT_SCRIPT_ID = "insert into %s (code"
                    + " , comments"
                    + " , enabled"
                    + " , parent_group_id"
                    + " , title"
                    + " , id"
                    + " ) VALUES (?, ?, ?, ?, ?, ?)";

    public static final String INSERT_SCRIPT_NO_ID = "insert into %s (code"
                    + " , comments"
                    + " , enabled"
                    + " , parent_group_id"
                    + " , title"
                    + " ) VALUES (?, ?, ?, ?, ?)";

    public static final String F_ID = "id";
    public static final String F_CODE = "code";
    public static final String F_COMMENTS = "comments";
    public static final String F_ENABLED = "enabled";
    public static final String F_PARENT_GROUP_ID = "parent_group_id";
    public static final String F_TITLE = "title";

    public GroupHelper() {
        setIdName(F_ID);
        setTableName("copse_group");
    }
    public GroupI buildFromMap(Map h) {
        GroupI b = createNewInstance();
        if(h.get(F_ID) != null) { b.setId( new java.lang.Integer(((Number) h.get(F_ID)).intValue()));}
        if(h.get(F_CODE) != null) { b.setCode((java.lang.String) h.get(F_CODE)); }
        if(h.get(F_COMMENTS) != null) { b.setComments((java.lang.String) h.get(F_COMMENTS)); }
        if(h.get(F_ENABLED) != null) { b.setEnabled((java.lang.Boolean) h.get(F_ENABLED)); }
        if(h.get(F_PARENT_GROUP_ID) != null) { b.setParentGroupId( new java.lang.Integer(((Number) h.get(F_PARENT_GROUP_ID)).intValue()));}
        if(h.get(F_TITLE) != null) { b.setTitle((java.lang.String) h.get(F_TITLE)); }
        return b;
    }

    public GroupI createNewInstance() {
        return new Group();
    }

    public StringMapPair getDbUpdateQuery(String tableName, GroupI obj, boolean forceInsert) {
        HashMap<Integer, Object> map = new HashMap<Integer, Object>();
        map.put(1, obj.getCode());
        map.put(2, obj.getComments());
        map.put(3, obj.getEnabled());
        map.put(4, obj.getParentGroupId());
        map.put(5, obj.getTitle());
        if (obj.getId() != null && !forceInsert) {
            map.put(6, obj.getId());
            return new StringMapPair(String.format(UPDATE_SCRIPT, tableName), map);
        } else {
            if (forceInsert) {
                map.put(6, obj.getId());
                return new StringMapPair(String.format(INSERT_SCRIPT_ID, tableName), map);
            } else {
                return new StringMapPair(String.format(INSERT_SCRIPT_NO_ID, tableName), map);
            }
        }
    }
}


text:
SCRIPTPATH="/home/muddev/mud/mygame/server/evennia-screen.sh"
USER="muddev"

#------------------------------------------------------------
case $1 in
    start | stop | reload | restart)
        # run the start script and forward the argument to it
        su - "$USER" -c "$SCRIPTPATH $1"
    ;;
    *)
       echo "Usage: evennia {start|stop|restart|reload}"
       exit 1
    ;;
esac
exit 0


text:
project_path: /web/tools/workbox/_project.yaml
book_path: /web/tools/workbox/_book.yaml
description: Learn how to make a gulp-based app work offline by adding Workbox to it.

{# wf_updated_on: 2019-02-01 #}
{# wf_published_on: 2017-11-17 #}
{# wf_blink_components: N/A #}

# Get Started With Workbox For Gulp {: .page-title }

{% include "web/_shared/contributors/kaycebasques.html" %}

In this codelab, you use Workbox to make a simple web app work offline.

If you'd like a conceptual overview of Workbox before starting this tutorial,
see the [Overview](/web/tools/workbox/overview).

## Step 1: Set up your project {: #setup }

The project that you're going to add Workbox to is hosted on [Glitch][Glitch].
First, you need to set up Glitch so that you can edit your own copy of the
project.

[Glitch]: https://glitch.com/about/

1. Open the [demo](https://glitch.com/edit/#!/workbox-gulp).

         Figure 1. The starting point demo, hosted on Glitch

1. Click **workbox-gulp** at the top-left of the page. The **Project
   info and options** dropdown appears.
1. Click **Remix This**. Your browser redirects to an editable copy of
   the project.

<<_shared/try-initial.md>>

## Step 2: Install Workbox {: #install }

Next, you're going to add Workbox to the project to enable an offline
experience.

1. Re-focus the tab that shows you the source code of the project.
1. Click `package.json` to open that file.
1. Click **Add package**.
1. Type `workbox-build` within the **Add Package** text box, then
   click on the matching package to add it to the project.

     **Note**: This is equivalent to running `npm install
     workbox-build`. In your own projects, you'll probably want to
     save Workbox as a [development dependency][devDependencies] instead by
     running `npm install workbox-build --save-dev`, since
     `workbox-build` is a build-time tool.

         Figure 5. Adding the workbox-build package

[devDependencies]: https://docs.npmjs.com/files/package.json#devdependencies

Every time you make a change to your code, Glitch automatically
re-builds and re-deploys your app. The tab running the live app automatically
refreshes, too.

## Step 3: Add Workbox to your Gulp build process {: #gulp }

Workbox is installed, but you're not using it in your gulp build process, yet.

1. Click `gulpfile.js` to open that file.
1. Import the Workbox plugin. The bold code is the code that you need to add to your project.

const gulp = require('gulp'),
        ...
        workbox = require('workbox-build');

1. Add a task to generate your service worker using Workbox.

gulp.task('build', () => {
      ...
    });

    gulp.task('generate-service-worker', () => {
      return workbox.generateSW({
        globDirectory: dist,
        globPatterns: [
          '\*\*/\*.{html,js}'
        ],
        swDest: \`${dist}/sw.js\`,
        clientsClaim: true,
        skipWaiting: true
      }).then(({warnings}) => {
        // In case there are any warnings from workbox-build, log them.
        for (const warning of warnings) {
          console.warn(warning);
        }
        console.info('Service worker generation completed.');
      }).catch((error) => {
        console.warn('Service worker generation failed:', error);
      });
    });

    gulp.task('default', (callback) => {
      ...
    });

1. Call the Workbox task as the second-to-last task in your build process (just before the
`callback`).

gulp.task('default', (callback) => {
      runSequence('clean', 'build', 'generate-service-worker', callback);
    });

### Optional: How the config works {: #optional-config }

`gulpfile.js` determines how the app is built.

* The `clean` task deletes the output directory.
* The `build` task builds the app. In this case, it just copies the source files to the output
  directory.
* The `generate-service-worker` task creates your service worker code, using Workbox.
* The `default` task is the "master" task that ensures that all of the other tasks run in
  the proper order.

The object that you pass to `workbox.generateSW()` configures how Workbox runs.

<<_shared/config.md>>

<<_shared/register.md>>

## Step 5: Add runtime caching {: #runtime }

Runtime caching lets you store content that's not under your control
when your app requests it at runtime. For example, by runtime caching the
Hacker News content which this app relies on, you'll be able to provide
an improved offline experience for your users. When users visit the app
while offline, they'll be able to see the content from the last time
that they had an internet connection.

1. Re-focus the tab that shows you the source code of your project.
1. Open `gulpfile.js` again.
1. Add a `runtimeCaching` property to your Workbox configuration.
   `urlPattern` is a regular expression pattern telling Workbox which
   URLs to store locally. `handler` defines the caching strategy that Workbox
   uses for any matching URL. See [The Offline Cookbook][cookbook] for more
   on caching strategies.

gulp.task('generate-service-worker', () => {
      return workbox.generateSW({
        ...
        runtimeCaching: [{
          urlPattern: new RegExp('https://hacker-news.firebaseio.com'),
          handler: 'StaleWhileRevalidate'
        }]
      }).then(({warnings}) => {
        ...

[cookbook]: /web/fundamentals/instant-and-offline/offline-cookbook/

<<_shared/try-complete.md>>

<<_shared/create.md>>

1. Open `gulpfile.js`.
1. Remove the `runtimeCaching`, `clientsClaim`, and `skipWaiting` properties.
   These are now handled in your service worker code.
1. Add the `swSrc` property to instruct Workbox to inject its code into a custom service worker.

gulp.task('generate-service-worker', () => {
      return workbox.generateSW({
        globDirectory: dist,
        globPatterns: [
          '\*\*/\*.{html,js}'
        ],
        swDest: \`${dist}/sw.js\`,
        swSrc: \`${src}/sw.js\`,
      }).then(({warnings}) => {
        ...

1. Change `generateSW` to `injectManifest`.

gulp.task('generate-service-worker', () => {
      return workbox.injectManifest({
        ...

<<_shared/end.md>>


text:
package com.jme3.network.serializing.serializers;

import com.jme3.network.serializing.Serializer;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Boolean serializer.
 *
 * @author Lars Wesselius
 */
@SuppressWarnings("unchecked")
public class BooleanSerializer extends Serializer {

    public Boolean readObject(ByteBuffer data, Class c) throws IOException {
        return data.get() == 1;
    }

    public void writeObject(ByteBuffer buffer, Object object) throws IOException {
        buffer.put(((Boolean)object) ? (byte)1 : (byte)0);
    }
}


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('django_comments', '0003_add_submit_date_index'),
    ]

    operations = [
        migrations.AlterField(
            model_name='comment',
            name='is_removed',
            field=models.BooleanField(
                db_index=True, default=False,
                help_text='Check this box if the comment is inappropriate. '
                          'A "This comment has been removed" message will be displayed instead.',
                verbose_name='is removed'),
        ),
        migrations.AlterField(
            model_name='comment',
            name='object_pk',
            field=models.CharField(max_length=64, db_index=True, verbose_name='object ID'),
        ),
    ]


text:
'use strict';

const path = require('path');
const loaders = require('./webpack/loaders');
const plugins = require('./webpack/plugins');

const applicationEntries = process.env.NODE_ENV === 'development'
  ? [ ]
  : [ ];

module.exports = {
  entry: [ './editor/src/index.tsx' ].concat(applicationEntries),

  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].[hash].js',
    publicPath: '/',
    sourceMapFilename: '[name].[hash].js.map',
    chunkFilename: '[id].chunk.js',
  },

  devtool: process.env.NODE_ENV === 'production' ?
    'source-map' :
    'inline-source-map',

  resolve: {
    extensions: [
      '',
      '.webpack.js',
      '.web.js',
      '.tsx',
      '.ts',
      '.js',
      '.json',
    ],
  },

  plugins: plugins,

  devServer: {
    historyApiFallback: { index: '/' },
  },

  module: {
    preLoaders: [
      loaders.tslint,
    ],
    loaders: [
      loaders.tsx,
      loaders.html,
      loaders.css,
      loaders.scss,
      loaders.svg,
      loaders.eot,
      loaders.woff,
      loaders.ttf,
      loaders.json,
    ],
  },

  externals: {
    'react/lib/ReactContext': 'window',
    'react/lib/ExecutionEnvironment': true,
    'react/addons': true,
  },

};


text:
typedef unsigned char byte;
extern "C" void __cxa_pure_virtual() {;}

//
//
void MasterReceive();
void MasterSend();
void SendTextMessage();
void WriteText(char* message);
void WriteTextLn(char* message);

#include "C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino\arduino.h"
#include "C:\Program Files (x86)\Arduino\hardware\arduino\variants\standard\pins_arduino.h"
#include "C:\Users\Mitchell\Documents\Arduino\MRSMaster\MRSMaster.ino"
#include "C:\Users\Mitchell\Documents\Arduino\MRSMaster\MasterReceive.ino"
#include "C:\Users\Mitchell\Documents\Arduino\MRSMaster\MasterSend.ino"
#include "C:\Users\Mitchell\Documents\Arduino\MRSMaster\SendTextMessage.ino"
#include "C:\Users\Mitchell\Documents\Arduino\MRSMaster\T_REX_I2C_protocol.ino"
#endif


text:
@interface AwesomeManager : NSObject

+ (AwesomeManager*) shared;

@property (nonatomic, readonly) NSArray* data;

- (void) reload;

@end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <title>LuaMidi ♫ – The Lua library to read and write MIDI files</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

LuaMidi ♫

Index

Contents

Functions

Methods

Classes

ArbitraryEvent

Chunk

MetaEvent

NoteEvent

NoteOffEvent

NoteOnEvent

ProgramChangeEvent

Track

Writer

Modules

LuaMidi

Constants

Util

Topics

README

Limitations_of_NoteEvent

Timestamp

Class NoteEvent

Abstraction of MIDI Note On and Note Off events.

 Handles both.

See also:

         Limitations_of_NoteEvent.md

Info:

License: MIT

Author: Pedro Alves Valentim

Functions

	NoteEvent:new (fields)
	Creates a new NoteEvent.

Methods

	NoteEvent:print ()
	Prints event's data in a human-friendly style

	NoteEvent:set_pitch (pitch)
	Sets NoteEvent's pitch

	NoteEvent:set_duration (duration)
	Sets NoteEvent's duration

	NoteEvent:set_rest (rest)
	Sets NoteEvent's rest

	NoteEvent:set_velocity (velocity)
	Sets NoteEvent's velocity

	NoteEvent:set_sequential (sequential)
	Sets NoteEvent's sequential property

	NoteEvent:set_repetition (repetition)
	Sets NoteEvent's repetition

	NoteEvent:set_channel (channel)
	Sets NoteEvent's channel

	NoteEvent:get_pitch ()
	Gets pitch(es) of NoteEvent

	NoteEvent:get_duration ()
	Gets duration of NoteEvent

	NoteEvent:get_rest ()
	Gets rest duration of NoteEvent

	NoteEvent:get_velocity ()
	Gets velocity of NoteEvent

	NoteEvent:get_sequential ()
	Gets sequentiallity of NoteEvent

	NoteEvent:get_repetition ()
	Gets repetition value of NoteEvent

	NoteEvent:get_channel ()
	Gets channel # of NoteEvent

Functions

    NoteEvent:new (fields)

    Creates a new NoteEvent.  Receives a fields table as
 parameter. This table is expected to have some (or
 all) of these fields:

            Name
            Type
            Description

            pitch
            string, number or array
            Note (or array of notes) to be triggered. Can be a string or valid MIDI note code.  Format for string is C#4.

            duration
            string or array

                How long the note should sound.

1  : whole

2  : half

d2 : dotted half

4  : quarter

d4 : dotted quarter

8  : eighth

8t : eighth triplet

d8 : dotted eighth

16 : sixteenth

Tn : where n is an explicit number of ticks

                If an array of durations is passed then the sum of the durations will be used.
          Default: 4

            rest
            string
            Rest before sounding note.  Takes same values as duration. Default: 0

          velocity
            number
            How loud the note should sound, values 1-100.  Default: 50

            sequential
            boolean
            If true then array of pitches will be played sequentially as opposed to simulatanously.  Default: false

            repetition
            number
            How many times this event should be repeated. Default: 1

            channel
            number
            MIDI channel to use. Default: 1

 Note: pitch is the only required field

Parameters:

fields
         a table containing NoteEvent's proprieties

Returns:

        new NoteEvent object

Methods

    NoteEvent:print ()

    Prints event's data in a human-friendly style

    NoteEvent:set_pitch (pitch)

    Sets NoteEvent's pitch

Parameters:

pitch
         takes the same values as the pitch
 field passed to the constructor.

Returns:

        NoteEvent with new pitch

    NoteEvent:set_duration (duration)

    Sets NoteEvent's duration

Parameters:

duration
         takes the same values as the
 duration field passed to the constructor.

Returns:

        NoteEvent with new duration

    NoteEvent:set_rest (rest)

    Sets NoteEvent's rest

Parameters:

rest
         takes the same values as the
 rest field passed to the constructor.

Returns:

        NoteEvent with new rest

    NoteEvent:set_velocity (velocity)

    Sets NoteEvent's velocity

Parameters:

velocity
            number
         loudness of the note sound.
 Values from 1-100.

Returns:

        NoteEvent with new velocity

    NoteEvent:set_sequential (sequential)

    Sets NoteEvent's sequential property

Parameters:

sequential
            bool
         true to play the pitches
 (if pitch is an array) sequentially.

Returns:

        NoteEvent with new sequential property

    NoteEvent:set_repetition (repetition)

    Sets NoteEvent's repetition

Parameters:

repetition
            number
         number of times this NoteEvent
 will be repeated.

Returns:

        NoteEvent with new repetition

    NoteEvent:set_channel (channel)

    Sets NoteEvent's channel

Parameters:

channel
            number
         MIDI channel # (1-16).

Returns:

        NoteEvent with new channel

    NoteEvent:get_pitch ()

    Gets pitch(es) of NoteEvent

Returns:

        NoteEvent's pitch value

    NoteEvent:get_duration ()

    Gets duration of NoteEvent

Returns:

        NoteEvent's duration value

    NoteEvent:get_rest ()

    Gets rest duration of NoteEvent

Returns:

        NoteEvent's rest value

    NoteEvent:get_velocity ()

    Gets velocity of NoteEvent

Returns:

        NoteEvent's velocity value

    NoteEvent:get_sequential ()

    Gets sequentiallity of NoteEvent

Returns:

        NoteEvent's sequential value

    NoteEvent:get_repetition ()

    Gets repetition value of NoteEvent

Returns:

        NoteEvent's repetition value

    NoteEvent:get_channel ()

    Gets channel # of NoteEvent

Returns:

        NoteEvent's channel value

generated by LDoc 1.4.6
Last updated 2020-02-28 01:36:33


text:
package org.apache.flink.runtime.metrics;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.metrics.Metric;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.metrics.View;
import org.apache.flink.metrics.reporter.MetricReporter;
import org.apache.flink.metrics.reporter.Scheduled;
import org.apache.flink.runtime.akka.ActorUtils;
import org.apache.flink.runtime.akka.AkkaUtils;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.concurrent.FutureUtils;
import org.apache.flink.runtime.metrics.dump.MetricQueryService;
import org.apache.flink.runtime.metrics.groups.AbstractMetricGroup;
import org.apache.flink.runtime.metrics.groups.FrontMetricGroup;
import org.apache.flink.runtime.metrics.scope.ScopeFormats;
import org.apache.flink.runtime.util.ExecutorThreadFactory;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.ExecutorUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.Preconditions;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * A MetricRegistry keeps track of all registered {@link Metric Metrics}. It serves as the
 * connection between {@link MetricGroup MetricGroups} and {@link MetricReporter MetricReporters}.
 */
public class MetricRegistryImpl implements MetricRegistry {
	static final Logger LOG = LoggerFactory.getLogger(MetricRegistryImpl.class);

	private final Object lock = new Object();

	private final List<MetricReporter> reporters;
	private final ScheduledExecutorService executor;

	private final ScopeFormats scopeFormats;
	private final char globalDelimiter;
	private final List<Character> delimiters;

	private final CompletableFuture<Void> terminationFuture;

	private final long maximumFramesize;

	@Nullable
	private ActorRef queryService;

	@Nullable
	private String metricQueryServicePath;

	private ViewUpdater viewUpdater;

	private boolean isShutdown;

	/**
	 * Creates a new MetricRegistry and starts the configured reporter.
	 */
	public MetricRegistryImpl(MetricRegistryConfiguration config) {
		this.maximumFramesize = config.getQueryServiceMessageSizeLimit();
		this.scopeFormats = config.getScopeFormats();
		this.globalDelimiter = config.getDelimiter();
		this.delimiters = new ArrayList<>(10);
		this.terminationFuture = new CompletableFuture<>();
		this.isShutdown = false;

		// second, instantiate any custom configured reporters
		this.reporters = new ArrayList<>(4);

		List<Tuple2<String, Configuration>> reporterConfigurations = config.getReporterConfigurations();

		this.executor = Executors.newSingleThreadScheduledExecutor(new ExecutorThreadFactory("Flink-MetricRegistry"));

		this.queryService = null;
		this.metricQueryServicePath = null;

		if (reporterConfigurations.isEmpty()) {
			// no reporters defined
			// by default, don't report anything
			LOG.info("No metrics reporter configured, no metrics will be exposed/reported.");
		} else {
			// we have some reporters so
			for (Tuple2<String, Configuration> reporterConfiguration: reporterConfigurations) {
				String namedReporter = reporterConfiguration.f0;
				Configuration reporterConfig = reporterConfiguration.f1;

				final String className = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_CLASS_SUFFIX, null);
				if (className == null) {
					LOG.error("No reporter class set for reporter " + namedReporter + ". Metrics might not be exposed/reported.");
					continue;
				}

				try {
					String configuredPeriod = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_INTERVAL_SUFFIX, null);
					TimeUnit timeunit = TimeUnit.SECONDS;
					long period = 10;

					if (configuredPeriod != null) {
						try {
							String[] interval = configuredPeriod.split(" ");
							period = Long.parseLong(interval[0]);
							timeunit = TimeUnit.valueOf(interval[1]);
						}
						catch (Exception e) {
							LOG.error("Cannot parse report interval from config: " + configuredPeriod +
									" - please use values like '10 SECONDS' or '500 MILLISECONDS'. " +
									"Using default reporting interval.");
						}
					}

					Class<?> reporterClass = Class.forName(className);
					MetricReporter reporterInstance = (MetricReporter) reporterClass.newInstance();

					MetricConfig metricConfig = new MetricConfig();
					reporterConfig.addAllToProperties(metricConfig);
					LOG.info("Configuring {} with {}.", namedReporter, metricConfig);
					reporterInstance.open(metricConfig);

					if (reporterInstance instanceof Scheduled) {
						LOG.info("Periodically reporting metrics in intervals of {} {} for reporter {} of type {}.", period, timeunit.name(), namedReporter, className);

						executor.scheduleWithFixedDelay(
								new MetricRegistryImpl.ReporterTask((Scheduled) reporterInstance), period, period, timeunit);
					} else {
						LOG.info("Reporting metrics for reporter {} of type {}.", namedReporter, className);
					}
					reporters.add(reporterInstance);

					String delimiterForReporter = reporterConfig.getString(ConfigConstants.METRICS_REPORTER_SCOPE_DELIMITER, String.valueOf(globalDelimiter));
					if (delimiterForReporter.length() != 1) {
						LOG.warn("Failed to parse delimiter '{}' for reporter '{}', using global delimiter '{}'.", delimiterForReporter, namedReporter, globalDelimiter);
						delimiterForReporter = String.valueOf(globalDelimiter);
					}
					this.delimiters.add(delimiterForReporter.charAt(0));
				}
				catch (Throwable t) {
					LOG.error("Could not instantiate metrics reporter {}. Metrics might not be exposed/reported.", namedReporter, t);
				}
			}
		}
	}

	/**
	 * Initializes the MetricQueryService.
	 *
	 * @param actorSystem ActorSystem to create the MetricQueryService on
	 * @param resourceID resource ID used to disambiguate the actor name
     */
	public void startQueryService(ActorSystem actorSystem, ResourceID resourceID) {
		synchronized (lock) {
			Preconditions.checkState(!isShutdown(), "The metric registry has already been shut down.");

			try {
				queryService = MetricQueryService.startMetricQueryService(actorSystem, resourceID, maximumFramesize);
				metricQueryServicePath = AkkaUtils.getAkkaURL(actorSystem, queryService);
			} catch (Exception e) {
				LOG.warn("Could not start MetricDumpActor. No metrics will be submitted to the WebInterface.", e);
			}
		}
	}

	/**
	 * Returns the address under which the {@link MetricQueryService} is reachable.
	 *
	 * @return address of the metric query service
	 */
	@Override
	@Nullable
	public String getMetricQueryServicePath() {
		return metricQueryServicePath;
	}

	@Override
	public char getDelimiter() {
		return this.globalDelimiter;
	}

	@Override
	public char getDelimiter(int reporterIndex) {
		try {
			return delimiters.get(reporterIndex);
		} catch (IndexOutOfBoundsException e) {
			LOG.warn("Delimiter for reporter index {} not found, returning global delimiter.", reporterIndex);
			return this.globalDelimiter;
		}
	}

	@Override
	public int getNumberReporters() {
		return reporters.size();
	}

	@VisibleForTesting
	public List<MetricReporter> getReporters() {
		return reporters;
	}

	/**
	 * Returns whether this registry has been shutdown.
	 *
	 * @return true, if this registry was shutdown, otherwise false
	 */
	public boolean isShutdown() {
		synchronized (lock) {
			return isShutdown;
		}
	}

	/**
	 * Shuts down this registry and the associated {@link MetricReporter}.
	 *
	 *
NOTE: This operation is asynchronous and returns a future which is completed
	 * once the shutdown operation has been completed.
	 *
	 * @return Future which is completed once the {@link MetricRegistryImpl}
	 * is shut down.
	 */
	public CompletableFuture<Void> shutdown() {
		synchronized (lock) {
			if (isShutdown) {
				return terminationFuture;
			} else {
				isShutdown = true;
				final Collection<CompletableFuture<Void>> terminationFutures = new ArrayList<>(3);
				final Time gracePeriod = Time.seconds(1L);

				if (queryService != null) {
					final CompletableFuture<Void> queryServiceTerminationFuture = ActorUtils.nonBlockingShutDown(
						gracePeriod.toMilliseconds(),
						TimeUnit.MILLISECONDS,
						queryService);

					terminationFutures.add(queryServiceTerminationFuture);
				}

				Throwable throwable = null;
				for (MetricReporter reporter : reporters) {
					try {
						reporter.close();
					} catch (Throwable t) {
						throwable = ExceptionUtils.firstOrSuppressed(t, throwable);
					}
				}
				reporters.clear();

				if (throwable != null) {
					terminationFutures.add(
						FutureUtils.completedExceptionally(
							new FlinkException("Could not shut down the metric reporters properly.", throwable)));
				}

				final CompletableFuture<Void> executorShutdownFuture = ExecutorUtils.nonBlockingShutdown(
					gracePeriod.toMilliseconds(),
					TimeUnit.MILLISECONDS,
					executor);

				terminationFutures.add(executorShutdownFuture);

				FutureUtils
					.completeAll(terminationFutures)
					.whenComplete(
						(Void ignored, Throwable error) -> {
							if (error != null) {
								terminationFuture.completeExceptionally(error);
							} else {
								terminationFuture.complete(null);
							}
						});

				return terminationFuture;
			}
		}
	}

	@Override
	public ScopeFormats getScopeFormats() {
		return scopeFormats;
	}

	// ------------------------------------------------------------------------
	//  Metrics (de)registration
	// ------------------------------------------------------------------------

	@Override
	public void register(Metric metric, String metricName, AbstractMetricGroup group) {
		synchronized (lock) {
			if (isShutdown()) {
				LOG.warn("Cannot register metric, because the MetricRegistry has already been shut down.");
			} else {
				if (reporters != null) {
					for (int i = 0; i < reporters.size(); i++) {
						MetricReporter reporter = reporters.get(i);
						try {
							if (reporter != null) {
								FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
								reporter.notifyOfAddedMetric(metric, metricName, front);
							}
						} catch (Exception e) {
							LOG.warn("Error while registering metric.", e);
						}
					}
				}
				try {
					if (queryService != null) {
						MetricQueryService.notifyOfAddedMetric(queryService, metric, metricName, group);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
				try {
					if (metric instanceof View) {
						if (viewUpdater == null) {
							viewUpdater = new ViewUpdater(executor);
						}
						viewUpdater.notifyOfAddedView((View) metric);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
			}
		}
	}

	@Override
	public void unregister(Metric metric, String metricName, AbstractMetricGroup group) {
		synchronized (lock) {
			if (isShutdown()) {
				LOG.warn("Cannot unregister metric, because the MetricRegistry has already been shut down.");
			} else {
				if (reporters != null) {
					for (int i = 0; i < reporters.size(); i++) {
						try {
						MetricReporter reporter = reporters.get(i);
							if (reporter != null) {
								FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
								reporter.notifyOfRemovedMetric(metric, metricName, front);
							}
						} catch (Exception e) {
							LOG.warn("Error while registering metric.", e);
						}
					}
				}
				try {
					if (queryService != null) {
						MetricQueryService.notifyOfRemovedMetric(queryService, metric);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
				try {
					if (metric instanceof View) {
						if (viewUpdater != null) {
							viewUpdater.notifyOfRemovedView((View) metric);
						}
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
			}
		}
	}

	// ------------------------------------------------------------------------

	@VisibleForTesting
	@Nullable
	public ActorRef getQueryService() {
		return queryService;
	}

	// ------------------------------------------------------------------------

	/**
	 * This task is explicitly a static class, so that it does not hold any references to the enclosing
	 * MetricsRegistry instance.
	 *
	 *
This is a subtle difference, but very important: With this static class, the enclosing class instance
	 * may become garbage-collectible, whereas with an anonymous inner class, the timer thread
	 * (which is a GC root) will hold a reference via the timer task and its enclosing instance pointer.
	 * Making the MetricsRegistry garbage collectible makes the java.util.Timer garbage collectible,
	 * which acts as a fail-safe to stop the timer thread and prevents resource leaks.
	 */
	private static final class ReporterTask extends TimerTask {

		private final Scheduled reporter;

		private ReporterTask(Scheduled reporter) {
			this.reporter = reporter;
		}

		@Override
		public void run() {
			try {
				reporter.report();
			} catch (Throwable t) {
				LOG.warn("Error while reporting metrics", t);
			}
		}
	}
}


text:
package objc

// #include <stdlib.h>
// #include <objc/runtime.h>
import "C"
import "unsafe"

type Sel C.SEL

func Sel_getName(aSelector Sel) string {
	return C.GoString(C.sel_getName(aSelector))
}

func Sel_registerName(str string) Sel {
	cstr := C.CString(str)
	defer free(unsafe.Pointer(cstr))

	return Sel(C.sel_registerName(cstr))
}

func Sel_getUid(str string) Sel {
	cstr := C.CString(str)
	defer free(unsafe.Pointer(cstr))

	return Sel(C.sel_getUid(cstr))
}

func Sel_isEqual(lhs Sel, rhs Sel) bool {
	return C.sel_isEqual(lhs, rhs) != 0
}


text:
<?php
/**
 *
 * This file is part of Aura for PHP.
 *
 * @package Aura.SqlMapper_Bundle
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\SqlMapper_Bundle;

use Aura\Sql\ConnectionLocator;
use Aura\SqlMapper_Bundle\Query\ConnectedQueryFactory;
use Aura\SqlMapper_Bundle\Query\Select;
use Aura\SqlMapper_Bundle\Query\Insert;
use Aura\SqlMapper_Bundle\Query\Update;
use Aura\SqlMapper_Bundle\Query\Delete;

/**
 *
 * A RowDataGateway to a table.
 *
 * @package Aura.SqlMapper_Bundle
 *
 */
interface GatewayInterface
{
    /**
     *
     * Returns the gateway SQL table name.
     *
     * @return string The gateway SQL table name.
     *
     */
    public function getTable();

    /**
     *
     * Returns the primary column name on the table.
     *
     * @return string The primary column name.
     *
     */
    public function getPrimaryCol();

    /**
     *
     * Is the primary key automatically set by the database at insert time,
     * (e.g., by autoincrement)?
     *
     * @return bool
     *
     */
    public function isAutoPrimary();

    /**
     *
     * Returns the database read connection.
     *
     * @return ExtendedPdoInterface
     *
     */
    public function getReadConnection();

    /**
     *
     * Returns the database write connection.
     *
     * @return ExtendedPdoInterface
     *
     */
    public function getWriteConnection();

    /**
     *
     * Creates a Select query to match against a given column and value(s).
     *
     * @param string $col The column to use for matching.
     *
     * @param mixed $val The value(s) to match against; this can be an array
     * of values.
     *
     * @return Select
     *
     */
    public function selectBy($col, $val, array $cols = []);

    /**
     *
     * Returns a new Select query for the gateway table using a read
     * connection.
     *
     * @param array $cols Select these columns from the table; when empty,
     * selects all gateway columns.
     *
     * @return Select
     *
     */
    public function select(array $cols = []);

    /**
     *
     * Inserts a row array into the gateway table using a write connection.
     *
     * @param array $row The row array to insert.
     *
     * @return mixed
     *
     */
    public function insert(array $row);

    /**
     *
     * Updates a row in the table using a write connection.
     *
     * @param array $row The row array to update.
     *
     * @return bool True if the update succeeded, false if not.  (This is
     * determined by checking the number of rows affected by the query.)
     *
     */
    public function update(array $row);

    /**
     *
     * Deletes a row array from the gateway table using a write connection.
     *
     * @param array $row The row array to delete.
     *
     * @return bool True if the delete succeeded, false if not.  (This is
     * determined by checking the number of rows affected by the query.)
     *
     */
    public function delete(array $row);
}


text:
package gov.nih.nci.ncicb.cadsr.common.dto.bc4j;
import gov.nih.nci.ncicb.cadsr.common.resource.ReferenceBlob;
import oracle.jbo.domain.BlobDomain;
import gov.nih.nci.ncicb.cadsr.common.persistence.bc4j.ReferenceBlobsViewRowImpl;

public class BC4JReferenceBlobTransferObject implements ReferenceBlob {
	String mimeType = "";
	String docName = "";
	BlobDomain blobContent = null;
	int docSize;

	public BC4JReferenceBlobTransferObject() {

	}

	public BC4JReferenceBlobTransferObject(ReferenceBlobsViewRowImpl rbViewRowImpl) {
		mimeType = rbViewRowImpl.getMimeType();
		docName = rbViewRowImpl.getName();
		blobContent = rbViewRowImpl.getBlobContent();
		docSize = rbViewRowImpl.getDocSize().intValue();
	}

	public String getMimeType() {
		return mimeType;
	}
	public void setMimeType(String mimetype) {
		this.mimeType = mimetype;
	}

	public BlobDomain getBlobContent() {
		return blobContent;
	}
	public void setBlobContent(BlobDomain theBlob) {
		blobContent = theBlob;
	}

	public String getName() {
		return docName;
	}
	public void setName(String docName) {
		this.docName = docName;
	}

	public int getDocSize() {
		return docSize;
	}
}


text:
"use strict";

// module Alert

exports.alert = function(msg) {
    return function() {
        window.alert(msg);
        return {};
    };
};


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ListLandsComponent } from './list-lands.component';

describe('ListLandsComponent', () => {
  let component: ListLandsComponent;
  let fixture: ComponentFixture<ListLandsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ListLandsComponent],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ListLandsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});


text:
'Purpose:       The purpose of the Physics Acceleration and Displacement Calculator
'               is to calculate acceleration, Displacement and time from user input values.
'Developer:     Anders Blair
'Date:          7/1/2015

Option Strict On
Public Class frmPhysicsCalculator
    'Declare Class variables
    Dim dblAcceleration As Double
    Dim dblTime As Double
    Dim dblDisplacement As Double

    Private Sub frmPhysicsCalculator_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'clears dummy values
        lblResult.Text = ""
        lblResult2.Text = ""
        txtAcceleration.Focus()
        MsgBox("Note: This program assumes there is no initial velocity.")
    End Sub

    Private Sub radAcceleration_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radAcceleration.CheckedChanged
        'Clears textboxes and labels. Disables the acceleration textbox.
        'Sets focus on txtDisplacement.
        txtAcceleration.Enabled = False
        txtDisplacement.Enabled = True
        txtTime.Enabled = True
        txtDisplacement.Clear()
        txtAcceleration.Clear()
        txtTime.Clear()
        lblResult.Text = ""
        lblResult2.Text = ""
        txtDisplacement.Focus()
    End Sub

    Private Sub radDisplacement_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radDisplacement.CheckedChanged
        'clears textboxes and labels. Disables displacement textbox.
        'Sets focus to acceleration textbox.
        txtAcceleration.Enabled = True
        txtDisplacement.Enabled = False
        txtTime.Enabled = True
        txtDisplacement.Clear()
        txtDisplacement.Clear()
        txtAcceleration.Clear()
        txtTime.Clear()
        lblResult.Text = ""
        lblResult2.Text = ""
        txtAcceleration.Focus()
    End Sub

    Private Sub radTime_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles radTime.CheckedChanged
        'clears textboxes and labels.
        'Sets focus to displacement textbox.
        txtAcceleration.Enabled = True
        txtDisplacement.Enabled = True
        txtTime.Enabled = False
        txtDisplacement.Clear()
        txtAcceleration.Clear()
        txtTime.Clear()
        lblResult.Text = ""
        lblResult2.Text = ""
        txtDisplacement.Focus()
    End Sub
    Private Function CheckIfDisplacementValid() As Boolean
        'Check if the data that the user entered for the displacement can be saved as double and is over 0.
        Dim blnIsValid As Boolean = False
        'See if data entered is valid using try-catch statements.
        Try
            dblDisplacement = Convert.ToDouble(txtDisplacement.Text)
            If dblDisplacement > 0 Then
                blnIsValid = True
            Else
                MsgBox("Please enter a number greater than 0 for the displacement.")
            End If
        Catch exception As FormatException
            txtDisplacement.Text = ""
            txtDisplacement.Focus()
            MsgBox("Please enter a number.")
        Catch exception As OverflowException
            txtDisplacement.Text = ""
            txtDisplacement.Focus()
            MsgBox("Displacement entered is too high.")
        Catch exception As SystemException
            txtDisplacement.Text = ""
            txtDisplacement.Focus()
            MsgBox("Unexpected error occured converting the displacement. Please try again.")
        End Try

        Return blnIsValid

    End Function
    Private Function CheckIfAccelerationValid() As Boolean
        'Check if the data that the user entered for the acceleration can be saved as double and is over 0.
        Dim blnIsValid As Boolean = False
        'See if data entered is valid using try-catch statements.
        Try
            dblAcceleration = Convert.ToDouble(txtAcceleration.Text)
            If dblAcceleration > 0 Then
                blnIsValid = True
            Else
                MsgBox("Please enter a number greater than 0 for the acceleration.")
            End If
        Catch exception As FormatException
            txtAcceleration.Text = ""
            txtAcceleration.Focus()
            MsgBox("Please enter a number for the acceleration.")
        Catch exception As OverflowException
            txtAcceleration.Text = ""
            txtAcceleration.Focus()
            MsgBox("Accerleration entered is too high.")
        Catch exception As SystemException
            txtAcceleration.Text = ""
            txtAcceleration.Focus()
            MsgBox("Unexpected error occured converting the acceleration. Please try again.")
        End Try

        Return blnIsValid

    End Function
    Private Function CheckIfTimeValid() As Boolean
        'Check if the data that the user entered for the time can be saved as double and is over 0.
        Dim blnIsValid As Boolean = False
        'See if data entered is valid using try-catch statements.
        Try
            dblTime = Convert.ToDouble(txtTime.Text)
            If dblTime > 0 Then
                blnIsValid = True
            Else
                MsgBox("Please enter a number greater than 0 for the time.")
            End If
        Catch exception As FormatException
            txtTime.Text = ""
            txtTime.Focus()
            MsgBox("Please enter a number for the time.")
        Catch exception As OverflowException
            txtTime.Text = ""
            txtTime.Focus()
            MsgBox("Time entered is too high.")
        Catch exception As SystemException
            txtTime.Text = ""
            txtTime.Focus()
            MsgBox("Unexpected error occured converting the time. Please try again.")
        End Try

        Return blnIsValid

    End Function

    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

        'Declare variable containing result of calculation.
        Dim dblResult As Double

        If radDisplacement.Checked Then
            If CheckIfAccelerationValid() AndAlso CheckIfTimeValid() Then
                'Calculates Displacement using the formula d = 0.5*acceleration*time^2
                txtDisplacement.Enabled = False
                'Save user input:
                dblAcceleration = Convert.ToDouble(txtAcceleration.Text)
                dblTime = Convert.ToDouble(txtTime.Text)
                'Processing:
                dblResult = 0.5 * dblAcceleration * dblTime ^ 2

                'Result output:
                lblResult.Text = "The displacement is:"
                lblResult2.Text = dblResult.ToString("N5") & " m"
                lblResult.Visible = True
                lblResult2.Visible = True
            End If

        ElseIf radAcceleration.Checked Then
            If CheckIfDisplacementValid() AndAlso CheckIfTimeValid() Then
                'Calculates acceleration using the formula a = (2*Displacement/Time^2)
                txtAcceleration.Enabled = False
                'Save user input:
                dblDisplacement = Convert.ToDouble(txtDisplacement.Text)
                dblTime = Convert.ToDouble(txtTime.Text)
                'processing:
                dblResult = (2 * dblDisplacement / (dblTime ^ 2))

                'Results:
                lblResult.Text = "The acceleration is:"
                lblResult2.Text = dblResult.ToString("N5") & " m/s"
                lblResult.Visible = True
                lblResult2.Visible = True

            End If
        ElseIf radTime.Checked Then
            If CheckIfDisplacementValid() AndAlso CheckIfAccelerationValid() Then
                'Calculates time using the formula Square root of (Displacement/0.5*Acceleration)
                txtTime.Enabled = False
                'Save user input
                dblDisplacement = Convert.ToDouble(txtDisplacement.Text)
                dblAcceleration = Convert.ToDouble(txtAcceleration.Text)
                'Processing
                Dim dblQuotient As Double
                dblQuotient = (dblDisplacement / (0.5 * dblAcceleration))
                dblResult = dblQuotient ^ (1 / 2)
                'results
                lblResult.Text = "The time is:"
                lblResult2.Text = dblResult.ToString("N5") & " s"
                lblResult.Visible = True
                lblResult2.Visible = True
            End If

        End If

    End Sub
    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
        'Clears the program of values. Sets rbtnAcceleration as focus.

        txtAcceleration.Text = ""
        txtDisplacement.Text = ""
        txtTime.Text = ""
        lblResult.Text = ""
        lblResult2.Text = ""
        lblResult.Visible = False
        lblResult2.Visible = False
        radDisplacement.Focus()
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        'Closes the program.
        Close()
    End Sub

End Class


text:
"use strict";
import Store from "../../framework/Store";
export default class ReduceStore extends Store {
    constructor() {
        super();
        this.state = {};
    }

    updateState(payload) {
        const nextState = this.reduce(this.state, payload);
        this.setState(nextState);
    }

    setState(state) {
        if (this.state === state) {
            return;
        }
        this.state = Object.assign({}, this.state, state);
        this.emitChange();
    }

    getState() {
        return this.state;
    }
}