text:
using Android.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MonoGameSaveImage
{
    /// <summary>
    /// Default Project Template
    /// </summary>
    public class Game1 : Game
    {

        #region Fields
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D logoTexture;
        #endregion

        TouchCollection lastTouches;

        #region Initialization

        public Game1()
        {

            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

            graphics.IsFullScreen = true;
            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;
        }

        /// <summary>
        /// Overridden from the base Game.Initialize. Once the GraphicsDevice is setup,
        /// we'll use the viewport to initialize some values.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// Load your graphics content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be use to draw textures.
            spriteBatch = new SpriteBatch(graphics.GraphicsDevice);

            // TODO: use this.Content to load your game content here eg.
            logoTexture = Content.Load<Texture2D>("chuck");
        }

        #endregion

        #region Update and Draw

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // TODO: Add your update logic here

            base.Update(gameTime);

            var touches = TouchPanel.GetState();
            if (touches.Count == 0 && lastTouches.Count > 0)
            {
                var directory = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);

                //Jpeg
                var path = Path.Combine(directory.AbsolutePath, "chuck.jpg");
                var mimeType = "image/jpeg";
                using (var stream = File.Create(path))
                {
                    logoTexture.SaveAsJpeg(stream, logoTexture.Width, logoTexture.Height);
                }

                //Png
                //var path = Path.Combine(directory.AbsolutePath, "chuck.jpg");
                //var mimeType = "image/png";
                //using (var stream = File.Create(path))
                //{
                //    logoTexture.SaveAsPng(stream, logoTexture.Width, logoTexture.Height);
                //}

                var intent = new Intent(Intent.ActionView);
                intent.SetDataAndType(Android.Net.Uri.Parse("file://" + path), mimeType);
                Game.Activity.StartActivity(intent);
            }
            lastTouches = touches;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            // Clear the backbuffer
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            // draw the logo
            spriteBatch.Draw(logoTexture, new Vector2(0, 0), Color.White);

            spriteBatch.End();

            //TODO: Add your drawing code here
            base.Draw(gameTime);
        }

        #endregion
    }
}


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>Smarty - Multipurpose + Admin</title>
		<meta name="keywords" content="HTML5,CSS3,Template" />
		<meta name="description" content="" />
		<meta name="Author" content="Dorin Grigoras [www.stepofweb.com]" />

		<meta name="viewport" content="width=device-width, maximum-scale=1, initial-scale=1, user-scalable=0" />

		<link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400%7CRaleway:300,400,500,600,700%7CLato:300,400,400italic,600,700" rel="stylesheet" type="text/css" />

		<link href="assets/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

		<link href="assets/css/essentials.css" rel="stylesheet" type="text/css" />
		<link href="assets/css/layout.css" rel="stylesheet" type="text/css" />

		<link href="assets/css/header-1.css" rel="stylesheet" type="text/css" />
		<link href="assets/css/color_scheme/green.css" rel="stylesheet" type="text/css" id="color_scheme" />

MAINTENANCE

					The site is undergoing some scheduled maintenance. Please come back later!

									Migrating Data

										63%

									Testing

										81%

redpajama_set_name: RedPajamaGithub


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="web server" type="Python.DjangoServer" factoryName="Django server" singleton="true">
    <option name="INTERPRETER_OPTIONS" value="" />
    <option name="PARENT_ENVS" value="true" />
    <envs>
      <env name="PYTHONUNBUFFERED" value="1" />
      <env name="DJANGO_SETTINGS_MODULE" value="web.settings" />
    </envs>
    <option name="SDK_HOME" value="$USER_HOME$/.pyenv/versions/remrun/bin/python" />
    <option name="WORKING_DIRECTORY" value="" />
    <option name="IS_MODULE_SDK" value="false" />
    <option name="ADD_CONTENT_ROOTS" value="true" />
    <option name="ADD_SOURCE_ROOTS" value="true" />
    <module name="remrun" />
    <option name="launchJavascriptDebuger" value="false" />
    <option name="port" value="8000" />
    <option name="host" value="" />
    <option name="additionalOptions" value="" />
    <option name="browserUrl" value="" />
    <option name="runTestServer" value="false" />
    <option name="runNoReload" value="false" />
    <option name="useCustomRunCommand" value="false" />
    <option name="customRunCommand" value="" />
    <method />
  </configuration>
</component>


text:
<?php

/*
* This was designed to take current query string values from your URI and add them to the next page during pagination
*/

namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;

