text:
from math import pi

import numpy as np
from numpy.linalg import norm
import openmc
import openmc.model
import pytest
import scipy.spatial

_RADIUS = 0.1
_PACKING_FRACTION = 0.35
_PARAMS = [
    {'shape': 'rectangular_prism', 'volume': 1**3},
    {'shape': 'x_cylinder', 'volume': 1*pi*1**2},
    {'shape': 'y_cylinder', 'volume': 1*pi*1**2},
    {'shape': 'z_cylinder', 'volume': 1*pi*1**2},
    {'shape': 'sphere', 'volume': 4/3*pi*1**3},
    {'shape': 'spherical_shell', 'volume': 4/3*pi*(1**3 - 0.5**3)}
]

@pytest.fixture(scope='module', params=_PARAMS)
def container(request):
    return request.param

@pytest.fixture(scope='module')
def centers(request, container):
    return request.getfixturevalue('centers_' + container['shape'])

@pytest.fixture(scope='module')
def centers_rectangular_prism():
    min_x = openmc.XPlane(0)
    max_x = openmc.XPlane(1)
    min_y = openmc.YPlane(0)
    max_y = openmc.YPlane(1)
    min_z = openmc.ZPlane(0)
    max_z = openmc.ZPlane(1)
    region = +min_x & -max_x & +min_y & -max_y & +min_z & -max_z
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def centers_x_cylinder():
    cylinder = openmc.XCylinder(r=1, y0=1, z0=2)
    min_x = openmc.XPlane(0)
    max_x = openmc.XPlane(1)
    region = +min_x & -max_x & -cylinder
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def centers_y_cylinder():
    cylinder = openmc.YCylinder(r=1, x0=1, z0=2)
    min_y = openmc.YPlane(0)
    max_y = openmc.YPlane(1)
    region = +min_y & -max_y & -cylinder
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def centers_z_cylinder():
    cylinder = openmc.ZCylinder(r=1, x0=1, y0=2)
    min_z = openmc.ZPlane(0)
    max_z = openmc.ZPlane(1)
    region = +min_z & -max_z & -cylinder
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def centers_sphere():
    sphere = openmc.Sphere(r=1, x0=1, y0=2, z0=3)
    region = -sphere
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def centers_spherical_shell():
    sphere = openmc.Sphere(r=1, x0=1, y0=2, z0=3)
    inner_sphere = openmc.Sphere(r=0.5, x0=1, y0=2, z0=3)
    region = -sphere & +inner_sphere
    return openmc.model.pack_spheres(radius=_RADIUS, region=region,
        pf=_PACKING_FRACTION, initial_pf=0.2)

@pytest.fixture(scope='module')
def triso_universe():
    sphere = openmc.Sphere(r=_RADIUS)
    cell = openmc.Cell(region=-sphere)
    univ = openmc.Universe(cells=[cell])
    return univ

def test_overlap(centers):
    """Check that none of the spheres in the packed configuration overlap."""
    # Create KD tree for quick nearest neighbor search
    tree = scipy.spatial.cKDTree(centers)

    # Find distance to nearest neighbor for all spheres
    d = tree.query(centers, k=2)[0]

    # Get the smallest distance between any two spheres
    d_min = min(d[:, 1])
    assert d_min > 2*_RADIUS or d_min == pytest.approx(2*_RADIUS)

def test_contained_rectangular_prism(centers_rectangular_prism):
    """Make sure all spheres are entirely contained within the domain."""
    d_max = np.amax(centers_rectangular_prism) + _RADIUS
    d_min = np.amin(centers_rectangular_prism) - _RADIUS
    assert d_max < 1 or d_max == pytest.approx(1)
    assert d_min > 0 or d_min == pytest.approx(0)

def test_contained_x_cylinder(centers_x_cylinder):
    """Make sure all spheres are entirely contained within the domain."""
    d = np.linalg.norm(centers_x_cylinder[:,[1,2]] - [1, 2], axis=1)
    r_max = max(d) + _RADIUS
    x_max = max(centers_x_cylinder[:,0]) + _RADIUS
    x_min = min(centers_x_cylinder[:,0]) - _RADIUS
    assert r_max < 1 or r_max == pytest.approx(1)
    assert x_max < 1 or x_max == pytest.approx(1)
    assert x_min > 0 or x_min == pytest.approx(0)

def test_contained_y_cylinder(centers_y_cylinder):
    """Make sure all spheres are entirely contained within the domain."""
    d = np.linalg.norm(centers_y_cylinder[:,[0,2]] - [1, 2], axis=1)
    r_max = max(d) + _RADIUS
    y_max = max(centers_y_cylinder[:,1]) + _RADIUS
    y_min = min(centers_y_cylinder[:,1]) - _RADIUS
    assert r_max < 1 or r_max == pytest.approx(1)
    assert y_max < 1 or y_max == pytest.approx(1)
    assert y_min > 0 or y_min == pytest.approx(0)

def test_contained_z_cylinder(centers_z_cylinder):
    """Make sure all spheres are entirely contained within the domain."""
    d = np.linalg.norm(centers_z_cylinder[:,[0,1]] - [1, 2], axis=1)
    r_max = max(d) + _RADIUS
    z_max = max(centers_z_cylinder[:,2]) + _RADIUS
    z_min = min(centers_z_cylinder[:,2]) - _RADIUS
    assert r_max < 1 or r_max == pytest.approx(1)
    assert z_max < 1 or z_max == pytest.approx(1)
    assert z_min > 0 or z_min == pytest.approx(0)

def test_contained_sphere(centers_sphere):
    """Make sure all spheres are entirely contained within the domain."""
    d = np.linalg.norm(centers_sphere - [1, 2, 3], axis=1)
    r_max = max(d) + _RADIUS
    assert r_max < 1 or r_max == pytest.approx(1)

def test_contained_spherical_shell(centers_spherical_shell):
    """Make sure all spheres are entirely contained within the domain."""
    d = np.linalg.norm(centers_spherical_shell - [1, 2, 3], axis=1)
    r_max = max(d) + _RADIUS
    r_min = min(d) - _RADIUS
    assert r_max < 1 or r_max == pytest.approx(1)
    assert r_min > 0.5 or r_min == pytest.approx(0.5)

def test_packing_fraction(container, centers):
    """Check that the actual PF is close to the requested PF."""
    pf = len(centers) * 4/3 * pi *_RADIUS**3 / container['volume']
    assert pf == pytest.approx(_PACKING_FRACTION, rel=1e-2)

def test_num_spheres():
    """Check that the function returns the correct number of spheres"""
    centers = openmc.model.pack_spheres(
        radius=_RADIUS, region=-openmc.Sphere(r=1), num_spheres=50
    )
    assert len(centers) == 50

def test_triso_lattice(triso_universe, centers_rectangular_prism):
    trisos = [openmc.model.TRISO(_RADIUS, triso_universe, c)
              for c in centers_rectangular_prism]

    lower_left = np.array((0, 0, 0))
    upper_right = np.array((1, 1, 1))
    shape = (3, 3, 3)
    pitch = (upper_right - lower_left)/shape
    background = openmc.Material()

    lattice = openmc.model.create_triso_lattice(
        trisos, lower_left, pitch, shape, background
    )

def test_container_input(triso_universe):
    # Invalid container shape
    with pytest.raises(ValueError):
        centers = openmc.model.pack_spheres(
            radius=_RADIUS, region=+openmc.Sphere(r=1), num_spheres=100
        )

def test_packing_fraction_input():
    # Provide neither packing fraction nor number of spheres
    with pytest.raises(ValueError):
        centers = openmc.model.pack_spheres(
            radius=_RADIUS, region=-openmc.Sphere(r=1)
        )

    # Specify a packing fraction that is too high for CRP
    with pytest.raises(ValueError):
        centers = openmc.model.pack_spheres(
            radius=_RADIUS, region=-openmc.Sphere(r=1), pf=1
        )

    # Specify a packing fraction that is too high for RSP
    with pytest.raises(ValueError):
        centers = openmc.model.pack_spheres(
            radius=_RADIUS, region=-openmc.Sphere(r=1), pf=0.5, initial_pf=0.4
        )


text:
require_relative '../../app/models/carto/analysis'
require_dependency 'carto/uuidhelper'
require 'helpers/unique_names_helper'

include UniqueNamesHelper

module AnalysisFactoryHelper
  def self.source_analysis_for_table(table_name, query)
    query ||= "select * from #{table_name}"
    {
      id:      unique_string,
      type:    'source',
      params:  { query: query },
      options: { table_name: table_name }
    }
  end
