text:
********
Tutorial
********

NDlib is built upon networkx and is designed to configure, simulate and visualize diffusion experiments.

Here you can find a few examples to get started with ``ndlib``: for a more comprehensive tutorial check the official `Jupyter Notebook`_.

------------
Installation
------------

In order to install the latest version of the library (with visualization facilities) use

.. code:: bash

    pip install ndlib

-----------------------
Chose a Diffusion model
-----------------------

Let's start importing the required libraries

.. code:: python

    import networkx as nx
    import ndlib.models.epidemics as ep

Once imported the epidemic model module and the networkx library we can initialize the simulation:

.. code:: python

    # Network Definition
    g = nx.erdos_renyi_graph(1000, 0.1)

    # Model Selection
    model = ep.SIRModel(g)

------------------------
Configure the simulation
------------------------

Each model has its own parameters: in order to completely instantiate the simulation we need to specify them using a ``Configuration`` object:

.. code:: python

    import ndlib.models.ModelConfig as mc

    # Model Configuration
    config = mc.Configuration()
    config.add_model_parameter('beta', 0.001)
    config.add_model_parameter('gamma', 0.01)
    config.add_model_parameter("fraction_infected", 0.05)
    model.set_initial_status(config)

The model configuration allows to specify model parameters (as in this scenario) as well as nodes' and edges' ones (e.g.  individual thresholds).

Moreover it allows to specify the initial fraction of infected nodes using the
``fraction_infected`` model parameter.

It is also possible to explicitly specify an initial set of infected nodes: see :ref:`model_conf` for the complete set of use cases.

----------------------
Execute the simulation
----------------------

In order to execute the simulation one, or more, iterations must be required using the ``model.iteration()`` and/or ``model.iteration_bunch(n_iterations)`` methods.

.. code:: python

	# Simulation
	iterations = model.iteration_bunch(200)
	trends = model.build_trends(iterations)

---------------------
Visualize the results
---------------------

At the end of the simulation the diffusion trend can be visualized as follows (for ``matplotlib`` change ``ndlib.viz.bokeh`` in ``ndlib.viz.mpl``)

.. code:: python

	from bokeh.io import output_notebook, show
	from ndlib.viz.bokeh.DiffusionTrend import DiffusionTrend

	viz = DiffusionTrend(model, trends)
	p = viz.plot(width=400, height=400)
	show(p)

Furthermore, a prevalence plot is also made available.

The prevalence plot captures the variation (delta) of nodes for each status in consecutive iterations.

.. code:: python

	from ndlib.viz.bokeh.DiffusionPrevalence import DiffusionPrevalence

	viz2 = DiffusionPrevalence(model, trends)
	p2 = viz2.plot(width=400, height=400)
	show(p2)

Multiple plots can be combined in a multiplot to provide a complete description of the diffusive process

.. code:: python

	from ndlib.viz.bokeh.MultiPlot import MultiPlot
	vm = MultiPlot()
	vm.add_plot(p)
	vm.add_plot(p2)
	m = vm.plot()
	show(m)

Multiplots - implemented only for the ``bokeh`` provider - are also useful to compare different diffusion models applied to the same graph (as well as a same model instantiated with different parameters)

.. code:: python

	import ndlib.models.epidemics as ep

	vm = MultiPlot()
	vm.add_plot(p)

	# SIS
	sis_model = ep.SISModel(g)
	config = mc.Configuration()
	config.add_model_parameter('beta', 0.001)
	config.add_model_parameter('lambda', 0.01)
	config.add_model_parameter("fraction_infected", 0.05)
	sis_model.set_initial_status(config)
	iterations = sis_model.iteration_bunch(200)
	trends = sis_model.build_trends(iterations)

	viz = DiffusionTrend(sis_model, trends)
	p3 = viz.plot(width=400, height=400)
	vm.add_plot(p3)

	# SI
	si_model = ep.SIModel(g)
	config = mc.Configuration()
	config.add_model_parameter('beta', 0.001)
	config.add_model_parameter("fraction_infected", 0.05)
	si_model.set_initial_status(config)
	iterations = si_model.iteration_bunch(200)
	trends = si_model.build_trends(iterations)

	viz = DiffusionTrend(si_model, trends)
	p4 = viz.plot(width=400, height=400)
	vm.add_plot(p4)

	# Threshold
	th_model = ep.ThresholdModel(g)
	config = mc.Configuration()

	# Set individual node threshold
	threshold = 0.40
	for n in g.nodes():
		config.add_node_configuration("threshold", n, threshold)

	config.add_model_parameter("fraction_infected", 0.30)
	th_model.set_initial_status(config)
	iterations = th_model.iteration_bunch(60)
	trends = th_model.build_trends(iterations)

	viz = DiffusionTrend(th_model, trends)
	p5 = viz.plot(width=400, height=400)
	vm.add_plot(p5)

	m = vm.plot()
	show(m)

.. _`Jupyter Notebook`: https://colab.research.google.com/github/KDDComplexNetworkAnalysis/CNA_Tutorials/blob/master/NDlib.ipynb#scrollTo=d80DUNRkKIn4


text:
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#include <boost/graph/fruchterman_reingold.hpp>
#include <boost/graph/random_layout.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/topology.hpp>
#include <boost/lexical_cast.hpp>
#include <string>
#include <iostream>
#include <map>
#include <vector>
#include <boost/random/linear_congruential.hpp>
#include <boost/progress.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost;

void usage()
{
  std::cerr << "Usage: fr_layout [options] <width> <height>\n"
            << "Arguments:\n"
            << "\t<width>\tWidth of the display area (floating point)\n"
            << "\t<Height>\tHeight of the display area (floating point)\n\n"
            << "Options:\n"
            << "\t--iterations n\tNumber of iterations to execute.\n"
            << "\t\t\tThe default value is 100.\n"
            << "Input:\n"
            << "  Input is read from standard input as a list of edges, one per line.\n"
            << "  Each edge contains two string labels (the endpoints) separated by a space.\n\n"
            << "Output:\n"
            << "  Vertices and their positions are written to standard output with the label,\n  x-position, and y-position of a vertex on each line, separated by spaces.\n";
}

typedef boost::rectangle_topology<> topology_type;
typedef topology_type::point_type point_type;

typedef adjacency_list<listS, vecS, undirectedS,
                       property<vertex_name_t, std::string> > Graph;

typedef graph_traits<Graph>::vertex_descriptor Vertex;

typedef std::map<std::string, Vertex> NameToVertex;

Vertex get_vertex(const std::string& name, Graph& g, NameToVertex& names)
{
  NameToVertex::iterator i = names.find(name);
  if (i == names.end())
    i = names.insert(std::make_pair(name, add_vertex(name, g))).first;
  return i->second;
}

class progress_cooling : public linear_cooling<double>
{
  typedef linear_cooling<double> inherited;

 public:
  explicit progress_cooling(std::size_t iterations) : inherited(iterations)
  {
    display.reset(new progress_display(iterations + 1, std::cerr));
  }

  double operator()()
  {
    ++(*display);
    return inherited::operator()();
  }

 private:
  shared_ptr<boost::progress_display> display;
};

int main(int argc, char* argv[])
{
  int iterations = 100;

  if (argc < 3) { usage(); return -1; }

  double width = 0;
  double height = 0;

  for (int arg_idx = 1; arg_idx < argc; ++arg_idx) {
    std::string arg = argv[arg_idx];
    if (arg == "--iterations") {
      ++arg_idx;
      if (arg_idx >= argc) { usage(); return -1; }
      iterations = lexical_cast<int>(argv[arg_idx]);
    } else {
      if (width == 0.0) width = lexical_cast<double>(arg);
      else if (height == 0.0) height = lexical_cast<double>(arg);
      else {
        usage();
        return -1;
      }
    }
  }

  if (width == 0.0 || height == 0.0) {
    usage();
    return -1;
  }

  Graph g;
  NameToVertex names;

  std::string source, target;
  while (std::cin >> source >> target) {
    add_edge(get_vertex(source, g, names), get_vertex(target, g, names), g);
  }

  typedef std::vector<point_type> PositionVec;
  PositionVec position_vec(num_vertices(g));
  typedef iterator_property_map<PositionVec::iterator,
                                property_map<Graph, vertex_index_t>::type>
    PositionMap;
  PositionMap position(position_vec.begin(), get(vertex_index, g));

  minstd_rand gen;
  topology_type topo(gen, -width/2, -height/2, width/2, height/2);
  random_graph_layout(g, position, topo);
  fruchterman_reingold_force_directed_layout
    (g, position, topo,
     cooling(progress_cooling(iterations)));

  graph_traits<Graph>::vertex_iterator vi, vi_end;
  for (boost::tie(vi, vi_end) = vertices(g); vi != vi_end; ++vi) {
    std::cout << get(vertex_name, g, *vi) << '\t'
              << position[*vi][0] << '\t' << position[*vi][1] << std::endl;
  }
  return 0;
}

redpajama_set_name: RedPajamaGithub


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

<TITLE>
ISEAAction
</TITLE>

<META NAME="keywords" CONTENT="avrora.actions.ISEAAction class">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

avrora.actions

Class ISEAAction

java.lang.Object
  avrora.util.help.HelpCategory
      avrora.actions.Action
          avrora.actions.ISEAAction

All Implemented Interfaces:
HelpItem

public class ISEAAction
extends Action

The ISEAAction class implements interprocedural side-effect analysis. This class
 implements an action that allows the user to invoke the analysis on a program from the command
 line.

