text:
package org.openestate.io.is24_csv.records;

import org.apache.commons.csv.CSVRecord;
import org.openestate.io.is24_csv.Is24CsvRecord;
import org.openestate.io.is24_csv.types.ObjektkategorieGrundstueck;
import org.openestate.io.is24_csv.types.Vermarktungsart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * General record from the IS24-CSV format for plots.
 *
 * @author Andreas Rudolph
 * @since 1.0
 */
@SuppressWarnings("SpellCheckingInspection")
public abstract class Grundstueck extends Is24CsvRecord {
    @SuppressWarnings("unused")
    private final static Logger LOGGER = LoggerFactory.getLogger(Grundstueck.class);

    /**
     * Vermarktungsart, Text 1
     */
    protected final static int FIELD_VERMARKTUNGSART = 60;

    /**
     * Objektkategorie 2, Zahl 3
     */
    protected final static int FIELD_OBJEKTKATEGORIE = 61;

    public ObjektkategorieGrundstueck getObjektkategorie() {
        return ObjektkategorieGrundstueck.parse(
                this.get(FIELD_OBJEKTKATEGORIE));
    }

    public static ObjektkategorieGrundstueck getObjektkategorie(CSVRecord record) {
        return ObjektkategorieGrundstueck.parse(
                record.get(FIELD_OBJEKTKATEGORIE));
    }

    public Vermarktungsart getVermarktungsart() {
        return Vermarktungsart.parse(
                this.get(FIELD_VERMARKTUNGSART));
    }

    public void setObjektkategorie(ObjektkategorieGrundstueck value) {
        this.set(FIELD_OBJEKTKATEGORIE,
                (value != null) ? value.print() : null);
    }