end

FactoryGirl.define do
  factory :source_analysis, class: Carto::Analysis do
    ignore do
      source_table 'subway_stops'
      query nil
    end

    analysis_definition { AnalysisFactoryHelper.source_analysis_for_table(source_table, query) }

    factory :analysis, class: Carto::Analysis do
      created_at { Time.now }
      updated_at { Time.now }
    end
  end

  factory :analysis_with_source, class: Carto::Analysis do
    ignore do
      source_table 'subway_stops'
      query nil
    end

    analysis_definition do
      {
        id: unique_string,
        type: "buffer",
        params: {
          source: AnalysisFactoryHelper.source_analysis_for_table(source_table, query)
        }
      }
    end
  end

  factory :analysis_point_in_polygon, class: Carto::Analysis do
    ignore do
      source_table 'subway_stops'
      source_query nil
      target_table 'districts'
      target_query nil
    end

    analysis_definition do
      {
        id: unique_string,
        type: "intersection",
        params: {
          source: AnalysisFactoryHelper.source_analysis_for_table(source_table, source_query),
          target: AnalysisFactoryHelper.source_analysis_for_table(target_table, target_query)
        }
      }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
.. _download:

Download the Native Client SDK
==============================

This page provides an overview of the Native Client SDK, and instructions for
downloading and installing the SDK.

.. raw:: html

  Download SDK Zip File

.. _sdk-overview:

Overview
--------

The Native Client SDK includes:

- **Support for multiple Pepper versions** to compile for specific minimum
  versions of Chrome.
- **Update utility** to download new bundles and updates to existing bundles.
- **Toolchains** to compile for Portable Native Client (PNaCl), traditional
  Native Client (NaCl), and for compiling architecture-specific Native Client
  applications with glibc.
- **Examples** Including C or C++ source files and header files illustrating
  how to use NaCl and Pepper, and Makefiles to build the example with each of
  the toolchains.
- **Tools** for validating Native Client modules and running modules from the
  command line.

Follow the steps below to download and install the Native Client SDK.

.. _prerequisites:

Prerequisites
-------------

.. _python27:

Python 2.7
^^^^^^^^^^

Make sure that the Python executable is in your ``PATH`` variable. Python 3.x is
not yet supported.

* On Mac and Linux, Python is likely preinstalled. Run the command ``python -V``
  in a terminal window, and make sure that the version you have is 2.7.x.
* On Windows, you may need to install Python. Go to `http://www.python.org/
  download/ <http://www.python.org/download/>`_ and select the latest 2.x
  version. In addition, be sure to add the Python directory (for example,
  ``C:\python27``) to the ``PATH`` `environment variable <http://en.wikipedia.
  org/wiki/Environment_variable>`_. Run ``python -V`` from a command line to
  verify that you properly configured the PATH variable.

.. _make:

Make
^^^^

* On the Mac, you need to install ``make`` on your system before you can build
  and run the examples in the SDK. One easy way to get ``make``, along with
  several other useful tools, is to install `Xcode Developer Tools
  <https://developer.apple.com/technologies/tools/>`_. After installing Xcode,
  go to the XCode menu, open the Preferences dialog box then select Downloads
  and Components. Verify that Command Line Tools are installed. If you'd rather
  not install Xcode, you can download and build an `open source version
  <http://mac.softpedia.com/dyn-postdownload.php?p=44632&t=4&i=1>`_ of ``make``.
  To build the program you may also need to download and install `gcc
  <https://github.com/kennethreitz/osx-gcc-installer>`_.
* On Windows, the Native Client SDK includes a copy of GNU Make.

.. _platforms:

Platforms
---------

Native Client supports several operating systems, including Windows, Linux, OSX,
and ChromeOS. It supports several architectures including on x86-32, x86-64,
ARM, and MIPS.

.. _versioning:

Versions
--------

Chrome is released on a six week cycle, and developer versions of Chrome are
pushed to the public beta channel three weeks before each release. As with any
software, each release of Chrome may include changes to Native Client and the
Pepper interfaces that may require modification to existing applications.
However, modules compiled for one version of Pepper/Chrome should work with
subsequent versions of Pepper/Chrome. The SDK includes multiple versions of the
Pepper APIs to help developers make adjustments to API changes and take
advantage of new features: `stable </native-client/pepper_stable>`_, `beta
</native-client/pepper_beta>`_ and `dev </native-client/pepper_dev>`_.

.. _installing-the-sdk:

Installing the SDK
------------------

.. _downloading-and-unzipping:

Downloading and Unzipping
^^^^^^^^^^^^^^^^^^^^^^^^^

#. Download the `SDK update zip file
   <http://storage.googleapis.com/nativeclient-mirror/nacl/nacl_sdk/nacl_sdk.zip>`_.

#. Unzip the file:

   * On Mac/Linux, run the command ``unzip nacl_sdk.zip`` in a terminal
     window.
   * On Windows, right-click on the .zip file and select "Extract All...". A
     dialog box opens; enter a location and click "Extract".

   A directory is created called ``nacl_sdk`` with the following files and
   directories:

   * ``naclsdk`` (and ``naclsdk.bat`` for Windows) --- the update utility,
     which is the command you run to download and update bundles.
   * ``sdk_cache`` --- a directory with a manifest file that lists the bundles
     you have already downloaded.
   * ``sdk_tools`` --- the code run by the ``naclsdk`` command.

.. _installing-the-stable-bundle:

Installing the stable bundle
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

#. To see the SDK bundles that are available for download, go to the
   ``nacl_sdk`` directory and run ``naclsdk`` with the ``list`` command. The SDK
   includes a separate bundle for each version of Chrome/Pepper.

   On Mac/Linux::

     $ cd nacl_sdk
     $ ./naclsdk list

   On Windows::

     > cd nacl_sdk
     > naclsdk list

   You should see output similar to this::

    Bundles:
     I: installed
     *: update available

      I  sdk_tools (stable)
         vs_addin (dev)
         pepper_31 (post_stable)
         pepper_32 (post_stable)
         pepper_33 (post_stable)
         pepper_34 (post_stable)
         pepper_35 (stable)
         pepper_36 (beta)
         pepper_37 (dev)
         pepper_canary (canary)
         bionic_canary (canary)

   The sample output above shows that several bundles are available for
   download, and that you have already installed the latest revision of the
   ``sdk_tools`` bundle, which was included in the zip file. You never need to
   update the ``sdk_tools`` bundle. It is updated automatically (if necessary)
   whenever you run ``naclsdk``.

   Bundles are labeled post-stable, stable, beta, dev, or canary. These labels
   usually correspond to the current versions of Chrome. We recommend that you
   develop against a "stable" bundle, because such bundles can be used by all
   current Chrome users. Native Client is designed to be backward-compatible.For
   example, applications developed with the ``pepper_37`` bundle can run in
   Chrome 37, Chrome 38, etc..

#. Run ``naclsdk`` with the ``update`` command to download recommended bundles,
   including the current "stable" bundle.

   On Mac/Linux::

     $ ./naclsdk update

   On Windows::

     > naclsdk update

   By default, ``naclsdk`` only downloads bundles that are recommended,
   generally those that are "stable." For example, if the current "stable"
   bundle is ``pepper_35``, then the ``update`` downloads that bundle. To
   download the ``pepper_36`` bundle you must ask for it explicitly::

     $ ./naclsdk update pepper_36

.. _updating-bundles:

Updating bundles
----------------

#. Run ``naclsdk`` with the ``list`` command. This shows you the list of available
   bundles and verifies which bundles you have installed.

   On Mac/Linux::

     $ ./naclsdk list

   On Windows::

     > naclsdk list

   An asterisk (*) next to a bundle indicates that there is an update available
   it. For example::

    Bundles:
     I: installed
     *: update available

      I  sdk_tools (stable)
         vs_addin (dev)
         pepper_31 (post_stable)
         pepper_32 (post_stable)
         pepper_33 (post_stable)
         pepper_34 (post_stable)
      I* pepper_35 (stable)
         pepper_36 (beta)
         pepper_37 (dev)
         pepper_canary (canary)
         bionic_canary (canary)

   If you run ``naclsdk update`` now, it warns you with a message similar to
   this::

     WARNING: pepper_35 already exists, but has an update available. Run update
     with the --force option to overwrite the existing directory. Warning: This
     will overwrite any modifications you have made within this directory.

#. To download and install the new bundle, run:

   On Mac/Linux::

     $ ./naclsdk update --force

   On Windows::

     > naclsdk update --force