Field Summary

protected  Option.Str
START

Fields inherited from class avrora.actions.Action

options

Fields inherited from class avrora.util.help.HelpCategory

COMPARATOR, help, name

Constructor Summary

ISEAAction()

Method Summary

 void
run(java.lang.String[] args)

          The run() method is called by the main class and is passed the remaining command line
 arguments after options have been stripped out.

Methods inherited from class avrora.actions.Action

newOption, newOption, newOption, newOption, newOption, newOptionList

Methods inherited from class avrora.util.help.HelpCategory

addCommandExample, addListSection, addOptionSection, addSection, addSubcategorySection, getHelp, getName, printHelp, setName

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

START

protected final Option.Str START

Constructor Detail

ISEAAction

public ISEAAction()

Method Detail

run

public void run(java.lang.String[] args)
         throws java.lang.Exception

Description copied from class: Action

The run() method is called by the main class and is passed the remaining command line
 arguments after options have been stripped out.

Specified by:
run in class Action

Parameters:
args - the command line arguments

Throws:

java.lang.Exception

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php

class CreateReservationRequestTest extends PHPUnit_Framework_TestCase
{
    public function testRequestDefaultUri()
    {
        $request = new \Rentlio\Api\Request\CreateNewReservationRequest();
        $uri     = $request->getUri();

        $this->assertEquals('/reservations', $uri->getPath());
        $this->assertEquals('', $uri->getQuery());
    }

    public function testJsonSerialize()
    {
        $request     = new \Rentlio\Api\Request\CreateNewReservationRequest();
        $requestBody = json_encode($request);
        $this->assertJson($requestBody);

        $reservation = new \Rentlio\Api\Request\Data\Reservation(1, '2018-07-23', '2018-07-25', 1, 2);
        $request->setReservation($reservation);

        $requestBody = json_encode($request);
        $this->assertJson($requestBody);
        $this->assertEquals('{"unitTypeId":1,"dateFrom":"2018-07-23","dateTo":"2018-07-25","persons":2,"rooms":1}', $requestBody);

        $reservation->setEmail('doe@rentl.io');
        $reservation->setNote('Testing request');
        $reservation->setRooms(2);
        $reservation->setPersons(3);
        $reservation->setExpiryYear(2022);
        $reservation->setCardHolder('John Doe');
        $reservation->setCardNumber('0987654321');
        $reservation->setExpiryMonth(8);

        $requestBody = json_encode($request);
        $this->assertJson($requestBody);
        $this->assertEquals('{"unitTypeId":1,"dateFrom":"2018-07-23","dateTo":"2018-07-25","email":"doe@rentl.io","persons":3,"rooms":2,"note":"Testing request","cardHolder":"John Doe","cardNumber":"0987654321","expiryMonth":8,"expiryYear":2022}', $requestBody);
    }
}


text:
> A text-mode interface for Git.

- Show the sequence of commits starting from the current one in reverse chronological order:

`tig`

- Show the history of a specific branch:

`tig {{branch}}`

- Show the history of specific files or directories:

`tig {{path1 path2 …}}`

- Show the difference between two references (such as branches or tags):

`tig {{base_ref}}..{{compared_ref}}`

- Display commits from all branches and stashes:

`tig --all`

- Start in stash view, displaying all saved stashes:

`tig stash`