    public void setVermarktungsart(Vermarktungsart value) {
        this.set(FIELD_VERMARKTUNGSART,
                (value != null) ? value.print() : null);
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""Used to unify various data providers under a single namespace."""

import logging
import gin
import gin.tf
import tensorflow as tf

from tf3d.datasets import rio  # pylint: disable=g-bad-import-order
from tf3d.datasets import scannet_scene  # pylint: disable=g-bad-import-order
from tf3d.datasets import waymo_object_per_frame  # pylint: disable=g-bad-import-order

_DATASET_MAP = {
    'rio': rio,
    'scannet_scene': scannet_scene,
    'waymo_object_per_frame': waymo_object_per_frame,
}

def get_file_pattern(dataset_name,
                     split_name,
                     dataset_format=None,
                     dataset_dir=None):
  """Returns the file pattern given the dataset name and split.

  Args:
    dataset_name: Dataset name.
    split_name: A train/test split name.
    dataset_format: A str of the dataset format.
    dataset_dir: The base directory of the dataset sources.

  Returns:
    A string containing the file pattern.
  """
  if dataset_dir is not None:
    return _DATASET_MAP[dataset_name].get_file_pattern(
        split_name=split_name,
        dataset_dir=dataset_dir,
        dataset_format=dataset_format)
  else:
    return _DATASET_MAP[dataset_name].get_file_pattern(split_name=split_name)

def get_decode_fn(dataset_name,
                  include_saved_predictions=False):
  decoder_params = {}
  if include_saved_predictions:
    decoder_params['include_saved_predictions'] = include_saved_predictions
  return _DATASET_MAP[dataset_name].get_decode_fn(**decoder_params)

def get_items_to_descriptions(dataset_name):
  return _DATASET_MAP[dataset_name].ITEMS_TO_DESCRIPTIONS

def get_num_samples(dataset_name, split_name):
  return _DATASET_MAP[dataset_name].SPLITS_TO_SIZES[split_name]

def _get_params(dataset_name):
  params = {}
  if _DATASET_MAP[dataset_name].IGNORE_LABEL is not None:
    params['ignore_label'] = _DATASET_MAP[dataset_name].IGNORE_LABEL
  if _DATASET_MAP[dataset_name].NUM_CLASSES is not None:
    params['num_classes'] = _DATASET_MAP[dataset_name].NUM_CLASSES
  return params

def _read_data(file_read_func, file_pattern, shuffle, num_readers,
               filenames_shuffle_buffer_size, num_epochs, read_block_length,
               shuffle_buffer_size):
  """Gets a dataset tuple.

  Args:
    file_read_func: Function to use in tf.contrib.data.parallel_interleave, to
      read every individual file into a tf.data.Dataset.
    file_pattern: A string containing a file pattern that corresponds to a set
      of files containing the data.
    shuffle: Whether data should be processed in the order they are read in, or
      shuffled randomly.
    num_readers: Number of file shards to read in parallel.
    filenames_shuffle_buffer_size: Buffer size to be used when shuffling file
      names.
    num_epochs: The number of times a data source is read. If set to zero, the
      data source will be reused indefinitely.
    read_block_length: Number of records to read from each reader at once.
    shuffle_buffer_size: Buffer size to be used when shuffling.

  Returns:
    A tf.data.Dataset.
  """
  # Shard, shuffle, and read files.
  dataset = tf.data.Dataset.list_files(
      file_pattern=file_pattern, shuffle=shuffle)
  if shuffle:
    dataset = dataset.shuffle(filenames_shuffle_buffer_size)
  elif num_readers > 1:
    logging.warning('`shuffle` is false, but the input data stream is '
                    'still slightly shuffled since `num_readers` > 1.')
  dataset = dataset.repeat(num_epochs or None)

  records_dataset = dataset.interleave(
      map_func=file_read_func,
      cycle_length=num_readers,
      block_length=read_block_length,
      num_parallel_calls=tf.data.experimental.AUTOTUNE,
      deterministic=shuffle)

  if shuffle:
    records_dataset = records_dataset.shuffle(shuffle_buffer_size)
  return records_dataset

def tfrecord_read_fn(filename):
  return tf.data.TFRecordDataset(filename).prefetch(1)

@gin.configurable(
    'get_tf_data_decoder', denylist=['batch_size', 'is_training'])
def get_tf_data_decoder(dataset_format,
                        decode_fn,
                        file_pattern,
                        batch_size,
                        is_training,
                        preprocess_fn=None,
                        feature_keys=None,
                        label_keys=None,
                        num_readers=64,
                        filenames_shuffle_buffer_size=100,
                        num_epochs=0,
                        read_block_length=32,
                        shuffle_buffer_size=256,
                        num_parallel_batches=8,
                        num_prefetch_batches=2,
                        ):
  """Reads a tf.data.Dataset given a decoder and outputs tensor dictionaries.

  Args:
    dataset_format: Currently 'tfexample' and 'recordio' are supported.
    decode_fn: Decoder function.
    file_pattern: A string containing the file pattern that represents the
      sstable.
    batch_size: Batch size.
    is_training: Whether reading data in training mode or not. If in training,
      data will be shuffled and if not it won't be shuffled. Also in training
      preprocessing can act different than in eval time.
    preprocess_fn: A function that preprocesses data.
    feature_keys: Either None or a list[str] with keys in features.
    label_keys: Either None or a list[str] with keys in labels.
    num_readers: Number of file shards to read in parallel.
    filenames_shuffle_buffer_size: Buffer size to be used when shuffling file
      names.
    num_epochs: The number of times a data source is read. If set to zero, the
      data source will be reused indefinitely.
    read_block_length: Number of records to read from each reader at once.
    shuffle_buffer_size: Buffer size to be used when shuffling.
    num_parallel_batches: Number of batches to produce in parallel. If this is
      run on a 2x2 TPU set this to 8.
    num_prefetch_batches: Number of batches to prefetch. Prefetch decouples
      input pipeline and model so they can be pipelined resulting in higher
      throughput. Set this to a small constant and increment linearly until the
      improvements become marginal or you exceed your cpu memory budget. Setting
      this to -1, automatically tunes this value for you.

  Returns:
    Return a tf.data.dataset where each element is a dictionary with features
    and labels; if not executing eagerly i.e. under tf1 environment, returns a
    dictionary with features and labels instead.
  """

  def _process_fn(key, value):
    """Sets up tf graph that decodes and preprocesses input."""
    tensors_dict = decode_fn(value)
    if preprocess_fn is None:
      return tensors_dict
    else:
      output_keys = feature_keys + label_keys
      return preprocess_fn(
          inputs=tensors_dict, output_keys=output_keys, is_training=is_training)

  if dataset_format == 'tfrecord':
    read_fn = tfrecord_read_fn
  else:
    raise ValueError('Unknown dataset type')

  # Read data
  dataset = _read_data(
      file_read_func=read_fn,
      file_pattern=file_pattern,
      num_readers=num_readers,
      shuffle=is_training,
      filenames_shuffle_buffer_size=filenames_shuffle_buffer_size,
      num_epochs=num_epochs,
      read_block_length=read_block_length,
      shuffle_buffer_size=shuffle_buffer_size)

  if dataset_format == 'tfrecord':
    # insert dummy key to form (key, value pair)
    dataset = dataset.map(lambda x: (None, x))

  # Preprocess data
  dataset_dict = tf.data.Dataset.batch(
      dataset.map(
          _process_fn, num_parallel_calls=num_parallel_batches),
      batch_size=batch_size,
      drop_remainder=True)
  dataset_dict = dataset_dict.prefetch(num_prefetch_batches)

  return dataset_dict

@gin.configurable(denylist=['batch_size', 'is_training'])
def get_tf_data_dataset(dataset_name,
                        split_name,
                        batch_size,
                        is_training,
                        preprocess_fn=None,
                        feature_keys=None,
                        label_keys=None,
                        num_readers=64,
                        filenames_shuffle_buffer_size=100,
                        num_epochs=0,
                        read_block_length=32,
                        shuffle_buffer_size=256,
                        num_parallel_batches=8,
                        num_prefetch_batches=2,
                        dataset_dir=None,
                        dataset_format=None):
  """Reads a tf.data.Dataset given a dataset name and split and outputs tensors.

  Args:
    dataset_name: Dataset name.
    split_name: A train/test split name.
    batch_size: Batch size.
    is_training: Whether reading data in training mode or not. If in training,
      data will be shuffled and if not it won't be shuffled. Also in training
      preprocessing can act different than in eval time.
    preprocess_fn: A function that preprocesses data.
    feature_keys: Either None or a list[str] with keys in features.
    label_keys: Either None or a list[str] with keys in labels.
    num_readers: Number of file shards to read in parallel.
    filenames_shuffle_buffer_size: Buffer size to be used when shuffling file
      names.
    num_epochs: The number of times a data source is read. If set to zero, the
      data source will be reused indefinitely.
    read_block_length: Number of records to read from each reader at once.
    shuffle_buffer_size: Buffer size to be used when shuffling.
    num_parallel_batches: Number of batches to produce in parallel. If this is
      run on a 2x2 TPU set this to 8.
    num_prefetch_batches: Number of batches to prefetch. Prefetch decouples
      input pipeline and model so they can be pipelined resulting in higher
      throughput. Set this to a small constant and increment linearly until the
      improvements become marginal or you exceed your cpu memory budget. Setting
      this to -1, automatically tunes this value for you.
    dataset_dir: The base directory of the dataset sources.
    dataset_format: If not None, a str of dataset format, can be 'tfrecord',
    'sstable' or 'recordio'.

  Returns:
    Return a tf.data.dataset where each element is a dictionary with features
    and labels; if not executing eagerly i.e. under tf1 environment, returns a
    dictionary with features and labels instead.
  """
  if dataset_format is None:
    dataset_format = _DATASET_MAP[dataset_name].DATASET_FORMAT
  file_pattern = get_file_pattern(
      dataset_name=dataset_name,
      split_name=split_name,
      dataset_dir=dataset_dir,
      dataset_format=dataset_format)

  decode_fn = get_decode_fn(dataset_name=dataset_name)
  if feature_keys is None:
    feature_keys = list(_DATASET_MAP[dataset_name].get_feature_keys())
  if label_keys is None:
    label_keys = list(_DATASET_MAP[dataset_name].get_label_keys())
  return get_tf_data_decoder(
      dataset_format=dataset_format,
      decode_fn=decode_fn,
      file_pattern=file_pattern,
      batch_size=batch_size,
      is_training=is_training,
      preprocess_fn=preprocess_fn,
      feature_keys=feature_keys,
      label_keys=label_keys,
      num_readers=num_readers,
      filenames_shuffle_buffer_size=filenames_shuffle_buffer_size,
      num_epochs=num_epochs,
      read_block_length=read_block_length,
      shuffle_buffer_size=shuffle_buffer_size,
      num_parallel_batches=num_parallel_batches,
      num_prefetch_batches=num_prefetch_batches)


text:
<?php

namespace Sylius\Bundle\CoreBundle\EventListener;

use Finite\Factory\FactoryInterface;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Order\OrderTransitions;
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * @author Alexandre Bacco <alexandre.bacco@gmail.com>
 */
class ConfirmOrderListener
{
    protected $finiteFactory;

    public function __construct(FactoryInterface $finiteFactory)
    {
        $this->finiteFactory = $finiteFactory;
    }

    /**
     * Set an Order as completed
     *
     * @param GenericEvent $event
     *
     * @throws UnexpectedTypeException
     */
    public function confirmOrder(GenericEvent $event)
    {
        $order = $this->getOrder($event);

        $this->finiteFactory->get($order, OrderTransitions::GRAPH)->apply(OrderTransitions::SYLIUS_CONFIRM);
    }

    protected function getOrder(GenericEvent $event)
    {
        $order = $event->getSubject();

        if (!$order instanceof OrderInterface) {
            throw new UnexpectedTypeException($order, 'Sylius\Component\Order\Model\OrderInterface');
        }

        return $order;
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.

/**
 * This package contains the implementation classes for DevSpacesManagementClient.
 * Dev Spaces Client.
 */
package com.microsoft.azure.management.devspaces.v2018_06_01_preview.implementation;


text:
    <meta http-equiv="refresh" content="5; URL=https://lucasnck.com/" />

    <meta name="theme-color" content="#333333">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Lucas Ribeiro Developer Portfolio" />
    <meta name="keywords" content="developer, programmer, java, javascript, lucasnck, portfolio, design, github, backend, frontend"
    />
    <meta name="author" content="lucasnck@hotmail.com" />
    <meta property="og:url" content="https://lucasnck.github.io/" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Lucasnck - Portfolio" />
    <meta property="og:description" content="Lucas Ribeiro Developer Portfolio" />
    <meta property="og:image" content="https://lucasnck.github.io/resources/img/photo.jpg" />

    <link rel="stylesheet" href="resources/bootstrap-4.1.1/css/bootstrap.css">

    <link rel="stylesheet" href="resources/fontawesome-free-5.0.13/css/fontawesome-all.css">

    <link rel="stylesheet" href="resources/slick/css/slick.css">

    <link rel="stylesheet" href="resources/css/default.css">

    <link href="https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700" rel="stylesheet">

    <link rel="icon" sizes="16x16" href="resources/img/favicon.png">
    <title>Lucasnck - Portfólio</title>

                    <button class="btn btn-toggle-menu">

                    </button>

Portfólio

                        <button class="btn btn-toggle-menu">
                            x
                        </button>

Sobre mim

                        Sou tecnólogo em Análise e Desenvolvimento de Sistemas, apaixonado por tecnologia e programação.

                            Selecione abaixo uma opção para ver as minhas Habilidades e Projetos de acordo com meu perfil

Desenvolvedor Back-end
                                        Ferreiro

Selecione para ver meu perfil como
                                        Desenvoledor de Lógica de Aplicações

Desenvolvedor Front-end
                                        Mago

Selecione para ver meu perfil como
                                        Desenvoledor de Aparência de Aplicações

Habilidades

Projetos

Carreira

Formação Acadêmica

Artigos Públicados

Idiomas

E ai o que achou do portfólio? Deixe seu comentário abaixo!

                    <address id="contact" class="text-left">

                             Contato

                         Sou de Marília/SP

                         +55 (14) 99630-9404

                         luucasnck@gmail.com
                    </address>

© Lucas Ribeiro. Todos os direitos reservados. Não é proibida a reprodução parcial ou total desse portfólio e
                você ainda pode cloná-lo

                    nesse repositôrio.

                         Preparando conteúdo

Aguarde enquanto preparo o conteúdo para você


text:
.. _dispatchers-java:

Dispatchers
===================

An Akka ``MessageDispatcher`` is what makes Akka Actors "tick", it is the engine of the machine so to speak.
All ``MessageDispatcher`` implementations are also an ``ExecutionContext``, which means that they can be used
to execute arbitrary code, for instance :ref:`futures-java`.

Default dispatcher
------------------

Every ``ActorSystem`` will have a default dispatcher that will be used in case nothing else is configured for an ``Actor``.
The default dispatcher can be configured, and is by default a ``Dispatcher`` with the specified ``default-executor``.
If an ActorSystem is created with an ExecutionContext passed in, this ExecutionContext will be used as the default executor for all
dispatchers in this ActorSystem. If no ExecutionContext is given, it will fallback to the executor specified in
``akka.actor.default-dispatcher.default-executor.fallback``. By default this is a "fork-join-executor", which
gives excellent performance in most cases.

.. _dispatcher-lookup-java:

Looking up a Dispatcher
-----------------------

Dispatchers implement the :class:`ExecutionContext` interface and can thus be used to run :class:`Future` invocations etc.

.. includecode:: code/docs/dispatcher/DispatcherDocTest.java#lookup

Setting the dispatcher for an Actor
-----------------------------------

So in case you want to give your ``Actor`` a different dispatcher than the default, you need to do two things, of which the first is
is to configure the dispatcher:

.. includecode:: ../scala/code/docs/dispatcher/DispatcherDocSpec.scala#my-dispatcher-config

And here's another example that uses the "thread-pool-executor":

.. includecode:: ../scala/code/docs/dispatcher/DispatcherDocSpec.scala#my-thread-pool-dispatcher-config

For more options, see the default-dispatcher section of the :ref:`configuration`.

Then you create the actor as usual and define the dispatcher in the deployment configuration.

.. includecode:: ../java/code/docs/dispatcher/DispatcherDocTest.java#defining-dispatcher-in-config

.. includecode:: ../scala/code/docs/dispatcher/DispatcherDocSpec.scala#dispatcher-deployment-config

An alternative to the deployment configuration is to define the dispatcher in code.
If you define the ``dispatcher`` in the deployment configuration then this value will be used instead
of programmatically provided parameter.

.. includecode:: ../java/code/docs/dispatcher/DispatcherDocTest.java#defining-dispatcher-in-code

.. note::
    The dispatcher you specify in ``withDispatcher`` and the ``dispatcher`` property in the deployment
    configuration is in fact a path into your configuration.
    So in this example it's a top-level section, but you could for instance put it as a sub-section,
    where you'd use periods to denote sub-sections, like this: ``"foo.bar.my-dispatcher"``

Types of dispatchers
--------------------

There are 4 different types of message dispatchers:

* Dispatcher

  - This is an event-based dispatcher that binds a set of Actors to a thread pool. It is the default dispatcher used if one is not specified.

  - Sharability: Unlimited

  - Mailboxes: Any, creates one per Actor

  - Use cases: Default dispatcher, Bulkheading

  - Driven by: ``java.util.concurrent.ExecutorService``
               specify using "executor" using "fork-join-executor",
               "thread-pool-executor" or the FQCN of
               an ``akka.dispatcher.ExecutorServiceConfigurator``

* PinnedDispatcher

  - This dispatcher dedicates a unique thread for each actor using it; i.e. each actor will have its own thread pool with only one thread in the pool.

  - Sharability: None

  - Mailboxes: Any, creates one per Actor

  - Use cases: Bulkheading

  - Driven by: Any ``akka.dispatch.ThreadPoolExecutorConfigurator``
               by default a "thread-pool-executor"

* CallingThreadDispatcher

  - This dispatcher runs invocations on the current thread only. This dispatcher does not create any new threads,
    but it can be used from different threads concurrently for the same actor. See :ref:`Java-CallingThreadDispatcher`
    for details and restrictions.

  - Sharability: Unlimited

  - Mailboxes: Any, creates one per Actor per Thread (on demand)

  - Use cases: Testing

  - Driven by: The calling thread (duh)

More dispatcher configuration examples
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Configuring a ``PinnedDispatcher``:

.. includecode:: ../scala/code/docs/dispatcher/DispatcherDocSpec.scala#my-pinned-dispatcher-config

And then using it:

.. includecode:: ../java/code/docs/dispatcher/DispatcherDocTest.java#defining-pinned-dispatcher

Note that ``thread-pool-executor`` configuration as per the above ``my-thread-pool-dispatcher`` example is
NOT applicable. This is because every actor will have its own thread pool when using ``PinnedDispatcher``,
and that pool will have only one thread.

Note that it's not guaranteed that the *same* thread is used over time, since the core pool timeout
is used for ``PinnedDispatcher`` to keep resource usage down in case of idle actors. To use the same
thread all the time you need to add ``thread-pool-executor.allow-core-timeout=off`` to the
configuration of the ``PinnedDispatcher``.


text:
#ifndef __VISUAL_H__
#define __VISUAL_H__

/**
 * Method for writing header information in vtk format.
 *
 * The name of the file consists of the problem name (szProblem)
 * and of the current time step. It gets the suffix .vtk.
 *
 * @param szProblem      File pointer for writing info.
 * @param timeStepNumber Number of the current time step to be printed.
 * @param xlength Length in x-direction
 * @param ylength Length in y-direction
 * @param imax    Maximum number of entries (?) in x-direction
 * @param jmax    Maximum number of entries (?) in y-direction
 * @param dx      Mesh size in x-direction
 * @param dy      Mesh size in x-direction
 * @param U       Velocities in x-direction
 * @param V       Velocities in y-direction
 * @param P       Pressure data
 *
 * @author Tobias Neckel
 */
void write_vtkFile(const char *szProblem,
		  int    timeStepNumber,
		  double xlength,
                  double ylength,
                  int    imax,
                  int    jmax,
		  double dx,
		  double dy,
                  double **U,
                  double **V,
                  double **P,
                  int **flag);

/**
 * Method for writing header information in vtk format.
 *
 * @param fp      File pointer for writing info.
 * @param imax    Maximum number of entries (minus 2) in x-direction
 * @param jmax    Maximum number of entries (minus 2) in y-direction
 * @param dx      mesh size dx
 * @param dy      mesh size dy
 *
 * @author Tobias Neckel
 */
void write_vtkHeader( FILE *fp, int imax, int jmax,
                      double dx, double dy);

/**
 * Method for writing grid coordinate information in vtk format.
 *
 * @param fp      File pointer for writing info.
 * @param imax    Maximum number of entries (minus 2) in x-direction
 * @param jmax    Maximum number of entries (minus 2) in y-direction
 * @param dx      mesh size dx
 * @param dy      mesh size dy
 *
 * @author Tobias Neckel
 */
void write_vtkPointCoordinates( FILE *fp, int imax, int jmax,
                                double dx, double dy);

#endif


text:
<?php
$TRANSLATIONS = array(
"Could not move %s - File with this name already exists" => "Nepavyko perkelti %s - failas su tokiu pavadinimu jau egzistuoja",
"Could not move %s" => "Nepavyko perkelti %s",
"File name cannot be empty." => "Failo pavadinimas negali būti tuščias.",
"Invalid name, '\\', '/', '<', '>', ':', '\"', '|', '?' and '*' are not allowed." => "Neleistinas pavadinimas, '\\', '/', '<', '>', ':', '\"', '|', '?' ir '*' yra neleidžiami.",
"The name %s is already used in the folder %s. Please choose a different name." => "Pavadinimas %s jau naudojamas aplanke %s. Prašome pasirinkti kitokį pavadinimą.",
"Not a valid source" => "Netinkamas šaltinis",
"Server is not allowed to open URLs, please check the server configuration" => "Serveriui neleidžiama atverti URL, prašome patikrinti serverio konfigūraciją",
"Error while downloading %s to %s" => "Klaida siunčiant %s į %s",
"Error when creating the file" => "Klaida kuriant failą",
"Folder name cannot be empty." => "Aplanko pavadinimas negali būti tuščias.",
"Error when creating the folder" => "Klaida kuriant aplanką",
"Unable to set upload directory." => "Nepavyksta nustatyti įkėlimų katalogo.",
"Invalid Token" => "Netinkamas ženklas",
"No file was uploaded. Unknown error" => "Failai nebuvo įkelti dėl nežinomos priežasties",
"There is no error, the file uploaded with success" => "Failas įkeltas sėkmingai, be klaidų",
"The uploaded file exceeds the upload_max_filesize directive in php.ini: " => "Įkeliamas failas yra didesnis nei leidžia upload_max_filesize php.ini faile:",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" => "Įkeliamo failo dydis viršija MAX_FILE_SIZE nustatymą, kuris naudojamas HTML formoje.",
"The uploaded file was only partially uploaded" => "Failas buvo įkeltas tik dalinai",
"No file was uploaded" => "Nebuvo įkeltas joks failas",
"Missing a temporary folder" => "Nėra laikinojo katalogo",
"Failed to write to disk" => "Nepavyko įrašyti į diską",
"Not enough storage available" => "Nepakanka vietos serveryje",
"Upload failed. Could not find uploaded file" => "Įkėlimas nepavyko. Nepavyko rasti įkelto failo",
"Upload failed. Could not get file info." => "Įkėlimas nepavyko. Nepavyko gauti failo informacijos.",
"Invalid directory." => "Neteisingas aplankas",
"Files" => "Failai",
"Unable to upload {filename} as it is a directory or has 0 bytes" => "Nepavyksta įkelti {filename}, nes tai katalogas arba yra 0 baitų dydžio",
"Upload cancelled." => "Įkėlimas atšauktas.",
"Could not get result from server." => "Nepavyko gauti rezultato iš serverio.",
"File upload is in progress. Leaving the page now will cancel the upload." => "Failo įkėlimas pradėtas. Jei paliksite šį puslapį, įkėlimas nutrūks.",
"URL cannot be empty" => "URL negali būti tuščias.",
"{new_name} already exists" => "{new_name} jau egzistuoja",
"Could not create file" => "Neįmanoma sukurti failo",
"Could not create folder" => "Neįmanoma sukurti aplanko",
"Error fetching URL" => "Klauda gaunant URL",
"Share" => "Dalintis",
"Delete permanently" => "Ištrinti negrįžtamai",
"Delete" => "Ištrinti",
"Rename" => "Pervadinti",
"Your download is being prepared. This might take some time if the files are big." => "Jūsų atsisiuntimas yra paruošiamas. tai gali užtrukti jei atsisiunčiamas didelis failas.",
"Pending" => "Laukiantis",
"Error moving file" => "Klaida perkeliant failą",
"Error" => "Klaida",
"Could not rename file" => "Neįmanoma pervadinti failo",
"Error deleting file." => "Klaida trinant failą.",
"Name" => "Pavadinimas",
"Size" => "Dydis",
"Modified" => "Pakeista",
"_%n folder_::_%n folders_" => array("%n aplankas","%n aplankai","%n aplankų"),
"_%n file_::_%n files_" => array("%n failas","%n failai","%n failų"),
"_Uploading %n file_::_Uploading %n files_" => array("Įkeliamas %n failas","Įkeliami %n failai","Įkeliama %n failų"),
"Your storage is full, files can not be updated or synced anymore!" => "Jūsų visa vieta serveryje užimta",
"Your storage is almost full ({usedSpacePercent}%)" => "Jūsų vieta serveryje beveik visa užimta ({usedSpacePercent}%)",
"Encryption App is enabled but your keys are not initialized, please log-out and log-in again" => "Šifravimo programa įjungta, bet Jūsų raktai nėra pritaikyti. Prašome atsijungti ir vėl prisijungti",
"Invalid private key for Encryption App. Please update your private key password in your personal settings to recover access to your encrypted files." => "Netinkamas privatus raktas Šifravimo programai. Prašome atnaujinti savo privataus rakto slaptažodį asmeniniuose nustatymuose, kad atkurti prieigą prie šifruotų failų.",
"Encryption was disabled but your files are still encrypted. Please go to your personal settings to decrypt your files." => "Šifravimas buvo išjungtas, bet Jūsų failai vis dar užšifruoti. Prašome eiti į asmeninius nustatymus ir iššifruoti savo failus.",
"{dirs} and {files}" => "{dirs} ir {files}",
"%s could not be renamed" => "%s negali būti pervadintas",
"File handling" => "Failų tvarkymas",
"Maximum upload size" => "Maksimalus įkeliamo failo dydis",
"max. possible: " => "maks. galima:",
"Save" => "Išsaugoti",
"WebDAV" => "WebDAV",
"Use this address to access your Files via WebDAV" => "Naudokite šį adresą, kad pasiektumėte savo failus per WebDAV",
"New" => "Naujas",
"New text file" => "Naujas tekstinis failas",
"Text file" => "Teksto failas",
"New folder" => "Naujas aplankas",
"Folder" => "Katalogas",
"From link" => "Iš nuorodos",
"You don't have permission to upload or create files here" => "Jūs neturite leidimo čia įkelti arba kurti failus",
"Nothing in here. Upload something!" => "Čia tuščia. Įkelkite ką nors!",
"Download" => "Atsisiųsti",
"Upload too large" => "Įkėlimui failas per didelis",
"The files you are trying to upload exceed the maximum size for file uploads on this server." => "Bandomų įkelti failų dydis viršija maksimalų, kuris leidžiamas šiame serveryje",
"Files are being scanned, please wait." => "Skenuojami failai, prašome palaukti."
);
$PLURAL_FORMS = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);";


text:
using System;

namespace Cvv.WebUtility.Core
{
    public class RealTimeProvider : ITimeProvider
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }
}


text:
class Admin::MinutesResourceController < Admin::ResourceController
  paginate_models
  # only_allow_access_to must be set

  prepend_before_filter :find_root

  def upload
    if params[:upload].blank?  # necessary params are missing
      render :text => '', :status => :bad_request
    else
      @minutes = model_class.create_from_upload!(params[:upload][:upload])
      response_for :create
    end
  end

  def new
    self.model = model_class.new_with_defaults
    response_for :new
  end

  def create
    model.update_attributes!(params[model_symbol])
    response_for :create
  end

  private

  def find_root
    unless Page.find_by_path(MinutesExtension.minutes_path)
      flash[:error] = t('minutes.root_required', :model => humanized_model_name, :root => MinutesExtension.minutes_path)
      redirect_to welcome_path and return false
    end
  end
end


text:
// Master implements the service MasterSerivce.
//
// A Master maintains the state of live graph computation
// sessions, each session orchestrates both local and remote devices
// to carry out the graph computation.
//
// A Master knows ahead of time local devices available as
// client devices.
//
// A Master discovers remote devices on-demand and keeps track of
// statistics of those remote devices.
//
// Each session analyses the graph, places nodes across available
// devices, and ultimately drives the graph computation by initiating
// RunGraph on the workers.

#include "tensorflow/core/distributed_runtime/master.h"

#include <unordered_set>
#include <vector>

#include "tensorflow/core/common_runtime/process_util.h"
#include "tensorflow/core/distributed_runtime/remote_device.h"
#include "tensorflow/core/distributed_runtime/worker_cache.h"
#include "tensorflow/core/distributed_runtime/worker_interface.h"
#include "tensorflow/core/framework/graph_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/master.pb.h"
#include "tensorflow/core/protobuf/worker.pb.h"
#include "tensorflow/core/public/session_options.h"

namespace tensorflow {

Master::Master(MasterEnv* env, double session_gc_seconds)
    : env_(env),
      last_1000_steps_(1000),
      step_count_(0),
      session_gc_seconds_(session_gc_seconds) {
  // Right now, a master service must be co-located with a device.
  // Otherwise, fetches do not work.
  CHECK(!env->local_devices.empty());

  if (session_gc_seconds_ > 0.0) {
    gc_thread_ = env_->env->StartThread(ThreadOptions(), "TF_master_GC",
                                        [this]() { GC(); });
  } else {
    gc_thread_ = nullptr;
  }
}

Master::~Master() {
  if (gc_thread_) {
    mutex_lock l(mu_);
    shutdown_ = true;
    shutdown_cv_.notify_all();
    delete gc_thread_;
  }
}

void Master::GC() {
  Env* env = Env::Default();
  while (true) {
    mutex_lock l(mu_);
    const int kTimeoutMilliseconds = 10 * 1000;  // 10 seconds.
    WaitForMilliseconds(&l, &shutdown_cv_, kTimeoutMilliseconds);
    if (shutdown_) {
      break;
    }
    std::vector<string> handles;
    const int64 num_micros = static_cast<int64>(session_gc_seconds_ * 1000000);
    for (const auto& entry : sessions_) {
      int64 lat = entry.second->last_access_time_usec();
      if (static_cast<int64>(env->NowMicros()) - lat > num_micros) {
        handles.push_back(entry.first);
        auto* sess = entry.second;
        SchedClosure([this, sess]() {
          LOG(WARNING) << "GC session " << sess->handle() << " after "
                       << session_gc_seconds_ << " seconds.  "
                       << "Note that if you are starting multiple replicas "
                       << "on a staggered delay, session_gc_seconds may need "
                       << "to be raised.";
          sess->GarbageCollect();
        });
      }
    }
    for (const auto& handle : handles) sessions_.erase(handle);
  }
}

class DeviceFinder {
 public:
  static Status GetRemoteDevices(
      const protobuf::RepeatedPtrField<string>& device_filters, MasterEnv* env,
      std::vector<Device*>* out_remote) {
    DeviceFinder finder(device_filters, env);
    finder.Start();
    TF_RETURN_IF_ERROR(finder.Wait());
    finder.GetRemoteDevices(env->local_devices, out_remote);
    return Status::OK();
  }

 private:
  explicit DeviceFinder(
      const protobuf::RepeatedPtrField<string>& device_filters, MasterEnv* env)
      : env_(env) {
    auto process_filter = [this](const string& filter) {
      DeviceNameUtils::ParsedName parsed;
      if (DeviceNameUtils::ParseFullName(filter, &parsed)) {
        filters_.push_back(parsed);
      } else {
        LOG(FATAL) << "Skipping invalid filter: " << filter;
      }
    };
    for (const string& filter : device_filters) {
      process_filter(filter);
    }
    // Enumerates all known workers' target. A target name is a
    // prefix of a device name. E.g., /job:mnist/replica:0/task:10.
    std::vector<string> workers;
    env_->worker_cache->ListWorkers(&workers);
    if (filters_.empty()) {
      std::swap(workers, targets_);
    } else {
      for (const string& name : workers) {
        if (MatchFilters(name)) {
          targets_.push_back(name);
        }
      }
    }
    seen_targets_.assign(targets_.size(), false);
  }

  ~DeviceFinder() {
    for (Device* dev : found_) delete dev;
  }

  void Start() {
    {
      mutex_lock l(mu_);
      num_pending_ = targets_.size();
      if (num_pending_ == 0) {
        pending_zero_.notify_all();
      }
    }
    // Talk to all workers to get the list of available devices.
    using std::placeholders::_1;
    using std::placeholders::_2;
    for (size_t i = 0; i < targets_.size(); ++i) {
      // TODO(mrry): Propagate a timeout here, since `this->WhenFound()` may
      // never be called.
      NewRemoteDevices(env_->env, env_->worker_cache, targets_[i],
                       std::bind(&ME::WhenFound, this, i, _1, _2));
    }
  }

  // Every `kLoggingPeriodMs`, while the DeviceFinder is still waiting
  // to hear from workers, log a list of the workers who have not
  // responded.
  const int32 kLoggingPeriodMs = 10 * 1000;

  Status Wait() {
    mutex_lock l(mu_);
    // TODO(mrry): Propagate a timeout here, since `num_pending_` may
    // never become zero.
    while (num_pending_ != 0) {
      pending_zero_.wait_for(l, std::chrono::milliseconds(kLoggingPeriodMs));
      if (num_pending_ != 0) {
        for (int i = 0; i < targets_.size(); ++i) {
          if (!seen_targets_[i]) {
            LOG(INFO)
                << "CreateSession still waiting for response from worker: "
                << targets_[i];
          }
        }
      }
    }
    return status_;
  }

  // The caller takes the ownership of returned remote devices.
  void GetRemoteDevices(const std::vector<Device*>& local,
                        std::vector<Device*>* remote) {
    std::unordered_set<string> names(local.size());
    for (Device* dev : local) names.insert(dev->name());
    mutex_lock l(mu_);
    for (Device* dev : found_) {
      const string& name = dev->name();
      if (names.insert(name).second && MatchFilters(name)) {
        remote->push_back(dev);
      } else {
        delete dev;
      }
    }
    found_.clear();
  }

  typedef DeviceFinder ME;
  const MasterEnv* env_;
  std::vector<DeviceNameUtils::ParsedName> filters_;

  mutex mu_;
  int num_pending_ GUARDED_BY(mu_);
  condition_variable pending_zero_;
  std::vector<Device*> found_ GUARDED_BY(mu_);
  // List of targets to be contacted by this DeviceFinder. The
  // respective `bool` in `seen_targets_` indicates whether we have
  // heard from this target or not.
  std::vector<string> targets_;
  std::vector<bool> seen_targets_ GUARDED_BY(mu_);
  Status status_;

  void WhenFound(int target_index, const Status& s,
                 std::vector<Device*>* devices) {
    mutex_lock l(mu_);
    seen_targets_[target_index] = true;
    if (!s.ok()) {
      LOG(ERROR) << "Master init: " << s;
      status_.Update(s);
    } else {
      found_.insert(found_.end(), devices->begin(), devices->end());
      devices->clear();
    }
    --num_pending_;
    if (num_pending_ == 0) {
      pending_zero_.notify_all();
    }
  }

  // Returns true iff the set of devices allowed by 'x' intersects
  // with the set of devices allowed by 'y'.
  bool Intersects(const DeviceNameUtils::ParsedName& x,
                  const DeviceNameUtils::ParsedName& y) {
    return (!x.has_job || !y.has_job || x.job == y.job) &&
           (!x.has_replica || !y.has_replica || x.replica == y.replica) &&
           (!x.has_task || !y.has_task || x.task == y.task) &&
           (!x.has_type || !y.has_type || x.type == y.type) &&
           (!x.has_id || !y.has_id || x.id == y.id);
  }

  // Returns true iff 'name' matches one of the filters_.
  bool MatchFilters(const string& name) {
    if (filters_.empty()) return true;
    DeviceNameUtils::ParsedName x;
    if (DeviceNameUtils::ParseFullName(name, &x)) {
      for (const auto& filter : filters_) {
        if (Intersects(x, filter)) return true;
      }
    }
    return false;
  }

  TF_DISALLOW_COPY_AND_ASSIGN(DeviceFinder);
};

void Master::CreateSession(const CreateSessionRequest* req,
                           CreateSessionResponse* resp, MyClosure done) {
  SchedClosure([this, req, resp, done]() {
    Status status = ValidateExternalGraphDefSyntax(req->graph_def());
    if (status.ok()) {
      // Ping all the workers and build the list of devices that the
      // session will use.
      std::vector<Device*> remote_devices;
      status = DeviceFinder::GetRemoteDevices(req->config().device_filters(),
                                              env_, &remote_devices);
      if (!status.ok()) {
        done(status);
        return;
      }
      SessionOptions options;
      options.config = req->config();
      MasterSession* session =
          env_->master_session_factory(options, env_, &remote_devices);
      GraphDef* gdef =
          const_cast<CreateSessionRequest*>(req)->mutable_graph_def();
      Status create_status = session->Create(gdef);
      if (!create_status.ok()) {
        session->Close().IgnoreError();
        session->Unref();
        done(create_status);
        return;
      }
      resp->set_session_handle(session->handle());
      // Insert into the session map, which takes ownership of the session.
      {
        mutex_lock l(mu_);
        CHECK(sessions_.insert({session->handle(), session}).second);
      }
    }
    done(status);
  });
}

void Master::ExtendSession(const ExtendSessionRequest* req,
                           ExtendSessionResponse* resp, MyClosure done) {
  mu_.lock();
  MasterSession* session = nullptr;
  session = gtl::FindPtrOrNull(sessions_, req->session_handle());
  if (session == nullptr) {
    mu_.unlock();
    done(errors::Aborted("Session ", req->session_handle(), " is not found."));
    return;
  }
  session->Ref();
  mu_.unlock();

  SchedClosure([session, req, resp, done]() {
    Status status = ValidateExternalGraphDefSyntax(req->graph_def());
    if (status.ok()) {
      status = session->Extend(req, resp);
    }
    session->Unref();
    done(status);
  });
}

void Master::PartialRunSetup(const PartialRunSetupRequest* req,
                             PartialRunSetupResponse* resp, MyClosure done) {
  mu_.lock();
  MasterSession* session = gtl::FindPtrOrNull(sessions_, req->session_handle());
  if (session == nullptr) {
    mu_.unlock();
    done(errors::Aborted("Session ", req->session_handle(), " is not found."));
    return;
  }
  session->Ref();
  mu_.unlock();

  SchedClosure([this, session, req, resp, done]() {
    Status s = session->PartialRunSetup(req, resp);
    session->Unref();
    done(s);
  });
}

void Master::RunStep(CallOptions* opts, const RunStepRequestWrapper* req,
                     MutableRunStepResponseWrapper* resp, MyClosure done) {
  mu_.lock();
  uint64 start_time = env_->env->NowMicros();
  MasterSession* session = gtl::FindPtrOrNull(sessions_, req->session_handle());
  if (session == nullptr) {
    mu_.unlock();
    done(errors::Aborted("Session ", req->session_handle(), " is not found."));
    return;
  }
  session->Ref();
  mu_.unlock();

  SchedClosure([this, start_time, session, opts, req, resp, done]() {
    Status status = session->Run(opts, *req, resp);
    session->Unref();
    uint64 done_time = env_->env->NowMicros();
    done(status);
    mutex_lock l(mu_);
    last_1000_steps_.AddValue((done_time - start_time) / 1e9);
    ++step_count_;
  });
}

void Master::CloseSession(const CloseSessionRequest* req,
                          CloseSessionResponse* resp, MyClosure done) {
  MasterSession* session = nullptr;
  {
    mu_.lock();
    auto iter = sessions_.find(req->session_handle());
    if (iter == sessions_.end()) {
      mu_.unlock();
      done(errors::Aborted(
          "Session ", req->session_handle(),
          " is not found. Possibly, this master has restarted."));
      return;
    }
    // NOTE(mrry): One reference to the session is transferred from
    // `sessions_[req->session_handle()]` to `session`.
    session = iter->second;
    sessions_.erase(iter);
    mu_.unlock();
  }

  // Session Close() blocks on thread shutdown. Therefore, we need to
  // delete it in non-critical thread.
  SchedClosure([session, done]() {
    Status s = session->Close();
    session->Unref();
    done(s);
  });
}

void Master::ListDevices(const ListDevicesRequest* req,
                         ListDevicesResponse* resp, MyClosure done) {
  SchedClosure([this, req, resp, done]() {
    std::vector<Device*> remote_devices;
    Status s = DeviceFinder::GetRemoteDevices({}, env_, &remote_devices);
    if (s.ok()) {
      for (Device* dev : env_->local_devices) {
        *(resp->add_local_device()) = dev->attributes();
      }
      for (Device* dev : remote_devices) {
        *(resp->add_remote_device()) = dev->attributes();
        delete dev;
      }
    }
    done(s);
  });
}

void Master::CleanupWorkers(const ResetRequest& reset) {
  std::vector<string> worker_names;
  env_->worker_cache->ListWorkers(&worker_names);
  if (!worker_names.empty()) {
    const int num_workers = worker_names.size();
    std::vector<Notification> n(num_workers);
    CleanupAllRequest req;
    (*req.mutable_container()) = reset.container();
    std::vector<CleanupAllResponse> resp(num_workers);
    int c = 0;
    for (int i = 0; i < num_workers; ++i) {
      const string& worker_name = worker_names[i];
      auto worker = env_->worker_cache->CreateWorker(worker_name);
      if (worker) {
        worker->CleanupAllAsync(
            &req, &resp[i], [this, &n, worker_name, worker, c](Status s) {
              TF_CHECK_OK(s);
              env_->worker_cache->ReleaseWorker(worker_name, worker);
              n[c].Notify();
            });
      } else {
        n[c].Notify();
      }
      ++c;
    }
    for (size_t i = 0; i < n.size(); ++i) {
      n[i].WaitForNotification();
    }
  }
}

void Master::Reset(const ResetRequest* req, ResetResponse* resp,
                   MyClosure done) {
  // Vector to hold the session pointers present in the sessions_
  // (string->Session*) map.
  std::vector<MasterSession*> sessions_to_close;
  {
    mutex_lock l(mu_);
    // NOTE(mrry): Transfer one reference to each session from the
    // `sessions_` map to the `sessions_to_close` vector.
    for (const auto& entry : sessions_) {
      sessions_to_close.push_back(entry.second);
    }
    sessions_.clear();
  }

  CleanupWorkers(*req);

  SchedClosure([sessions_to_close, done]() {
    Status s;
    for (MasterSession* session : sessions_to_close) {
      s.Update(session->Close());
      session->Unref();
    }
    done(s);
  });
}

}  // end namespace tensorflow


text:
local function callback(extra, success, result)
  if success then
    print('File downloaded to:', result)
  else
    print('Error downloading: '..extra)
  end
end

local function run(msg, matches)
  if msg.media then
    if msg.media.type == 'document' then
      load_document(msg.id, callback, msg.id)
    end
    if msg.media.type == 'photo' then
      load_photo(msg.id, callback, msg.id)
    end
    if msg.media.type == 'video' then
      load_video(msg.id, callback, msg.id)
    end
    if msg.media.type == 'audio' then
      load_audio(msg.id, callback, msg.id)
    end
  end
end

local function pre_process(msg)
  if not msg.text and msg.media then
    msg.text = '['..msg.media.type..']'
  end
  return msg
end

return {
  description = "When bot receives a media msg, download the media.",
  usage = "",
  run = run,
  patterns = {
    '%[(document)%]',
    '%[(photo)%]',
    '%[(video)%]',
    '%[(audio)%]'
  },
  pre_process = pre_process
}


text:
package com.fuzz.android.salvager.objects.icepick;

import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author Andrew Grosner (fuzz)
 */
public class ComplexObject {

    List<String> list;

    Map<String, Integer> map;
}


text:
require 'puppet/application'

class Formatter

  def initialize(width)
    @width = width
  end

  def wrap(txt, opts)
    return "" unless txt && !txt.empty?
    work = (opts[:scrub] ? scrub(txt) : txt)
    indent = (opts[:indent] ? opts[:indent] : 0)
    textLen = @width - indent
    patt = Regexp.new("^(.{0,#{textLen}})[ \n]")
    prefix = " " * indent

    res = []

    while work.length > textLen
      if work =~ patt
        res << $1
        work.slice!(0, $MATCH.length)
      else
        res << work.slice!(0, textLen)
      end
    end
    res << work if work.length.nonzero?
    prefix + res.join("\n#{prefix}")
  end

  def header(txt, sep = "-")
    "\n#{txt}\n" + sep * txt.size
  end

  private

  def scrub(text)
    # For text with no carriage returns, there's nothing to do.
    return text if text !~ /\n/
    indent = nil

    # If we can match an indentation, then just remove that same level of
    # indent from every line.
    if text =~ /^(\s+)/
      indent = $1
      return text.gsub(/^#{indent}/,'')
    else
      return text
    end
  end

end

class TypeDoc

  def initialize
    @format = Formatter.new(76)
    @types = {}
    Puppet::Type.loadall
    Puppet::Type.eachtype { |type|
      next if type.name == :component
      @types[type.name] = type
    }
  end

  def list_types
    puts "These are the types known to puppet:\n"
    @types.keys.sort { |a, b|
      a.to_s <=> b.to_s
    }.each do |name|
      type = @types[name]
      s = type.doc.gsub(/\s+/, " ")
      n = s.index(". ")
      if n.nil?
        s = ".. no documentation .."
      elsif n > 45
        s = s[0, 45] + " ..."
      else
        s = s[0, n]
      end
      printf "%-15s - %s\n", name, s
    end
  end

  def format_type(name, opts)
    name = name.to_sym
    unless @types.has_key?(name)
      puts "Unknown type #{name}"
      return
    end
    type = @types[name]
    puts @format.header(name.to_s, "=")
    puts @format.wrap(type.doc, :indent => 0, :scrub => true) + "\n\n"

    puts @format.header("Parameters")
    if opts[:parameters]
      format_attrs(type, [:property, :param])
    else
      list_attrs(type, [:property, :param])
    end

    if opts[:meta]
      puts @format.header("Meta Parameters")
      if opts[:parameters]
        format_attrs(type, [:meta])
      else
        list_attrs(type, [:meta])
      end
    end

    if type.providers.size > 0
      puts @format.header("Providers")
      if opts[:providers]
        format_providers(type)
      else
        list_providers(type)
      end
    end
  end

  # List details about attributes
  def format_attrs(type, attrs)
    docs = {}
    type.allattrs.each do |name|
      kind = type.attrtype(name)
      docs[name] = type.attrclass(name).doc if attrs.include?(kind) && name != :provider
    end

    docs.sort { |a,b|
      a[0].to_s <=> b[0].to_s
    }.each { |name, doc|
      print "\n- **#{name}**"
      if type.key_attributes.include?(name) and name != :name
        puts " (*namevar*)"
      else
        puts ""
      end
      puts @format.wrap(doc, :indent => 4, :scrub => true)
    }
  end

  # List the names of attributes
  def list_attrs(type, attrs)
    params = []
    type.allattrs.each do |name|
      kind = type.attrtype(name)
      params << name.to_s if attrs.include?(kind) && name != :provider
    end
    puts @format.wrap(params.sort.join(", "), :indent => 4)
  end

  def format_providers(type)
    type.providers.sort { |a,b|
      a.to_s <=> b.to_s
    }.each { |prov|
      puts "\n- **#{prov}**"
      puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true)
    }
  end

  def list_providers(type)
    list = type.providers.sort { |a,b|
      a.to_s <=> b.to_s
    }.join(", ")
    puts @format.wrap(list, :indent => 4)
  end

end

class Puppet::Application::Describe < Puppet::Application
  banner "puppet describe [options] [type]"

  option("--short", "-s", "Only list parameters without detail") do |arg|
    options[:parameters] = false
  end

  option("--providers","-p")
  option("--list", "-l")
  option("--meta","-m")

  def help
    <<-'HELP'

puppet-describe(8) -- Display help about resource types
========

SYNOPSIS
--------
Prints help about Puppet resource types, providers, and metaparameters.

USAGE
-----
puppet describe [-h|--help] [-s|--short] [-p|--providers] [-l|--list] [-m|--meta]

OPTIONS
-------
* --help:
  Print this help text

* --providers:
  Describe providers in detail for each type

* --list:
  List all types

* --meta:
  List all metaparameters

* --short:
  List only parameters without detail

EXAMPLE
-------
    $ puppet describe --list
    $ puppet describe file --providers
    $ puppet describe user -s -m

AUTHOR
------
David Lutterkort

COPYRIGHT
---------
Copyright (c) 2011 Puppet Labs, LLC Licensed under the Apache 2.0 License

    HELP
  end

  def preinit
    options[:parameters] = true
  end

  def main
    doc = TypeDoc.new

    if options[:list]
      doc.list_types
    else
      options[:types].each { |name| doc.format_type(name, options) }
    end
  end

  def setup
    options[:types] = command_line.args.dup
    handle_help(nil) unless options[:list] || options[:types].size > 0
    $stderr.puts "Warning: ignoring types when listing all types" if options[:list] && options[:types].size > 0
  end

end


text:
import Em from 'ember';
import Treetab from 'ember-cli-filtertable/helpers/tree-tab';

export default Treetab;


text:
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;

namespace Potato.Net.Shared.Utils {
    /// <summary>
    /// A variety of extenstions for various tasks on a collection
    /// </summary>
    public static class CollectionExtensions {
        /// <summary>
        /// Finds the mean value given a function defining the value from an object to use.
        /// </summary>
        public static float Mean<T>(this ICollection<T> items, Func<T, float> value) {
            return items.Select(value).DefaultIfEmpty().Average(r => r);
        }

        /// <summary>
        /// Finds the mean value given a function defining the value from an object to use.
        /// </summary>
        public static float Mean<T>(this ICollection<T> items, Func<T, int> value) {
            return items.Select(value).DefaultIfEmpty().Average(r => (float)r);
        }

        /// <summary>
        /// Fetches the standard deviation of a set given a function defining the value from an object to use.
        /// </summary>
        public static float StdDev<T>(this ICollection<T> items, Func<T, float> value, float mean) {
            float standardDeviation = 0;
            float count = items.Count();

            if (count > 1) {
                float sum = items.Select(value).Sum(s => (s - mean) * (s - mean));

                standardDeviation = (float)Math.Sqrt(sum / count);
            }

            return standardDeviation;
        }

        /// <summary>
        /// Fetches the standard deviation of a set given a function defining the value from an object to use.
        /// </summary>
        public static float StdDev<T>(this ICollection<T> items, Func<T, int> value, float mean) {
            return StdDev(items, t => (float) value(t), mean);
        }
    }
}


text:
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Http.Dispatcher;

namespace DoNetExample.Service.config
{
    public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Enable Cors
            config.EnableCors();

            // Override IHttpControllerTypeResolver implementation
            // Original idea obtain from here: http://www.strathweb.com/2013/02/but-i-dont-want-to-call-web-api-controllers-controller/
            config.Services.Replace(typeof(IHttpControllerTypeResolver), new EndpointControllerTypeResolver());

            // We cleaned the field "ControllerSuffix", which stores the hardcoded controller suffix, "Controller"
            // using reflection.
            var suffix = typeof(DefaultHttpControllerSelector).GetField("ControllerSuffix", BindingFlags.Static | BindingFlags.Public);
            if (suffix != null) suffix.SetValue(null, "Endpoint");

            // Json Formatter Setings
            // Code obtain from here: http://bitoftech.net/2013/11/25/implement-model-factory-dependency-injection-configuring-formatters-web-api/
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            // Json keys in camel case format
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            // Datetime in new ISO 8601 format
            // Code obtain from here: http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
            // jsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }
    }
}


text:
import React, { PropTypes } from 'react';
import TimePeriodPill from '../commons/time-period-pills';

class NodeHeader extends React.Component {

  static propTypes = {
    nodes: PropTypes.array,
    period: PropTypes.string,
    onNodeSelect: PropTypes.func,
    onPeriodSelect: PropTypes.func
  }

  state = {
    selected: 'Select Node'
  }

  constructor(props) {
    super(props);
  }

  handleNodeItemClick = e => {
    this.props.onNodeSelect(e.target.text);
    this.setState({
      selected: e.target.text
    });
  }

  render() {
    const nodes = this.props.nodes.map((node) => {
      return (

{ node }

      );
    });

    return (

            Nodes

              <button
                type='button'
                className='btn btn-default dropdown-toggle'
                data-toggle='dropdown'
                aria-haspopup='true'
                aria-expanded='false'>
                { this.state.selected }
              </button>

                { nodes }

            <TimePeriodPill
              active={ this.props.period }
              onPeriodSelect={ this.props.onPeriodSelect }/>

    );
  }
}

export default NodeHeader;


text:
<resources>
    <string name="app_name">React Native Container</string>
</resources>