.. _help-with-the-naclsdk-utility:

Help with the ``naclsdk`` utility
---------------------------------

#. For more information about the ``naclsdk`` utility, run:

   On Mac/Linux::

     $ ./naclsdk help

   On Windows::

     > naclsdk help

.. _next-steps:

Next steps
----------

* Browse the `Release Notes <release-notes>`_ for important
  information about the SDK and new bundles.
* If you're just starting with Native Client, we recommend reading the
  `Technical Overview <../overview>`_ and walking through the
  `Getting Started Tutorial <devguide/tutorial/tutorial-part1>`_.
* If you'd rather dive in, see
  `Building Native Client Modules <devguide/devcycle/building>`_.


text:
package org.apache.hadoop.hdfs.server.federation.router;

import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.fs.CacheFlag;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.BatchedRemoteIterator.BatchedEntries;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveEntry;
import org.apache.hadoop.hdfs.protocol.CacheDirectiveInfo;
import org.apache.hadoop.hdfs.protocol.CachePoolEntry;
import org.apache.hadoop.hdfs.protocol.CachePoolInfo;
import org.apache.hadoop.hdfs.server.federation.resolver.ActiveNamenodeResolver;
import org.apache.hadoop.hdfs.server.federation.resolver.FederationNamespaceInfo;
import org.apache.hadoop.hdfs.server.federation.resolver.RemoteLocation;
import org.apache.hadoop.hdfs.server.namenode.NameNode;

/**
 * Module that implements all the RPC calls in
 * {@link org.apache.hadoop.hdfs.protocol.ClientProtocol} related to Cache Admin
 * in the {@link RouterRpcServer}.
 */
public class RouterCacheAdmin {

  /** RPC server to receive client calls. */
  private final RouterRpcServer rpcServer;
  /** RPC clients to connect to the Namenodes. */
  private final RouterRpcClient rpcClient;
  /** Interface to identify the active NN for a nameservice or blockpool ID. */
  private final ActiveNamenodeResolver namenodeResolver;

  public RouterCacheAdmin(RouterRpcServer server) {
    this.rpcServer = server;
    this.rpcClient = this.rpcServer.getRPCClient();
    this.namenodeResolver = this.rpcClient.getNamenodeResolver();
  }

  public long addCacheDirective(CacheDirectiveInfo path,
      EnumSet<CacheFlag> flags) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    final List<RemoteLocation> locations =
        rpcServer.getLocationsForPath(path.getPath().toString(), true, false);
    RemoteMethod method = new RemoteMethod("addCacheDirective",
        new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class},
        new RemoteParam(getRemoteMap(path, locations)), flags);
    Map<RemoteLocation, Long> response =
        rpcClient.invokeConcurrent(locations, method, false, false, long.class);
    return response.values().iterator().next();
  }

  public void modifyCacheDirective(CacheDirectiveInfo directive,
      EnumSet<CacheFlag> flags) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    Path p = directive.getPath();
    if (p != null) {
      final List<RemoteLocation> locations = rpcServer
          .getLocationsForPath(directive.getPath().toString(), true, false);
      RemoteMethod method = new RemoteMethod("modifyCacheDirective",
          new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class},
          new RemoteParam(getRemoteMap(directive, locations)), flags);
      rpcClient.invokeConcurrent(locations, method);
      return;
    }
    RemoteMethod method = new RemoteMethod("modifyCacheDirective",
        new Class<?>[] {CacheDirectiveInfo.class, EnumSet.class}, directive,
        flags);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    rpcClient.invokeConcurrent(nss, method, false, false);
  }

  public void removeCacheDirective(long id) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    RemoteMethod method = new RemoteMethod("removeCacheDirective",
        new Class<?>[] {long.class}, id);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    rpcClient.invokeConcurrent(nss, method, false, false);
  }

  public BatchedEntries<CacheDirectiveEntry> listCacheDirectives(long prevId,
      CacheDirectiveInfo filter) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.READ, true);
    if (filter.getPath() != null) {
      final List<RemoteLocation> locations = rpcServer
          .getLocationsForPath(filter.getPath().toString(), true, false);
      RemoteMethod method = new RemoteMethod("listCacheDirectives",
          new Class<?>[] {long.class, CacheDirectiveInfo.class}, prevId,
          new RemoteParam(getRemoteMap(filter, locations)));
      Map<RemoteLocation, BatchedEntries> response = rpcClient.invokeConcurrent(
          locations, method, false, false, BatchedEntries.class);
      return response.values().iterator().next();
    }
    RemoteMethod method = new RemoteMethod("listCacheDirectives",
        new Class<?>[] {long.class, CacheDirectiveInfo.class}, prevId,
        filter);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    Map<FederationNamespaceInfo, BatchedEntries> results = rpcClient
        .invokeConcurrent(nss, method, true, false, BatchedEntries.class);
    return results.values().iterator().next();
  }

  public void addCachePool(CachePoolInfo info) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    RemoteMethod method = new RemoteMethod("addCachePool",
        new Class<?>[] {CachePoolInfo.class}, info);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    rpcClient.invokeConcurrent(nss, method, true, false);
  }

  public void modifyCachePool(CachePoolInfo info) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    RemoteMethod method = new RemoteMethod("modifyCachePool",
        new Class<?>[] {CachePoolInfo.class}, info);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    rpcClient.invokeConcurrent(nss, method, true, false);
  }

  public void removeCachePool(String cachePoolName) throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.WRITE, true);
    RemoteMethod method = new RemoteMethod("removeCachePool",
        new Class<?>[] {String.class}, cachePoolName);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    rpcClient.invokeConcurrent(nss, method, true, false);
  }

  public BatchedEntries<CachePoolEntry> listCachePools(String prevKey)
      throws IOException {
    rpcServer.checkOperation(NameNode.OperationCategory.READ, true);
    RemoteMethod method = new RemoteMethod("listCachePools",
        new Class<?>[] {String.class}, prevKey);
    Set<FederationNamespaceInfo> nss = namenodeResolver.getNamespaces();
    Map<FederationNamespaceInfo, BatchedEntries> results = rpcClient
        .invokeConcurrent(nss, method, true, false, BatchedEntries.class);
    return results.values().iterator().next();
  }

  /**
   * Returns a map with the CacheDirectiveInfo mapped to each location.
   * @param path CacheDirectiveInfo to be mapped to the locations.
   * @param locations the locations to map.
   * @return map with CacheDirectiveInfo mapped to the locations.
   */
  private Map<RemoteLocation, CacheDirectiveInfo> getRemoteMap(
      CacheDirectiveInfo path, final List<RemoteLocation> locations) {
    final Map<RemoteLocation, CacheDirectiveInfo> dstMap = new HashMap<>();
    Iterator<RemoteLocation> iterator = locations.iterator();
    while (iterator.hasNext()) {
      dstMap.put(iterator.next(), path);
    }
    return dstMap;
  }
}


text:
declare function dispatch_introspection_hook_queue_callout_begin(queue: NSObject, context: interop.Pointer | interop.Reference<any>, _function: interop.FunctionReference<(p1: interop.Pointer | interop.Reference<any>) => void>): void;

declare function dispatch_introspection_hook_queue_callout_end(queue: NSObject, context: interop.Pointer | interop.Reference<any>, _function: interop.FunctionReference<(p1: interop.Pointer | interop.Reference<any>) => void>): void;

declare function dispatch_introspection_hook_queue_create(queue: NSObject): void;

declare function dispatch_introspection_hook_queue_destroy(queue: NSObject): void;

declare function dispatch_introspection_hook_queue_item_complete(item: NSObject): void;

declare function dispatch_introspection_hook_queue_item_dequeue(queue: NSObject, item: NSObject): void;

declare function dispatch_introspection_hook_queue_item_enqueue(queue: NSObject, item: NSObject): void;


text:
"use strict";

var setup = require("./setup");
var db = require("../index");
var expect = require("chai").expect;
var DbUtil = require("./db-util");
var util = require("./util");
var conti = require("conti");
var m = require("./model");

var initDb = util.createClearTableFun(["hoken_koukikourei"]);

function mkHoken(patientId, validFrom, validUpto){
	return m.koukikourei({patient_id: patientId, valid_from: validFrom, valid_upto: validUpto});
}