text:
/******************************************************************************
  This source file is part of the Avogadro project.
  This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/

#include "clientserver.h"
#include "RemoteMoleculeService.pb.h"
#include "connectionsettingsdialog.h"
#include "filedialog.h"

#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QSettings>
#include <QtCore/QStringList>
#include <QtCore/QTimer>
#include <QtGui/QAction>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>

#include <vtkNew.h>
#include <vtkSocketCommunicator.h>
#include <vtkSocketController.h>

#include <avogadro/io/fileformatmanager.h>
#include <avogadro/qtgui/molecule.h>

#include <google/protobuf/stubs/common.h>
#include <protocall/runtime/vtkcommunicatorchannel.h>

using namespace google::protobuf;
using namespace ProtoCall::Runtime;

namespace Avogadro {
namespace QtPlugins {

ClientServer::ClientServer(QObject* parent_)
  : Avogadro::QtGui::ExtensionPlugin(parent_), m_dialog(nullptr),
    m_openAction(new QAction(this)), m_settingsAction(new QAction(this)),
    m_molecule(nullptr), m_controller(nullptr), m_communicator(nullptr),
    m_channel(nullptr)
{
  m_openAction->setEnabled(true);
  m_openAction->setText("Open Molecule");
  m_actions.append(m_openAction);

  m_settingsAction->setEnabled(true);
  m_settingsAction->setText("Settings");
  m_actions.append(m_settingsAction);

  connect(m_openAction, SIGNAL(triggered()), SLOT(openFile()));
  connect(m_settingsAction, SIGNAL(triggered()), SLOT(openSettings()));
  connect(this, SIGNAL(connectionError()), SLOT(onConnectionError()));
}

ClientServer::~ClientServer()
{
  disconnect();
}

QString ClientServer::description() const
{
  return tr("Client server operations.");
}

QList<QAction*> ClientServer::actions() const
{
  return m_actions;
}

QStringList ClientServer::menuPath(QAction*) const
{
  return QStringList() << tr("&Extensions") << tr("S&erver");
}

void ClientServer::disconnect()
{

  if (m_communicator)
    m_communicator->CloseConnection();

  delete m_channel;
  m_channel = nullptr;
  if (m_communicator)
    m_communicator->Delete();
  if (m_controller)
    m_controller->Delete();
}

void ClientServer::select()
{
  if (m_channel) {
    if (m_channel->select()) {
      if (!m_channel->receive()) {
        emit connectionError();
        return;
      }
    }
    QTimer::singleShot(100, this, SLOT(select()));
  }
}

bool ClientServer::isConnected()
{
  return m_channel != nullptr;
}

bool ClientServer::connectToServer(const QString& host, int port)
{

  if (m_channel)
    disconnect();

  m_controller = vtkSocketController::New();
  m_communicator = vtkSocketCommunicator::New();
  m_controller->SetCommunicator(m_communicator);
  m_controller->Initialize();

  if (!m_communicator->ConnectTo(host.toLocal8Bit().data(), port)) {
    m_controller->Delete();
    m_communicator->Delete();

    return false;
  }

  m_channel = new vtkCommunicatorChannel(m_communicator);

  // Start the event loop
  select();

  return true;
}

void ClientServer::openFile()
{
  QSettings settings;
  if (!isConnected()) {
    QString host = settings
                     .value("clientServer/connectionSettings/hostName",
                            ConnectionSettingsDialog::defaultHost)
                     .toString();
    int port = settings
                 .value("clientServer/connectionSettings/port",
                        ConnectionSettingsDialog::defaultPort)
                 .toInt();

    if (!connectToServer(host.toLocal8Bit().data(), port)) {
      QMessageBox::critical(qobject_cast<QWidget*>(parent()),
                            tr("Connection failed"),
                            tr("The connection to %2:%3 failed: connection"
                               " refused.")
                              .arg(host)
                              .arg(port));
      return;
    }
  }

  RemoteMoleculeService::Proxy proxy(m_channel);
  FileFormats* response = new FileFormats();
  Closure* callback =
    NewCallback(this, &ClientServer::handleFileFormatsResponse, response);

  proxy.fileFormats(response, callback);
}

void ClientServer::openFile(const QString& filePath)
{
  QSettings settings;
  QFileInfo fileInfo(filePath);
  settings.setValue(lastOpenDirSettingPath(), fileInfo.dir().path());

  RemoteMoleculeService::Proxy proxy(m_channel);

  OpenRequest request;
  request.set_path(filePath.toStdString());

  OpenResponse* response = new OpenResponse();
  Closure* callback =
    NewCallback(this, &ClientServer::handleOpenResponse, response);

  proxy.open(&request, response, callback);
}

void ClientServer::setMolecule(QtGui::Molecule* mol)
{
  // Do nothing
}

bool ClientServer::readMolecule(QtGui::Molecule& mol)
{
  if (m_molecule) {
    mol = *m_molecule;

    return true;
  }

  return false;
}

void ClientServer::handleOpenResponse(OpenResponse* response)
{
  if (!response->hasError()) {
    m_molecule = response->mutable_molecule()->get();

    emit ExtensionPlugin::moleculeReady(1);
  } else {
    QMessageBox::warning(qobject_cast<QWidget*>(parent()),
                         tr("Remote service error"),
                         response->errorString().c_str());
    return;
  }

  delete response;
}

void ClientServer::onConnectionError()
{
  QMessageBox::critical(
    qobject_cast<QWidget*>(parent()), tr("Remote service error"),
    tr("Connection failed with: %1").arg(m_channel->errorString().c_str()));
  disconnect();
}

void ClientServer::openSettings()
{
  if (!m_dialog) {
    m_dialog = new ConnectionSettingsDialog(qobject_cast<QWidget*>(parent()));
    connect(m_dialog, SIGNAL(settingsChanged()), this, SLOT(disconnect()));
  }
  m_dialog->show();
}

QString ClientServer::lastOpenDirSettingPath()
{
  QSettings settings;
  QString host =
    settings.value("clientServer/connectionSettings/hostName").toString();
  QString port =
    settings.value("clientServer/connectionSettings/port").toString();

  QString settingsPath =
    tr("clientServer/%1:%2/lastOpenDir").arg(host).arg(port);

  return settingsPath;
}

void ClientServer::handleFileFormatsResponse(FileFormats* response)
{
  QSettings settings;

  QStringList filters;
  for (int i = 0; i < response->formats_size(); i++) {
    FileFormat format = response->formats(i);
    QString filter = tr("%1 (").arg(QString::fromStdString(format.name()));
    for (int j = 0; j < format.extension_size(); j++) {
      filter += tr("*.%1").arg(QString::fromStdString(format.extension(j)));

      if (j != format.extension_size() - 1)
        filter += " ";
    }

    filter += ")";
    filters << filter;
  }

  qDebug() << filters.join(";;");

  QString dir = settings.value(lastOpenDirSettingPath()).toString();
  FileDialog* remoteFileDialog = new FileDialog(
    m_channel, nullptr, QString("Remote File Dialog"), dir, filters.join(";;"));

  connect(remoteFileDialog, SIGNAL(accepted()), this, SLOT(onAccepted()));
  connect(remoteFileDialog, SIGNAL(finished(int)), this, SLOT(onFinished(int)));

  remoteFileDialog->show();

  delete response;
}

void ClientServer::onAccepted()
{
  FileDialog* dialog = qobject_cast<FileDialog*>(sender());

  if (!dialog)
    return;

  QString file = dialog->getSelectedFile();

  if (!file.isEmpty())
    openFile(file);
}

void ClientServer::onFinished(int result)
{
  FileDialog* dialog = qobject_cast<FileDialog*>(sender());

  if (dialog)
    dialog->deleteLater();
}

} // namespace QtPlugins
}


text:
'use strict';

import * as nls from 'vs/nls';
import {isFalsyOrEmpty} from 'vs/base/common/arrays';
import {onUnexpectedError} from 'vs/base/common/errors';
import {KeyCode, KeyMod} from 'vs/base/common/keyCodes';
import {cAll} from 'vs/base/common/lifecycle';
import Severity from 'vs/base/common/severity';
import URI from 'vs/base/common/uri';
import {TPromise} from 'vs/base/common/winjs.base';
import {IEditorService} from 'vs/platform/editor/common/editor';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {ICommandHandler, IKeybindingContextKey, IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {KeybindingsRegistry} from 'vs/platform/keybinding/common/keybindingsRegistry';
import {IMessageService} from 'vs/platform/message/common/message';
import {ITelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {Position} from 'vs/editor/common/core/position';
import {Range} from 'vs/editor/common/core/range';
import {EditorAction} from 'vs/editor/common/editorAction';
import {Behaviour} from 'vs/editor/common/editorActionEnablement';
import * as editorCommon from 'vs/editor/common/editorCommon';
import {CommonEditorRegistry, ContextKey, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {IReference} from 'vs/editor/common/modes';
import {ICodeEditor} from 'vs/editor/browser/editorBrowser';
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import {Events, IPeekViewService, getOuterEditor} from 'vs/editor/contrib/zoneWidget/browser/peekViewWidget';
import {ReferenceRegistry, findReferences} from '../common/referenceSearch';
import {EventType, ReferencesModel} from './referenceSearchModel';
import {ReferenceWidget} from './referenceSearchWidget';

export class FindReferencesController implements editorCommon.IEditorContribution {

	public static ID = 'editor.contrib.findReferencesController';

	private editor:ICodeEditor;
	private widget:ReferenceWidget;
	private requestIdPool: number;
	private callOnClear:Function[];
	private model:ReferencesModel;
	private modelRevealing:boolean;

	private editorService: IEditorService;
	private telemetryService: ITelemetryService;
	private messageService: IMessageService;
	private instantiationService: IInstantiationService;
	private contextService: IWorkspaceContextService;
	private peekViewService: IPeekViewService;
	private keybindingService: IKeybindingService;

	private _startTime: number = -1;
	private _referenceSearchVisible: IKeybindingContextKey<boolean>;

	static getController(editor:editorCommon.ICommonCodeEditor): FindReferencesController {
		return <FindReferencesController> editor.getContribution(FindReferencesController.ID);
	}

	public constructor(editor:ICodeEditor, @IEditorService editorService: IEditorService, @ITelemetryService telemetryService: ITelemetryService, @IMessageService messageService: IMessageService, @IInstantiationService instantiationService: IInstantiationService, @IPeekViewService peekViewService: IPeekViewService, @IWorkspaceContextService contextService: IWorkspaceContextService, @IKeybindingService keybindingService: IKeybindingService) {
		this.requestIdPool = 0;
		this.callOnClear = [];
		this.editorService = editorService;
		this.telemetryService = telemetryService;
		this.messageService = messageService;
		this.instantiationService = instantiationService;
		this.peekViewService = peekViewService;
		this.contextService = contextService;
		this.keybindingService = keybindingService;
		this.modelRevealing = false;
		this.editor = editor;
		this._referenceSearchVisible = keybindingService.createKey(CONTEXT_REFERENCE_SEARCH_VISIBLE, false);
	}

	public getId(): string {
		return FindReferencesController.ID;
	}

	public dispose(): void {
		if (this.widget) {
			this.widget.dispose();
			this.widget = null;
		}
		this.editor = null;
	}

	public isInPeekView() : boolean {
		return this.peekViewService && this.peekViewService.isActive;
	}

	public closeReferenceSearch(): void {
		this.clear();
	}

	public processRequest(range: editorCommon.IEditorRange, referencesPromise: TPromise<IReference[]>, metaTitleFn:(references:IReference[])=>string) : ReferenceWidget {
		var widgetPosition = !this.widget ? null : this.widget.position;

		// clean up from previous invocation
		var widgetClosed = this.clear();

		// Close if the position is still the same
		if(widgetClosed && !!widgetPosition && range.containsPosition(widgetPosition)) {
			return null;
		}

		this._referenceSearchVisible.set(true);

		// close the widget on model/mode changes
		this.callOnClear.push(this.editor.addListener(editorCommon.EventType.ModelModeChanged, () => { this.clear(); }));
		this.callOnClear.push(this.editor.addListener(editorCommon.EventType.ModelChanged, () => {
			if(!this.modelRevealing) {
				this.clear();
			}
		}));

		this.widget = new ReferenceWidget(this.editorService, this.keybindingService, this.contextService, this.instantiationService, this.editor);
		this.widget.setTitle(nls.localize('labelLoading', "Loading..."));
		this.widget.show(range, 18);
		this.callOnClear.push(this.widget.addListener(Events.Closed, () => {
			this.widget = null;
			this.clear();
		}));
		this.callOnClear.push(this.widget.addListener(ReferenceWidget.Events.EditorDoubleClick, (event:any) => {

			if(!event.reference) {
				return;
			}

			// open editor
			this.editorService.openEditor({
				resource: event.reference,
				options: { selection: event.range }
			}, event.originalEvent.ctrlKey || event.originalEvent.metaKey).done(null, onUnexpectedError);

			// close zone
			if (!(event.originalEvent.ctrlKey || event.originalEvent.metaKey)) {
				this.clear();
			}
		}));
		var requestId = ++this.requestIdPool,
			editorModel = this.editor.getModel();

		var timer = this.telemetryService.start('findReferences', {
			mode: editorModel.getMode().getId()
		});

		referencesPromise.then((references:IReference[]) => {

			// still current request?
			if(requestId !== this.requestIdPool) {
				timer.stop();
				return;
			}

			// has a result
			if (isFalsyOrEmpty(references)) {
				this.widget.showMessage(nls.localize('noResults', "No results"));
				timer.stop();
				return;
			}

			// create result model
			this.model = new ReferencesModel(references, this.editorService);
			this.model.currentReference = this.model.findReference(editorModel.getAssociatedResource(), range.getStartPosition());

			var unbind = this.model.addListener(EventType.CurrentReferenceChanged, () => {

				this.modelRevealing = true;

				this.editorService.openEditor({
					resource: this.model.currentReference.resource,
					options: { selection: this.model.currentReference.range }
				}).done((openedEditor) => {
					if(!openedEditor || openedEditor.getControl() !== this.editor) {
						// TODO@Alex TODO@Joh
						// when opening the current reference we might end up
						// in a different editor instance. that means we also have
						// a different instance of this reference search controller
						// and cannot hold onto the widget (which likely doesn't
						// exist). Instead of bailing out we should find the
						// 'sister' action and pass our current model on to it.
						this.clear();
						return;
					}
					this.modelRevealing = false;
					this.widget.show(this.model.currentReference.range, 18);
					this.widget.focus();
				}, (err) => {
					this.modelRevealing = false;
					onUnexpectedError(err);
				});
			});

			this.callOnClear.push(unbind);

			// show widget
			this._startTime = Date.now();
			if (this.widget) {
				this.widget.setMetaTitle(metaTitleFn(references));
				this.widget.setModel(this.model);
			}
			timer.stop();

		}, (error:any) => {
			this.messageService.show(Severity.Error, error);
			timer.stop();
		});

		return this.widget;
	}

	private clear():boolean {

		if (this._startTime !== -1) {
			this.telemetryService.publicLog('zoneWidgetShown', {
				mode: 'reference search',
				elapsedTime: Date.now() - this._startTime
			});
			this._startTime = -1;
		}

		this._referenceSearchVisible.reset();

		cAll(this.callOnClear);

		this.model = null;

		var result = false;
		if(this.widget) {
			this.widget.dispose();
			this.widget = null;
			result = true;
		}

		this.editor.focus();
		this.requestIdPool += 1; // Cancel pending requests
		return result;
	}

}

export class ReferenceAction extends EditorAction {

	public static ID = 'editor.action.referenceSearch.trigger';

	private peekViewService: IPeekViewService;

	// state - changes with every invocation

	constructor(descriptor:editorCommon.IEditorActionDescriptorData, editor:editorCommon.ICommonCodeEditor, @IPeekViewService peekViewService: IPeekViewService, @IKeybindingService keybindingService: IKeybindingService) {
		super(descriptor, editor, Behaviour.WidgetFocus | Behaviour.ShowInContextMenu | Behaviour.UpdateOnCursorPositionChange);

		this.label = nls.localize('references.action.label', "Find All References");

		this.peekViewService = peekViewService;
		if (this.peekViewService) {
			keybindingService.createKey(this.peekViewService.contextKey, true);
		}
	}

	public getGroupId(): string {
		return '1_goto/4_references';
	}

	public isSupported():boolean {
		return ReferenceRegistry.has(this.editor.getModel()) && super.isSupported();
	}

	public getEnablementState():boolean {
		if(this.peekViewService && this.peekViewService.isActive) {
			return false;
		}

		let model = this.editor.getModel();
		let position = this.editor.getSelection().getStartPosition();
		let context = model.getLineContext(position.lineNumber);
		let offset = position.column - 1;

		return ReferenceRegistry.all(model).some(support => {
			return support.canFindReferences(context, offset);
		});
	}

	public run():TPromise<boolean> {
		let range = this.editor.getSelection();
		let model = this.editor.getModel();
		let request = findReferences(model, range.getStartPosition());
		let controller = FindReferencesController.getController(this.editor);
		return TPromise.as(controller.processRequest(range, request, metaTitle)).then(() => true);
	}
}

function metaTitle(references: IReference[]): string {
	if (references.length > 1) {
		return nls.localize('meta.titleReference', " – {0} references", references.length);
	}
}

let findReferencesCommand: ICommandHandler = (accessor, args) => {

	let resource = <URI>args[0];
	let position = <editorCommon.IPosition>args[1];

	if (!(resource instanceof URI)) {
		throw new Error('illegal argument, uri');
	}
	if (!position) {
		throw new Error('illega argument, position');
	}

	return accessor.get(IEditorService).openEditor({ resource }).then(editor => {

		let control = <editorCommon.ICommonCodeEditor>editor.getControl();
		if (!control || typeof control.getEditorType !== 'function') {
			return;
		}

		let request = findReferences(control.getModel(), position);
		let controller = FindReferencesController.getController(control);
		let range = new Range(position.lineNumber, position.column, position.lineNumber, position.column);
		return TPromise.as(controller.processRequest(range, request, metaTitle));
	});
};

let showReferencesCommand: ICommandHandler = (accessor, args:[URI, editorCommon.IPosition, IReference[]]) => {
	if (!(args[0] instanceof URI)) {
		throw new Error('illegal argument, uri expected');
	}

	return accessor.get(IEditorService).openEditor({ resource: args[0] }).then(editor => {

		let control = <editorCommon.ICommonCodeEditor>editor.getControl();
		if (!control || typeof control.getEditorType !== 'function') {
			return;
		}

		let controller = FindReferencesController.getController(control);
		let range = Position.asEmptyRange(args[1]);
		return TPromise.as(controller.processRequest(Range.lift(range), TPromise.as(args[2]), metaTitle)).then(() => true);
	});
};

var CONTEXT_REFERENCE_SEARCH_VISIBLE = 'referenceSearchVisible';

// register action
EditorBrowserRegistry.registerEditorContribution(FindReferencesController);
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(ReferenceAction, ReferenceAction.ID, nls.localize('references.action.name', "Show References"), {
	context: ContextKey.EditorTextFocus,
	primary: KeyMod.Shift | KeyCode.F12
}));
KeybindingsRegistry.registerCommandDesc({
	id: 'editor.action.findReferences',
	handler: findReferencesCommand,
	weight: CommonEditorRegistry.commandWeight(50),
	context: null,
	primary: undefined
});
KeybindingsRegistry.registerCommandDesc({
	id: 'editor.action.showReferences',
	handler: showReferencesCommand,
	weight: CommonEditorRegistry.commandWeight(50),
	context: null,
	primary: undefined,
	description: {
		description: 'Show references at a position in a file',
		args: [
			{ name: 'uri', description: 'The text document in which to show references', constraint: URI },
			{ name: 'position', description: 'The position at which to show', constraint: Position.isIPosition },
			{ name: 'locations', description: 'An array of locations.', constraint: Array },
		]
	}
});
CommonEditorRegistry.registerEditorCommand('closeReferenceSearch', CommonEditorRegistry.commandWeight(50), { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, false, CONTEXT_REFERENCE_SEARCH_VISIBLE, (accessor, editor, args) => {
	var outerEditor = getOuterEditor(accessor, args);
	if (outerEditor) {
		var controller = FindReferencesController.getController(outerEditor);
		controller.closeReferenceSearch();
	}
});
CommonEditorRegistry.registerEditorCommand('closeReferenceSearchEditor', CommonEditorRegistry.commandWeight(-101), { primary: KeyCode.Escape, secondary: [KeyMod.Shift | KeyCode.Escape] }, false, ReferenceWidget.INNER_EDITOR_CONTEXT_KEY, (accessor, editor, args) => {
	var outerEditor = getOuterEditor(accessor, args);
	if (outerEditor) {
		var controller = FindReferencesController.getController(outerEditor);
		controller.closeReferenceSearch();
	}
});


text:
package me.themadjem;

import org.jetbrains.annotations.NotNull;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class UI_Listener implements ActionListener {

    private final Main_UI m;

    /**
     * Constructor
     * @param ui Main_UI used for referencing methods
     */
    UI_Listener(Main_UI ui) {
        m = ui;
    }

    /**
     * Called whenever an action is performed
     * @param e Event
     */
    @Override
    public void actionPerformed(@NotNull ActionEvent e) {
        if (e.getActionCommand().equalsIgnoreCase(m.getEnableEditingCheckBox().getActionCommand())) changeDataEditMode();
        if (e.getActionCommand().equalsIgnoreCase(m.getManualTimeCheckBox().getActionCommand())) changeTimeMode();
        if (e.getActionCommand().equalsIgnoreCase(m.getManualDateCheckBox().getActionCommand())) changeDateMode();
        if (e.getActionCommand().equalsIgnoreCase(m.getProcessButton().getActionCommand())) Main.process();

    }

    /**
     * Enables or Disables editing for data fields
     */
    private void changeDataEditMode() {
        if (m.getEnableEditingCheckBox().isSelected()) {
            m.getIcr_field().setEditable(true);
            m.getCorrection_field().setEditable(true);
            m.getTargetBG_field().setEditable(true);
        } else {
            m.getIcr_field().setEditable(false);
            m.getCorrection_field().setEditable(false);
            m.getTargetBG_field().setEditable(false);
        }
    }

    /**
     * Enables or Disables editing for Time fields
     */
    private void changeTimeMode() {
        if (m.getManualTimeCheckBox().isSelected()) {
            m.getHour_field().setEditable(true);
            m.getMinute_field().setEditable(true);
        } else {
            m.getHour_field().setEditable(false);
            m.getMinute_field().setEditable(false);
        }
    }

    /**
     * Enables or Disables editing for Date fields
     */
    private void changeDateMode() {
        if (m.getManualDateCheckBox().isSelected()) {
            m.getMonth_field().setEditable(true);
            m.getDay_field().setEditable(true);
            m.getYear_field().setEditable(true);
        } else {
            m.getMonth_field().setEditable(false);
            m.getDay_field().setEditable(false);
            m.getYear_field().setEditable(false);
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"/>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

        <link href='https://fonts.googleapis.com/css?family=Raleway:400,700' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}" ></style>

        <title>Nonprofit Overhead Analyzer</title>

        {% block content %}
        {% endblock %}

                Provided by Urban Affairs Coalition

                215-851-0110

                1207 Chestnut Street, Philadelphia, PA 19107


text:
import React from 'react';

import { isSameDay } from 'date-fns';
import {
  Button,
  DateRange,
  DayPicker,
  DayProps,
  useDayRender
} from 'react-day-picker';

function DayWithShiftKey(props: DayProps) {
  const buttonRef = React.useRef<HTMLButtonElement>(null);
  const dayRender = useDayRender(props.date, props.displayMonth, buttonRef);

  if (dayRender.isHidden) {
    return <></>;
  }
  if (!dayRender.isButton) {
    return
;
  }

  const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
    if (
      !dayRender.selectedDays ||
      dayRender.activeModifiers.selected ||
      e.shiftKey
    ) {
      dayRender.buttonProps?.onClick?.(e);
    }
  };

  return (
    <Button {...dayRender.buttonProps} ref={buttonRef} onClick={handleClick} />
  );
}