class QueryPaginateHelper extends AbstractHelper
{
    public function __invoke($data)
    {

        unset($data['page']);
        if (! empty($data)) {
            return  '&'.http_build_query($data);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace MsgPhp\User\Infrastructure\Security;

use MsgPhp\User\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

/**
 * @author Roland Franssen <franssen.roland@gmail.com>
 */
final class UserArgumentValueResolver implements ArgumentValueResolverInterface
{
    use TokenStorageAwareTrait;

    public function supports(Request $request, ArgumentMetadata $argument): bool
    {
        if (null === $type = $argument->getType()) {
            return false;
        }

        return is_a($type, User::class, true) ? ($argument->isNullable() || $this->isUser()) : false;
    }

    public function resolve(Request $request, ArgumentMetadata $argument): \Generator
    {
        yield $this->toUser();
    }
}


text:
"use strict";
var common_1 = require('angular2/common');
var menu_1 = require('../components/menu/menu');
var menu_toggle_1 = require('../components/menu/menu-toggle');
var menu_close_1 = require('../components/menu/menu-close');
var badge_1 = require('../components/badge/badge');
var button_1 = require('../components/button/button');
var blur_1 = require('../components/blur/blur');
var content_1 = require('../components/content/content');
var img_1 = require('../components/img/img');
var scroll_1 = require('../components/scroll/scroll');
var infinite_scroll_1 = require('../components/infinite-scroll/infinite-scroll');
var infinite_scroll_content_1 = require('../components/infinite-scroll/infinite-scroll-content');
var refresher_1 = require('../components/refresher/refresher');
var refresher_content_1 = require('../components/refresher/refresher-content');
var slides_1 = require('../components/slides/slides');
var tabs_1 = require('../components/tabs/tabs');
var tab_1 = require('../components/tabs/tab');
var list_1 = require('../components/list/list');
var item_1 = require('../components/item/item');
var item_sliding_1 = require('../components/item/item-sliding');
var virtual_scroll_1 = require('../components/virtual-scroll/virtual-scroll');
var virtual_item_1 = require('../components/virtual-scroll/virtual-item');
var toolbar_1 = require('../components/toolbar/toolbar');
var icon_1 = require('../components/icon/icon');
var spinner_1 = require('../components/spinner/spinner');
var checkbox_1 = require('../components/checkbox/checkbox');
var select_1 = require('../components/select/select');
var option_1 = require('../components/option/option');
var toggle_1 = require('../components/toggle/toggle');
var input_1 = require('../components/input/input');
var label_1 = require('../components/label/label');
var segment_1 = require('../components/segment/segment');
var radio_button_1 = require('../components/radio/radio-button');
var radio_group_1 = require('../components/radio/radio-group');
var searchbar_1 = require('../components/searchbar/searchbar');
var nav_1 = require('../components/nav/nav');
var nav_push_1 = require('../components/nav/nav-push');
var nav_router_1 = require('../components/nav/nav-router');
var navbar_1 = require('../components/navbar/navbar');
var id_1 = require('../components/app/id');
var show_hide_when_1 = require('../components/show-hide-when/show-hide-when');
/**
 * @name IONIC_DIRECTIVES
 * @description
 * The core Ionic directives as well as Angular's `CORE_DIRECTIVES` and `FORM_DIRECTIVES` are
 * avaialbe automatically when you bootstrap your app with the `@App` decorator. This means
 * if you are using custom components you no longer need to import `IONIC_DIRECTIVES` as they
 * are part of the `@App`s default directives.
 *
 * If you would like to **not** have them included by default, you would need to bootstrap
 * the app differently.
 *
 * Instead of starting your app like so:
 *
 * ```typescript
 * @App({
 *  template: "<ion-nav></ion-nav>"
 * })
 *
 * export class MyApp{
 *
 * }
 * ```
 *
 * We would use Angulars default way of bootstrap an app, import `IONIC_DIRECTIVES` and `ionicProviders`, then
 * declare `ionicProviders` as a dependencey.
 *
 * ```typescript
 *  import {IONIC_DIRECTIVES, ionicProviders} from 'ionic-angular';
 *  import {bootstrap} from 'angular2/platform/browser';
 *
 *  @Component({
 *      //default selector, and theme.
 *      directives: [IONIC_DIRECTIVES]
 *  })
 *  class App {}
 *
 *  bootstrap(App,ionicProviders())
 * ```
 *
 *
 *
 * #### Angular
 * - CORE_DIRECTIVES
 * - FORM_DIRECTIVES
 *
 * #### Ionic
 * - Menu
 * - MenuToggle
 * - MenuClose
 * - Badge
 * - Button
 * - Blur
 * - Content
 * - Scroll
 * - InfiniteScroll
 * - InfiniteScrollContent
 * - Refresher
 * - RefresherContent
 * - Img
 * - List
 * - ListHeader
 * - Item
 * - ItemSliding
 * - VirtualScroll
 * - VirtualItem
 * - VirtualHeader
 * - VirtualFooter
 * - Slides
 * - Slide
 * - SlideLazy
 * - Tabs
 * - Tab
 * - Toolbar
 * - ToolbarTitle
 * - ToolbarItem
 * - Icon
 * - Spinner
 * - Searchbar
 * - SearchbarInput
 * - Segment
 * - SegmentButton
 * - Checkbox
 * - RadioGroup
 * - RadioButton
 * - Select
 * - Option
 * - Toggle
 * - TextArea
 * - TextInput
 * - Label
 * - Nav
 * - NavbarTemplate
 * - Navbar
 * - NavPush
 * - NavPop
 * - NavRouter
 * - IdRef
 * - ShowWhen
 * - HideWhen
 */
exports.IONIC_DIRECTIVES = [
    // Angular
    common_1.CORE_DIRECTIVES,
    common_1.FORM_DIRECTIVES,
    // Content
    menu_1.Menu,
    menu_toggle_1.MenuToggle,
    menu_close_1.MenuClose,
    badge_1.Badge,
    button_1.Button,
    blur_1.Blur,
    content_1.Content,
    scroll_1.Scroll,
    infinite_scroll_1.InfiniteScroll,
    infinite_scroll_content_1.InfiniteScrollContent,
    refresher_1.Refresher,
    refresher_content_1.RefresherContent,
    img_1.Img,
    // Lists
    list_1.List,
    list_1.ListHeader,
    item_1.Item,
    item_sliding_1.ItemSliding,
    virtual_scroll_1.VirtualScroll,
    virtual_item_1.VirtualItem,
    virtual_item_1.VirtualHeader,
    virtual_item_1.VirtualFooter,
    // Slides
    slides_1.Slides,
    slides_1.Slide,
    slides_1.SlideLazy,
    // Tabs
    tabs_1.Tabs,
    tab_1.Tab,
    // Toolbar
    toolbar_1.Toolbar,
    toolbar_1.ToolbarTitle,
    toolbar_1.ToolbarItem,
    // Media
    icon_1.Icon,
    spinner_1.Spinner,
    // Forms
    searchbar_1.Searchbar,
    searchbar_1.SearchbarInput,
    segment_1.Segment,
    segment_1.SegmentButton,
    checkbox_1.Checkbox,
    radio_group_1.RadioGroup,
    radio_button_1.RadioButton,
    select_1.Select,
    option_1.Option,
    toggle_1.Toggle,
    input_1.TextArea,
    input_1.TextInput,
    label_1.Label,
    // Nav
    nav_1.Nav,
    navbar_1.NavbarTemplate,
    navbar_1.Navbar,
    nav_push_1.NavPush,
    nav_push_1.NavPop,
    nav_router_1.NavRouter,
    id_1.IdRef,
    show_hide_when_1.ShowWhen,
    show_hide_when_1.HideWhen
];


text:
title: "Tensor2Tensor presentation slides"
layout: slides
---

## Gentle Introduction to Tensor2Tensor

* Models
* Modalities
* Estimators
* Datasets
* Problems
* Metrics

---

## Introduction

* Training models is a very complex process and for large part similar in
  different projects.
    * Layers, optimizers, checkpointing.
* TensorFlow offers many constructs on top of the basic functionality that make
  modeling easier.
* `tf.contrib` module for volatile or experimental code.
* Tensor2Tensor is a toolkit for sequence-to-sequence modeling.
    * Very flexible: machine translation, end-to-end ASR, image classification,
      language modeling, abstractive summarization.
    * Should be easy to get started—can even download the data automatically.
    * Maintained by Google Brain team.
    * Frequent contributions.
    * Bugs and incomplete documentation.

---

## Tensor2Tensor Models

* Consist of three parts: input modality, model body, and output modality.
* Modalities abstract away the type of source and target data (words, audio,
  images).
    * Input modality converts input into feature vectors, e.g. word embeddings.
    * Output modality converts activations into outputs, e.g. word IDs.
    * Output modality also implements the loss function.
* The model body defines the architecture for low-dimensional input/output, i.e.
  everything between the modalities.

---

## Tensor2Tensor Models

![Input, body, and output of an encoder-decoder model](../assets/images/tensorflow-slides/tensor2tensor-modalities.png)

---

## Model Body

* Base class for the model body is `T2TModel`.
* The toolkit recognizes models that are registered using
  `@registry.register_model` decorator (can be selected using `--model` flag).
* Subclasses, e.g. `LSTMSeq2SeqAttention`, override `body()`.
* `model_fn()` stacks the body function between given modalities.
    * During training returns the loss.
    * During decoding returns the output distribution for the last time step.

---

## Modalities

* Base class for modalities is `Modality`.
* Subclasses implement some of `bottom()`, `top()`, `loss()`.
* Input modality provides the features, e.g. word embeddings, through `bottom()`
  method.
* Output modality provides the logits through `top()` method.
    * During training `loss()` is used.

---

## Data Parallelism

* `T2TModel` supports data parallelism.
* The data that is moved between the model parts is represented as a list of
  tensors, one for each shard.
* `expert_utils.Parallelism` is a helper class that calls a function on each
  element of a list and collects the results into a list.

---

## Estimator

* `Estimator` class is a TensorFlow abstraction that combines a model with
  instructions how to use it.
* Takes care of the training loop, variable initialization, checkpointing /
  restoring training, saving summaries for TensorBoard.
* Three modes:
    * `TRAIN` estimates model parameters.
    * `PREDICT` predicts the output distribution using a trained model.
    * `EVAL` computes the loss and possible other evaluation metrics.
* The user provides an input function `input_fn`, which the estimator uses to
  read the input data. When called, an input function returns two variables:
    * `features`, a mapping from feature name to an array of values, and
    * `labels`, an array of labels.

---

## Estimator Example

* TensorFlow provides `Estimator` subclasses that implement some common models.
* There are functions for creating `input_fn` from e.g. NumPy and pandas tables.
* `feature_columns` defines what features to use and how to handle e.g.
  categorical data.
* `model_dir` specifies a directory where checkpoints are created.
    * A checkpoint contains everything needed to continue training or evaluate
      the model.

```python
feature_cols = [tf.feature_column.numeric_column("x", shape=[28, 28])]
dnn = tf.estimator.DNNClassifier([32, 64, 32],
                                 feature_cols,
                                 model_dir,
                                 n_classes,
dnn.train(input_fn=train_input_fn, steps=2000)
accuracy = dnn_classifier.evaluate(input_fn=eval_input_fn)["accuracy"]
```

---

## Dataset

* `tf.data.Dataset` class represents a sequence of elements (for example
  input-output sentence pairs).
* The data can be for example in tensors, text files, or binary files.
* A new `Dataset` can be created by applying a transformation to another
  `Dataset`.
    * `shuffle(buffer_size)` randomizes the order of the elements.
    * `repeat()` iterates the dataset repeatedly.
    * `batch(batch_size)` always takes the next `batch_size` elements and
      creates a tensor with one more dimension.
    * `group_by_window(key_func, reduce_func, window_size)` creates batches of
      `window_size` elements with matching key.
    * `map(map_func)` performs the function `map_func` on the elements.

---

## Dataset Iterators

* `tf.data.Iterator` is an interface for reading the sequence one element at a
  time.
    * Can be created from a `Dataset` using `make_one_shot_iterator()`.
* Mimics Python iterator interface, which makes it confusing.
    * `get_next()` is called only once—it returns a `Tensor` that represents
      the next element.
    * The value of the Tensor changes on each evaluation of the graph.

---

## Input Function Example

images = tf.constant(["train/img1.png", "train/img2.png", "train/img3.png",
                      "train/img4.png", "train/img5.png", "train/img6.png"])
labels = tf.constant([0, 0, 0, 1, 1, 1])

def preprocess(image_path, label):
  image_data = tf.read_file(image_path)
  image = tf.image.decode_image(image_data, channels=3)
  return image, label

def train_input_fn():
  dataset = tf.data.Dataset.from_tensor_slices((images, labels))
  dataset = dataset.map(preprocess)
  dataset = dataset.shuffle(6)
  dataset = dataset.repeat()
  dataset = dataset.batch(2)
  iter = dataset.make_one_shot_iterator()
  return iter.get_next()

---

## Bucketing

* It would be efficient to have as little padding in mini-batches as possible.
* Tensor2Tensor uses `group_by_window()` to create mini-batches of sequences that
  are similar in length.

```
def get_bucket_id(example):
  seq_length = get_length(example)
  cond = tf.logical_and(
      tf.less_equal(buckets_min, seq_length),
      tf.less(seq_length, buckets_max))
  return tf.reduce_min(tf.where(cond))

def create_batch(bucket_id, dataset):
  padded_shapes = dict(
      [(name, [None] * len(shape))
       for name, shape in dataset.output_shapes.items()])
  return dataset.padded_batch(batch_size, padded_shapes)

dataset = dataset.apply(group_by_window(get_bucket_id,
                                        create_batch,
                                        batch_size))
```

---

## Bucketing

![Illustration of batching using group_by_window() dataset transformation](../assets/images/tensorflow-slides/group-by-window.png)

---

## TFRecord

* Before training a model with Tensor2Tensor, the dataset is converted into
  TFRecord format (using t2t-datagen).
* The data is already in raw binary format and training will be faster.
* Words are converted to integer IDs, meaning that the TFRecord files are
  created using a specific vocabulary.
* The data can be read and passed to an Estimator using `TFRecordDataset`.

---

## Custom Estimators

* Tensor2Tensor uses the base `Estimator` class, which takes `model_fn`,
  hyperparameters, and configuration (e.g. model directory) in constructor.
* `model_fn` specifies how to compute model output, given the input and the mode.
    * Such a function is given by `T2TModel` as the `estimator_model_fn()`
      method.
    * Returns a slightly different graph depending on the mode.

---

## Custom Estimators

* `model_fn` takes the following arguments:
    * `features`: feature tensors returned by the `input_fn`
    * `labels`: label tensor returned by the `input_fn`
    * `mode`: `TRAIN`, `PREDICT`, or `EVAL`
    * `params`: model hyperparameters
    * Tensor2Tensor adds `hparams` and `decode_hparams`.
* `model_fn` returns an `EstimatorSpec` that describes the output of the model
  using the input tensors:
    * In `PREDICT` mode that includes the predicted probabilities.
    * In `EVAL` mode that includes the loss and possibly a dictionary of
      operations that are used to compute other evaluation metrics.
    * In `TRAIN` mode that includes the loss and `train_op` that defines the
      optimization step.

---

## Model Function Example

def model_fn(features, labels, mode, params):
  hidden_activations = tf.layers.dense(features["inputs"], 256)
  logits = tf.layers.dense(hidden_activations, params["num_classes"])
  predicted_classes = tf.argmax(logits, 1)

  # For PREDICT, the predicted classes and probabilities are needed.
  if mode == tf.estimator.ModeKeys.PREDICT:
    predictions = {"class_ids": predicted_classes[:, tf.newaxis],
                   "probabilities": tf.nn.softmax(logits),
                   "logits": logits}
    return EstimatorSpec(mode, predictions=predictions)

  # For TRAIN and EVAL, compute the loss.
  loss = sparse_softmax_cross_entropy(labels, logits)

  # For EVAL, compute the evaluation metrics.
  if mode == tf.estimator.ModeKeys.EVAL:
    accuracy = tf.metrics.accuracy(labels, predicted_classes)
    metrics = {"accuracy": accuracy}
    return EstimatorSpec(mode, loss=loss, eval_metric_ops=metrics)

  # For TRAIN, return also the optimizer.
  optimizer = tf.train.AdagradOptimizer(learning_rate=0.1)
  train_op = optimizer.minimize(loss)
  return EstimatorSpec(mode, loss=loss, train_op=train_op)

---

## Estimator – Training

* `train_and_evaluate()` performs training, periodically evaluating the model
  and possibly executing other *hooks*.

```python
train_spec = tf.estimator.TrainSpec(train_input_fn, max_steps, hooks)
eval_spec = tf.estimator.EvalSpec(eval_input_fn)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)
```

* Recently changed; Tensor2Tensor uses the deprecated
  `tf.contrib.learn.Experiment` class.

---

## Estimator – Hooks

* Hooks are attached to a certain point of the execution.
    * Can be used to initialize, save, and monitor things.
    * Derived from `SessionRunHook`, which calls a method when a session is
      created or `run()` is called.
* Tensor2Tensor implements `MetricsBasedHook`, which quits training after loss
  has stopped decreasing.
* A dataset can be parameterized using a `tf.placeholder()` and initialized at
  the beginning of a session.

---

## Problem

* `Problem` is a Tensor2Tensor concept that defines data generation and the
  evaluation metrics that are computed during training.
    * These cannot be changed using hyperparameters, but many other aspects can.
* Subclasses implement `generate_data()` method that generates train and dev
  sets.
    * Normally downloads the data from the Internet.
* `Text2TextProblem` typically creates a vocabulary and encodes text.
    * `SubwordTextEncoder` encodes text using a subword vocabulary.

---

## Problem – Metrics

* The metrics computed at each validation are defined at `eval_metrics()`.
    * Can be monitored using TensorBoard.
* The metric that is used for early stopping is specified using the
  `--eval_early_stopping_metric` flag.
    * If not set, the loss function is used.
    * Otherwise has to be one of those returned by `eval_metrics()`.

---

## Problem – Applying

* Problem classes are registered using `@registry.register_problem` decorator
  and selected using the `--problem` command line flag.
* The data processing is done by `t2t-datagen` tool, which creates TFRecord
  files.
* Training is done by `t2t-trainer`, which operates on the binary files.

---

## Hyperparameters

* Hyperparameters are used by the problem (e.g. vocabulary size, sampling rate)
  and the model (e.g. number of layers, layer size).
* Typically a set of default hyperparameters are defined for each model in a
  function that returns a `tf.contrib.training.HParams` object.
    * Registered using `@registry.register_hparams` decorator and selected using
      the `--hparams_set` flag.
* The default values can be overridden using configuration flags.

---

## Code Organization

* `data_generators`: `Problem` and subclasses
* `data_generators/text_problems.py`: `Text2TextProblem`
* `layers/common_hparams.py`: A common set of hyperparameters
* `layers/modalities.py`: `Modality` subclasses
* `models`: `T2TModel` subclasses
* `models/lstm.py`: LSTM models and their default hyperparameter sets
* `utils/beam_search.py`: Beam search decoder
* `utils/data_reader.py`: Bucketing functions
* `utils/flags.py`: Configuration flags (other than hyperparameters)
* `utils/metrics.py`: Evaluation metrics
* `utils/modality.py`: Base `Modality` class
* `utils/rouge.py`: Functions for ROUGE score computation
* `utils/t2t_model.py`: Base `T2TModel` class
* `utils/trainer_lib.py`: Functions for creating estimator, experiment, hooks


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

<title>BankAccount</title>
<meta name="date" content="2017-01-15">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

entity

Class BankAccount

java.lang.Object

entity.BankAccount

public class BankAccount
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

BankAccount()

Constructor that sets balance to 30000.

BankAccount(int balance)

Constructor for the BankAccount class which takes an integer to set balance.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
deposit(int amount)

Deposits money to the BankAccount.

int
getBalance()

Returns the current balance of the BankAccount.

void
setBalance(int balance)

Changes the balance to new balance

boolean
transfer(Player receiver,
        int amount)

Transfers amount to receiver from the player if player has the required balance

boolean
withdraw(int amount)

Withdraws money from the BankAccount if player has the required balance

Methods inherited from class java.lang.Object

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

Constructor Detail

BankAccount

public BankAccount()

Constructor that sets balance to 30000.

BankAccount

public BankAccount(int balance)

Constructor for the BankAccount class which takes an integer to set balance.

Parameters:

balance - - integer amount to instantiate object with

Method Detail

withdraw

public boolean withdraw(int amount)

Withdraws money from the BankAccount if player has the required balance

Parameters:

amount - to withdraw

Returns:

boolean - whether the withdrawal has been completed or not

deposit

public void deposit(int amount)

Deposits money to the BankAccount.

Parameters:

amount - to deposit.

transfer

public boolean transfer(Player receiver,
                        int amount)

Transfers amount to receiver from the player if player has the required balance

Parameters:

receiver - to receive the amount

amount - to transfer

Returns:

boolean - whether the transfer has been completed or not

getBalance

public int getBalance()

Returns the current balance of the BankAccount.

Returns:

balance - the current balance.

setBalance

public void setBalance(int balance)

Changes the balance to new balance

Parameters:

balance - - the new balance

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.springframework.cloud.dataflow.server.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.dataflow.core.DataFlowPropertyKeys;

/**
 * Properties for version information of core dependencies.
 *
 * @author Gunnar Hillert
 * @author Glenn Renfro
 */
@ConfigurationProperties(prefix = VersionInfoProperties.VERSION_INFO_PREFIX)
public class VersionInfoProperties {

	public static final String VERSION_INFO_PREFIX = DataFlowPropertyKeys.PREFIX + "version-info";

	private DependencyStatus dependencyFetch;

	private Dependencies dependencies;

	/**
	 * @return instance of a {@link DependencyStatus} that determines if
	 * checksum information should be returned.
	 */
	public DependencyStatus getDependencyFetch() {
		return dependencyFetch;
	}

	/**
	 * Establish whether checksum information should be returned.
	 *
	 * @param dependencyFetch instance of {@link DependencyStatus}
	 */
	public void setDependencyFetch(DependencyStatus dependencyFetch) {
		this.dependencyFetch = dependencyFetch;
	}

	/**
	 *
	 * @return an instance of {@link Dependencies} containing about information
	 * about dependencies.
	 */
	public Dependencies getDependencies() {
		return dependencies;
	}

	/**
	 * Establishes the {@link Dependencies} instance that contains information
	 * about the dependencies.
	 *
	 * @param dependencies instance of {@link Dependencies}
	 */
	public void setDependencies(Dependencies dependencies) {
		this.dependencies = dependencies;
	}

	/**
	 * Represents whether dependency information should be returned as a part
	 * of the about result set.
	 */
	public static class DependencyStatus {
		private boolean enabled;

		/**
		 * @return true if dependencies should be returned.
		 * False if dependencies should not be returned.
		 */
		public boolean isEnabled() {
			return enabled;
		}

		/**
		 * Establishes if dependencies should returned.
		 *
		 * @param enabled true if dependencies should be returned, otherwise false.
		 */
		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}
	}

	/**
	 * The dependencies that will be returned by the about controller.
	 */
	public static class Dependencies {
		private DependencyAboutInfo springCloudDataflowShell;

		private DependencyAboutInfo springCloudDataflowCore;

		private DependencyAboutInfo springCloudDataflowDashboard;

		private DependencyAboutInfo springCloudDataflowImplementation;

		/**
		 * @return {@link DependencyAboutInfo} for the shell.
		 */
		public DependencyAboutInfo getSpringCloudDataflowShell() {
			return springCloudDataflowShell;
		}

		/**
		 * Establish the {@link DependencyAboutInfo} for the shell.
		 *
		 * @param springCloudDataflowShell the {@link DependencyAboutInfo} containing
		 *                                 information about the shell.
		 */
		public void setSpringCloudDataflowShell(DependencyAboutInfo springCloudDataflowShell) {
			this.springCloudDataflowShell = springCloudDataflowShell;
		}

		/**
		 * @return {@link DependencyAboutInfo} for the core.
		 */
		public DependencyAboutInfo getSpringCloudDataflowCore() {
			return springCloudDataflowCore;
		}

		/**
		 * Establish the {@link DependencyAboutInfo} for the core.
		 *
		 * @param springCloudDataflowCore the {@link DependencyAboutInfo} containing
		 *                                information about the core.
		 */
		public void setSpringCloudDataflowCore(DependencyAboutInfo springCloudDataflowCore) {
			this.springCloudDataflowCore = springCloudDataflowCore;
		}

		/**
		 * @return {@link DependencyAboutInfo} for the dashboard.
		 */
		public DependencyAboutInfo getSpringCloudDataflowDashboard() {
			return springCloudDataflowDashboard;
		}

		/**
		 * Establish the {@link DependencyAboutInfo} for the dashboard.
		 *
		 * @param springCloudDataflowDashboard the {@link DependencyAboutInfo} containing
		 *                                     information about the dashboard.
		 */
		public void setSpringCloudDataflowDashboard(DependencyAboutInfo springCloudDataflowDashboard) {
			this.springCloudDataflowDashboard = springCloudDataflowDashboard;
		}

		/**
		 * @return {@link DependencyAboutInfo} for the implementation.
		 */
		public DependencyAboutInfo getSpringCloudDataflowImplementation() {
			return springCloudDataflowImplementation;
		}

		/**
		 * Establish the {@link DependencyAboutInfo} for the implementation.
		 *
		 * @param springCloudDataflowImplementation the {@link DependencyAboutInfo} containing
		 *                                          information about the implementation.
		 */
		public void setSpringCloudDataflowImplementation(DependencyAboutInfo springCloudDataflowImplementation) {
			this.springCloudDataflowImplementation = springCloudDataflowImplementation;
		}
	}

	/**
	 * Information about the dependency.
	 */
	public static class DependencyAboutInfo {
		private String name;

		private String version;

		private String url;

		private String checksumSha1;

		private String checksumSha1Url;

		private String checksumSha256;

		private String checksumSha256Url;

		/**
		 *
		 * @return the display name of the dependency.
		 */
		public String getName() {
			return name;
		}

		/**
		 * Establish the display name for the dependency.
		 *
		 * @param name String containing the name to be displayed.
		 */
		public void setName(String name) {
			this.name = name;
		}

		/**
		 *
		 * @return the version of the dependency.
		 */
		public String getVersion() {
			return version;
		}

		/**
		 * Establish the version for the dependency.
		 *
		 * @param version String containing the version.
		 */
		public void setVersion(String version) {
			this.version = version;
		}

		/**
		 *
		 * @return the url of the dependency.
		 */
		public String getUrl() {
			return url;
		}

		/**
		 * Establish the url for the dependency.
		 *
		 * @param url String containing the url.
		 */
		public void setUrl(String url) {
			this.url = url;
		}

		/**
		 *
		 * @return the sha1 encoding that should be returned for the dependency.
		 */
		public String getChecksumSha1() {
			return checksumSha1;
		}

		/**
		 * Establish the checksumSha1 for the dependency.
		 *
		 * @param checksumSha1 String containing the checksum value.
		 */
		public void setChecksumSha1(String checksumSha1) {
			this.checksumSha1 = checksumSha1;
		}

		/**
		 *
		 * @return the url to the file that contains the sha1 checksum.
		 */
		public String getChecksumSha1Url() {
			return checksumSha1Url;
		}

		/**
		 * Establish the url where the checksumSha1 file exists..
		 *
		 * @param checksumSha1Url String containing the url.
		 */
		public void setChecksumSha1Url(String checksumSha1Url) {
			this.checksumSha1Url = checksumSha1Url;
		}

		/**
		 *
		 * @return the sha256 encoding that should be returned for the dependency.
		 */
		public String getChecksumSha256() {
			return checksumSha256;
		}

		/**
		 * Establish the checksumSha256 for the dependency.
		 *
		 * @param checksumSha256 String containing the checksum value.
		 */
		public void setChecksumSha256(String checksumSha256) {
			this.checksumSha256 = checksumSha256;
		}

		/**
		 *
		 * @return the url to the file that contains the sha256 checksum.
		 */
		public String getChecksumSha256Url() {
			return checksumSha256Url;
		}

		/**
		 * Establish the url where the checksumSha256 file exists..
		 *
		 * @param checksumSha256Url String containing the url.
		 */
		public void setChecksumSha256Url(String checksumSha256Url) {
			this.checksumSha256Url = checksumSha256Url;
		}
	}
}


text:
package com.aspose.cloud.sdk.cells.model;
import java.util.ArrayList;

import com.aspose.cloud.sdk.common.BaseResponse;
import com.aspose.cloud.sdk.common.LinkModel;
import com.google.gson.annotations.SerializedName;

public class ChartsResponse extends BaseResponse {
	@SerializedName("Charts")
	public ChartsResult charts;

	public class ChartsResult {
		public ArrayList<ChartLink> ChartList;
		public LinkModel link;
	}

	public class ChartLink {
		public LinkModel link;
	}
}


text:
import React      from "react";
import Pages      from "../pages";
import { Link }   from "react-router";

export default class SiteList extends React.Component {
  render() {
    return(

        {this.props.site.domain}
        {this.props.site.protocol}

          <Link to={Pages.site(this.props.site.id)} className="site-link" >
            <button>Details</button>
          </Link>

    );
  }
}

SiteList.propTypes = {
  site: React.PropTypes.object.isRequired
};


text:
ARapid_2PlayerController::ARapid_2PlayerController()
{
	bShowMouseCursor = true;
	DefaultMouseCursor = EMouseCursor::Crosshairs;
}

void ARapid_2PlayerController::PlayerTick(float DeltaTime)
{
	Super::PlayerTick(DeltaTime);

	// keep updating the destination every tick while desired
	if (bMoveToMouseCursor)
	{
		MoveToMouseCursor();
	}
}

void ARapid_2PlayerController::SetupInputComponent()
{
	// set up gameplay key bindings
	Super::SetupInputComponent();

	InputComponent->BindAction("SetDestination", IE_Pressed, this, &ARapid_2PlayerController::OnSetDestinationPressed);
	InputComponent->BindAction("SetDestination", IE_Released, this, &ARapid_2PlayerController::OnSetDestinationReleased);

	// support touch devices
	InputComponent->BindTouch(EInputEvent::IE_Pressed, this, &ARapid_2PlayerController::MoveToTouchLocation);
	InputComponent->BindTouch(EInputEvent::IE_Repeat, this, &ARapid_2PlayerController::MoveToTouchLocation);
}

void ARapid_2PlayerController::MoveToMouseCursor()
{
	// Trace to see what is under the mouse cursor
	FHitResult Hit;
	GetHitResultUnderCursor(ECC_Visibility, false, Hit);

	if (Hit.bBlockingHit)
	{
		// We hit something, move there
		SetNewMoveDestination(Hit.ImpactPoint);
	}
}

void ARapid_2PlayerController::MoveToTouchLocation(const ETouchIndex::Type FingerIndex, const FVector Location)
{
	FVector2D ScreenSpaceLocation(Location);

	// Trace to see what is under the touch location
	FHitResult HitResult;
	GetHitResultAtScreenPosition(ScreenSpaceLocation, CurrentClickTraceChannel, true, HitResult);
	if (HitResult.bBlockingHit)
	{
		// We hit something, move there
		SetNewMoveDestination(HitResult.ImpactPoint);
	}
}

void ARapid_2PlayerController::SetNewMoveDestination(const FVector DestLocation)
{
	APawn* const Pawn = GetPawn();
	if (Pawn)
	{
		UNavigationSystem* const NavSys = GetWorld()->GetNavigationSystem();
		float const Distance = FVector::Dist(DestLocation, Pawn->GetActorLocation());

		// We need to issue move command only if far enough in order for walk animation to play correctly
		if (NavSys && (Distance > 120.0f))
		{
			NavSys->SimpleMoveToLocation(this, DestLocation);
		}
	}
}

void ARapid_2PlayerController::OnSetDestinationPressed()
{
	// set flag to keep updating destination until released
	bMoveToMouseCursor = true;
}

void ARapid_2PlayerController::OnSetDestinationReleased()
{
	// clear flag to indicate we should stop updating the destination
	bMoveToMouseCursor = false;
}


text:
$(document).ready(function() {

    $(".lines-button").click(function(e) {
        e.preventDefault();
        $(this).toggleClass("close");
        $("header nav").toggleClass("open");
        return true;
    });

    $("#text_toggle").click(function(e) {
        e.preventDefault();
        $(".text_hide").slideToggle();
        $(this).html($(this).text() == 'Nascondi' ? 'Leggi tutto »' : 'Nascondi');
        return true;
    });

    $("#content_tab li").hide(); // Initially hide all content
    $("#tabs li:first").attr("id","current"); // Activate first tab
    $("#content_tab li:first").fadeIn(); // Show first tab content

    $('#tabs li a').click(function(e) {
        e.preventDefault();
        if ($(this).attr("class") == "current"){ //detection for current tab
            return
        }
        else{
            $("#content_tab li").hide(); //Hide all content
            $("#tabs li").attr("class",""); //Reset id's
            $(this).parent().attr("class","current"); // Activate this
            $( $(this).attr('href')).fadeIn(); // Show content for current tab
        }
    });

    $('section[data-type="background"]').each(function(){
        var $bgobj = $(this); // assigning the object

        $(window).scroll(function() {
            var yPos = -($(this).scrollTop() / $bgobj.data('speed'));

            // Put together our final background position
            var coords = '50% '+ yPos + 'px';

            // Move the background
            $bgobj.css({ backgroundPosition: coords });

        });
    });

    $('nav a[href*=#]:not([href=#])').click(function(e) {
        e.preventDefault();
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {

             if ($(".lines-button").hasClass('close')) {
                 $(".lines-button").removeClass('close');
                 $("nav").removeClass('open');

                 $('html,body').animate({ scrollTop: target.offset().top }, 1000);
                 return false;
             }
             else {
                 $('html,body').animate({ scrollTop: target.offset().top - 70}, 1000);
                 return false;
             }
          }
        }
    });
});

var base = new google.maps.LatLng(45.497536, 9.221286);
var marker;
var map;

function initialize() {
    var styles = [
        {
          stylers: [
            { hue: "#ff6600" },
            { saturation: 10 }
          ]
        },{
          featureType: "road",
          elementType: "geometry",
          stylers: [
            { lightness: 100 },
            { visibility: "simplified" }
          ]
        },{
          featureType: "road",
          elementType: "labels",
          stylers: [
            { visibility: "off" }
          ]
        }
    ];

    var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"});

    var mapOptions = {
        zoom: 17,
        center: base,
        disableDefaultUI: true,
        scrollwheel: false,
        mapTypeControlOptions: {
          mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
        }
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    marker = new google.maps.Marker({
      position: base,
      map: map,
      animation: google.maps.Animation.DROP,
    });

    google.maps.event.addListener(marker, 'click', toggleBounce);

    map.mapTypes.set('map_style', styledMap);
    map.setMapTypeId('map_style');
}

function toggleBounce() {
    if (marker.getAnimation() != null) {
        marker.setAnimation(null);
    } else {
        marker.setAnimation(google.maps.Animation.BOUNCE);
    }
}

google.maps.event.addDomListener(window, 'load', initialize);


text:
package org.apache.sqoop.manager.oracle;

import java.util.Iterator;

/**
 * Contains a list of Oracle columns.
 */
public class OracleTableColumns extends
    OraOopGenerics.ObjectList<OracleTableColumn> {

  public OracleTableColumn findColumnByName(String columnName) {

    OracleTableColumn result;

    Iterator<OracleTableColumn> iterator = this.iterator();
    while (iterator.hasNext()) {
      result = iterator.next();
      if (result.getName().equals(columnName)) {
        return result;
      }
    }
    return null;
  }

}


text:
package org.apache.pulsar.broker.service;

import org.apache.pulsar.common.policies.data.Policies;
import org.apache.pulsar.common.policies.data.PublishRate;

public class PublishRateLimiterDisable implements PublishRateLimiter {

    public static final PublishRateLimiterDisable DISABLED_RATE_LIMITER = new PublishRateLimiterDisable();

    @Override
    public void checkPublishRate() {
        // No-op
    }

    @Override
    public void incrementPublishCount(int numOfMessages, long msgSizeInBytes) {
        // No-op
    }

    @Override
    public boolean resetPublishCount() {
        // No-op
        return false;
    }

    @Override
    public boolean isPublishRateExceeded() {
        return false;
    }

    @Override
    public void update(Policies policies, String clusterName) {
        // No-op
    }

    @Override
    public void update(PublishRate maxPublishRate) {
        // No-op
    }

    @Override
    public boolean tryAcquire(int numbers, long bytes) {
        // Always allow
        return true;
    }

    @Override
    public void close() {
        // No-op
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using BetterStarterTemplate.Web.Services;
using BetterStarterTemplate.Identity.Data;
using Microsoft.Extensions.FileProviders;
//using Microsoft.AspNetCore.Hosting.Internal;
using System.IO;

namespace BetterStarterTemplate.Builder
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets("aspnet-BetterStarterTemplate.Web-5e621f9a-2638-44a6-845a-f9205732cb41");
            }

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc()
                ;
                //Adding controllers from another assembly
                //.ConfigureApplicationPartManager(manager => manager.ApplicationParts.Clear())
                //.AddApplicationPart(typeof(Controllers.AccountController).GetTypeInfo().Assembly)
                //.AddRazorOptions(options =>
                //{
                    //options.FileProviders.Clear();
                    //options.FileProviders.Add(new PhysicalFileProvider(
                    //        typeof(Client.ViewLocationExpander).GetTypeInfo().Assembly.Location
                    //    )
                    //);
                    //options.FileProviders.Add(new PhysicalFileProvider(Directory.GetCurrentDirectory() + "..\\..\\"));
                    //options.FileProviders.Add(new CompositeFileProvider(
                    //   new EmbeddedFileProvider(
                    //       typeof(Client.ViewLocationExpander).GetTypeInfo().Assembly,
                    //       "BetterStarterTemplate.Web.Client" // your external assembly's base namespace
                    //   )
                    //));

                    //options.ViewLocationExpanders.Add(new Client.ViewLocationExpander());
                //});

            //.AddApplicationPart(typeof(BetterStarterTemplate.App.Controllers.HomeController).GetTypeInfo().Assembly);

            // Add application services.
            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<ISmsSender, AuthMessageSender>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
                //app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}


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

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<title>Melocactus factsheet on ARKive - Melocactus ferreophilus</title>
        <link rel="canonical" href="http://www.arkive.org/melocactus/melocactus-ferreophilus/" />
		<link rel="stylesheet" type="text/css" media="screen,print" href="/rcss/factsheet.css" />
		<link rel="icon" href="/favicon.ico" type="image/x-icon" />
		<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />

Melocactus (Melocactus ferreophilus)

Kingdom	Plantae

Phylum	Tracheophyta

Class	Magnoliopsida

Order	Caryophyllales

Family	Cactaceae

Genus	Melocactus (1)

Melocactus ferreophilus is classified as Critically Endangered (CR) on the IUCN Red List and listed on Appendix II of CITES (2).

Information on Melocactus ferreophilus is currently being researched and written and will appear here shortly.

This information is awaiting authentication by a species expert, and will be updated as soon as possible. If you are able to help please contact:
arkive@wildscreen.org.uk

IUCN Red List (August, 2013)
http://www.iucnredlist.org

CITES (August, 2010)
http://www.cites.org


text:
'use strict';

var Pokedex = require('../pokedex'),
    logger = require('winston'),
    config = require('config.json')('./config.json');

/**
 * Start command
 * @module command/start
 */
module.exports = {

    /** Command name */
    name: '/start',

    /** Command regex pattern */
    pattern: /\/start/,

    /** Command's description to be listed in /help */
    description: '/start - Start the bot',

    /** Is the command listed in Telegram's command list? */
    list: function(user) {
        return user.active === false;
    },

    /**
     * Callback to execute when a user executes the command.
     * @param {Object} msg - The Telegram message object.
     * @param {Array}  match - The regex match result.
     * @param {Object} user - The user's stored Mongoose model.
     * @param {Boolean} created - Was the user created as a result of the command call?
     */
    callback: function(msg, match, user, created) {
        if (created) {
            logger.info('Created new user with id %s', user.telegramId);
            // New users start with the default watchlist
            user.watchlist = Pokedex.getPokemonIdsByNames(config.watchlist);
        } else {
            user.active = true;
            user.save();
        }

        logger.info('User %s is now active', user.telegramId);
        return 'Bot activated! Type /stop to stop.';
    }

};


text:
from Bio import Restriction
from Bio import Seq
from Bio.Alphabet import IUPAC

import os

from ..util import svg
from ..util import report
from ..nucleotide import fasta_file
from ..nucleotide.primer import Primer,Primers
from ..util.parser import TreekvParser

from ..util.dirutils import Filepath
from .. import db

from . import template as temp
from . import block, bsa_block, dbtss_block

from .baseseq_renderer import BaseseqRenderer
from .outline_renderer import OutlineRenderer

LENGTH_THRESHOLD = 5000

__all__ = ['Seqview']

class Seqview(object):
    def __init__(self, name, template):
        self.name = name
        self.template = template

        self.primers = Primers()
        self.restrictions = []

        self.pcrs = block.PcrsBlock(self.template, self.primers)
        self.bs_pcrs = block.BsPcrsBlock(self.template, self.primers)
        self.rt_pcrs = block.RtPcrsBlock(self.template, self.primers)

        self.bsa = bsa_block.BsaBlock(self.bs_pcrs)

        self.blocks = [self.bsa,
                       self.pcrs,
                       self.bs_pcrs,
                       self.rt_pcrs]

        self.show_bisulfite = False

    def add_block(self, block):
        self.blocks.append(block)

    def add_dbtss(self, tissues):
        block = dbtss_block.DbtssBlock(self.template, tissues)
        self.add_block(block)

    def set_show_bisulfite(self, b):
        self.show_bisulfite = b

    @classmethod
    def load_seqv(cls, filename):
        parser = TreekvParser()

        inputp = Filepath(filename)
        relative_path = lambda x: inputp.relative(x)

        post_processing = []

        def ignore_child(kv):
            if kv.has_items():
                print('Ignoring unkown child items')
                print(kv.lineinfo.error_msg())

        with open(filename,'r') as fileobj:
            bn = os.path.basename(filename)

            tree = parser.readfp(fileobj, filename)

            e = None

            kv = tree.get_one('general/genbank')
            if kv:
                with open(relative_path(kv.value), 'r') as f:
                    e = cls.create_genbank(bn, f.read())
            else:
                kv = tree.get_one('general/sequence')
                if kv:
                    e = cls.create_sequence(bn, kv.value)
                else:
                    kv = tree.get_one('general/gene')
                    if kv:
                        try:
                            e = cls.create_gene(kv.value.strip())
                        except db.NoSuchGene as e:
                            print('gene entry: No such Gene %s'%kv.value)
            if not e:
                print('unkown sequence. exit.')
                return None

            kv = tree.get_one('general/primers')
            if kv:
                for v in kv.value_list():
                    e.primers.load_file(relative_path(v))

            kv = tree.get_one('general/tss')
            if kv:
                e.add_dbtss(kv.value_list())

            kv = tree.get_one('general/restriction')
            if kv:
                for v in kv.value_list():
                    # AllEnzymes is not RestrictionBatch, but set....
                    if v not in Restriction.CommOnly.elements():
                        print('No such Restriction Enzyme: {0}'.format(v))
                        continue
                    e.restrictions.append(v)

            kv = tree.get_one('general/show_bisulfite')
            if kv:
                if kv.value in ['True','1','true','t','T']:
                    e.set_show_bisulfite(True)
                elif kv.value in ['False','0','false','f','F']:
                    e.set_show_bisulfite(False)
                else:
                    print('Unkown Boolean value: {0}. must be True or False'.format(kv.value))

            kv = tree.get_one('general/bsa')
            if kv:
                kv = tree.get_one('general/bsa/result')
                if kv:
                    bsa_file = relative_path(kv.value)
                    def lazy():
                        e.bsa.read(relative_path(bsa_file))
                    post_processing.append(lazy)
                kv = tree.get_one('general/bsa/celllines')
                if kv:
                    e.bsa.set_celllines(kv.value_list())

            for kv in tree.get_one('general').get_unused():
                print(kv.lineinfo.error_msg('Ignored.'))

            kv = tree.get_one('primers')
            if kv:
                for kv in list(kv.items()):
                    e.primers.append(Primer(kv.key, kv.value))

            def pcr_line(kv):
                name = kv.key.split(',')[0].strip()
                ls = kv.value.split(',')
                if len(ls)!=2:
                    print('you must specify 2 primer names separated by "," for each pcr: %s'%name)
                    return None, None, None
                fw = ls[0].strip()
                rv = ls[1].strip()
                return name, fw, rv

            pp = tree.get_one('pcr')
            if pp:
                for kv in list(pp.items()):
                    name, fw, rv = pcr_line(kv)
                    if not name:
                        continue
                    e.pcrs.add(name, fw, rv)

            pp = tree.get_one('rt_pcr')
            if pp:
                for kv in list(pp.items()):
                    name, fw, rv = pcr_line(kv)
                    if not name:
                        continue
                    e.rt_pcrs.add(name, fw, rv)

            pp = tree.get_one('bs_pcr')
            if pp:
                for kv in list(pp.items()):
                    name, fw, rv = pcr_line(kv)
                    if not name:
                        continue
                    e.bs_pcrs.add(name, fw, rv)

        for p in post_processing:
            p()
        return e

    @classmethod
    def create_genbank(cls, name, content):
        template = temp.GenbankTemplate(content, None)
        return cls(name, template)

    @classmethod
    def create_sequence(cls, name, content):
        sequence = Seq.Seq(content.upper(), IUPAC.unambiguous_dna)
        template = temp.SequenceTemplate(sequence)
        return cls(name, template)

    @classmethod
    def create_gene(cls, gene_symbol):
        locus = db.instance.genomedb.get_gene_locus(gene_symbol)
        print(gene_symbol,locus)
        locus = locus.expand(1000,1000)
        genbank = db.instance.centrez.get_genbank(locus)
        template = temp.GenbankTemplate(genbank, locus)
        return cls(gene_symbol, template)

    def svg_genome(self):
        # todo change track_genome to svg_genome(self, t)

        scale = 1.
        length = len(self.template.seq)
        if length > LENGTH_THRESHOLD:
            scale = 1.*length/LENGTH_THRESHOLD

        t = OutlineRenderer(scale)

        start = -1* self.template.transcript_start_site
        t.add_sequence_track(self.template.seq, self.template.features, start)

        for block in self.blocks:
            t.add_hline(length, 10)
            block.svg_genome(t)

        return svg.SvgPadding(20,20,t).svg()

    def svg_transcript(self):
        t = OutlineRenderer(1)

        for tr in self.template.transcripts:
            t.add_transcript_track(tr.name, tr.seq, tr.feature)
            self.rt_pcrs.svg_transcript(t, tr)
        return svg.SvgPadding(20,20,t).svg()

    def baseseq_renderer(self, template, bisulfite):
        key = '_baseseq_{}'.format(bisulfite)
        if not hasattr(template, key):
            aseq = BaseseqRenderer(template, bisulfite)

            for p in self.primers:
                aseq.add_primer(p)

            aseq.add_restriction_batch(Restriction.RestrictionBatch(self.restrictions))
            setattr(template, key, aseq)
        return getattr(template, key)

    def fasta(self):
        name = '{} : {}'.format(self.template.name, self.template.description)
        return fasta_file(name, self.template.seq)

    def has_transcripts(self):
        return not not self.template.transcripts

    def html_content(self, b, toc, subfs):
        svgs = [('genome.svg', 'Outline', self.svg_genome())]
        if self.has_transcripts():
            svgs.append(('transcript.svg', 'Transcript', self.svg_transcript()))

        for filename, name, svg in svgs:
            subfs.write(filename, svg)
            link = subfs.get_link_path(filename)
            with report.section(b, toc, name):
                with b.a(href=link):
                    #b.write_raw(svg.svg_node())
                    b.img(src=link, width='1000px')

        baseseq = self.baseseq_renderer(self.template.seq, self.show_bisulfite).track(width = 120).svg()
        links = [('baseseq.svg', 'Base Sequence', baseseq),
                 ('seq.seq.txt', 'genome sequence (.seq)', str(self.template.seq)),
                 ('seq.fasta.txt', 'genome sequence (.fasta)', self.fasta())]
        with report.section(b, toc, 'Files'):
            with b.ul:
                for filename, name, svg in links:
                    subfs.write(filename, svg)
                    link = subfs.get_link_path(filename)
                    with b.li:
                        b.a(name, href=link)

        for block in self.blocks:
            if 'html_content' in dir(block):
                block.html_content(b, toc, subfs, self)

    def write_html(self, outputp):
        report.write_html(outputp, 'Seqview: '+self.name, self.html_content)


text:
laboratory on search engine.

- lucenenetty
 - lucene   create index and query
 -  netty   http server with websocket

- elasticsearch plugin
 -   rest module   provide extra http api
 - script module   native script score

- phantomjs
 - spider   load page, word frequency, link collect

- word2vec

- tiny
 - matchbox : simplified in-memory graph engine
 - brook : event router, send incomming events to registered urls
 - binlog\_publisher : read mysql/mariadb binlog from remote server and publish database changes


text:
package com.thaiopensource.util;

public class Equal {
  private Equal() { }

  static public boolean equal(Object obj1, Object obj2) {
    return obj1 == null ? obj2 == null : obj1.equals(obj2);
  }
}


text:
<?php

namespace AppBundle\DataFixtures\ORM;

use AppBundle\Entity\Article;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Yaml\Yaml;

class LoadArticleData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        // Load users data from YML
        $articlesData = Yaml::parse(file_get_contents(realpath(dirname(__FILE__).'/../YML/articles.yml')));

        foreach ($articlesData as $articleData) {
            $article = new Article();
            $article
                ->setTitle($articleData['title'])
                ->setContent($articleData['content'])
                ->setAuthor($this->getReference('User.'.$articleData['author']))
                ->setCreatedAt(new \DateTime())
                ->setUpdatedAt(new \DateTime())
            ;

            if (!empty($articleData['publishedAt'])) {
                $article->setPublishedAt(new \DateTime($articleData['publishedAt']));
            }

            $manager->persist($article);
        }

        $manager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getOrder()
    {
        return 20;
    }
}


text:
package cc.mallet.types.tests;

import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.util.Arrays;
import java.io.IOException;

import cc.mallet.types.MatrixOps;
import cc.mallet.types.Matrixn;
import cc.mallet.types.SparseMatrixn;

/**
 * Created: Aug 30, 2004
 *
 * @author casutton@cs.umass.edu
 * @version $Id: TestSparseMatrixn.java,v 1.1 2007/10/22 21:37:55 mccallum Exp $
 */
public class TestSparseMatrixn extends TestCase {

  public TestSparseMatrixn (String name)
  {
    super (name);
  }

  public void testIndexing1d ()
  {
    double m1[] = new double[]{1.0, 2.0, 3.0, 4.0};
    int idx1[] = new int[1];
    SparseMatrixn a = new SparseMatrixn (m1);
    a.singleToIndices (3, idx1);
    assertEquals (3, idx1[0]);
    assertEquals (3, a.singleIndex (idx1));
  }

  public void testIndexing2d ()
  {
    int[] sizes = new int[]{2, 3};
    double[] m1 = new double[6];
    for (int i = 0; i < 6; i++) {
      m1[i] = 2.0 * i;
    }
    SparseMatrixn a = new SparseMatrixn (sizes, m1);
    int[] idx1 = new int[2];
    a.singleToIndices (5, idx1);
    System.out.println (idx1[0]+" , "+idx1[1]);

    int[] trueIdx = new int[] {1, 2};
    assertTrue (Arrays.equals (trueIdx, idx1));
    assertEquals (5, a.singleIndex (idx1));
    assertEquals (10.0, a.value (idx1), 1e-12);
  }

  public void testIndexing3d ()
  {
    SparseMatrixn a = make3dMatrix ();
    int[] idx1 = new int[3];
    a.singleToIndices (21, idx1);

    int[] trueIdx = new int[]{1, 2, 1};
    assertTrue (Arrays.equals (trueIdx, idx1));
    assertEquals (21, a.singleIndex (idx1));
    assertEquals (0, a.value (idx1), 1e-12);

    int[] idx2 = new int[]{1, 2, 2};
    assertEquals (22, a.singleIndex (idx2));
    assertEquals (44.0, a.value (idx2), 1e-12);
  }

  private SparseMatrixn make3dMatrix ()
  {
    int[] sizes = new int[]{2, 3, 4};
    TIntArrayList idxs = new TIntArrayList ();
    TDoubleArrayList vals = new TDoubleArrayList ();

    for (int i = 0; i < 24; i++) {
      if (i % 3 != 0) {
        idxs.add (i);
        vals.add (2.0 * i);
      }
    }

    SparseMatrixn a = new SparseMatrixn (sizes, idxs.toArray (), vals.toArray ());
    return a;
  }

  public void testSparseMatrixnSerializable () throws IOException, ClassNotFoundException
  {
    SparseMatrixn a = make3dMatrix ();
    SparseMatrixn b = (SparseMatrixn) TestSerializable.cloneViaSerialization (a);

    assertEquals (a.singleSize(), b.singleSize());
    for (int i = 0; i < a.singleSize (); i++) {
      int[] idxa = new int [a.getNumDimensions ()];
      int[] idxb = new int [a.getNumDimensions ()];

      a.singleToIndices (i, idxa);
      b.singleToIndices (i, idxb);

      assertTrue (Arrays.equals (idxa, idxb));
      assertEquals (a.value (idxa), b.value (idxb), 1e-12);
    }
  }

  public static Test suite ()
  {
    return new TestSuite (TestSparseMatrixn.class);
  }

  public static void main (String[] args) throws Throwable
  {
    TestSuite theSuite;
    if (args.length > 0) {
      theSuite = new TestSuite ();
      for (int i = 0; i < args.length; i++) {
        theSuite.addTest (new TestSparseMatrixn (args[i]));
      }
    } else {
      theSuite = (TestSuite) suite ();
    }

    junit.textui.TestRunner.run (theSuite);
  }

}


text:
import pyximport
pyximport.install()

import foo2


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace Karpach.DebugAttachManager.Controls
{
    /// <summary>
    /// Interaction logic for ToggleImageButton.xaml
    /// </summary>
    public partial class ToggleImageButton : UserControl
    {
        public ToggleImageButton()
        {
            InitializeComponent();
        }

        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static readonly DependencyProperty TextProperty =
          DependencyProperty.Register("Text", typeof(string), typeof(ToggleImageButton), new UIPropertyMetadata(""));

        public ImageSource Image
        {
            get { return (ImageSource)GetValue(ImageProperty); }
            set { SetValue(ImageProperty, value); }
        }

        public static readonly DependencyProperty ImageProperty =
           DependencyProperty.Register("Image", typeof(ImageSource), typeof(ToggleImageButton), new UIPropertyMetadata(null));

        public bool IsChecked
        {
            get { return (bool)GetValue(IsCheckedProperty); }
            set { SetValue(IsCheckedProperty, value); }
        }

        public static readonly DependencyProperty IsCheckedProperty =
          DependencyProperty.Register("IsChecked", typeof(bool), typeof(ToggleImageButton), new UIPropertyMetadata(false));

        public delegate void CheckedHandler(object sender, RoutedEventArgs e);
        public event CheckedHandler Checked;

        public void ToggleButtonChecked(object sender, RoutedEventArgs e)
        {
            var toggleButton = sender as ToggleButton;
            if (toggleButton != null)
            {
                var grid = toggleButton.Parent as Grid;
                if (grid != null)
                {
                    var toggleImageButton = grid.Parent as ToggleImageButton;
                    if (toggleImageButton != null)
                    {
                        toggleImageButton.Checked(sender, e);
                    }
                }
            }
            e.Handled = false;
        }

        public delegate void UnCheckedHandler(object sender, RoutedEventArgs e);
        public event UnCheckedHandler UnChecked;

        public void ToggleButtonUnChecked(object sender, RoutedEventArgs e)
        {
            var toggleButton = sender as ToggleButton;
            if (toggleButton != null)
            {
                var grid = toggleButton.Parent as Grid;
                if (grid != null)
                {
                    var toggleImageButton = grid.Parent as ToggleImageButton;
                    if (toggleImageButton != null)
                    {
                        toggleImageButton.UnChecked(sender, e);
                    }
                }
            }
            e.Handled = false;
        }
    }
}


text:
define(function (require) {

    require('../../model/Component').registerSubTypeDefaulter('dataZoom', function (option) {
        // Default 'slider' when no type specified.
        return 'slider';
    });

});


text:
import React from 'react';
import styled from 'styled-components';
import { injectIntl } from 'react-intl';
import Markdown from 'react-remarkable';
import ContentBlock from 'components/ContentBlock';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import {Epigraph as EpigraphContainer, ContentContainer} from 'components/ToolPage/Main';

function Epigraph(props) {
  const { locale } = props.intl;
  const content = props.epigraphs ?
                  props.epigraphs.map(item => {
                    const text = item.replace(/(—[^—]+)$/g, '\r\n\r\n$1');

                    return (
                      <EpigraphContainer key={text} ar={locale === 'ar'}>
                        <Markdown source={text}/>
                      </EpigraphContainer>
                    );
                  }) :
                  null;

  return (
    <ContentContainer>
      <LanguageThemeProvider>
        <ContentBlock>
          {content}
        </ContentBlock>
      </LanguageThemeProvider>
    </ContentContainer>
  )
}

export default injectIntl(Epigraph);


text:
module.exports = function(api) {

	var Entry = require('../schema/entry');

	// on routes that end in /entries
	// ----------------------------------------------------
	api.route('/entries')

		// get all the entries (accessed at GET http://localhost:8080/api/entries)
		.get(function(req, res) {
			Entry.find(function(err, entries) {
				if (err)
					res.send(err);
				else res.json(entries);
			});
		})

		// create an entry (accessed at /api/entries)
		.post(function(req, res) {

			var entry = new Entry(req.body);      // create a new instance of the Entry model

			// save the entry and check for errors
			entry.save(function(err) {
				if (err)
					res.send(err);
				else
					res.json({
						message: 'Entry successfully created for ' + entry._user.email,
						entry: entry
					});
			});

		});

	// on routes that end in /entries/:entry_id
	// ----------------------------------------------------
	api.route('/entries/:entry_id')

		// get the entry with a specific ID
		.get(function(req, res) {
			Entry.findById(req.params.entry_id, function(err, entry){
				if (err)
					res.send(err)
				else res.json(entry);
			});
		})

		// update a specific entry
		.put(function(req, res){
			Entry.findOneAndUpdate({_id: req.params.entry_id}, req.body, function(err, entry){
				if (err)
					res.send(err);
				else
					res.json({
						message: "Entry successfully updated.",
						entry: entry
					});
			});
		})

		// delete a specific entry
		.delete(function(req, res){
			Entry.findOneAndRemove({_id: req.params.entry_id}, function(err, entry){
				if (err)
					res.send(err);
				else
					res.json({
						message: "Entry successfully deleted.",
						entry: entry
					});
			});
		});
}


text:
package org.wso2.carbon.apimgt.api;

/**
 * Thrown when the new block condition user tries to add already exists in the system
 */
public class BlockConditionAlreadyExistsException extends APIMgtResourceAlreadyExistsException {

    public BlockConditionAlreadyExistsException(String msg) {
        super(msg);
    }

    public BlockConditionAlreadyExistsException(String msg, Throwable e) {
        super(msg, e);
    }

    public BlockConditionAlreadyExistsException(Throwable throwable) {
        super(throwable);
    }
}


text:
package com.sequenceiq.environment.environment.dto;

import com.sequenceiq.environment.environment.domain.Environment;

public class EnvironmentExperienceDto {

    private final String name;

    private final String crn;

    private final String accountId;

    private final String cloudPlatform;

    private EnvironmentExperienceDto(String name, String crn, String accountId, String cloudPlatform) {
        this.crn = crn;
        this.name = name;
        this.accountId = accountId;
        this.cloudPlatform = cloudPlatform;
    }

    public String getName() {
        return name;
    }

    public String getCrn() {
        return crn;
    }

    public String getAccountId() {
        return accountId;
    }

    public String getCloudPlatform() {
        return cloudPlatform;
    }

    public static EnvironmentExperienceDto fromEnvironment(Environment environment) {
        return new Builder().fromEnvironment(environment);
    }

    public static EnvironmentExperienceDto fromEnvironmentDto(EnvironmentDto environmentDto) {
        return new Builder().fromEnvironmentDto(environmentDto);
    }

    @Override
    public String toString() {
        return "EnvironmentExperienceDto{" +
                "name='" + name + '\'' +
                ", crn='" + crn + '\'' +
                ", cloudPlatform='" + cloudPlatform + '\'' +
                ", accountId='" + accountId + '\'' +
                '}';
    }

    public static final class Builder {

        private String name;

        private String crn;

        private String accountId;

        private String cloudPlatform;

        public Builder() {
        }

        public Builder withName(String name) {
            this.name = name;
            return this;
        }

        public Builder withCrn(String crn) {
            this.crn = crn;
            return this;
        }

        public Builder withAccountId(String accountId) {
            this.accountId = accountId;
            return this;
        }

        public Builder withCloudPlatform(String cloudPlatform) {
            this.cloudPlatform = cloudPlatform;
            return this;
        }

        public EnvironmentExperienceDto build() {
            return new EnvironmentExperienceDto(name, crn, accountId, cloudPlatform);
        }

        public EnvironmentExperienceDto fromEnvironment(Environment environment) {
            return withName(environment.getName())
                    .withName(environment.getName())
                    .withCrn(environment.getResourceCrn())
                    .withAccountId(environment.getAccountId())
                    .withCloudPlatform(environment.getCloudPlatform())
                    .build();
        }

        public EnvironmentExperienceDto fromEnvironmentDto(EnvironmentDto environmentDto) {
            return withName(environmentDto.getName())
                    .withCrn(environmentDto.getResourceCrn())
                    .withAccountId(accountId)
                    .withCloudPlatform(environmentDto.getCloudPlatform())
                    .build();
        }

    }

}


text:
namespace clspv {
struct NativeMathPass : llvm::PassInfoMixin<NativeMathPass> {
  llvm::PreservedAnalyses run(llvm::Module &M, llvm::ModuleAnalysisManager &);
};
} // namespace clspv

#endif // _CLSPV_LIB_NATIVE_MATH_PASS_H


text:
<?php

namespace AcmePhp\Ssl\Exception;

/**
 * @author Jérémy Derussé <jeremy@derusse.com>
 */
class KeyPairGenerationException extends KeyGenerationException
{
}


text:
/*
 * RectangleGeometry.h
 *
 *  Created on: 2016年7月14日
 *      Author: lijing
 */

#ifndef POLA_RECTANGLEGEOMETRY_H_
#define POLA_RECTANGLEGEOMETRY_H_

#include "pola/graphic/geometries/Geometry2D.h"

namespace pola {
namespace graphic {

class RectangleGeometry: public Geometry2D {
public:
	RectangleGeometry(float x, float y, float w, float h);
	virtual ~RectangleGeometry();
};

} /* namespace graphic */
} /* namespace pola */

#endif /* POLA_RECTANGLEGEOMETRY_H_ */


text:
package mcjty.rftools.blocks.generator;

import mcjty.lib.thirteen.ConfigSpec;

public class CoalGeneratorConfiguration {

    public static final String CATEGORY_COALGEN = "coalgen";

    public static ConfigSpec.BooleanValue enabled;
    public static ConfigSpec.IntValue MAXENERGY; // TODO change these to longs once Configuration supports them
    public static ConfigSpec.IntValue SENDPERTICK;
    public static ConfigSpec.IntValue CHARGEITEMPERTICK;
    public static ConfigSpec.IntValue rfPerTick;
    public static ConfigSpec.IntValue ticksPerCoal;

    public static void init(ConfigSpec.Builder SERVER_BUILDER, ConfigSpec.Builder CLIENT_BUILDER) {
        SERVER_BUILDER.comment("Settings for the coal generator").push(CATEGORY_COALGEN);
        CLIENT_BUILDER.comment("Settings for the coal generator").push(CATEGORY_COALGEN);

        enabled = SERVER_BUILDER
                .comment("Whether the coal generator should exist")
                .define("enabled", true);

        rfPerTick = SERVER_BUILDER
                .comment("Amount of RF generated per tick")
                .defineInRange("generatePerTick", 60, 0, Integer.MAX_VALUE);
        ticksPerCoal = SERVER_BUILDER
                .comment("Amount of ticks generated per coal")
                .defineInRange("ticksPerCoal", 600, 0, Integer.MAX_VALUE);
        MAXENERGY = SERVER_BUILDER
                .comment("Maximum RF storage that the generator can hold")
                .defineInRange("generatorMaxRF", 500000, 0, Integer.MAX_VALUE);
        SENDPERTICK = SERVER_BUILDER
                .comment("RF per tick that the generator can send")
                .defineInRange("generatorRFPerTick", 2000, 0, Integer.MAX_VALUE);
        CHARGEITEMPERTICK = SERVER_BUILDER
                .comment("RF per tick that the generator can charge items with")
                .defineInRange("generatorChargePerTick", 1000, 0, Integer.MAX_VALUE);

        SERVER_BUILDER.pop();
        CLIENT_BUILDER.pop();
    }
}


text:
<?php
	$appDir=realpath(dirname(__FILE__).'/../');
	require_once($appDir."/models/db_base.php");
	class Match_Result extends CI_Model {
		public function __construct() {
			parent::__construct();
			$this->tmacDB = db_base::getInstance("tmac");
		}
		public function GetMatchInfo($schoolid, $leagueid) {//(cells []map[string]string) {
        		$sql = "select teamid1,teamid2,match_time,match_address,status,matchid from `match`
				where  schoolid = $schoolid and leagueid = $leagueid";
			$res = $this->tmacDB->get_data($sql);
        		return $res;
		}
		public function GetMatchResultInfo($matchid){// (cells []map[string]string) {
        		$sql = "select matchid, teamid, firstpart, secondpart, thirdpart, fourthpart, score, penalty_hit_rate, twopoint_hit_rate, threepoint_hit_rate, backboard, foul, assist, steal, mistake, modify_time, create_time  from match_result where  matchid = $matchid";
			$res = $this->tmacDB->get_data($sql);
        		return $res;
 		}
	}


text:
package shopify

import (
    "testing"
    "gopkg.in/jarcoal/httpmock.v1"
)

func TestOrderServiceRequest_Get(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("GET", "https://johnstore1.myshopify.com/admin/orders.json",
        httpmock.NewBytesResponder(200, loadSimple("orders.json")))

    _, err := client.Order.Get(nil)
    if err != nil {
        t.Errorf("Order.Get() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Find(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("GET", "https://johnstore1.myshopify.com/admin/orders/450789469.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Find(450789469, nil)
    if err != nil {
        t.Errorf("Order.Find() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Count(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("GET", "https://johnstore1.myshopify.com/admin/orders/count.json",
        httpmock.NewStringResponder(200, `{"count": 2}`))

    orderCount, err := client.Order.Count(nil)
    if err != nil {
        t.Errorf("Order.Count() returned error: %v", err)
    }

    expected := 2
    if orderCount != expected {
        t.Errorf("Order.Count() returned %d, expected %d", orderCount, expected)
    }
}

func TestOrderServiceRequest_Close(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("POST", "https://johnstore1.myshopify.com/admin/orders/450789469/close.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Close(450789469)
    if err != nil {
        t.Errorf("Order.Close() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Open(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("POST", "https://johnstore1.myshopify.com/admin/orders/450789469/open.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Open(450789469)
    if err != nil {
        t.Errorf("Order.Open() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Cancel(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("POST", "https://johnstore1.myshopify.com/admin/orders/450789469/cancel.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Cancel(450789469, nil)
    if err != nil {
        t.Errorf("Order.Cancel() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Create(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("POST", "https://johnstore1.myshopify.com/admin/orders.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Create(nil)
    if err != nil {
        t.Errorf("Order.Create() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Update(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("PUT", "https://johnstore1.myshopify.com/admin/orders/450789469.json",
        httpmock.NewBytesResponder(200, loadSimple("order.json")))

    _, err := client.Order.Update(450789469, nil)
    if err != nil {
        t.Errorf("Order.Update() returned error: %v", err)
    }
}

func TestOrderServiceRequest_Delete(t *testing.T) {
    setUp()
    defer tearDown()

    httpmock.RegisterResponder("DELETE", "https://johnstore1.myshopify.com/admin/orders/450789469.json",
        httpmock.NewStringResponder(200, `{}`))

    err := client.Order.Delete(450789469)
    if err != nil {
        t.Errorf("Order.Delete() returned error: %v", err)
    }
}


text:
import sys

from abc import ABC, abstractmethod
from shutil import get_terminal_size
from textwrap import indent, wrap
from typing import Dict, Optional

from sanic import __version__
from sanic.log import logger

class MOTD(ABC):
    def __init__(
        self,
        logo: Optional[str],
        serve_location: str,
        data: Dict[str, str],
        extra: Dict[str, str],
    ) -> None:
        self.logo = logo
        self.serve_location = serve_location
        self.data = data
        self.extra = extra
        self.key_width = 0
        self.value_width = 0

    @abstractmethod
    def display(self):
        ...  # noqa

    @classmethod
    def output(
        cls,
        logo: Optional[str],
        serve_location: str,
        data: Dict[str, str],
        extra: Dict[str, str],
    ) -> None:
        motd_class = MOTDTTY if sys.stdout.isatty() else MOTDBasic
        motd_class(logo, serve_location, data, extra).display()

class MOTDBasic(MOTD):
    def display(self):
        if self.logo:
            logger.debug(self.logo)
        lines = [f"Sanic v{__version__}"]
        if self.serve_location:
            lines.append(f"Goin' Fast @ {self.serve_location}")
        lines += [
            *(f"{key}: {value}" for key, value in self.data.items()),
            *(f"{key}: {value}" for key, value in self.extra.items()),
        ]
        for line in lines:
            logger.info(line)

class MOTDTTY(MOTD):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.set_variables()

    def set_variables(self):  # no  cov
        fallback = (108, 24)
        terminal_width = max(
            get_terminal_size(fallback=fallback).columns, fallback[0]
        )
        self.max_value_width = terminal_width - fallback[0] + 36

        self.key_width = 4
        self.value_width = self.max_value_width
        if self.data:
            self.key_width = max(map(len, self.data.keys()))
            self.value_width = min(
                max(map(len, self.data.values())), self.max_value_width
            )
        self.logo_lines = self.logo.split("\n") if self.logo else []
        self.logo_line_length = 24
        self.centering_length = (
            self.key_width + self.value_width + 2 + self.logo_line_length
        )
        self.display_length = self.key_width + self.value_width + 2

    def display(self):
        version = f"Sanic v{__version__}".center(self.centering_length)
        running = (
            f"Goin' Fast @ {self.serve_location}"
            if self.serve_location
            else ""
        ).center(self.centering_length)
        length = len(version) + 2 - self.logo_line_length
        first_filler = "─" * (self.logo_line_length - 1)
        second_filler = "─" * length
        display_filler = "─" * (self.display_length + 2)
        lines = [
            f"\n┌{first_filler}─{second_filler}┐",
            f"│ {version} │",
            f"│ {running} │",
            f"├{first_filler}┬{second_filler}┤",
        ]

        self._render_data(lines, self.data, 0)
        if self.extra:
            logo_part = self._get_logo_part(len(lines) - 4)
            lines.append(f"| {logo_part} ├{display_filler}┤")
            self._render_data(lines, self.extra, len(lines) - 4)

        self._render_fill(lines)

        lines.append(f"└{first_filler}┴{second_filler}┘\n")
        logger.info(indent("\n".join(lines), "  "))

    def _render_data(self, lines, data, start):
        offset = 0
        for idx, (key, value) in enumerate(data.items(), start=start):
            key = key.rjust(self.key_width)

            wrapped = wrap(value, self.max_value_width, break_on_hyphens=False)
            for wrap_index, part in enumerate(wrapped):
                part = part.ljust(self.value_width)
                logo_part = self._get_logo_part(idx + offset + wrap_index)
                display = (
                    f"{key}: {part}"
                    if wrap_index == 0
                    else (" " * len(key) + f"  {part}")
                )
                lines.append(f"│ {logo_part} │ {display} │")
                if wrap_index:
                    offset += 1

    def _render_fill(self, lines):
        filler = " " * self.display_length
        idx = len(lines) - 5
        for i in range(1, len(self.logo_lines) - idx):
            logo_part = self.logo_lines[idx + i]
            lines.append(f"│ {logo_part} │ {filler} │")

    def _get_logo_part(self, idx):
        try:
            logo_part = self.logo_lines[idx]
        except IndexError:
            logo_part = " " * (self.logo_line_length - 3)
        return logo_part


text:
package vidada.client.model.browser;

import archimedes.core.data.IDataProvider;
import archimedes.core.data.events.CollectionEventArg;
import archimedes.core.events.EventArgs;
import archimedes.core.events.EventHandlerEx;
import archimedes.core.events.IEvent;
import vidada.model.media.MediaItem;

import java.util.List;

/**å
 * Represents a folder-node of IBrowserItems
 * @author IsNull
 *
 */
public abstract class BrowserFolderItem implements IBrowserItem, IDataProvider<IBrowserItem> {

	private List<IBrowserItem> children = null;

	transient private final EventHandlerEx<EventArgs> openRequestEvent = new EventHandlerEx<EventArgs>();
	public IEvent<EventArgs> getOpenRequestEvent() { return openRequestEvent; }

	private final EventHandlerEx<CollectionEventArg<IBrowserItem>> mediasChangedEvent = new EventHandlerEx<CollectionEventArg<IBrowserItem>>();

	@Override
	public IEvent<CollectionEventArg<IBrowserItem>> getItemsChangedEvent() { return mediasChangedEvent; }

	/**
	 * Create a new BrowserFolderItem
	 */
	protected BrowserFolderItem() { }

	/**
	 * Load all children of this folder
	 * @return
	 */
	protected abstract List<IBrowserItem> loadChildren();

	/**
	 * Get the name of this folder
	 */
	@Override
	public abstract String getName();

	/**
	 * Since this is a folder, this will always return true.
	 */
	@Override
	public final boolean isFolder() {
		return true;
	}

	@Override
	public List<IBrowserItem> getChildren() {
		if(children == null)
			children = loadChildren();
		return children;
	}

	@Override
	public final MediaItem getData() { return null; }

	public void requestOpen() {
		openRequestEvent.fireEvent(this, EventArgs.Empty);
	}

	//
	// Implementation of IListProvider<IBrowserItem>
	//

	@Override
	public IBrowserItem get(int index) {
		return getChildren().get(index);
	}

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

	@Override
	public boolean isEmpty() {
		return getChildren().isEmpty();
	}

	@Override
	public String toString(){
		return "[" + getName() + "]";
	}

}


text:
import Person from './Person'

export default class SystemUser extends Person {
    constructor() {
        super();
    	this.loginNm=null;
    }

    getClassNames() {
        return ["BaseEntity","Person","SystemUser"];
    }

    createNew() {
        return new SystemUser();

    }
}
SystemUser.prototype.typeName = SystemUser.typeName = 'SystemUser';//for quick inspection
flexiciousNmsp.SystemUser = SystemUser;


text:
'use strict';

var knex = require('../../db/Knex'),
	Controller = require('../Controller'),
	Constants = require('../../payment/Constants'),
	GeneralConfig = require('../../GeneralConfiguration'),
	PaymentAPI = require('../../payment/Mediator'),
	defaultError = require('../../logger/HttpUtils').defaultHttpResponseError,
	OrderStore = require('../../models/store/Orders'),
	CartStore = require('../../models/store/Carts'),
	CartItemStore = require('../../models/store/CartItems'),
	notificate = require('../../config.json').mail.notificate,
	sendSuccessEmail = require('../../mail/sender').sendOrderUpdate;

class Payment extends Controller {

	notification( req, res ) {
		PaymentAPI.notification(req.body.notificationCode)
			.then((result) => {
				let transaction = PaymentAPI.getTransactionObject(result.transaction);

				OrderStore.updateFromAPI(transaction);

				sendSuccessEmail({
					subject: 'Compra atualizada para: ' + Constants.statusText[transaction.getStatus()],
					to: notificate
				}, {
					name: transaction.getSender().name,
					items: transaction.getItems(),
					shipping: transaction.getShipping().cost,
					total: transaction.getGrossAmount()
				}, function(err, info){
					if(err){
						return logger.log('error', err);
					}

					logger.log('info', info);
				});

				res.send(result);
			})
			.catch((error) => {
				console.log(error);
				res.send(error);
			});
	}

	checkout( req, res ) {
		const cartToken = CartStore.getToken(req, res);

		CartItemStore.getAll(cartToken, ['products.description']).then(result => {
			let items = result.map(item => {
				return {
					id: item.product_id,
					description: item.name,
					amount: item.value.toFixed(2),
					quantity: item.quantity
				};
			});

			knex.transaction(trx => {

				OrderStore.create({
					token: cartToken,
					pagseguro_checkout_id: 0,
					status: Constants.status.waiting_payment,
					date_created: knex.raw('now()'),
					date_updated: knex.raw('now()')
				}, items, trx).then(result => {

					let data = {
						checkout: {
							currency: Constants.currency,
							reference: result.id,
							notificationURL: GeneralConfig.getBaseUrl() + 'rest/payment/notification',
							shipping: Constants.shipping,
							items: {
								item: items
							}
						}
					};

					PaymentAPI.checkout(data)
						.then((result) => {
							let code = result.checkout.code[0];

							CartStore.removeItems(cartToken, trx).then(result => {
								trx.commit(code);

								res.send({
									success: true,
									url: PaymentAPI.getConfig().getCheckoutUrl(code)
								});
							}).catch(trx.rollback);
						})
						.catch(trx.rollback);
				}).catch(trx.rollback);
			})
			.then(result => {
				//console.log(result);
			})
			.catch(error => defaultError(res, error));
		})
		.catch(error => defaultError(res, error));
	}
}

module.exports = Payment;