describe("Testing available koukikourei", function(){
	var conn;

	beforeEach(initDb);

	beforeEach(function(done){
		setup.connect(function(err, conn_){
			if( err ){
				done(err);
				return;
			}
			conn = conn_;
			done();
		})
	});

	afterEach(function(done){
		setup.release(conn, done);
	});

	afterEach(initDb);

	var valid_from = "2016-04-01";
	var at = "2016-06-26 21:35:21";
	var valid_upto = "2018-03-31";
	var valid_upto_no_limit = "0000-00-00";

	it("empty", function(done){
		db.listAvailableShahokokuho(conn, 1, at, function(err, result){
			if( err ){
				done(err);
				return;
			}
			expect(result).eql([]);
			done();
		})
	});

	it("simple", function(done){
		var patientId = 2000;
		var shaho = mkHoken(patientId, valid_from, valid_upto);
		shaho.save(conn, function(err){
			db.listAvailableKoukikourei(conn, patientId, at, function(err, result){
				if( err ){
					done(err);
					return;
				}
				expect(result).eql([shaho.data]);
				done();
			})
		})
	});

	it("with out of date", function(done){
		var patientId = 2000;
		var prev = mkHoken(patientId, "2016-01-01", "2016-03-31");
		var curr = mkHoken(patientId, "2016-04-01", "2017-03-31");
		m.batchSave(conn, [prev, curr], function(err){
			db.listAvailableKoukikourei(conn, patientId, at, function(err, result){
				if( err ){
					done(err);
					return;
				}
				expect(result).eql([curr.data]);
				done();
			})
		});
	})

	it("multiple", function(done){
		var patientId = 2000;
		var prev = mkHoken(patientId, "2016-01-01", "2016-03-31");
		var curr = mkHoken(patientId, "2016-04-01", "2017-03-31");
		var curr2 = mkHoken(patientId, "2016-04-01", "0000-00-00");
		m.batchSave(conn, [prev, curr, curr2], function(err){
			db.listAvailableKoukikourei(conn, patientId, at, function(err, result){
				if( err ){
					done(err);
					return;
				}
				expect(result).eql([curr.data, curr2.data]);
				done();
			})
		});
	})
})


text:
REST API Version History
========================

This documents the changes made to the REST API with every
microversion change. The description for each version should be a
verbose one which has enough information to be suitable for use in
user documentation.

2.1
---

  This is the initial version of the v2.1 API which supports
  microversions. The V2.1 API is from the REST API users's point of
  view exactly the same as v2.0 except with strong input validation.

  A user can specify a header in the API request::

    X-OpenStack-Nova-API-Version: <version>

  where ``<version>`` is any valid api version for this API.

  If no version is specified then the API will behave as if a version
  request of v2.1 was requested.

2.2
---

  Added Keypair type.

  A user can request the creation of a certain 'type' of keypair (``ssh`` or ``x509``)
  in the ``os-keypairs`` plugin

  If no keypair type is specified, then the default ``ssh`` type of keypair is
  created.

  Fixes status code for ``os-keypairs`` create method from 200 to 201

  Fixes status code for ``os-keypairs`` delete method from 202 to 204

2.3 (Maximum in Kilo)
---------------------

  Exposed additional attributes in ``os-extended-server-attributes``:
  ``reservation_id``, ``launch_index``, ``ramdisk_id``, ``kernel_id``, ``hostname``,
  ``root_device_name``, ``userdata``.

  Exposed ``delete_on_termination`` for ``volumes_attached`` in ``os-extended-volumes``.

  This change is required for the extraction of EC2 API into a standalone
  service. It exposes necessary properties absent in public nova APIs yet.
  Add info for Standalone EC2 API to cut access to Nova DB.

2.4
---

  Show the ``reserved`` status on a ``FixedIP`` object in the ``os-fixed-ips`` API
  extension. The extension allows one to ``reserve`` and ``unreserve`` a fixed IP
  but the show method does not report the current status.

2.5
---

  Before version 2.5, the command ``nova list --ip6 xxx`` returns all servers
  for non-admins, as the filter option is silently discarded. There is no
  reason to treat ip6 different from ip, though, so we just add this
  option to the allowed list.

2.6
---

  A new API for getting remote console is added::

    POST /servers/<uuid>/remote-consoles
    {
      "remote_console": {
        "protocol": ["vnc"|"rdp"|"serial"|"spice"],
        "type": ["novnc"|"xpvnc"|"rdp-html5"|"spice-html5"|"serial"]
      }
    }

  Example response::

    {
      "remote_console": {
        "protocol": "vnc",
        "type": "novnc",
        "url": "http://example.com:6080/vnc_auto.html?token=XYZ"
      }
    }

  The old APIs 'os-getVNCConsole', 'os-getSPICEConsole', 'os-getSerialConsole'
  and 'os-getRDPConsole' are removed.

2.7
---

  Check the ``is_public`` attribute of a flavor before adding tenant access
  to it. Reject the request with HTTPConflict error.

2.8
---
  Add 'mks' protocol and 'webmks' type for remote consoles.

2.9
---

  Add a new ``locked`` attribute to the detailed view, update,
  and rebuild action. ``locked`` will be ``true`` if anyone is currently holding
  a lock on the server, ``false`` otherwise.

2.10
----

  Added user_id parameter to os-keypairs plugin, as well as a new property
  in the request body, for the create operation.

  Administrators will be able to list, get details and delete keypairs owned by
  users other than themselves and to create new keypairs on behalf of their
  users.

2.11
----

  Exposed attribute ``forced_down`` for ``os-services``.
  Added ability to change the ``forced_down`` attribute by calling an update.

2.12 (Maximum in Liberty)
-------------------------

  Exposes VIF ``net_id`` attribute in ``os-virtual-interfaces``.
  User will be able to get Virtual Interfaces ``net_id`` in Virtual Interfaces
  list and can determine in which network a Virtual Interface is plugged into.

2.13
----

  Add information ``project_id`` and ``user_id`` to ``os-server-groups``
  API response data.

2.14
----

  Remove ``onSharedStorage`` parameter from server's evacuate action. Nova will
  automatically detect if the instance is on shared storage.
  Also adminPass is removed from the response body. The user can get the
  password with the server's os-server-password action.

2.15
----

  From this version of the API users can choose 'soft-affinity' and
  'soft-anti-affinity' rules too for server-groups.

2.16
----

  Exposes new host_status attribute for servers/detail and servers/{server_id}.
  Ability to get nova-compute status when querying servers. By default, this is
  only exposed to cloud administrators.

2.17
----

  Add a new API for triggering crash dump in an instance. Different operation
  systems in instance may need different configurations to trigger crash dump.

2.18
----
  Establishes a set of routes that makes project_id an optional construct in v2.1.

2.19
----
  Allow the user to set and get the server description.
  The user will be able to set the description when creating, rebuilding,
  or updating a server, and get the description as part of the server details.

2.20
----
  From this version of the API user can call detach and attach volumes for
  instances which are in shelved and shelved_offloaded state.

2.21
----

  The ``os-instance-actions`` API now returns information from deleted
  instances.

2.22
----

  A new resource servers:migrations added. A new API to force live migration
  to complete added::

    POST /servers/<uuid>/migrations/<id>/action
    {
      "force_complete": null
    }

2.23
----

  From this version of the API users can get the migration summary list by
  index API or the information of a specific migration by get API.
  And the old top-level resource `/os-migrations` won't be extended anymore.
  Add migration_type for old /os-migrations API, also add ref link to the
  /servers/{uuid}/migrations/{id} for it when the migration is an in-progress
  live-migration.

2.24
----

  A new API call to cancel a running live migration::

    DELETE /servers/<uuid>/migrations/<id>

2.25 (Maximum in Mitaka)
------------------------

  Modify input parameter for ``os-migrateLive``. The block_migration will
  support 'auto' value, and disk_over_commit flag will be removed.

2.26
----

  Added support of server tags.

  A user can create, update, delete or check existence of simple string tags
  for servers by the os-server-tags plugin.

  The resource point for these operations is /servers/<server_id>/tags

  A user can add a single tag to the server by sending PUT request to the
  /servers/<server_id>/tags/<tag>

  where <tag> is any valid tag name.

  A user can replace **all** current server tags to the new set of tags
  by sending PUT request to the /servers/<server_id>/tags. New set of tags
  must be specified in request body. This set must be in list 'tags'.

  A user can remove specified tag from the server by sending DELETE request
  to the /servers/<server_id>/tags/<tag>

  where <tag> is tag name which user wants to remove.

  A user can remove **all** tags from the server by sending DELETE request
  to the /servers/<server_id>/tags

  A user can get a set of server tags with information about server by sending
  GET request to the /servers/<server_id>

  Request returns dictionary with information about specified server, including
  list 'tags' ::

      {
          'id': {server_id},
          ...
          'tags': ['foo', 'bar', 'baz']
      }

  A user can get **only** a set of server tags by sending GET request to the
  /servers/<server_id>/tags

  Response ::

      {
         'tags': ['foo', 'bar', 'baz']
      }

  A user can check if a tag exists or not on a server by sending
  GET /servers/{server_id}/tags/{tag}

  Request returns `204 No Content` if tag exist on a server or `404 Not Found`
  if tag doesn't exist on a server.

  A user can filter servers in GET /servers request by new filters:

  * tags
  * tags-any
  * not-tags
  * not-tags-any

  These filters can be combined. Also user can use more than one string tags
  for each filter. In this case string tags for each filter must be separated
  by comma: GET /servers?tags=red&tags-any=green,orange