export default function App() {
  const [range, setRange] = React.useState<DateRange>();

  let footer =
Please pick a day.
;

  if (range?.from && range?.to) {
    if (isSameDay(range.from, range.to)) {
      footer =
Press Shift to choose more days.
;
    } else {
      footer = (

          {range.from.toLocaleDateString()}—{range.to.toLocaleDateString()}.

      );
    }
  }
  return (
    <DayPicker
      components={{
        Day: DayWithShiftKey
      }}
      mode="range"
      onSelect={setRange}
      selected={range}
      footer={footer}
    />
  );
}


text:
using System.Collections.Generic;
using Xunit;

namespace Octokit.Tests.Models
{
    public class NewRepositoryWebHookTests
    {
        public class TheCtor
        {
            [Fact]
            public void UsesDefaultValuesForDefaultConfig()
            {
                var create = new NewRepositoryWebHook("windowsazure", new Dictionary<string, string>(), "http://test.com/example");
                Assert.Equal("http://test.com/example", create.Url);
                Assert.Equal(WebHookContentType.Form, create.ContentType);
                Assert.Empty(create.Secret);
                Assert.False(create.InsecureSsl);

                var request = create.ToRequest();
                Assert.Equal(4, request.Config.Count);

                Assert.True(request.Config.ContainsKey("url"));
                Assert.True(request.Config.ContainsKey("content_type"));
                Assert.True(request.Config.ContainsKey("secret"));
                Assert.True(request.Config.ContainsKey("insecure_ssl"));

                Assert.Equal("http://test.com/example", request.Config["url"]);
                Assert.Equal(request.Config["content_type"], WebHookContentType.Form.ToParameter());
                Assert.Equal("", request.Config["secret"]);
                Assert.Equal("False", request.Config["insecure_ssl"]);
            }

            [Fact]
            public void CombinesUserSpecifiedContentTypeWithConfig()
            {
                var config = new Dictionary<string, string>
                {
                    {"hostname", "http://hostname.url"},
                    {"username", "username"},
                    {"password", "password"}
                };

                var create = new NewRepositoryWebHook("windowsazure", config, "http://test.com/example")
                {
                    ContentType = WebHookContentType.Json,
                    Secret = string.Empty,
                    InsecureSsl = true
                };

                Assert.Equal("http://test.com/example", create.Url);
                Assert.Equal(WebHookContentType.Json, create.ContentType);
                Assert.Empty(create.Secret);
                Assert.True(create.InsecureSsl);

                var request = create.ToRequest();

                Assert.Equal(7, request.Config.Count);

                Assert.True(request.Config.ContainsKey("url"));
                Assert.True(request.Config.ContainsKey("content_type"));
                Assert.True(request.Config.ContainsKey("secret"));
                Assert.True(request.Config.ContainsKey("insecure_ssl"));

                Assert.Equal("http://test.com/example", request.Config["url"]);
                Assert.Equal(request.Config["content_type"], WebHookContentType.Json.ToParameter());
                Assert.Equal("", request.Config["secret"]);
                Assert.Equal(request.Config["insecure_ssl"], true.ToString());

                Assert.True(request.Config.ContainsKey("hostname"));
                Assert.Equal(request.Config["hostname"], config["hostname"]);
                Assert.True(request.Config.ContainsKey("username"));
                Assert.Equal(request.Config["username"], config["username"]);
                Assert.True(request.Config.ContainsKey("password"));
                Assert.Equal(request.Config["password"], config["password"]);
            }

            [Fact]
            public void CanSetHookAsActive()
            {
                var config = new Dictionary<string, string>
                {
                    {"hostname", "http://hostname.url"},
                    {"username", "username"},
                    {"password", "password"}
                };

                var create = new NewRepositoryWebHook("web", config, "http://test.com/example")
                {
                    Active = true
                };

                var request = create.ToRequest();

                Assert.True(request.Active);
            }

            [Fact]
            public void CanSetHookEvents()
            {
                var create = new NewRepositoryWebHook("web", new Dictionary<string, string>(), "http://test.com/example")
                {
                    Events = new List<string> { "*" }
                };

                var request = create.ToRequest();

                Assert.Contains("*", request.Events);
            }

            [Fact]
            public void EnsureCanCallToRequestMultipleTimes()
            {
                var create = new NewRepositoryWebHook("web", new Dictionary<string, string>(), "http://test.com/example")
                {
                    Events = new List<string> { "*" }
                };

                var request = create.ToRequest();
                var requestRepeated = create.ToRequest();

                Assert.Contains("*", request.Events);
                Assert.Contains("*", requestRepeated.Events);
            }

            [Fact]
            public void ShouldNotContainDuplicateConfigEntriesOnSubsequentRequests()
            {
                var create = new NewRepositoryWebHook("web", new Dictionary<string, string>(), "http://test.com/example");

                var request = create.ToRequest();
                var requestRepeated = create.ToRequest();

                Assert.Equal(4, request.Config.Count);
                Assert.Equal(4, requestRepeated.Config.Count);
            }

            [Fact]
            public void ShouldNotContainDuplicateConfigEntriesOnSubsequentRequestsWithCustomisedConfig()
            {
                var config = new Dictionary<string, string>
                {
                    {"url", "http://example.com/test"},
                    {"hostname", "http://hostname.url"},
                    {"username", "username"},
                    {"password", "password"}
                };

                var create = new NewRepositoryWebHook("web", config, "http://test.com/example");

                var request = create.ToRequest();
                var requestRepeated = create.ToRequest();

                //This is not 8, because `url` used in config, is already part of the base config
                Assert.Equal(7, request.Config.Count);
                Assert.Equal(7, requestRepeated.Config.Count);
            }

            [Fact]
            public void PropertiesShouldTakePrecedenceOverConfigPassedIn()
            {
                var config = new Dictionary<string, string>
                {
                    {"url", "http://originalurl.com/test"},
                };

                var create = new NewRepositoryWebHook("web", config, "http://test.com/example");

                var request = create.ToRequest();

                Assert.Equal("http://test.com/example", request.Config["url"]);

                var subsequentRequest = create.ToRequest();
                Assert.Equal("http://test.com/example", subsequentRequest.Config["url"]);
            }
        }
    }
}


text:
/*jshint unused: false */
/*jslint indent: 4 */
/*global jasmine, process, require, define, describe, xdescribe, it, xit, expect, beforeEach, afterEach, afterLast */
(function () {

    'use strict';

    var result, helper, base, stats,
        cwd = process.cwd(),
        OS = require('os'),
        FS = require('fs'),
        Path = require('path'),
        sinon = require('sinon'),
        Utils = require(Path.join(cwd, 'src', 'lib', 'utils'));

    describe('Utils', function () {

        describe('stats', function () {
            describe('as object for a directory', function () {
                base = Path.join(cwd, 'spec', 'expected');
                stats = FS.statSync(base);
                result = Utils.stats(stats);
                it('returns an object', function () {
                    expect(result).toEqual(jasmine.any(Object));
                });
                it('dev', function () {
                    expect(result.dev).toEqual(jasmine.any(Number));
                });
                it('ino', function () {
                    expect(result.ino).toEqual(jasmine.any(Number));
                });
                it('mode', function () {
                    expect(result.mode).toEqual(jasmine.any(Number));
                });
                it('nlink', function () {
                    expect(result.nlink).toEqual(jasmine.any(Number));
                });
                it('uid', function () {
                    expect(result.uid).toEqual(jasmine.any(Number));
                });
                it('gid', function () {
                    expect(result.gid).toEqual(jasmine.any(Number));
                });
                it('rdev', function () {
                    expect(result.rdev).toEqual(jasmine.any(Number));
                });
                it('size', function () {
                    expect(result.size).toEqual(jasmine.any(Number));
                });
                xit('blksize', function () {
                    expect(result.blksize).toEqual(undefined);
                });
                xit('blocks', function () {
                    expect(result.blocks).toEqual(undefined);
                });
                it('atime', function () {
                    expect(result.atime).toEqual(jasmine.any(Number));
                });
                it('mtime', function () {
                    expect(result.mtime).toEqual(jasmine.any(Number));
                });
                it('ctime', function () {
                    expect(result.ctime).toEqual(jasmine.any(Number));
                });
                it('birthtime', function () {
                    expect(result.birthtime).toEqual(jasmine.any(Number));
                });
            });
        });

        describe('dirname', function () {

            it('returns on linux', function () {
                base = 'file/to/point';
                result = Utils.dirname(base, '/');
                expect(result).toEqual('point');
            });

            it('returns on windows', function () {
                base = 'file\\to\\point';
                result = Utils.dirname(base, '\\');
                expect(result).toEqual('point');
            });

            it('returns on windows native', function () {
                if (OS.platform().toLocaleLowerCase() === 'win32') {
                    base = 'file\\to\\point';
                    result = Utils.dirname(base);
                    expect(result).toEqual('point');
                } else {
                    base = 'file/to/point';
                    result = Utils.dirname(base);
                    expect(result).toEqual('point');
                }
            });

        });

    });

}());


text:
description: tf.distribute strategy utils for Ranking pipeline in tfr.keras.

<meta itemprop="name" content="tfr.keras.strategy_utils" />
<meta itemprop="path" content="Stable" />
<meta itemprop="property" content="MIRRORED_STRATEGY"/>
<meta itemprop="property" content="MWMS_STRATEGY"/>
<meta itemprop="property" content="PS_STRATEGY"/>
<meta itemprop="property" content="TPU_STRATEGY"/>

# Module: tfr.keras.strategy_utils

    View source on GitHub

tf.distribute strategy utils for Ranking pipeline in tfr.keras.

In TF2, the distributed training can be easily handled with Strategy offered in
tf.distribute. Depending on device and MapReduce technique, there are four
strategies are currently supported. They are: MirroredStrategy: synchronous
strategy on a single CPU/GPU worker. MultiWorkerMirroredStrategy: synchronous
strategy on multiple CPU/GPU workers. TPUStrategy: distributed strategy working
on TPU. ParameterServerStrategy: asynchronous distributed strategy on CPU/GPU
workers.