2.27
----

  Added support for the new form of microversion headers described in the
  `Microversion Specification
  <http://specs.openstack.org/openstack/api-wg/guidelines/microversion_specification.html>`_.
  Both the original form of header and the new form is supported.

2.28
----

  Nova API hypervisor.cpu_info change from string to JSON object.

  From this version of the API the hypervisor's 'cpu_info' field will be
  will returned as JSON object (not string) by sending GET request
  to the /v2.1/os-hypervisors/{hypervisor_id}.

2.29
----

  Updates the POST request body for the ``evacuate`` action to include the
  optional ``force`` boolean field defaulted to False.
  Also changes the evacuate action behaviour when providing a ``host`` string
  field by calling the nova scheduler to verify the provided host unless the
  ``force`` attribute is set.

2.30
----

  Updates the POST request body for the ``live-migrate`` action to include the
  optional ``force`` boolean field defaulted to False.
  Also changes the live-migrate action behaviour when providing a ``host``
  string field by calling the nova scheduler to verify the provided host unless
  the ``force`` attribute is set.

2.31
----

  Fix os-console-auth-tokens to return connection info for all types of tokens,
  not just RDP.

2.32
----

  Adds an optional, arbitrary 'tag' item to the 'networks' item in the server
  boot request body. In addition, every item in the block_device_mapping_v2
  array can also have an optional, arbitrary 'tag' item. These tags are used to
  identify virtual device metadata, as exposed in the metadata API and on the
  config drive. For example, a network interface on the virtual PCI bus tagged
  with 'nic1' will appear in the metadata along with its bus (PCI), bus address
  (ex: 0000:00:02.0), MAC address, and tag ('nic1').

2.33
----

  Support pagination for hypervisor by accepting limit and marker from the GET
  API request::

    GET /v2.1/{tenant_id}/os-hypervisors?marker={hypervisor_id}&limit={limit}

2.34
----

  Checks in ``os-migrateLive`` before live-migration actually starts are now
  made in background. ``os-migrateLive`` is not throwing `400 Bad Request` if
  pre-live-migration checks fail.

2.35
----

  Added pagination support for keypairs.

  Optional parameters 'limit' and 'marker' were added to GET /os-keypairs
  request, the default sort_key was changed to 'name' field as ASC order,
  the generic request format is::

    GET /os-keypairs?limit={limit}&marker={kp_name}

2.36
----

  All the APIs which proxy to another service were deprecated in this version,
  also the fping API. Those APIs will return 404 with Microversion 2.36. The
  network related quotas and limits are removed from API also. The deprecated
  API endpoints as below::

    '/images'
    '/os-networks'
    '/os-tenant-networks'
    '/os-fixed-ips'
    '/os-floating-ips'
    '/os-floating-ips-bulk'
    '/os-floating-ip-pools'
    '/os-floating-ip-dns'
    '/os-security-groups'
    '/os-security-group-rules'
    '/os-security-group-default-rules'
    '/os-volumes'
    '/os-snapshots'
    '/os-baremetal-nodes'
    '/os-fping'

2.37
----

  Added support for automatic allocation of networking, also known as "Get Me a
  Network". With this microversion, when requesting the creation of a new
  server (or servers) the ``networks`` entry in the ``server`` portion of the
  request body is required. The ``networks`` object in the request can either
  be a list or an enum with values:

  #. *none* which means no networking will be allocated for the created
     server(s).
  #. *auto* which means either a network that is already available to the
     project will be used, or if one does not exist, will be automatically
     created for the project. Automatic network allocation for a project only
     happens once for a project. Subsequent requests using *auto* for the same
     project will reuse the network that was previously allocated.

  Also, the ``uuid`` field in the ``networks`` object in the server create
  request is now strictly enforced to be in UUID format.

2.38 (Maximum in Newton)
------------------------

  Before version 2.38, the command ``nova list --status invalid_status`` was
  returning empty list for non admin user and 500 InternalServerError for admin
  user. As there are sufficient statuses defined already, any invalid status
  should not be accepted. From this version of the API admin as well as non
  admin user will get 400 HTTPBadRequest if invalid status is passed to nova
  list command.

2.39
----

  Deprecates image-metadata proxy API that is just a proxy for Glance API
  to operate the image metadata. Also removes the extra quota enforcement with
  Nova `metadata` quota (quota checks for 'createImage' and 'createBackup'
  actions in Nova were removed). After this version Glance configuration
  option `image_property_quota` should be used to control the quota of
  image metadatas. Also, removes the `maxImageMeta` field from `os-limits`
  API response.

2.40
----

  Optional parameters 'limit' and 'marker' were added to the GET
  /os-simple-tenant-usage and GET os-simple-tenant-usage/{tenant_id}
  requests. The aggregate usage data no longer reflects all instances for a
  tenant, but rather just the paginated instances ordered by instance id ASC.
  API consumers will need to stitch the aggregate data back up (add the totals)
  if a tenant's instances span several pages.

    GET /os-simple-tenant-usage?limit={limit}&marker={instance_uuid}
    GET /os-simple-tenant-usage/{tenant_id}?limit={limit}&marker={instance_uuid}

  Older versions of the `os-simple-tenant-usage` endpoints will not accept
  these new paging query parameters, but they will start to silently limit by
  `CONF.api.max_limit` to encourage the adoption of this new microversion,
  and circumvent the existing possibility DoS-like usage requests on systems
  with thousands of instances.

2.41
----

  The 'uuid' attribute of an aggregate is now returned from calls to the
  `/os-aggregates` endpoint. This attribute is auto-generated upon creation of
  an aggregate. The `os-aggregates` API resource endpoint remains an
  administrator-only API.


text:
package services_test