Note: ParameterServerStrategy is not fully compatible with `model.fit` in
current version of tensorflow, thus not supported.

Please check https://www.tensorflow.org/guide/distributed_training for more
information.

## Classes

[`class NullContextManager`](../../tfr/keras/strategy_utils/NullContextManager.md):
A null context manager for local training.

## Functions

[`get_output_filepath(...)`](../../tfr/keras/strategy_utils/get_output_filepath.md):
Gets filepaths for different workers to resolve conflict of MWMS.

[`get_strategy(...)`](../../tfr/keras/strategy_utils/get_strategy.md): Creates
and initializes the requested tf.distribute strategy.

[`strategy_scope(...)`](../../tfr/keras/strategy_utils/strategy_scope.md): Gets
the strategy.scope() for training with strategy.

<colgroup><col width="214px"><col></colgroup>

Other Members

MIRRORED_STRATEGY

`'MirroredStrategy'`

MWMS_STRATEGY

`'MultiWorkerMirroredStrategy'`

PS_STRATEGY

`'ParameterServerStrategy'`

TPU_STRATEGY

`'TPUStrategy'`


text:
import simplejson
from werkzeug.exceptions import HTTPException
from werkzeug.wrappers import Request, Response

class Application(object):
    """Simple app class with basic dispatch convention - endpoint
    should corespond to method name with `serve_` prefix:

        werkzeug.routing.Rule('/profile/<int:id>',
                              endpoint='user-profile')

    above rule will be dispatched to this call (where `self`
    is Application instance):

        self.serve_user_profile(request, *args)

    P.S. you should not store any state on app instance as this is
    not thread safe.
    """

    Request = Request
    Response = Response
    # list of tuples [(header, value), ...]
    extra_headers = []
    url_map = None

    def __init__(self, url_map=None, extra_headers=None):
        self.url_map = url_map or self.url_map
        if not self.url_map:
            raise ValueError('You have to pass or define url_map value')
        self.extra_headers = extra_headers or self.extra_headers

    def __call__(self, environ, start_response):
        def _start_response(c, headers):
            response_headers = {h for h,v in headers}
            for k, v in self.extra_headers:
                if k not in response_headers:
                    headers.append((k, v))
            return start_response(c, headers)
        url_dispatcher = self.url_map.bind_to_environ(environ)
        request = self.Request(environ)
        try:
            view, args = url_dispatcher.match(request.path)
        except HTTPException, e:
            response = e
        else:
            response = self._serve(view, request, args)
        return response(environ, _start_response)

    def _serve(self, view, request, args):
        if isinstance(view, basestring):
            view_name = 'serve_%s' % view.replace('-', '_')
            if not hasattr(self, view_name):
                view_method = getattr(self, view_name)
                return view_method(request, **args)
            else:
                raise ValueError('View method missing: %s' % view_name)
        raise ValueError('Base _serve implementation expects view '
                         'name as first parameter')

    def obj_to_json_response(self, obj):
        return self.Response(simplejson.dumps(obj, indent='  '),
                             mimetype='application/json')


text:
require 'spec_helper'

describe "php::5_4_29" do
  let(:facts) { default_test_facts }

  it do
    should contain_php__version("5.4.29")
  end
end


text:
package org.jboss.seam.examples.seamcrm.comment;

import java.util.List;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.FlushModeType;

import org.jboss.seam.examples.seamcrm.aaa.SessionUser;
import org.jboss.seam.examples.seamcrm.core.BaseEntity;
import org.jboss.solder.logging.Logger;

/**
 *
 * @author Cody Lerum
 *
 */
@Named
@RequestScoped
public class EntityComments
{

    @Inject
    private Logger log;

    @Inject
    private EntityManager em;

    @Inject
    private SessionUser sessionUser;

    public List<Comment> fetch(BaseEntity baseEntity)
    {
        log.info("Fetching Comment List for: " + baseEntity.getEntityType() + " <" + baseEntity.getEntityId() + ">");

        return em.createQuery("from Comment c join fetch c.user where c.entityType=:entityType and c.entityId=:entityId order by c.dateCreated desc", Comment.class)
                .setParameter("entityType", baseEntity.getEntityType())
                .setParameter("entityId", baseEntity.getEntityId())
                .setFlushMode(FlushModeType.COMMIT)
                .getResultList();
    }

    public void comment(@Observes Comment comment)
    {
        comment.setUser(sessionUser.getUser());
        em.persist(comment);
    }

}


text:
define(
	[
		'util/Localizer'
	],
	function define_koBindings_collapse(Loc)
	{
		return {
			init: function initCollapse(element, valueAccessor, allBindings, _dep, bindingContext)
			{
				var openLabel = Loc(bindingContext.$data._locContext + "collapse_more");
				var closeLabel = Loc(bindingContext.$data._locContext + "collapse_less");
				var button = document.createElement("BUTTON");
				button.className = "collapse_button";
				var start = valueAccessor() || 'closed';
				button.innerText = ((start === "closed")?openLabel:closeLabel);

				var display = element.style.display;

				button.addEventListener("click", function toggleCollapsible()
				{
					if (button.innerText === openLabel)
					{
						element.style.display = display;
						button.innerText = closeLabel;
					}
					else
					{
						element.style.display = "none";
						button.innerText = openLabel;
					}
				});

				element.parentNode.insertBefore(button, element);

				if (start === "closed")
					{ element.style.display = "none"; }
			},
			update: function updateCollapse(element, valueAccessor, allBindings, _dep, bindingContext)
			{

			}
		};
	}
)


text:
var caniuse = require('caniuse-db/data').agents;
var path    = require('path');
var fs      = require('fs');

var uniq = function (array) {
    var filtered = [];
    for ( var i = 0; i < array.length; i++ ) {
        if ( filtered.indexOf(array[i]) == -1 ) filtered.push(array[i]);
    }
    return filtered;
};

// Return array of browsers by selection queries:
//
//   browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8']
browserslist = function (selections, opts) {
    if ( typeof(opts) == 'undefined' ) opts = { };

    if ( typeof(selections) == 'undefined' || selections === null ) {
        var config = browserslist.readConfig(opts.path);
        if ( config === false ) {
            selections = browserslist.defaults;
        } else {
            selections = config;
        }
    }

    if ( typeof(selections) == 'string' ) {
        selections = selections.split(/,\s*/);
    }

    var result = [];

    var query, match, array, used;
    selections.forEach(function (selection) {
        if ( selection.trim() === '' ) return;
        used = false;

        for ( var i in browserslist.queries ) {
            query = browserslist.queries[i];
            match = selection.match(query.regexp);
            if ( match ) {
                array  = query.select.apply(browserslist, match.slice(1));
                result = result.concat(array);
                used   = true;
                break;
            }
        }

        if ( !used ) {
            throw 'Unknown browser query `' + selection + '`';
        }
    });

    return uniq(result).sort(function (name1, name2) {
        name1 = name1.split(' ');
        name2 = name2.split(' ');
        if ( name1[0] == name2[0] ) {
            return parseFloat(name2[1]) - parseFloat(name1[1]);
        } else {
            return name1[0].localeCompare(name2[0]);
        }
    });
};

// Will be filled by Can I Use data below
browserslist.data  = { };
browserslist.usage = {
    global: { }
};

// Default browsers query
browserslist.defaults = [
    '> 1%',
    'last 2 versions',
    'Firefox ESR',
    'Opera 12.1'
];

// What browsers will be used in `last n version` query
browserslist.major = ['safari', 'opera', 'ios_saf', 'ie_mob', 'ie',
                      'firefox', 'chrome'];

// Browser names aliases
browserslist.aliases = {
    fx:             'firefox',
    ff:             'firefox',
    ios:            'ios_saf',
    explorer:       'ie',
    blackberry:     'bb',
    explorermobile: 'ie_mob',
    operamini:      'op_mini',
    operamobile:    'op_mob',
    chromeandroid:  'and_chr',
    firefoxandroid: 'and_ff'
};

// Get browser data by alias or case insensitive name
browserslist.byName = function (name) {
    name = name.toLowerCase();
    name = browserslist.aliases[name] || name;

    var data = browserslist.data[name];
    if ( !data ) throw 'Unknown browser ' + name;
    return data;
};

// Find config, read file and parse it
browserslist.readConfig = function (from) {
    if ( from === false )   return false;
    if ( !fs.readFileSync ) return false;
    if ( typeof(from) == 'undefined' ) from = '.';

    var dirs = path.resolve(from).split(path.sep);
    var config, stat;
    while ( dirs.length ) {
        config = dirs.concat(['browserslist']).join(path.sep);

        if ( fs.existsSync(config) && fs.lstatSync(config).isFile() ) {
            return browserslist.parseConfig( fs.readFileSync(config) );
        }

        dirs.pop();
    }

    return false;
};

// Return array of queries from config content
browserslist.parseConfig = function (string) {
    return string.toString()
                 .replace(/#[^\n]*/g, '')
                 .split(/\n/)
                 .map(function (i) {
                    return i.trim();
                 })
                 .filter(function (i) {
                    return i !== '';
                 });
};

browserslist.queries = {

    lastVersions: {
        regexp: /^last (\d+) versions?$/i,
        select: function (versions) {
            var selected = [];
            browserslist.major.forEach(function (name) {
                var data  = browserslist.byName(name);
                var array = data.released.slice(-versions);

                array = array.map(function (v) {
                    return data.name + ' ' + v;
                });
                selected = selected.concat(array);
            });
            return selected;
        }
    },

    lastByBrowser: {
        regexp: /^last (\d+) (\w+) versions?$/i,
        select: function (versions, name) {
            var data = browserslist.byName(name);
            return data.released.slice(-versions).map(function (v) {
                return data.name + ' ' + v;
            });
        }
    },

    globalStatistics: {
        regexp: /^> (\d+\.?\d*)%$/,
        select: function (popularity) {
            popularity = parseFloat(popularity);
            var result = [];

            for ( var version in browserslist.usage.global ) {
                if ( browserslist.usage.global[version] > popularity ) {
                    result.push(version);
                }
            }

            return result;
        }
    },

    countryStatistics: {
        regexp: /^> (\d+\.?\d*)% in (\w\w)$/,
        select: function (popularity, country) {
            popularity = parseFloat(popularity);
            country    = country.toUpperCase();
            var result = [];

            var usage = browserslist.usage[country];
            if ( !usage ) {
                usage = { };
                var data = require('caniuse-db/region-usage-json/' + country);
                for ( var i in data.data ) {
                    fillUsage(usage, i, data.data[i]);
                }
                browserslist.usage[country] = usage;
            }

            for ( var version in usage ) {
                if ( usage[version] > popularity ) {
                    result.push(version);
                }
            }

            return result;
        }
    },

    versions: {
        regexp: /^(\w+) (>=?|<=?)\s*([\d\.]+)/,
        select: function (name, sign, version) {
            var data = browserslist.byName(name);
            version  = parseFloat(version);

            var filter;
            if ( sign == '>' ) {
                filter = function (v) {
                    return parseFloat(v) > version;
                };
            } else if ( sign == '>=' ) {
                filter = function (v) {
                    return parseFloat(v) >= version;
                };
            } else if ( sign == '<' ) {
                filter = function (v) {
                    return parseFloat(v) < version;
                };
            } else if ( sign == '<=' ) {
                filter = function (v) {
                    return parseFloat(v) <= version;
                };
            }

            return data.released.filter(filter).map(function (v) {
                return data.name + ' ' + v;
            });
        }
    },

    esr: {
        regexp: /^(firefox|ff|fx) esr$/i,
        select: function (versions) {
            return ['firefox 31'];
        }
    },

    direct: {
        regexp: /^(\w+) ([\d\.]+)$/,
        select: function (name, version) {
            var data = browserslist.byName(name);
            if ( data.versions.indexOf(version) == -1 ) {
                throw 'Unknown version ' + version + ' of ' + name;
            }

            return [data.name + ' ' + version];
        }
    }

};

// Get and convert Can I Use data

var normalizeVersion = function (version) {
    var interval = version.split('-');
    return interval[interval.length - 1];
};

var normalize = function (versions) {
    return versions
        .filter(function (version) {
            return typeof(version) == 'string';
        })
        .map(normalizeVersion);
};

var fillUsage = function (result, name, data) {
    for ( var i in data ) {
        result[name + ' ' + normalizeVersion(i)] = data[i];
    }
};

for ( var name in caniuse ) {
    browserslist.data[name] = {
        name:     name,
        versions: normalize(caniuse[name].versions),
        released: normalize(caniuse[name].versions.slice(0, -3))
    };
    fillUsage(browserslist.usage.global, name, caniuse[name].usage_global);
}

module.exports = browserslist;


text:
package com.saasquatch.jsonschemainferrer;

import java.util.HashSet;
import java.util.Set;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;

public final class TestJunkDrawer {

  private TestJunkDrawer() {}

  public static final JsonNodeFactory jnf = JsonNodeFactory.instance;
  public static final ObjectMapper mapper = new ObjectMapper();

  public static Set<String> toStringSet(JsonNode arrayNode) {
    final Set<String> result = new HashSet<>();
    arrayNode.forEach(j -> result.add(j.textValue()));
    return result;
  }

}


text:
module Rebase.GHC.IO.Encoding.UTF16
(
  module GHC.IO.Encoding.UTF16
)
where

import GHC.IO.Encoding.UTF16


text:
#if !defined(CETTY_CHANNEL_SOCKET_ASIO_ASIODATAGRAMPIPELINESINK_H)
#define CETTY_CHANNEL_SOCKET_ASIO_ASIODATAGRAMPIPELINESINK_H

/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 * Distributed under under the Apache License, version 2.0 (the "License").
 */

#include "cetty/channel/AbstractChannelSink.h"

namespace cetty { namespace channel {
class ChannelFuture;
class SocketAddress;
}}

namespace cetty { namespace channel { namespace socket { namespace asio {

using namespace cetty::channel;

class AsioDatagramChannel;
class AsioServicePool;

/**
 * Receives downstream events from a {@link ChannelPipeline}.  It contains
 * an array of I/O workers.
 *
 *
 * @author Trustin Lee
 * @author Daniel Bevenius (dbevenius@jboss.com)
 *
 * @author Frankee Zhou
 */
class AsioDatagramPipelineSink : public cetty::channel::AbstractChannelSink {
public:
    /**
     * Creates a new {@link NioDatagramPipelineSink} with a the number of {@link NioDatagramWorker}s specified in workerCount.
     * The {@link NioDatagramWorker}s take care of reading and writing for the {@link NioDatagramChannel}.
     *
     * @param workerExecutor
     *        the {@link Executor} that will run the {@link NioDatagramWorker}s
     *        for this sink
     * @param workerCount
     *        the number of {@link NioDatagramWorker}s for this sink
     */
    AsioDatagramPipelineSink(AsioServicePool& servicePool)
        : ioServicePool(servicePool) {
    }

    /**
     * Handle downstream MessageEvent.
     *
     * @param pipeline the {@link ChannelPipeline} that passes down the
     *                 downstream event.
     * @param e The MessageEvent.
     */
    virtual void writeRequested(const cetty::channel::ChannelPipeline& pipeline,
                                const cetty::channel::MessageEvent& e);

    /**
     * Handle downstream ChannelStateEvent.
     *
     * @param pipeline the {@link ChannelPipeline} that passes down the
     *                 downstream event.
     * @param e The ChannelStateEvent.
     */
    virtual void stateChangeRequested(const cetty::channel::ChannelPipeline& pipeline,
                                      const cetty::channel::ChannelStateEvent& e);

private:
    void handleStateChange(AsioDatagramChannel& channel, const ChannelStateEvent& evt);

    void close(AsioDatagramChannel& channel,
               const ChannelFuturePtr& future);

    void bind(AsioDatagramChannel& channel,
              const ChannelFuturePtr& future,
              const SocketAddress& address);

    void connect(AsioDatagramChannel& channel,
                 const ChannelFuturePtr& future,
                 const SocketAddress& remoteAddress);

    void startChannel(AsioDatagramChannel &channel);

private:
    int ioThreadCount;
    AsioServicePool& ioServicePool;
};

}}}}

#endif //#if !defined(CETTY_CHANNEL_SOCKET_ASIO_ASIODATAGRAMPIPELINESINK_H)


text:
package com.github.droibit.plugin.rxjava.postfix.example;

import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.Single;

import java.util.Arrays;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        final List<String> textList = Arrays.asList("a", "b", "c");
        Observable.fromIterable(textList)
                .forEach(System.out::println);
        Flowable.fromIterable(textList)
                .forEach(System.out::println);

        final String[] textArray = {"a", "b", "c"};
        Observable.fromArray(textArray)
                .forEach(System.out::println);
        Flowable.fromArray(textArray)
                .forEach(System.out::println);

        final String text = "text";
        Observable.just(text)
                .forEach(System.out::println);
        Flowable.just(text)
                .forEach(System.out::println);

        Observable.error(new RuntimeException())
                .subscribe();

        Single.error(new RuntimeException())
                .subscribe();

        Flowable.error(new RuntimeException())
                .subscribe();
    }
}


text:
using Gacho.MvpVm.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
#if NET45 || NET40
using System.Linq;
using System.Threading.Tasks;
#endif
using System.Text;
using System.Web.UI;
using System.Web;

namespace Gacho.MvpVm.WebForms
{
    public abstract class PageView<TModel, TPresenter> : Page, IView<TModel, TPresenter>
        where TModel : class, IViewModel, new()
        where TPresenter : class, IPresenter<TModel>
    {
        private TModel model;

#if NET45 || NET40

        public virtual TModel Model
        {
            get
            {
                if (this.model == null)
                {
                    throw new InvalidOperationException("Model cannot be null.");
                }

                return this.model;
            }

            set
            {
                this.model = value;
                this.RegisterToViewModel();
            }
        }
#elif NET20
        public virtual TModel Model
        {
            get
            {
                if (this.model == null)
                {
                    throw new InvalidOperationException("Model cannot be null.");
                }

                return this.model;
            }

            set
            {
                this.model = value;
                ViewModelRegistration.RegisterToViewModel(this);
            }
        }
#endif

        private TPresenter presenter;

        public TPresenter Presenter
        {
            get
            {
                if (this.presenter == null)
                {
                    this.presenter = BuildPresenter();
                }

                return this.presenter;
            }
        }

        protected abstract TPresenter BuildPresenter();

        protected virtual TModel CreateViewModelInstance()
        {
            return new TModel();
        }

        protected override void FrameworkInitialize()
        {
            base.FrameworkInitialize();
            this.Model = this.CreateViewModelInstance();
        }

#if NET45
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.Page.IsAsync)
            {
                this.Page.RegisterAsyncTask(new PageAsyncTask(() => this.Presenter.InitializeAsync(this.Model)));
            }
            else
            {
                this.Presenter.InitializeAsync(this.Model).Wait();
            }
        }