import (
	"errors"

	"github.com/cloudfoundry-incubator/notifications/testing/mocks"
	"github.com/cloudfoundry-incubator/notifications/v1/models"
	"github.com/cloudfoundry-incubator/notifications/v1/services"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("PreferencesFinder", func() {
	var (
		finder          *services.PreferencesFinder
		preferencesRepo *mocks.PreferencesRepo
		preferences     []models.Preference
		database        *mocks.Database
		conn            *mocks.Connection
	)

	BeforeEach(func() {
		preferences = []models.Preference{
			{
				ClientID:          "raptors",
				SourceDescription: "raptors description",
				KindID:            "non-critical-kind",
				KindDescription:   "non critical kind description",
				Email:             true,
			},
			{
				ClientID:          "raptors",
				SourceDescription: "raptors description",
				KindID:            "other-kind",
				KindDescription:   "other kind description",
				Email:             false,
			},
		}

		fakeGlobalUnsubscribesRepo := mocks.NewGlobalUnsubscribesRepo()
		fakeGlobalUnsubscribesRepo.GetCall.Returns.Unsubscribed = true

		preferencesRepo = mocks.NewPreferencesRepo()
		preferencesRepo.FindNonCriticalPreferencesCall.Returns.Preferences = preferences

		conn = mocks.NewConnection()
		database = mocks.NewDatabase()
		database.ConnectionCall.Returns.Connection = conn

		finder = services.NewPreferencesFinder(preferencesRepo, fakeGlobalUnsubscribesRepo)
	})

	Describe("Find", func() {
		It("returns the set of notifications that are not critical", func() {
			expectedResult := services.NewPreferencesBuilder()
			expectedResult.Add(preferences[0])
			expectedResult.Add(preferences[1])
			expectedResult.GlobalUnsubscribe = true

			resultPreferences, err := finder.Find(database, "correct-user")
			Expect(err).NotTo(HaveOccurred())
			Expect(resultPreferences).To(Equal(expectedResult))

			Expect(preferencesRepo.FindNonCriticalPreferencesCall.Receives.Connection).To(Equal(conn))
			Expect(preferencesRepo.FindNonCriticalPreferencesCall.Receives.UserGUID).To(Equal("correct-user"))
		})

		Context("when the preferences repo returns an error", func() {
			It("should propagate the error", func() {
				preferencesRepo.FindNonCriticalPreferencesCall.Returns.Error = errors.New("BOOM!")

				_, err := finder.Find(database, "correct-user")
				Expect(err).To(Equal(preferencesRepo.FindNonCriticalPreferencesCall.Returns.Error))
			})
		})
	})
})


text:
<?php
/*
 * Generate Login page
 */
session_start();

if( isset( $_SESSION['Username'] ) )
{

	if( $_SESSION['Username'] == 'admin' )
	{
		header("Location:includes/dashboard/Admin.php");
	}
	else if( isset( $_SESSION['PostName'] ) )
	{
		header("Location:includes/dashboard/PostDashBoard.php");
	}
	else
	{
		header("Location:includes/dashboard/User.php");
	}
	die();
}

$html = <<<HTML
<!DOCTYPE html>

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="image/gogreen.jpg" />
<title>Login</title>
<meta name="viewport" content="width=device-width, initial-scale=.5">

<title>Login!</title>

HTML;
echo $html;
include 'dashboard/Watch.php';
$html = <<<HTML

Please Enter your Login credentials.

<form action="includes/dashboard/Dashboard.php" method="post">

WELCOME

Username  :	 <input type="text" name="User" required autofocus/>

Password  : 	<input type="password" name="Passwd" required/>

<input  type="submit" name="login" value="Login!" style="cursor: pointer; font-size : 30px; height:auto; width:auto ;background-color: 	transparent ;border:1px solid white;color:white" />
</form>
</centre>

ABOUT US

HTML;

echo $html;

?>


text:
<?php

namespace Matthias\SphinxDocumentation;

class TableOfContentsGenerator implements TableOfContentsGeneratorInterface
{
    private $linksDirectory;
    private $maxDepth;

    public function __construct($linksDirectory, $maxDepth = 2)
    {
        $this->linksDirectory = $linksDirectory;
        $this->maxDepth = $maxDepth;
    }

    public function generateFor(array $documentRoots)
    {
        $tableOfContents = '.. toctree::' . "\n";

        foreach (array_keys($documentRoots) as $name) {
            $tableOfContents .= '   ' . $name . '/index' . "\n";
        }

        file_put_contents($this->linksDirectory . 'index.rst', $tableOfContents);
    }
}


text:
package breadth_first_search.min_steps;

import java.util.*;

public class Q126WordLadderII {

    //Difficulty: hard
    //TAG: Amazon
    //TAG: dfs
    //TAG: bfs

    /**
     * 126. Word Ladder II
     * Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
     *
     * Only one letter can be changed at a time
     * Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
     * Note:
     *
     * Return an empty list if there is no such transformation sequence.
     * All words have the same length.
     * All words contain only lowercase alphabetic characters.
     * You may assume no duplicates in the word list.
     * You may assume beginWord and endWord are non-empty and are not the same.
     * Example 1:
     *
     * Input:
     * beginWord = "hit",
     * endWord = "cog",
     * wordList = ["hot","dot","dog","lot","log","cog"]
     *
     * Output:
     * [
     *   ["hit","hot","dot","dog","cog"],
     *   ["hit","hot","lot","log","cog"]
     * ]
     * Example 2:
     *
     * Input:
     * beginWord = "hit"
     * endWord = "cog"
     * wordList = ["hot","dot","dog","lot","log"]
     *
     * Output: []
     *
     * Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
     */

    /*
    Solution:

    bfs find shorted path count the dfs find all paths with the same count

    Time: O(n + n!)
    Space: O(n)
     */

    public List<List<String>> findLadders(String start, String end, List<String> wordList) {
        HashSet<String> dict = new HashSet<>(wordList);
        List<List<String>> res = new ArrayList<>();
        HashMap<String, ArrayList<String>> nodeNeighbors = new HashMap<>();
        HashMap<String, Integer> distance = new HashMap<>();
        ArrayList<String> solution = new ArrayList<>();

        dict.add(start);
        bfs(start, end, dict, nodeNeighbors, distance);
        dfs(start, end, nodeNeighbors, distance, solution, res);
        return res;
    }

    // BFS: Trace every node's distance from the start node (level by level).
    private void bfs(String start, String end, Set<String> dict, HashMap<String, ArrayList<String>> nodeNeighbors,
                     HashMap<String, Integer> distance) {
        for (String str : dict)
            nodeNeighbors.put(str, new ArrayList<>());

        Queue<String> queue = new LinkedList<>();
        queue.offer(start);
        distance.put(start, 0);

        while (!queue.isEmpty()) {
            int count = queue.size();
            boolean foundEnd = false;
            for (int i = 0; i < count; i++) {
                String cur = queue.poll();
                int curDistance = distance.get(cur);
                ArrayList<String> neighbors = getNeighbors(cur, dict);

                for (String neighbor : neighbors) {
                    nodeNeighbors.get(cur).add(neighbor);
                    if (!distance.containsKey(neighbor)) {
                        distance.put(neighbor, curDistance + 1);
                        if (end.equals(neighbor))
                            foundEnd = true;
                        else
                            queue.offer(neighbor);
                    }
                }
            }

            if (foundEnd) break;
        }
    }

    // Find all next level nodes.
    private ArrayList<String> getNeighbors(String node, Set<String> dict) {
        ArrayList<String> res = new ArrayList<>();
        char chs[] = node.toCharArray();

        for (char ch ='a'; ch <= 'z'; ch++) {
            for (int i = 0; i < chs.length; i++) {
                if (chs[i] == ch) continue;
                char old_ch = chs[i];
                chs[i] = ch;
                if (dict.contains(String.valueOf(chs))) {
                    res.add(String.valueOf(chs));
                }
                chs[i] = old_ch;
            }
        }
        return res;
    }

    // DFS: output all paths with the shortest distance.
    private void dfs(String cur, String end, HashMap<String, ArrayList<String>> nodeNeighbors, HashMap<String, Integer> distance, ArrayList<String> solution, List<List<String>> res) {
        solution.add(cur);
        if (end.equals(cur)) {
            res.add(new ArrayList<>(solution));
        } else {
            for (String next : nodeNeighbors.get(cur)) {
                if (distance.get(next) == distance.get(cur) + 1) {
                    dfs(next, end, nodeNeighbors, distance, solution, res);
                }
            }
        }
        solution.remove(solution.size() - 1);
    }

}


text:
<!DOCTYPE html>
<html>
	<head>
	    <meta charset="utf-8">
	    <title>Is Node VM Fast Yet?</title>
	    <link href="/viewer/main.css" rel="stylesheet" type="text/css">
	</head>
	<body>
		<script src="/viewer/d3.min.js"></script>
		<script src="/viewer/graph.js"></script>
		<script src="/viewer/loader.js"></script>
	</body>
</html>


text:
<button type="button" class="btn btn-primary" (click)="onCreate($event)"></button>

{{item.name}}

{{item.webSiteUrl}}

{{item.address}}

 {{item.email}}

 {{item.phone1}}

 {{item.phone2}}

Created {{item.createdAt|amTimeAgo}}

        Card link
        Edit

{{item|json}}


text:
package goacmedns

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"runtime"
	"time"
)

const (
	// ua is a custom user-agent identifier.
	ua = "goacmedns"
)

// userAgent returns a string that can be used as a HTTP request `User-Agent`
// header. It includes the `ua` string alongside the OS and architecture of the
// system.
func userAgent() string {
	return fmt.Sprintf("%s (%s; %s)", ua, runtime.GOOS, runtime.GOARCH)
}

var (
	// defaultTimeout is used for the httpClient Timeout settings.
	defaultTimeout = 30 * time.Second
	// httpClient is a `http.Client` that is customized with the `defaultTimeout`.
	httpClient = http.Client{
		CheckRedirect: nil,
		Jar:           nil,
		Timeout:       defaultTimeout,
		Transport: &http.Transport{ //nolint:exhaustivestruct
			Proxy: http.ProxyFromEnvironment,
			Dial: (&net.Dialer{ //nolint:exhaustivestruct
				Timeout:   defaultTimeout,
				KeepAlive: defaultTimeout,
			}).Dial,
			TLSHandshakeTimeout:   defaultTimeout,
			ResponseHeaderTimeout: defaultTimeout,
			ExpectContinueTimeout: 1 * time.Second,
		},
	}
)