#elif NET40
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.Page.IsAsync)
            {
                this.Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(this.BeginInitializeModel), new EndEventHandler(this.EndInitializeModel), null, null, true));
            }
            else
            {
                this.Presenter.InitializeAsync(this.Model).Wait();
            }
        }

        private IAsyncResult BeginInitializeModel(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            return this.Presenter.InitializeAsync(this.Model);
        }

        private void EndInitializeModel(IAsyncResult ar)
        {
            ((Task)ar).Wait();
        }
#else
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (this.Page.IsAsync)
            {
                this.Page.RegisterAsyncTask(new PageAsyncTask(new BeginEventHandler(this.BeginInitializeModel), new EndEventHandler(this.EndInitializeModel), null, null, true));
            }
            else
            {
                this.Presenter.Initialize(this.Model);
            }
        }

        private IAsyncResult BeginInitializeModel(object sender, EventArgs e, AsyncCallback cb, object extraData)
        {
            var del = new InitializeDelegate<TModel>(this.Presenter.Initialize);
            return del.BeginInvoke(this.Model, null, null);
        }

        private void EndInitializeModel(IAsyncResult ar)
        {
            var del = (InitializeDelegate<TModel>)ar.AsyncState;
            del.EndInvoke(ar);
        }
#endif

        protected override void OnUnload(EventArgs e)
        {
            base.OnUnload(e);
            this.Presenter.Dispose();
        }
    }
}


text:
import '../test/assert';
import '../test/async_hooks';
import '../test/child_process';
import '../test/cluster';
import '../test/constants';
import '../test/crypto';
import '../test/dgram';
import '../test/diagnostic_channel';
import '../test/dns';
import '../test/events';
import '../test/fs';
import '../test/global';
import '../test/globals';
import '../test/http';
import '../test/http2';
import '../test/https';
import '../test/module';
import '../test/net';
import '../test/os';
import '../test/path';
import '../test/perf_hooks';
import '../test/process';
import '../test/readline';
import '../test/repl';
import '../test/stream';
import '../test/timers';
import '../test/timers_promises';
import '../test/string_decoder';
import '../test/tls';
import '../test/tty';
import '../test/util';
import '../test/util_types';
import '../test/v8';
import '../test/vm';
import '../test/wasi';
import '../test/worker_threads';
import '../test/zlib';

import * as fs from 'fs';
import * as console2 from 'console';
import * as inspector from 'inspector';
import * as trace_events from 'trace_events';

/////////////////////////////////////////////////////
/// WASI tests : https://nodejs.org/api/wasi.html ///
/////////////////////////////////////////////////////

import { WASI } from 'wasi';

const wasi = new WASI({
  args: process.argv,
  env: process.env,
  preopens: {
    '/sandbox': '/some/real/path/that/wasm/can/access'
  },
  returnOnExit: false,
});
const importObject = { wasi_unstable: wasi.wasiImport };
(async () => {
  const wasm = await WebAssembly.compile(Buffer.from('dummy'));
  const instance = await WebAssembly.instantiate(wasm, importObject);
  wasi.start(instance);
})();

/////////////////////////////////////////////////////////
/// Errors Tests : https://nodejs.org/api/errors.html ///
/////////////////////////////////////////////////////////

{
    {
        Error.stackTraceLimit = Infinity;
    }
    {
        const myObject = {};
        Error.captureStackTrace(myObject);
    }
    {
        const frames: NodeJS.CallSite[] = [];
        Error.prepareStackTrace!(new Error(), frames);
    }
    {
        const frame: NodeJS.CallSite = null!;
        const frameThis: any = frame.getThis();
        const typeName: string | null  = frame.getTypeName();
        const func: Function | undefined  = frame.getFunction();
        const funcName: string | null = frame.getFunctionName();
        const meth: string | null  = frame.getMethodName();
        const fname: string | null  = frame.getFileName();
        const lineno: number | null  = frame.getLineNumber();
        const colno: number | null  = frame.getColumnNumber();
        const evalOrigin: string | undefined  = frame.getEvalOrigin();
        const isTop: boolean = frame.isToplevel();
        const isEval: boolean = frame.isEval();
        const isNative: boolean = frame.isNative();
        const isConstr: boolean = frame.isConstructor();
    }
}

///////////////////////////////////////////////////////////
/// Console Tests : https://nodejs.org/api/console.html ///
///////////////////////////////////////////////////////////

{
    {
        let _c: Console = console;
        _c = console2;
    }
    {
        const writeStream = fs.createWriteStream('./index.d.ts');
        let consoleInstance: Console = new console.Console(writeStream);

        consoleInstance = new console.Console(writeStream, writeStream);
        consoleInstance = new console.Console(writeStream, writeStream, true);
        consoleInstance = new console.Console({
            stdout: writeStream,
            stderr: writeStream,
            colorMode: 'auto',
            ignoreErrors: true
        });
        consoleInstance = new console.Console({
            stdout: writeStream,
            colorMode: false
        });
        consoleInstance = new console.Console({
            stdout: writeStream
        });
    }
    {
        console.assert('value');
        console.assert('value', 'message');
        console.assert('value', 'message', 'foo', 'bar');
        console.clear();
        console.count();
        console.count('label');
        console.countReset();
        console.countReset('label');
        console.debug();
        console.debug('message');
        console.debug('message', 'foo', 'bar');
        console.dir('obj');
        console.dir('obj', { depth: 1 });
        console.error();
        console.error('message');
        console.error('message', 'foo', 'bar');
        console.group();
        console.group('label');
        console.group('label1', 'label2');
        console.groupCollapsed();
        console.groupEnd();
        console.info();
        console.info('message');
        console.info('message', 'foo', 'bar');
        console.log();
        console.log('message');
        console.log('message', 'foo', 'bar');
        console.table({ foo: 'bar' });
        console.table([{ foo: 'bar' }]);
        console.table([{ foo: 'bar' }], ['foo'] as ReadonlyArray<string>);
        console.time();
        console.time('label');
        console.timeEnd();
        console.timeEnd('label');
        console.timeLog();
        console.timeLog('label');
        console.timeLog('label', 'foo', 'bar');
        console.trace();
        console.trace('message');
        console.trace('message', 'foo', 'bar');
        console.warn();
        console.warn('message');
        console.warn('message', 'foo', 'bar');

        // --- Inspector mode only ---
        console.profile();
        console.profile('label');
        console.profileEnd();
        console.profileEnd('label');
        console.timeStamp();
        console.timeStamp('label');
    }
}

/*****************************************************************************
 *                                                                           *
 * The following tests are the modules not mentioned in document but existed *
 *                                                                           *
 *****************************************************************************/

///////////////////////////////////////////////////////////
/// Inspector Tests                                     ///
///////////////////////////////////////////////////////////

{
    {
        const b: inspector.Console.ConsoleMessage = {source: 'test', text: 'test', level: 'error' };
        inspector.open();
        inspector.open(0);
        inspector.open(0, 'localhost');
        inspector.open(0, 'localhost', true);
        inspector.close();
        const inspectorUrl: string | undefined = inspector.url();

        const session = new inspector.Session();
        session.connect();
        session.disconnect();

        // Unknown post method
        session.post('A.b', { key: 'value' }, (err, params) => {});
        // TODO: parameters are implicitly 'any' and need type annotation
        session.post('A.b', (err: Error | null, params?: {}) => {});
        session.post('A.b');
        // Known post method
        const parameter: inspector.Runtime.EvaluateParameterType = { expression: '2 + 2' };
        session.post('Runtime.evaluate', parameter,
            (err: Error | null, params: inspector.Runtime.EvaluateReturnType) => {});
        session.post('Runtime.evaluate', (err: Error, params: inspector.Runtime.EvaluateReturnType) => {
            const exceptionDetails: inspector.Runtime.ExceptionDetails = params.exceptionDetails!;
            const resultClassName: string = params.result.className!;
        });
        session.post('Runtime.evaluate');

        // General event
        session.on('inspectorNotification', message => {
            message; // $ExpectType InspectorNotification<{}>
        });
        // Known events
        session.on('Debugger.paused', (message: inspector.InspectorNotification<inspector.Debugger.PausedEventDataType>) => {
            const method: string = message.method;
            const pauseReason: string = message.params.reason;
        });
        session.on('Debugger.resumed', () => {});
        // Node Inspector events
        session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification<inspector.NodeTracing.DataCollectedEventDataType>) => {
          const value: Array<{}> = message.params.value;
        });
    }
}

///////////////////////////////////////////////////////////
/// Trace Events Tests                                  ///
///////////////////////////////////////////////////////////

{
    const enabledCategories: string | undefined = trace_events.getEnabledCategories();
    const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] });
    const categories: string = tracing.categories;
    const enabled: boolean = tracing.enabled;
    tracing.enable();
    tracing.disable();
}

////////////////////////////////////////////////////
/// Node.js ESNEXT Support
////////////////////////////////////////////////////

{
    const s = 'foo';
    const s1: string = s.trimLeft();
    const s2: string = s.trimRight();
    const s3: string = s.trimStart();
    const s4: string = s.trimEnd();
}