// postAPI makes an HTTP POST request to the given URL, sending the given body
// and attaching the requested custom headers to the request. If there is no
// error the HTTP response body and HTTP response object are returned, otherwise
// an error is returned.. All POST requests include a `User-Agent` header
// populated with the `userAgent` function and a `Content-Type` header of
// `application/json`.
func postAPI(url string, body []byte, headers map[string]string) ([]byte, *http.Response, error) {
	ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
	defer cancel()

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(body))
	if err != nil {
		return nil, nil, fmt.Errorf("Failed to make req: %w", err)
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("User-Agent", userAgent())

	for h, v := range headers {
		req.Header.Set(h, v)
	}

	resp, err := httpClient.Do(req)
	if err != nil {
		return nil, resp, fmt.Errorf("Failed to do req: %w", err)
	}

	defer func() { _ = resp.Body.Close() }()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, resp, fmt.Errorf("Failed to read body: %w", err)
	}

	return respBody, resp, nil
}

// ClientError represents an error from the ACME-DNS server. It holds
// a `Message` describing the operation the client was doing, a `HTTPStatus`
// code returned by the server, and the `Body` of the HTTP Response from the
// server.
type ClientError struct {
	// Message is a string describing the client operation that failed
	Message string
	// HTTPStatus is the HTTP status code the ACME DNS server returned
	HTTPStatus int
	// Body is the response body the ACME DNS server returned
	Body []byte
}

// Error collects all of the ClientError fields into a single string.
func (e ClientError) Error() string {
	return fmt.Sprintf("%s : status code %d response: %s",
		e.Message, e.HTTPStatus, string(e.Body))
}

// newClientError creates a ClientError instance populated with the given
// arguments.
func newClientError(msg string, respCode int, respBody []byte) ClientError {
	return ClientError{
		Message:    msg,
		HTTPStatus: respCode,
		Body:       respBody,
	}
}

// Client is a struct that can be used to interact with an ACME DNS server to
// register accounts and update TXT records.
type Client struct {
	// baseURL is the address of the ACME DNS server
	baseURL string
}

// NewClient returns a Client configured to interact with the ACME DNS server at
// the given URL.
func NewClient(url string) Client {
	return Client{
		baseURL: url,
	}
}

// RegisterAccount creates an Account with the ACME DNS server. The optional
// `allowFrom` argument is used to constrain which CIDR ranges can use the
// created Account.
func (c Client) RegisterAccount(allowFrom []string) (Account, error) {
	var body []byte

	if len(allowFrom) > 0 {
		req := struct {
			AllowFrom []string
		}{
			AllowFrom: allowFrom,
		}

		reqBody, err := json.Marshal(req)
		if err != nil {
			return Account{}, fmt.Errorf("Failed to marshal account: %w", err)
		}

		body = reqBody
	}

	url := fmt.Sprintf("%s/register", c.baseURL)

	// golangci-lint doesn't know it but postAPI() defers a body close.
	respBody, resp, err := postAPI(url, body, nil) //nolint:bodyclose
	if err != nil {
		return Account{}, err
	}

	if resp.StatusCode != http.StatusCreated {
		return Account{}, newClientError(
			"failed to register account", resp.StatusCode, respBody)
	}

	var acct Account

	err = json.Unmarshal(respBody, &acct)
	if err != nil {
		return Account{}, fmt.Errorf("Failed to unmarshal account: %w", err)
	}

	acct.ServerURL = c.baseURL

	return acct, nil
}

// UpdateTXTRecord updates a TXT record with the ACME DNS server to the `value`
// provided using the `account` specified.
func (c Client) UpdateTXTRecord(account Account, value string) error {
	update := struct {
		SubDomain string
		Txt       string
	}{
		SubDomain: account.SubDomain,
		Txt:       value,
	}

	updateBody, err := json.Marshal(update)
	if err != nil {
		return fmt.Errorf("Failed to marshal update: %w", err)
	}

	headers := map[string]string{
		"X-Api-User": account.Username,
		"X-Api-Key":  account.Password,
	}

	url := fmt.Sprintf("%s/update", c.baseURL)

	// golangci-lint doesn't know it but postAPI() defers a body close.
	respBody, resp, err := postAPI(url, updateBody, headers) //nolint:bodyclose
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return newClientError(
			"failed to update txt record", resp.StatusCode, respBody)
	}

	return nil
}


text:
var UnconnectedNodesLayout = function() {
	this.nodes = new Array();
	this.nodeLinks = new Object();
	this.nodesAtLevel = new Object();
	this.maxLevel = -1;
};

UnconnectedNodesLayout.prototype.addNode = function(node, links) {
	this.nodes.push(node);
	this.nodeLinks[node.id] = links;
};

UnconnectedNodesLayout.prototype.computeNodePositions = function(h, levelHeight, width, maxRight) {
	this.maxLevel = -1;
	this.h = h;
	this.levelHeight = levelHeight;

	//Compute Nodes at each level
	for (var i = 0; i < this.nodes.length; i++) {
		var node = this.nodes[i];
		var level = node["height"];
		node["width"] = width;
		node["x"] = 10 + width / 2;
		this._computeNodeY(node);

		if (this.nodesAtLevel[level] == null) {
			this.nodesAtLevel[level] = new Array();
		}
		this.nodesAtLevel[level].push(node);
		if (level > this.maxLevel)
			this.maxLevel = level;
	}

	this._layoutNodesAtLevel1(width);
	for (var i = 2; i <= this.maxLevel; i++)
		this._layoutNodesAtLevel(i, width);

	for (var i = 1; i <= this.maxLevel; i++)
		this._computeNodeWidthOnLinks(i);

	var allIn = false;
	while (!allIn) {
		allIn = true;
		//bump levels if nodes are out of the maxLeft
		for (var i = 1; i <= this.maxLevel; i++) {
			var inAtLevel = this._checkMaxLeftAtLevel(i, maxRight);
			if (!inAtLevel) {
				allIn = false;
			}
		}
		if (!allIn) {
			this._removeEmptyLevels(this.maxLevel);
		}
		this._computeMaxLevel();
	}

	console.log("Final floating node positions:");
	for (var i = 0; i < this.nodes.length; i++) {
		var node = this.nodes[i];
		console.log(node.id + " x:" + node["x"] + " left:" + (node["x"] - node["width"] / 2));
	}
};

UnconnectedNodesLayout.prototype.getMaxLevel = function() {
	return this.maxLevel;
};

UnconnectedNodesLayout.prototype.setNewH = function(h) {
	this.h = h;
	for (var i = 0; i < this.nodes.length; i++) {
		var node = this.nodes[i];
		this._computeNodeY(node);
	}
};

UnconnectedNodesLayout.prototype._layoutNodesAtLevel1 = function(width) {
	var nodes = this.nodesAtLevel[1];
	if (nodes) {
		var left = 10;

		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			node["x"] = left + width / 2;
			left += width + 50;
		}
	}
};

UnconnectedNodesLayout.prototype._getNodeById = function(id) {
	for (var i = 0; i < this.nodes.length; i++) {
		var node = this.nodes[i];
		if (node.id == id)
			return node;
	}
	return null;
};

UnconnectedNodesLayout.prototype._layoutNodesAtLevel = function(level, width) {
	var nodes = this.nodesAtLevel[level];
	if (nodes) {
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];

			var links = this.nodeLinks[node.id];
			var left = 999999;
			if (links) {
				for (var j = 0; j < links.length; j++) {
					var linkId = links[j];
					var nodeConnect = this._getNodeById(linkId);
					if (nodeConnect["height"] > level)
						continue;
					if (nodeConnect["x"] < left)
						left = nodeConnect["x"] - width / 2;
				}
			}

			if (left == 999999) {
				var maxXAtPrevLevel = this._getMaxXAtLevel(level - 1);
				if (maxXAtPrevLevel != -1)
					left = this._getMaxXAtLevel(level - 1) + width + 50;
				else
					left = 10;
				for (var j = 0; j < i; j++) {
					var doneNode = nodes[j];
					var doneLeft = doneNode["x"] - width / 2;
					if (left <= doneLeft) {
						left = doneLeft + width + 50;
					}
				}
			}
			if (left < 10) left = 10;
			node["x"] = left + width / 2;
		}
	}
};

UnconnectedNodesLayout.prototype._getMaxXAtLevel = function(level) {
	var nodes = this.nodesAtLevel[level];
	var maxLeft = -1;
	if (nodes) {
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			var width = node["width"];
			var x = node["x"] - width / 2;
			if (x > maxLeft)
				maxLeft = x;
		}
	}
	return maxLeft;
};

UnconnectedNodesLayout.prototype._computeNodeWidthOnLinks = function(level) {
	var nodes = this.nodesAtLevel[level];
	if (nodes) {
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			var links = this.nodeLinks[node.id];
			if (links) {
				var width = node["width"];
				var extremeLeftX = node["x"] - width / 2;
				var extremeRightX = node["x"] + width / 2;

				for (var j = 0; j < links.length; j++) {
					var linkId = links[j];
					var nodeConnect = this._getNodeById(linkId);
					if (nodeConnect["height"] > level)
						continue;

					var ncWidth = nodeConnect["width"];
					var x = nodeConnect["x"];
					//var y = nodeConnect["y"];
					var leftX = x - ncWidth / 2;
					var rightX = x + ncWidth / 2;
					if (leftX < extremeLeftX)
						extremeLeftX = leftX;
					if (rightX > extremeRightX)
						extremeRightX = rightX;
				}

				width = extremeRightX - extremeLeftX;
				if (extremeLeftX < 10) extremeLeftX = 10;
				node["x"] = extremeLeftX + width / 2;
				node["width"] = width;
			}
		}
	}
};

UnconnectedNodesLayout.prototype._checkMaxLeftAtLevel = function(level, maxRight) {
	var nodes = this.nodesAtLevel[level];
	var allIn = true;
	if (nodes) {
		for (var i = 0; i < nodes.length; i++) {
			var node = nodes[i];
			var x = node["x"];
			var width = node["width"];
			var rightX = x + width / 2;
			var leftX = x - width / 2;
			if (rightX > maxRight) {
				//need to bump this
				allIn = false;
				this._setNodeLevel(node, this.maxLevel + node["height"]);
				var left = leftX - maxRight;
				if (left < 10) left = 10;
				node["x"] = left + width / 2;
			}
		}
	}
	return allIn;
};

UnconnectedNodesLayout.prototype._setNodeLevel = function(node, level) {
	node["height"] = level;
	if (this.nodesAtLevel[level] == null) {
		this.nodesAtLevel[level] = new Array();
	}
	this.nodesAtLevel[level].push(node);
	this._computeNodeY(node);
};

UnconnectedNodesLayout.prototype._removeEmptyLevels = function(startLevel) {
	this._computeMaxLevel();
	var max = this.maxLevel;
	for (var i = startLevel; i < max; i++) {
		var nodes = this.nodesAtLevel[i];
		if (nodes) {

		} else {
			//move all at i+1 here
			var next = i + 1;
			var done = false;
			while (!done && next <= max) {
				var upper = this.nodesAtLevel[next];
				if (upper) {
					done = true;
					this.nodesAtLevel[next] = undefined;
					for (var j = 0; j < upper.length; j++) {
						var node = upper[j];
						this._setNodeLevel(node, i);
					}
				}
				next++;
			}
		}
	}
};

UnconnectedNodesLayout.prototype._computeNodeY = function(node) {
	node["y"] = this.h - ((node["height"] * this.levelHeight));
};

UnconnectedNodesLayout.prototype._computeMaxLevel = function() {
	this.maxLevel = -1;
	for (var i = 0; i < this.nodes.length; i++) {
		var node = this.nodes[i];
		var level = node["height"];

		if (level > this.maxLevel)
			this.maxLevel = level;
	}
};


text:
from SPARQLWrapper import SPARQLWrapper, JSON
import sys
import json
import os.path

results = {
    "commissioni" : [],
    "ddl": []
}

def cleanData(data):
    rows = []
    for result in data["results"]["bindings"]:
        row = {};
        for field in result:
            row[field] = result[field]['value']
        rows.append(row)
    return rows

def getAssegnazioniByFaseNr(assegnazioni, faseNr):
    rows = list(filter(lambda x: x["nomeFase"] == faseNr, assegnazioni))
    groups = {}
    for row in rows:
        date = row["dataAssegnazione"]
        if date not in groups:
            groups[date] = []
        row.pop("dataAssegnazione", None)
        groups[date].append(row)

    for date in groups:
        commissioni = []
        for commissione in groups[date]:
            try:
                index = results["commissioni"].index(commissione["label"])
            except:
                index = len(results["commissioni"])
                results["commissioni"].append(commissione["label"])
            commissioni.append(index)
        groups[date] = commissioni
    return groups

def downloadAssegnazioniOffset(legislatura, offset):
    query = """PREFIX osr: <http://dati.senato.it/osr/>
    SELECT DISTINCT ?nomeFase ?dataAssegnazione ?label
    WHERE
    {
        ?ddl a osr:Ddl.
        ?ddl osr:idDdl ?idDdl.
        ?iter a osr:IterDdl.
        ?iter osr:idDdl ?idDdl.
        ?iter osr:fase ?faseIter.
        ?faseIter osr:ddl ?fase.
        ?fase osr:numeroFase ?numeroFase.
        ?fase osr:assegnazione ?assegnazione.
        ?assegnazione osr:dataAssegnazione ?dataAssegnazione.
        ?assegnazione rdfs:label ?label.
        ?fase osr:fase ?nomeFase.
        ?ddl osr:legislatura %d.
    }
    OFFSET %d""" % (legislatura, offset)

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    return cleanData(sparql.query().convert())

def downloadAssegnazioni(legislatura):
    assegnazioni = []
    maxResults = 10000
    query = """PREFIX osr: <http://dati.senato.it/osr/>
    SELECT count(?assegnazione) AS ?numAssegnazioni
    WHERE
    {
        ?ddl a osr:Ddl.
        ?iter a osr:IterDdl.
        ?ddl osr:idDdl ?idDdl.
        ?iter osr:idDdl ?idDdl.
        ?iter osr:fase ?faseIter.
        ?faseIter osr:ddl ?fase.
        ?fase osr:assegnazione ?assegnazione.
        ?ddl osr:legislatura %d.
    }""" % (legislatura,)

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    results = cleanData(sparql.query().convert())

    numAssegnazioni = int(results[0]["numAssegnazioni"])
    for i in range((numAssegnazioni//maxResults)+1):
        assegnazioni = assegnazioni + downloadAssegnazioniOffset(legislatura, i*maxResults)

    return assegnazioni

def downloadAllDdl(legislatura):
    counter = 0
    query = """PREFIX osr: <http://dati.senato.it/osr/>
	SELECT DISTINCT ?stato ?dataPresentazione ?titolo ?fase ?idfase ?progressivoIter ?idddl ?ramo ?natura ?numeroFase ?dataStato
	{
		?ddl a osr:Ddl; osr:legislatura %d; osr:statoDdl ?stato; osr:dataStatoDdl ?dataStato; osr:dataPresentazione ?dataPresentazione;
		osr:titolo ?titolo; osr:fase ?fase; osr:idFase ?idfase; osr:progressivoIter ?progressivoIter; osr:idDdl ?idddl;
		osr:ramo ?ramo; osr:natura ?natura; osr:numeroFase ?numeroFase.
	}""" % (legislatura,)

    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    results = sparql.query().convert()

    assegnazioni = downloadAssegnazioni(legislatura)

    rows = cleanData(results)

    for row in rows:
        row["assegnazioni"] = getAssegnazioniByFaseNr(assegnazioni, row["fase"])
    return rows

def writeToFile(data, filePath):
    with open(filePath, 'w') as outfile:
        json.dump(data, outfile, ensure_ascii=False)

if len(sys.argv) > 2:
    LEGISLATURA=int(sys.argv[1])
    OUTPUTFILE=sys.argv[2]
else:
    print("Usage: createDataset.py legislatura outputFile")
    exit()

print("Scaricamento legislatura %s" % (LEGISLATURA,))

sparql = SPARQLWrapper("http://dati.senato.it/sparql")

results["ddl"] = downloadAllDdl(LEGISLATURA)
results["legislatura"] = LEGISLATURA

writeToFile(results, OUTPUTFILE)


text:
layout: blog
published: false
title: This is my title
tags:
  - apples
---
## A New Post

Enter text in [Markdown](http://daringfireball.net/projects/markdown/). Use the toolbar above, or click the **?** button for formatting help.


text:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<title>Sign In</title>
	</head>
	<body>
		<form th:action="@{/signin/facebook}" method="POST">
			<button type="submit">Sign in with Facebook</button>
			<input type="hidden" name="scope" value="email,publish_stream,offline_access" />
		</form>
	</body>
</html>