text:
class Membership
  include Mongoid::Document
  include Mongoid::Timestamps

  field :year, type: Integer
  field :start, type: Time

  embedded_in :member

  def to_s
    "Year: #{year}\tRegistered on: #{created_at.strftime('%d-%m-%Y')}"
  end

  def current?
    year >= this_year
  end

  def expired?
    year < this_year
  end

  def this_year
    self.class.this_year
  end

  def self.this_year
    Date.today.month < 5 ? Date.today.year - 1 : Date.today.year
  end

  def self.register
    new year: Date.today.year, start: Time.now
  end

end


text:
package org.wisdom.tinkerpop.view;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.wisdom.tinkerpop.WisdomTinkerPopConstants;

/**
 * A view of the Graph
 */
class GraphView
{
    private Graph graph;

    public GraphView(Graph graph)
    {
        this.graph = graph;
    }

    public String getName()
    {
        return this.graph.configuration().getString(WisdomTinkerPopConstants.GRAPH_ID);
    }

    public long getEdgeCount()
    {
        return IteratorUtils.count(graph.edges());
    }

    public long getVertexCount()
    {
        return IteratorUtils.count(graph.vertices());
    }

    public Map<Object, Object> getConfiguration()
    {
        return ConfigurationConverter.getMap(graph.configuration());
    }

    public String getGraphSON()
    {
        try
        {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            GraphSONWriter.build().wrapAdjacencyList(true).create().writeGraph(os, graph);
            return new String(os.toByteArray(), "UTF8");
        }
        catch (IOException e)
        {
            return e.getMessage();
        }
    }

    public Map<String, Boolean> getGraphFeatures()
    {
        Graph.Features.GraphFeatures features = graph.features().graph();
        Map<String, Boolean> graphFeatures = new HashMap<>();
        graphFeatures.put(Graph.Features.GraphFeatures.FEATURE_COMPUTER, features.supportsComputer());
        graphFeatures.put(Graph.Features.GraphFeatures.FEATURE_CONCURRENT_ACCESS, features.supportsConcurrentAccess());
        graphFeatures.put(Graph.Features.GraphFeatures.FEATURE_PERSISTENCE, features.supportsPersistence());
        graphFeatures.put(Graph.Features.GraphFeatures.FEATURE_THREADED_TRANSACTIONS, features.supportsThreadedTransactions());
        graphFeatures.put(Graph.Features.GraphFeatures.FEATURE_TRANSACTIONS, features.supportsTransactions());

        return graphFeatures;
    }

    public Map<String, Boolean> getEdgeFeatures()
    {
        Graph.Features.EdgeFeatures features = graph.features().edge();
        Map<String, Boolean> edgeFeatures = new HashMap<>();
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES, features.supportsAddEdges());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_ADD_PROPERTY, features.supportsAddProperty());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_ANY_IDS, features.supportsAnyIds());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_CUSTOM_IDS, features.supportsCustomIds());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_NUMERIC_IDS, features.supportsNumericIds());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_REMOVE_EDGES, features.supportsRemoveEdges());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_REMOVE_PROPERTY, features.supportsRemoveProperty());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_STRING_IDS, features.supportsStringIds());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_USER_SUPPLIED_IDS, features.supportsUserSuppliedIds());
        edgeFeatures.put(Graph.Features.EdgeFeatures.FEATURE_UUID_IDS, features.supportsUuidIds());

        return edgeFeatures;
    }

    public Map<String, Boolean> getVertexFeatures()
    {
        Graph.Features.VertexFeatures features = graph.features().vertex();
        Map<String, Boolean> vertexFeatures = new HashMap<>();
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_ADD_PROPERTY, features.supportsAddProperty());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES, features.supportsAddVertices());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_ANY_IDS, features.supportsAnyIds());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_CUSTOM_IDS, features.supportsCustomIds());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_META_PROPERTIES, features.supportsMetaProperties());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_MULTI_PROPERTIES, features.supportsMultiProperties());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_NUMERIC_IDS, features.supportsNumericIds());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_REMOVE_PROPERTY, features.supportsRemoveProperty());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_REMOVE_VERTICES, features.supportsRemoveVertices());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_STRING_IDS, features.supportsStringIds());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_USER_SUPPLIED_IDS, features.supportsUserSuppliedIds());
        vertexFeatures.put(Graph.Features.VertexFeatures.FEATURE_UUID_IDS, features.supportsUuidIds());
        return vertexFeatures;
    }
}

redpajama_set_name: RedPajamaGithub


text:
Factory Muffin
==============

[![Build Status](https://img.shields.io/travis/thephpleague/factory-muffin/2.1.svg?style=flat-square)](https://travis-ci.org/thephpleague/factory-muffin)
[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/thephpleague/factory-muffin.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/factory-muffin/code-structure)
[![Quality Score](https://img.shields.io/scrutinizer/g/thephpleague/factory-muffin.svg?style=flat-square)](https://scrutinizer-ci.com/g/thephpleague/factory-muffin)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
[![Latest Version](https://img.shields.io/github/release/thephpleague/factory-muffin.svg?style=flat-square)](https://github.com/thephpleague/factory-muffin/releases)
[![Total Downloads](https://img.shields.io/packagist/dt/league/factory-muffin.svg?style=flat-square)](https://packagist.org/packages/league/factory-muffin)

The goal of this package is to enable the rapid creation of objects for the purpose of testing.

It's basically a "[factory\_girl](https://github.com/thoughtbot/factory_girl)", simplified for use with PHP.

## Installing

[PHP](https://php.net) 5.3+ and [Composer](https://getcomposer.org) are required.

In your composer.json, simply add `"league/factory-muffin": "~2.0"` to your `"require-dev"` section:
```json
{
    "require-dev": {
        "league/factory-muffin": "~2.0"
    }
}
```

## Upgrading

It maybe be useful for existing users to check out the [upgrade guide](UPGRADING.md).

## Usage

### Introduction

This is the usage guide for Factory Muffin 2.1. Within this guide, you will see "the `xyz` function can be called". You should assume that these functions should be called statically on the `League\FactoryMuffin\Facade` class. It should also be noted that you can see a real example at the end of the guide.

### The Facade

The facade class (`League\FactoryMuffin\Facade`) should always be your main point of entry for communicating with Factory Muffin. It will dynamically proxy static method calls to the underlying factory instance. The other classes, including the factory class (`League\FactoryMuffin\Factory`), are not intended for direct public use. The facade additionally provides a `reset` method that will re-create the underlying factory instance. Also, note that all public methods that would have returned void, return the factory instance in order to support method chaining.

### Factory Definitions

You can define model factories using the `define` function. You may call it like this: `League\FactoryMuffin\Facade::define('Fully\Qualifed\ModelName', array('foo' => 'bar'))`, where `foo` is the name of the attribute you want set on your model, and `bar` describes how you wish to generate the attribute. Please see the generators section for more information on how this works.

You can also define multiple different factory definitions for your models. You can do this by prefixing the model class name with your "group" followed by a colon. This results in you defining your model like this: `League\FactoryMuffin\Facade::define('myGroup:Fully\Qualifed\ModelName', array('foo' => 'bar'))`. You don't have to entirely define your model here because we will first look for a definition without the group prefix, then apply your group definition on top of that definition, overriding attribute definitions where required.

We have provided a nifty way for you to do this in your tests. PHPUnit provides a `setupBeforeClass` function. Within that function you can call `League\FactoryMuffin\Facade::loadFactories(__DIR__ . '/factories');`, and it will include all files in the factories folder. Within those php files, you can put your definitions (all your code that calls the define function). The `loadFactories` function will throw a `League\FactoryMuffin\Exceptions\DirectoryNotFoundException` exception if the directory you're loading is not found.

### Creation/Instantiation Callbacks

You may optionally specify a callback to be executed on model creation/instantiation as a third parameter when defining a definition. We will pass your model instance as the first parameter to the closure if you specify one. We additionally pass a boolean as the second parameter that will be `true` if the model is being persisted to the database (the create function was used), and `false` if it's not being persisted (the instance function was used). We're using the `isPendingOrSaved` function under the hood here. Note that if you specify a callback and use the create function, we will try to save your model to the database both before and after we execute the callback.

### Generators

#### Generic

The generic generator will be the generator you use the most. It will communicate with the faker library in order to generate your attribute.

##### Example 1

There is a simple example of setting a few different attributes.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'foo'    => 'word',          // Set the foo attribute to a random word
    'name'   => 'firstNameMale', // Set the name attribute to a random male first name
    'email'  => 'email',         // Set the email attribute to a random email address
    'body'   => 'text',          // Set the body attribute to a random string of text
    'slogan' => 'sentence',      // Set the slogan attribute to a random sentence
));
```

##### Example 2

This will set the `age` attribute to a random number between 20 and 40. Note how we're using the `;` here to pass multiple arguments to the faker method.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'age' => 'numberBetween|20;40',
));
```

##### Example 3

This will set the `name` attribute to a random female first name. It will ensure that it is unique between all your generated models.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'name' => 'unique:firstNameFemale',
));
```

##### Example 4

This will set the `profile_pic` attribute to a random image url of dimensions 400 by 400. Because we've added the optional flag at the start, not all the generated models will have an image url set; sometimes we will return null.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'profile_pic' => 'optional:imageUrl|400;400',
));
```

##### More

Check out the [faker library](https://github.com/fzaninotto/Faker) itself to see all the available methods. There are far too many to cover in the documentation here, and far too many for them to cover in their documentation too. Note that you may access the underlying faker instance using the `getFaker` method.

#### Factory

The factory generator can be useful for setting up relationships between models. The factory generator will return the model id of the model you ask it to generate.

##### Example 1

When we create a Foo object, we will find that the Bar object will been generated and saved too, and it's id will be assigned to the `bar_id` attribute of the Foo model.
```php
League\FactoryMuffin\Facade::define('Foo', array(
    'bar_id' => 'factory|Bar'
));

League\FactoryMuffin\Facade::define('Bar', array(
    'baz' => 'date|Y-m-d'
));
```

#### Call

The call generator allows you to generate attributes by calling **static** methods on your models.

##### Example 1

This will set the `foo` attribute to whatever calling `MyModel::exampleMethod()` returns.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'foo' => 'call|exampleMethod',
));
```

##### Example 2

This will set the `bar` attribute to whatever calling `MyModel::anotherMethod('hello')` returns.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'bar' => 'call|anotherMethod|hello',
));
```

##### Example 3

This will set the `baz` attribute to whatever calling the `exampleMethod` method on the `OtherModel` after we generate and save it.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'baz' => 'call|exampleMethod|factory|OtherModel',
));

League\FactoryMuffin\Facade::define('OtherModel', array(
    'example' => 'boolean',
));
```

#### Closure

The closure generator can be used if you want a more custom solution. Whatever you return from the closure you write will be set as the attribute. Note that we pass an instance of your model as the first parameter of the closure to give you even more flexibility to modify it as you wish. We additionally pass a boolean as the second parameter that will be `true` if the model is being persisted to the database (the create function was used), and `false` if it's not being persisted (the instance function was used). We're using the `isPendingOrSaved` function under the hood here.

##### Example 1

As you can see from this example, the ability to use a closure to generate attributes can be so useful and flexible. Here we use it to generate a slug based on the initially randomly generated 5 word long title.
```php
League\FactoryMuffin\Facade::define('MyModel', array(
    'title' => 'sentence|5',
    'slug' => function ($object, $saved) {
        $slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $object->title);
        $slug = strtolower(trim($slug, '-'));
        $slug = preg_replace("/[\/_|+ -]+/", '-', $slug);

        return $slug;
    },
));
```

### Creating And Seeding

The `create` function will create and save your model, and will also save anything you generate with the `Factory` generator too. If you want to create multiple instances, check out the seed `seed` function, which accepts an additional argument at the start which is the number of models to generate in the process. The `seed` function will effectively be calling the `create` function over and over. It should be noted that you can set a custom save function before you get going with the `setSaveMethod` function. Also, a reminder that the `instance` function is still available if you don't want database persistence.

You may encounter the following exceptions:
* `League\FactoryMuffin\Exceptions\ModelNotFoundException` will be thrown if the model class defined is not found.
* `League\FactoryMuffin\Exceptions\NoDefinedFactoryException` will be thrown if you try to create a model and you haven't defined a factory definition for it earlier.
* `League\FactoryMuffin\Exceptions\SaveFailedException` will be thrown if the save function on your model returns false.
* `League\FactoryMuffin\Exceptions\SaveMethodNotFoundException` will be thrown if the save function on your model does not exist.
* Any other exception thrown by your model while trying to create or save it.

There are 5 other helper functions available:
* You may call `pending` to return an array of all the objects waiting to be saved.
* You may call `isPending` with an instance of a model to check if will be saved.
* You may call `saved` to return an array of all the saved objects.
* You may call `isSaved` with an instance of a model to check if it's saved.
* You may call `isPendingOrSaved` with an instance of a model to check if it will be saved, or is already saved.

### Deleting

You can delete all your saved models with the `deleteSaved` function. It should be noted that you can set a custom delete function before you get going with the `setDeleteMethod` function.

If one or more models cannot be deleted, a `League\FactoryMuffin\Exceptions\DeletingFailedException` will be raised after we have attempted to delete all the saved models. You may access each underlying exception, in the order they were thrown during the whole process, with the `getExceptions` function which will return an array of exceptions. You may encounter the following exceptions:
* `League\FactoryMuffin\Exceptions\DeleteFailedException` will be thrown if the delete function on your model returns false.
* `League\FactoryMuffin\Exceptions\DeleteMethodNotFoundException` will be thrown if the delete function on your model does not exist.
* Any other exception thrown by your model while trying to delete it.

It's recommended that you call the `deleteSaved` function from PHPUnit's `tearDownAfterClass` function.

### Additional Customisation

You may call `League\FactoryMuffin\Facade::setCustomMaker(function ($class) { return new $class('example'); })` in order to register a closure to customise the model creation. This will be used internally by Factory Muffin rather than us just straight up using `new $class()`.

You may call  `League\FactoryMuffin\Facade::setCustomSetter(function ($object, $name, $value) { $object->set($name, $value); })` in order to register a closure to customise the attribute setting. This will be used internally by Factory Muffin when setting your attributes rather than us just using `$object->$name = $value`.

You may call `League\FactoryMuffin\Facade::setCustomSaver(function ($object) { $object->save(); $object->push(); return true; })` in order to save your object in a custom way. This will be used internally by Factory Muffin when saving your object rather than us just using `$object->save()`.

You may call `League\FactoryMuffin\Facade::setCustomDeleter(function ($object) { $object->forceDelete(); return true; })` in order to delete your object in a custom way. This will be used internally by Factory Muffin when deleting your object rather than us just using `$object->delete()`.

### Exceptions

Each exception is documented with the documentation for the functions that throw them.

You can see a diagram showing the exception hierarchy here:

![diagram](https://cloud.githubusercontent.com/assets/2829600/3857444/5dba7f1a-1f03-11e4-928a-5b24ca0f1e26.png)

### Real Examples

To start with, we need to create some definitions:
```php
# tests/factories/all.php

use League\FactoryMuffin\Facade as FactoryMuffin;

FactoryMuffin::define('Message', array(
    'user_id'      => 'factory|User',
    'subject'      => 'sentence',
    'message'      => 'text',
    'phone_number' => 'randomNumber|8',
    'created'      => 'date|Ymd h:s',
    'slug'         => 'call|makeSlug|word',
), function ($object, $saved) {
    // we're taking advantage of the callback functionality here
    $object->message .= '!';
});

FactoryMuffin::define('User', array(
    'username' => 'firstNameMale',
    'email'    => 'email',
    'avatar'   => 'imageUrl|400;600',
    'greeting' => RandomGreeting::get(),
    'four'     => function() {
        return 2 + 2;
    },
));
```

You can then use these factories in your tests:
```php
# tests/TestUserModel.php

use League\FactoryMuffin\Facade as FactoryMuffin;

class TestUserModel extends PHPUnit_Framework_TestCase
{
    public static function setupBeforeClass()
    {
        // note that method chaining is supported
        FactoryMuffin::setFakerLocale('en_EN')->setSaveMethod('save'); // optional step
        FactoryMuffin::loadFactories(__DIR__ . '/factories');
    }

    public function testSampleFactory()
    {
        $message = FactoryMuffin::create('Message');
        $this->assertInstanceOf('Message', $message);
        $this->assertInstanceOf('User', $message->user);
    }

    public static function tearDownAfterClass()
    {
        FactoryMuffin::setDeleteMethod('delete'); // optional step
        FactoryMuffin::deleteSaved();
    }
}
```

### Further Information

If you want more information, the following resources are available to you:
  * Generated api docs are available [here](http://factory-muffin.thephpleague.com/api/).
  * [Philip Brown's](https://github.com/philipbrown) article is available [here](http://culttt.com/2013/05/27/laravel-4-fixture-replacement-with-factorymuff/).
  * Our [test suite](tests) may also be useful to you.

## Contributing

Please check out our [contribution guidelines](CONTRIBUTING.md) for details.

## Credits

Factory Muffin is based on [Zizaco Zizuini](https://github.com/Zizaco)'s original work on "Factory Muff", and is currently maintained by [Scott Robertson](https://github.com/scottrobertson) and [Graham Campbell](https://github.com/GrahamCampbell). Thank you to all our wonderful [contributors](https://github.com/thephpleague/factory-muffin/contributors) too.

## License

Factory Muffin is licensed under [The MIT License (MIT)](LICENSE).


text:
<?xml version="1.0" encoding="utf-8"?>

<!--

  Copyright 2014 Sergio Carrozzo

  This file is part of Facial Expression Recognizer.

  Facial Expression Recognizer is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

   Facial Expression Recognizer is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Facial Expression Recognizer.  If not, see <http://www.gnu.org/licenses/>.

 -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textCustomDialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="5dp"/>

     <Button
        android:id="@+id/dialogCustomButtonOK"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text=" Ok "
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/textCustomDialog"/>

</RelativeLayout>


text:
'use strict';

var request = require('request'),
    step = require('step');

var core = {};

core.start = function(program) {
  var weatherApiUrl = "http://weather.livedoor.com/forecast/webservice/json/v1?city=" + program.place;
  var yoAllApi      = "http://api.justyo.co/yoall/";

  step(
    function() {
      request(weatherApiUrl, this);
    },
    function(err, response, body) {
      if (err) return;
      var json;

      if (response.statusCode == "200") {
        try {
          json = JSON.parse(body);
        } catch(e) {
          console.log("JSON parse error...");
          process.exit(1);
          return;
        }

        var forecast = json.forecasts[0];

        if (forecast.telop.indexOf("雨") != -1) {
          var params = {
            method: "POST",
            uri: yoAllApi,
            form: {api_token: program.key}
          };

          console.log("It's rainy day. :( ");
          request(params, this);

        } else {
          console.log("It's sunny day. :) ");
        }
      }
    },
    function(err, response, body) {
      if (err) return;

      if (response.statusCode == "200") {
        console.log("Yo API calling finished.");
      }
    }
  );
}

module.exports = core;


text:
<?php

namespace Victoire\Bundle\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Victoire\Bundle\PageBundle\Entity\Page;

/**
 * PostPage.
 *
 * @ORM\Entity(repositoryClass="Victoire\Bundle\BlogBundle\Repository\BlogRepository"))
 * @ORM\Table("vic_blog")
 */
class Blog extends Page
{
    const TYPE = 'blog';

    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="blog", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    protected $categories;

    /**
     * @var string
     *
     * @ORM\OneToMany(targetEntity="\Victoire\Bundle\BlogBundle\Entity\Article", mappedBy="blog")
     */
    protected $articles;

    /**
     * @var string
     *
     * @ORM\OneToMany(targetEntity="\Victoire\Bundle\BlogBundle\Entity\Tag", mappedBy="blog")
     */
    protected $tags;

    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
        $this->articles = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getArticles()
    {
        return $this->articles;
    }

    public function setArticles($articles)
    {
        $this->articles = $articles;

        return $this;
    }

    /**
     * Set categories.
     *
     * @param string $categories
     *
     * @return Blog
     */
    public function setCategories($categories)
    {
        foreach ($categories as $category) {
            $category->setBlog($this);
        }
        $this->categories = $categories;

        return $this;
    }

    /**
     * Add category.
     *
     * @param string $category
     *
     * @return Blog
     */
    public function addCategorie($category)
    {
        $category->setBlog($this);
        $this->categories[] = $category;

        return $this;
    }

    /**
     * Remove category.
     *
     * @param string $category
     *
     * @return Blog
     */
    public function removeCategorie($category)
    {
        $this->categories->removeElement($category);

        return $this;
    }

    /**
     * Get categories.
     *
     * @return string
     */
    public function getCategories()
    {
        return $this->categories;
    }

    /**
     * Get root categories.
     *
     * @return string
     */
    public function getRootCategories()
    {
        $rootCategories = [];
        foreach ($this->categories as $categories) {
            if ($categories->getLvl() == 0) {
                $rootCategories[] = $categories;
            }
        }

        return $rootCategories;
    }

    /**
     * Add rootCategory.
     *
     * @param string $rootCategory
     *
     * @return Blog
     */
    public function addRootCategory($rootCategory)
    {
        $rootCategory->setBlog($this);
        $this->categories[] = $rootCategory;

        return $this;
    }

    /**
     * Remove rootCategory.
     *
     * @param string $rootCategory
     *
     * @return Blog
     */
    public function removeRootCategory($rootCategory)
    {
        $this->categories->removeElement($rootCategory);

        return $this;
    }

    /**
     * @return string
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * @param string $tags
     */
    public function setTags($tags)
    {
        $this->tags = $tags;
    }
}


text:
package org.platanios.tensorflow.api.tensors.ops

import org.platanios.tensorflow.api.core.Shape
import org.platanios.tensorflow.api.core.exception.InvalidShapeException
import org.platanios.tensorflow.api.implicits.Implicits._
import org.platanios.tensorflow.api.ops.NN.{CNNDataFormat, NCWFormat, NWCFormat, ConvPaddingMode}
import org.platanios.tensorflow.api.tensors.{executionContext, Context, Tensor, TensorOps}
import org.platanios.tensorflow.api.types.{DataType, FLOAT16, FLOAT32, FLOAT64, INT32, INT64}
import org.platanios.tensorflow.jni.generated.tensors.{NN => NativeTensorOpsNN}

import java.nio.charset.StandardCharsets

import scala.util.DynamicVariable

/** Contains functions for executing ops related to neural networks.
  *
  * @author Emmanouil Antonios Platanios
  */
private[api] trait NN {
  //region Core Ops

  /** $OpDocNNAddBias
    *
    * @group NNOps
    * @param  value         Value tensor.
    * @param  bias          Bias tensor that must be one-dimensional (i.e., it must have rank 1).
    * @param  cNNDataFormat Data format of the input and output tensors. With the default format [[NWCFormat]], the
    *                       `bias` tensor will be added to the last dimension of the `value` tensor. Alternatively, the
    *                       format could be [[NCWFormat]], and the `bias` tensor would be added to the third-to-last
    *                       dimension.
    * @return Result as a new tensor.
    */
  def addBias(value: Tensor, bias: Tensor, cNNDataFormat: CNNDataFormat = CNNDataFormat.default): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.biasAdd(
      executionContext.value.nativeHandle, value.nativeHandle, bias.nativeHandle,
      cNNDataFormat.toString.getBytes(StandardCharsets.ISO_8859_1)))
  }

  /** $OpDocNNLinear
    *
    * @group NNOps
    * @param  x       Input tensor.
    * @param  weights Weights tensor.
    * @param  bias    Bias tensor.
    * @return Result as a new tensor.
    */
  def linear(x: Tensor, weights: Tensor, bias: Tensor = null): Tensor = {
    val product = {
      if (x.rank > 2)
        Math.tensorDot(x, weights, Seq(x.rank - 1), Seq(0))
      else
        Math.matmul(x, weights)
    }
    if (bias != null)
      addBias(product, bias)
    else
      product
  }

  /** $OpDocNNL2Normalize
    *
    * @group NNOps
    * @param  x       Input tensor.
    * @param  axes    Tensor containing the axes along which to normalize.
    * @param  epsilon Lower bound value for the norm. The created op will use `sqrt(epsilon)` as the divisor, if
    *                 `norm < sqrt(epsilon)`.
    * @return Result as a new tensor.
    */
  def l2Normalize(
      x: Tensor, axes: Tensor, epsilon: Float = 1e-12f): Tensor = {
    val dataType = DataType.mostPrecise(x.dataType, FLOAT32)
    val preciseX = Math.cast(x, dataType)
    val squareSum = Math.sum(Math.square(preciseX), axes = axes, keepDims = true)
    val xInverseNorm = Math.rsqrt(Math.maximum(squareSum, Tensor(dataType, epsilon)))
    Math.cast(Math.multiply(preciseX, xInverseNorm), x.dataType)
  }

  //endregion Core Ops

  //region Activation Ops

  /** $OpDocNNRelu
    *
    * @group NNOps
    * @param  input Input tensor.
    * @param  alpha Slope of the negative section, also known as leakage parameter. If other than `0.0f`, the negative
    *               part will be equal to `alpha * x` instead of `0`. Defaults to `0`.
    * @return Result as a new tensor.
    */
  def relu(input: Tensor, alpha: Float = 0.0f): Tensor = {
    def reluOp[T: TensorOps](i: T): T = {
      implicitly[TensorOps[T]]
          .applyUnary(i, t =>
            Tensor.fromNativeHandle(NativeTensorOpsNN.relu(executionContext.value.nativeHandle, t.nativeHandle)))
    }

    if (alpha == 0.0) {
      reluOp(input)
    } else {
      val positive = reluOp(input)
      val negative = reluOp(-input)
      positive - (Tensor(negative.dataType, alpha) * negative)
    }
  }

  /** $OpDocNNRelu6
    *
    * @group NNOps
    * @param  input Input tensor.
    * @return Result as a new tensor.
    */
  def relu6(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.relu6(executionContext.value.nativeHandle, input.nativeHandle))
  }

  /** $OpDocNNCrelu
    *
    * @group NNOps
    * @param  input Input tensor.
    * @param  axis  Along along which the output values are concatenated along.
    * @return Result as a new tensor.
    */
  def crelu(input: Tensor, axis: Tensor = -1): Tensor = relu(Basic.concatenate(Seq(input, -input), axis = axis))

  /** $OpDocNNElu
    *
    * @group NNOps
    * @param  input Input tensor.
    * @return Result as a new tensor.
    */
  def elu(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.elu(executionContext.value.nativeHandle, input.nativeHandle))
  }

  /** $OpDocNNSelu
    *
    * @group NNOps
    * @param  input Input tensor.
    * @return Result as a new tensor.
    */
  def selu(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.selu(executionContext.value.nativeHandle, input.nativeHandle))
  }

  /** $OpDocNNSoftplus
    *
    * @group NNOps
    * @param  input Input tensor.
    * @return Result as a new tensor.
    */
  def softplus(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.softplus(executionContext.value.nativeHandle, input.nativeHandle))
  }

  /** $OpDocNNSoftsign
    *
    * @group NNOps
    * @param  input Input tensor.
    * @return Result as a new tensor.
    */
  def softsign(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.softsign(executionContext.value.nativeHandle, input.nativeHandle))
  }

  //endregion Activation Ops

  /** Helper function for [[softmax]] and [[logSoftmax]] that reshapes and transposes the input logits into
    * two-dimensional tensors and then creates the corresponding native op. The output is transposed and reshaped
    * back. */
  private[this] def softmaxHelper(logits: Tensor, opFunction: Long => Long, axis: Int = -1): Tensor = {
    // We need the original shape of the logits for shape inference.
    val shape = logits.shape
    val isLastAxis = axis == -1 || axis == shape.rank - 1
    if (shape.rank == 2 && isLastAxis) {
      Tensor.fromNativeHandle(opFunction(logits.nativeHandle))
    } else if (isLastAxis) {
      // If axis is the last axis, we simply reshape the logits to a matrix and apply the internal softmax.
      val inputShape = Basic.shape(logits)
      val flattenedLogits = NN.flattenOuterAxes(logits)
      val output = Tensor.fromNativeHandle(opFunction(flattenedLogits.nativeHandle))
      Basic.reshape(output, inputShape)
    } else {
      // If axis is not the last dimension, we have to do a reshape and transpose so that we can still perform softmax
      // on its last dimension.
      // We swap the logits' axis of axis and its last axis.
      val inputRank = Basic.rank(logits)
      val swappedLogits = NN.swapAxes(logits, axis, Math.subtract(inputRank, 1))
      val shapeAfterSwap = Basic.shape(swappedLogits)
      // We reshape the logits into a matrix.
      val flattenedLogits = NN.flattenOuterAxes(swappedLogits)
      // We perform the actual softmax on the last axis.
      var output = Tensor.fromNativeHandle(opFunction(flattenedLogits.nativeHandle))
      // We transform back the output tensor.
      output = Basic.reshape(output, shapeAfterSwap)
      output = NN.swapAxes(output, axis, Math.subtract(inputRank, 1))
      output
    }
  }

  /** $OpDocNNSoftmax
    *
    * @group NNOps
    * @param  logits Tensor containing the logits with data type [[FLOAT16]], [[FLOAT32]], or [[FLOAT64]].
    * @param  axis   Axis along which to perform the softmax. Defaults to `-1` denoting the last axis.
    * @return Result as a new tensor.
    */
  def softmax(logits: Tensor, axis: Int = -1): Tensor = {
    softmaxHelper(logits, NativeTensorOpsNN.softmax(executionContext.value.nativeHandle, _), axis)
  }

  /** $OpDocNNLogSoftmax
    *
    * @group NNOps
    * @param  logits Tensor containing the logits with data type [[FLOAT16]], [[FLOAT32]], or [[FLOAT64]].
    * @param  axis   Axis along which to perform the log-softmax. Defaults to `-1` denoting the last axis.
    * @return Result as a new tensor.
    */
  def logSoftmax(logits: Tensor, axis: Int = -1): Tensor = {
    softmaxHelper(logits, NativeTensorOpsNN.logSoftmax(executionContext.value.nativeHandle, _), axis)
  }

  //region Loss Ops

  /** $OpDocNNL2Loss
    *
    * @group NNOps
    * @param  input [[FLOAT16]], [[FLOAT32]], or [[FLOAT64]] input tensor.
    * @return Result as a new tensor.
    */
  def l2Loss(input: Tensor): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.l2Loss(executionContext.value.nativeHandle, input.nativeHandle))
  }

  private[this] def nativeCrossEntropyProxy(
      features: Long,
      labels: Long,
      function: (Long, Long, Long) => Array[Long]
  ): Array[Long] = {
    function(executionContext.value.nativeHandle, features, labels)
  }

  /** $OpDocNNSoftmaxCrossEntropy
    *
    * @group NNOps
    * @param  logits Tensor of shape `[D0, D1, ..., Dr-1, numClasses]` and data type [[FLOAT16]], [[FLOAT32]], or
    *                [[FLOAT64]], containing unscaled log probabilities.
    * @param  labels Tensor of shape `[D0, D1, ..., Dr-1, numClasses]` and data type [[FLOAT16]], [[FLOAT32]], or
    *                [[FLOAT64]], where each row must be a valid probability distribution.
    * @param  axis   The class axis, along which the softmax is computed. Defaults to `-1`, which is the last axis.
    * @return Result as a new tensor, with rank one less than that of `logits` and the same data type as `logits`,
    *         containing the softmax cross entropy loss.
    */
  def softmaxCrossEntropy(logits: Tensor, labels: Tensor, axis: Int = -1): Tensor = {
    // Labels and logits must be of the same data type.
    val preciseLogits = if (logits.dataType == FLOAT16) Math.cast(logits, FLOAT32) else logits
    val preciseLabels = Math.cast(labels, preciseLogits.dataType)
    val inputRank = Basic.rank(preciseLogits)
    // We move axis to the end, if it's not already the last axis.
    val transposedLogits = NN.moveAxisToEnd(preciseLogits, axis, inputRank)
    val transposedLabels = NN.moveAxisToEnd(preciseLabels, axis, inputRank)
    val inputShape = Basic.shape(preciseLogits)
    // Flatten transposedLogits and transposedLabels into matrices.
    val flattenedLogits = NN.flattenOuterAxes(transposedLogits)
    val flattenedLabels = NN.flattenOuterAxes(transposedLabels)
    // Create the native op.
    // The second output tensor contains the gradients, which is used for the gradient computation.
    val output = Tensor.fromNativeHandle(nativeCrossEntropyProxy(
      flattenedLogits.nativeHandle, flattenedLabels.nativeHandle,
      NativeTensorOpsNN.softmaxCrossEntropyWithLogits).apply(0))
    // The output shape should be the input shape without the axis over which the cross entropy was computed.
    val outputShape = Basic.slice(
      inputShape,
      Tensor.fill(inputShape.dataType, Shape(1))(0),
      Basic.expandDims(Math.subtract(inputRank, 1), -1))
    val reshapedTensor = Basic.reshape(output, outputShape)
    // We cast back to the original logits data type, if necessary.
    if (logits.dataType == FLOAT16)
      Math.cast(reshapedTensor, FLOAT16)
    else
      reshapedTensor
  }

  /** $OpDocNNSparseSoftmaxCrossEntropy
    *
    * @group NNOps
    * @param  logits Tensor of shape `[D0, D1, ..., Dr-1, numClasses]` (where `r` is the rank of `labels` and of the
    *                result) and data type [[FLOAT16]], [[FLOAT32]], or [[FLOAT64]], containing unscaled log
    *                probabilities.
    * @param  labels Tensor of shape `[D0, D1, ..., Dr-1]` (where `r` is the rank of `labels` and of the result) and
    *                data type [[INT32]] or [[INT64]]. Each entry in `labels` must be an index in `[0, numClasses)`.
    *                Other values will raise an exception when this op is run on a CPU, and return `NaN` values for the
    *                corresponding loss and gradient rows when this op is run on a GPU.
    * @param  axis   The class axis, along which the softmax is computed. Defaults to `-1`, which is the last axis.
    * @return Result as a new tensor, with the same shape as `labels` and the same data type as `logits`, containing the
    *         softmax cross entropy loss.
    */
  def sparseSoftmaxCrossEntropy(logits: Tensor, labels: Tensor, axis: Int = -1): Tensor = {
    val preciseLogits = if (logits.dataType == FLOAT16) Math.cast(logits, FLOAT32) else logits
    // Check if no reshapes are required.
    val output = {
      if (logits.rank == 2) {
        // Create the native op.
        // The second output tensor contains the gradients, which is used for the gradient computation.
        Tensor.fromNativeHandle(nativeCrossEntropyProxy(
          preciseLogits.nativeHandle, labels.nativeHandle,
          NativeTensorOpsNN.sparseSoftmaxCrossEntropyWithLogits).apply(0))
      } else {
        // Reshape logits to rank 2 and labels to rank 1.
        val flattenedLogits = NN.flattenOuterAxes(preciseLogits)
        val flattenedLabels = Basic.reshape(labels, -1)
        // Create the native op.
        // The second output tensor contains the gradients, which is used for the gradient computation.
        val output = Tensor.fromNativeHandle(nativeCrossEntropyProxy(
          flattenedLogits.nativeHandle, flattenedLabels.nativeHandle,
          NativeTensorOpsNN.sparseSoftmaxCrossEntropyWithLogits).apply(0))
        Basic.reshape(output, Basic.shape(labels))
      }
    }
    // We cast back to the original logits data type, if necessary.
    if (logits.dataType == FLOAT16)
      Math.cast(output, FLOAT16)
    else
      output
  }

  /** $OpDocNNSigmoidCrossEntropy
    *
    * @group NNOps
    * @param  logits  Tensor of shape `[D0, D1, ..., Dr-1, numClasses]` and data type [[FLOAT16]], [[FLOAT32]], or
    *                 [[FLOAT64]], containing unscaled log probabilities.
    * @param  labels  Tensor of shape `[D0, D1, ..., Dr-1, numClasses]` and data type [[FLOAT16]], [[FLOAT32]], or
    *                 [[FLOAT64]], where each row must be a valid probability distribution.
    * @param  weights Optionally, a coefficient to use for the positive examples.
    * @return Result as a new tensor, with rank one less than that of `logits` and the same data type as `logits`,
    *         containing the sigmoid cross entropy loss.
    */
  def sigmoidCrossEntropy(logits: Tensor, labels: Tensor, weights: Tensor = null): Tensor = {
    val output = {
      if (weights == null) {
        // Labels and logits must be of the same data type.
        val preciseLogits = if (logits.dataType == FLOAT16) Math.cast(logits, FLOAT32) else logits
        val preciseLabels = Math.cast(labels, preciseLogits.dataType)
        // The logistic loss formula from above is:
        //   x - x * z + log(1 + exp(-x))
        // For x < 0, a more numerically stable formula is:
        //   -x * z + log(1 + exp(x))
        // Note that these two expressions can be combined into the following single expression:
        //   max(x, 0) - x * z + log(1 + exp(-abs(x)))
        // To allow computing gradients at zero, we define custom versions of the max and the abs functions.
        val zeros = Tensor.zerosLike(preciseLogits)
        val condition = Math.greaterEqual(preciseLogits, zeros)
        val reluLogits = Math.select(condition, preciseLogits, zeros)
        val negativeAbsLogits = Math.select(condition, -preciseLogits, preciseLogits)
        Math.add(reluLogits - (preciseLogits * preciseLabels), Math.log1p(Math.exp(negativeAbsLogits)))
      } else {
        // Labels and logits must be of the same data type.
        val preciseLogits = if (logits.dataType == FLOAT16) Math.cast(logits, FLOAT32) else logits
        val preciseLabels = Math.cast(labels, preciseLogits.dataType)
        val preciseWeights = Math.cast(weights, preciseLogits.dataType)
        // The logistic loss formula from above is:
        //   (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(-x))
        // For x < 0, a more numerically stable formula is:
        //   (1 - z) * x + (1 + (q - 1) * z) * log(1 + exp(x)) - l * x
        // To avoid branching, we use the following single expression:
        //   (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))
        val logWeights = ((preciseWeights - 1) * preciseLabels) + 1
        Math.add(
          (1 - preciseLabels) * preciseLogits,
          (logWeights * Math.log1p(Math.exp(-Math.abs(preciseLogits)))) + relu(-preciseLogits))
      }
    }
    // We cast back to the original logits data type, if necessary.
    if (logits.dataType == FLOAT16)
      Math.cast(output, FLOAT16)
    else
      output
  }

  /** $OpDocNNLogPoissonLoss
    *
    * @group NNOps
    * @param  logPredictions  Tensor containing the log-predictions.
    * @param  targets         Tensor with the same shape as `logPredictions`, containing the target values.
    * @param  computeFullLoss If `true`, Stirling's Approximation is used to approximate the full loss. Defaults to
    *                         `false`, meaning that the constant term is ignored.
    * @return Result as a new tensor.
    */
  def logPoissonLoss(logPredictions: Tensor, targets: Tensor, computeFullLoss: Boolean = false): Tensor = {
    val output = Math.exp(logPredictions) - (logPredictions * targets)
    if (computeFullLoss) {
      // Need to create constant tensors here so that their data types can be matched to that of the targets.
      val pointFive = Tensor(targets.dataType, 0.5)
      val twoPi = Tensor(targets.dataType, 2 * math.Pi)
      val stirlingApproximation = (targets * Math.log(targets)) - targets + (pointFive * Math.log(twoPi * targets))
      val zeros = Tensor.zerosLike(targets)
      val ones = Tensor.onesLike(targets)
      val condition = Math.logicalAnd(Math.greaterEqual(targets, zeros), Math.lessEqual(targets, ones))
      output + Math.select(condition, zeros, stirlingApproximation)
    } else {
      output
    }
  }

  /** $OpDocNNSequenceLoss
    *
    * @group NNOps
    * @param  logits                 Tensor of shape `[batchSize, sequenceLength, numClasses]` containing unscaled log
    *                                probabilities.
    * @param  labels                 Tensor of shape `[batchSize, sequenceLength]` containing the true label at each
    *                                time step.
    * @param  weights                Optionally, a tensor of shape `[batchSize, sequenceLength]` containing weights to
    *                                use for each prediction. When using `weights` as masking, set all valid time steps
    *                                to 1 and all padded time steps to 0 (e.g., a mask returned by `tf.sequenceMask`).
    * @param  averageAcrossTimeSteps If `true`, the loss is summed across the sequence dimension and divided by the
    *                                total label weight across all time steps.
    * @param  averageAcrossBatch     If `true`, the loss is summed across the batch dimension and divided by the batch
    *                                size.
    * @param  lossFn                 Loss function to use that takes the predicted logits and the true labels as inputs
    *                                and returns the loss value. Defaults to `sparseSoftmaxCrossEntropy`.
    * @return Result as a new tensor.
    * @throws InvalidShapeException If any of `logits`, `labels`, or `weights` has invalid shape.
    */
  @throws[InvalidShapeException]
  def sequenceLoss(
      logits: Tensor,
      labels: Tensor,
      weights: Tensor = null,
      averageAcrossTimeSteps: Boolean = true,
      averageAcrossBatch: Boolean = true,
      lossFn: (Tensor, Tensor) => Tensor = sparseSoftmaxCrossEntropy(_, _)
  ): Tensor = {
    if (logits.rank != 3)
      throw InvalidShapeException(
        s"'logits' must have shape [batchSize, sequenceLength, numClasses], but had: ${logits.shape}.")
    if (labels.rank != 2)
      throw InvalidShapeException(s"'labels' must have shape [batchSize, sequenceLength], but had: ${labels.shape}.")
    if (weights != null && weights.rank != 2)
      throw InvalidShapeException(s"'weights' must have shape [batchSize, sequenceLength], but had: ${weights.shape}.")
    val numClasses = Basic.shape(logits)(2)
    val flattenedLogits = Basic.reshape(logits, Basic.stack(Seq(-1, numClasses)))
    val flattenedLabels = Basic.reshape(labels, Shape(-1))
    var loss = lossFn(flattenedLogits, flattenedLabels)
    if (weights != null)
      loss = loss * Basic.reshape(weights, Shape(-1))
    if (averageAcrossTimeSteps && averageAcrossBatch) {
      loss = Math.sum(loss)
      val totalSize = if (weights != null) Math.sum(weights) + 1e-12 else Basic.size(flattenedLabels)
      loss = Math.divide(loss, totalSize)
    } else {
      loss = Basic.reshape(loss, Basic.shape(logits)(0 :: 2))
    }
    if (averageAcrossTimeSteps && !averageAcrossBatch) {
      loss = Math.sum(loss, axes = 1)
      val totalSize = if (weights != null) Math.sum(weights, axes = 1) + 1e-12 else Basic.shape(labels)(1)
      loss = Math.divide(loss, totalSize)
    }
    if (!averageAcrossTimeSteps && averageAcrossBatch) {
      loss = Math.sum(loss, axes = 0)
      val totalSize = if (weights != null) Math.sum(weights, axes = 0) + 1e-12 else Basic.shape(labels)(0)
      loss = Math.divide(loss, totalSize)
    }
    loss
  }

  //endregion Loss Ops

  /** $OpDocNNDropout
    *
    * @group NNOps
    * @param  input           Input tensor.
    * @param  keepProbability Probability (i.e., number in the interval `(0, 1]`) that each element is kept.
    * @param  scaleOutput     If `true`, the outputs will be divided by the keep probability.
    * @param  noiseShape      [[INT32]] rank-1 tensor representing the shape for the randomly generated keep/drop flags.
    * @param  seed            Optional random seed, used to generate a random seed pair for the random number
    *                         generator, when combined with the graph-level seed.
    * @return Result as a new tensor that has the same shape as `input`.
    */
  def dropout(
      input: Tensor,
      keepProbability: Float,
      scaleOutput: Boolean = true,
      noiseShape: Tensor = null,
      seed: Option[Int] = None
  ): Tensor = {
    require(keepProbability > 0.0 && keepProbability <= 1.0, s"'keepProbability' ($keepProbability) must be in (0, 1].")
    // Do nothing if we know that keepProbability == 1.
    if (keepProbability == 1.0) {
      input
    } else {
      val inferredNoiseShape = if (noiseShape == null) Basic.shape(input) else noiseShape
      // Uniform random variable in [keepProbability, 1.0 + keepProbability).
      val probability = Tensor(input.dataType, keepProbability)
      val random = Random.randomUniform(
        input.dataType, inferredNoiseShape, minValue = probability, maxValue = probability + 1.0, seed = seed)
      // 0.0 if in [keepProbability, 1.0) and 1.0 if [1.0, 1.0 + keepProbability).
      val binaryTensor = Math.floor(random)
      if (scaleOutput) Math.divide(input, probability) * binaryTensor else input * binaryTensor
    }
  }

  /** $OpDocNNTopK
    *
    * @group NNOps
    * @param  input  Input tensor whose last axis has size at least `k`.
    * @param  k      Scalar [[INT32]] tensor containing the number of top elements to look for along the last axis of
    *                `input`.
    * @param  sorted If `true`, the resulting `k` elements will be sorted by their values in descending order.
    * @return Tuple containing the created tensors: (i) `values`: the `k` largest elements along each last
    *         dimensional slice, and (ii) `indices`: the indices of `values` within the last axis of `input`.
    */
  def topK(
      input: Tensor,
      k: Tensor = 1,
      sorted: Boolean = true
  ): (Tensor, Tensor) = {
    val outputs = NativeTensorOpsNN.topKV2(
      executionContext.value.nativeHandle, input.nativeHandle, k.nativeHandle, sorted)
    (Tensor.fromNativeHandle(outputs(0)), Tensor.fromNativeHandle(outputs(1)))
  }

  /** $OpDocNNInTopK
    *
    * @group NNOps
    * @param  predictions [[FLOAT32]] tensor containing the predictions.
    * @param  targets     [[INT32]] or [[INT64]] tensor containing the targets.
    * @param  k           Scalar [[INT32]] or [[INT64]] tensor containing the number of top elements to look at.
    * @return Result as a new tensor.
    */
  def inTopK(predictions: Tensor, targets: Tensor, k: Tensor): Tensor = {
    val mostPreciseDataType = DataType.mostPrecise(targets.dataType, k.dataType)
    Tensor.fromNativeHandle(NativeTensorOpsNN.inTopKV2(
      executionContext.value.nativeHandle, predictions.nativeHandle, targets.cast(mostPreciseDataType).nativeHandle,
      k.cast(mostPreciseDataType).nativeHandle))
  }

  //region Convolution Ops

  /** $OpDocConv2D
    *
    * @param  input         4-D tensor whose dimension order is interpreted according to the value of `dataFormat`.
    * @param  filter        4-D tensor with shape `[filterHeight, filterWidth, inChannels, outChannels]`.
    * @param  stride1       Stride of the sliding window along the second dimension of `input`.
    * @param  stride2       Stride of the sliding window along the third dimension of `input`.
    * @param  padding       Padding mode to use.
    * @param  dataFormat    Format of the input and output data.
    * @param  useCuDNNOnGPU Boolean value indicating whether or not to use CuDNN for the created op, if its placed on a
    *                       GPU, as opposed to the TensorFlow implementation.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def conv2D(
      input: Tensor,
      filter: Tensor,
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default,
      useCuDNNOnGPU: Boolean = true
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.conv2D(
      executionContext.value.nativeHandle, input.nativeHandle, filter.nativeHandle,
      Array[Long](1, stride1, stride2, 1), padding.name.getBytes(StandardCharsets.ISO_8859_1), useCuDNNOnGPU,
      dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  /** $OpDocConv2DBackpropInput
    *
    * @param  inputSizes     Integer vector representing the shape of the original input, which is a 4-D tensor.
    * @param  filter         4-D tensor with shape `[filterHeight, filterWidth, inChannels, outChannels]`.
    * @param  outputGradient 4-D tensor containing the gradients w.r.t. the output of the convolution and whose shape
    *                        depends on the value of `dataFormat`.
    * @param  stride1        Stride of the sliding window along the second dimension of `input`.
    * @param  stride2        Stride of the sliding window along the third dimension of `input`.
    * @param  padding        Padding mode to use.
    * @param  dataFormat     Format of the input and output data.
    * @param  useCuDNNOnGPU  Boolean value indicating whether or not to use CuDNN for the created op, if its placed on a
    *                        GPU, as opposed to the TensorFlow implementation.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def conv2DBackpropInput(
      inputSizes: Tensor,
      filter: Tensor,
      outputGradient: Tensor,
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default,
      useCuDNNOnGPU: Boolean = true
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.conv2DBackpropInput(
      executionContext.value.nativeHandle, inputSizes.nativeHandle, filter.nativeHandle, outputGradient.nativeHandle,
      Array[Long](1, stride1, stride2, 1), padding.name.getBytes(StandardCharsets.ISO_8859_1), useCuDNNOnGPU,
      dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  /** $OpDocConv2DBackpropFilter
    *
    * @param  input          4-D tensor whose dimension order is interpreted according to the value of `dataFormat`.
    * @param  filterSizes    Integer vector representing the shape of the original filter, which is a 4-D tensor.
    * @param  outputGradient 4-D tensor containing the gradients w.r.t. the output of the convolution and whose shape
    *                        depends on the value of `dataFormat`.
    * @param  stride1        Stride of the sliding window along the second dimension of `input`.
    * @param  stride2        Stride of the sliding window along the third dimension of `input`.
    * @param  padding        Padding mode to use.
    * @param  dataFormat     Format of the input and output data.
    * @param  useCuDNNOnGPU  Boolean value indicating whether or not to use CuDNN for the created op, if its placed on a
    *                        GPU, as opposed to the TensorFlow implementation.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def conv2DBackpropFilter(
      input: Tensor,
      filterSizes: Tensor,
      outputGradient: Tensor,
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default,
      useCuDNNOnGPU: Boolean = true
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.conv2DBackpropFilter(
      executionContext.value.nativeHandle, input.nativeHandle, filterSizes.nativeHandle, outputGradient.nativeHandle,
      Array[Long](1, stride1, stride2, 1), padding.name.getBytes(StandardCharsets.ISO_8859_1), useCuDNNOnGPU,
      dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  //endregion Convolution Ops

  //region Pooling Ops

  /** $OpDocMaxPool
    *
    * @param  input      4-D tensor whose dimension order is interpreted according to the value of `dataFormat`.
    * @param  windowSize The size of the pooling window for each dimension of the input tensor.
    * @param  stride1    Stride of the sliding window along the second dimension of `input`.
    * @param  stride2    Stride of the sliding window along the third dimension of `input`.
    * @param  padding    Padding mode to use.
    * @param  dataFormat Format of the input and output data.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def maxPool(
      input: Tensor,
      windowSize: Seq[Long],
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.maxPool(
      executionContext.value.nativeHandle, input.nativeHandle, windowSize.toArray,
      Array[Long](1, stride1, stride2, 1), padding.name.getBytes(StandardCharsets.ISO_8859_1),
      dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  /** $OpDocMaxPoolGrad
    *
    * @param  originalInput  Original input tensor.
    * @param  originalOutput Original output tensor.
    * @param  outputGradient 4-D tensor containing the gradients w.r.t. the output of the max pooling and whose shape
    *                        depends on the value of `dataFormat`.
    * @param  windowSize     The size of the pooling window for each dimension of the input tensor.
    * @param  stride1        Stride of the sliding window along the second dimension of `input`.
    * @param  stride2        Stride of the sliding window along the third dimension of `input`.
    * @param  padding        Padding mode to use.
    * @param  dataFormat     Format of the input and output data.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def maxPoolGrad(
      originalInput: Tensor,
      originalOutput: Tensor,
      outputGradient: Tensor,
      windowSize: Seq[Long],
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.maxPoolGrad(
      executionContext.value.nativeHandle, originalInput.nativeHandle, originalOutput.nativeHandle,
      outputGradient.nativeHandle, windowSize.toArray, Array[Long](1, stride1, stride2, 1),
      padding.name.getBytes(StandardCharsets.ISO_8859_1), dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  /** $OpDocMaxPoolGradGrad
    *
    * @param  originalInput  Original input tensor.
    * @param  originalOutput Original output tensor.
    * @param  outputGradient 4-D tensor containing the gradients w.r.t. the output of the max pooling and whose shape
    *                        depends on the value of `dataFormat`.
    * @param  windowSize     The size of the pooling window for each dimension of the input tensor.
    * @param  stride1        Stride of the sliding window along the second dimension of `input`.
    * @param  stride2        Stride of the sliding window along the third dimension of `input`.
    * @param  padding        Padding mode to use.
    * @param  dataFormat     Format of the input and output data.
    * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
    */
  def maxPoolGradGrad(
      originalInput: Tensor,
      originalOutput: Tensor,
      outputGradient: Tensor,
      windowSize: Seq[Long],
      stride1: Long,
      stride2: Long,
      padding: ConvPaddingMode,
      dataFormat: CNNDataFormat = CNNDataFormat.default
  ): Tensor = {
    Tensor.fromNativeHandle(NativeTensorOpsNN.maxPoolGradGrad(
      executionContext.value.nativeHandle, originalInput.nativeHandle, originalOutput.nativeHandle,
      outputGradient.nativeHandle, windowSize.toArray, Array[Long](1, stride1, stride2, 1),
      padding.name.getBytes(StandardCharsets.ISO_8859_1), dataFormat.name.getBytes(StandardCharsets.ISO_8859_1)))
  }

  //endregion Pooling Ops
}

object NN extends NN {
  case class NNOps(tensor: Tensor) {
    //region Core Ops

    /** $OpDocNNAddBias
      *
      * @group NNOps
      * @param  bias          Bias tensor that must be one-dimensional (i.e., it must have rank 1).
      * @param  cNNDataFormat Data format of the input and output tensors. With the default format [[NWCFormat]], the
      *                       `bias` tensor will be added to the last dimension of the `value` tensor. Alternatively, the
      *                       format could be [[NCWFormat]], and the `bias` tensor would be added to the third-to-last
      *                       dimension.
      * @return Result as a new tensor.
      */
    def addBias(bias: Tensor, cNNDataFormat: CNNDataFormat = CNNDataFormat.default): Tensor = {
      NN.addBias(tensor, bias, cNNDataFormat)
    }

    /** $OpDocNNLinear
      *
      * @group NNOps
      * @param  weights Weights tensor.
      * @param  bias    Bias tensor.
      * @return Result as a new tensor.
      */
    def linear(weights: Tensor, bias: Tensor = null): Tensor = NN.linear(tensor, weights, bias)

    /** $OpDocNNL2Normalize
      *
      * @group NNOps
      * @param  axes    Tensor containing the axes along which to normalize.
      * @param  epsilon Lower bound value for the norm. The created op will use `sqrt(epsilon)` as the divisor, if
      *                 `norm < sqrt(epsilon)`.
      * @return Result as a new tensor.
      */
    def l2Normalize(axes: Tensor, epsilon: Float = 1e-12f): Tensor = NN.l2Normalize(tensor, axes, epsilon)

    //endregion Core Ops

    //region Activation Ops

    /** $OpDocNNRelu
      *
      * @group NNOps
      * @param  alpha Slope of the negative section, also known as leakage parameter. If other than `0.0f`, the negative
      *               part will be equal to `alpha * x` instead of `0`. Defaults to `0`.
      * @return Result as a new tensor.
      */
    def relu(alpha: Float = 0.0f): Tensor = NN.relu(tensor, alpha)

    /** $OpDocNNRelu6
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def relu6: Tensor = NN.relu6(tensor)

    /** $OpDocNNCrelu
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def crelu: Tensor = NN.crelu(tensor)

    /** $OpDocNNElu
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def elu: Tensor = NN.elu(tensor)

    /** $OpDocNNSelu
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def selu: Tensor = NN.selu(tensor)

    /** $OpDocNNSoftplus
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def softplus: Tensor = NN.softplus(tensor)

    /** $OpDocNNSoftsign
      *
      * @group NNOps
      * @return Result as a new tensor.
      */
    def softsign: Tensor = NN.softsign(tensor)

    //endregion Activation Ops

    /** $OpDocNNSoftmax
      *
      * @group NNOps
      * @param  axis Axis along which to perform the softmax. Defaults to `-1` denoting the last axis.
      * @return Result as a new tensor.
      */
    def softmax(axis: Int = -1): Tensor = NN.softmax(tensor, axis)

    /** $OpDocNNLogSoftmax
      *
      * @group NNOps
      * @param  axis Axis along which to perform the log-softmax. Defaults to `-1` denoting the last axis.
      * @return Result as a new tensor.
      */
    def logSoftmax(axis: Int = -1): Tensor = NN.logSoftmax(tensor, axis)

    /** $OpDocNNDropout
      *
      * @group NNOps
      * @param  keepProbability Probability (i.e., number in the interval `(0, 1]`) that each element is kept.
      * @param  scaleOutput     If `true`, the outputs will be divided by the keep probability.
      * @param  noiseShape      [[INT32]] rank-1 tensor representing the shape for the randomly generated keep/drop flags.
      * @param  seed            Optional random seed, used to generate a random seed pair for the random number
      *                         generator, when combined with the graph-level seed.
      * @return Result as a new tensor that has the same shape as `input`.
      */
    def dropout(
        keepProbability: Float,
        scaleOutput: Boolean = true,
        noiseShape: Tensor = null,
        seed: Option[Int] = None
    ): Tensor = {
      NN.dropout(tensor, keepProbability, scaleOutput, noiseShape, seed)
    }

    /** $OpDocNNTopK
      *
      * @group NNOps
      * @param  k      Scalar [[INT32]] tensor containing the number of top elements to look for along the last axis of
      *                `input`.
      * @param  sorted If `true`, the resulting `k` elements will be sorted by their values in descending order.
      * @return Tuple containing the created op outputs: (i) `values`: the `k` largest elements along each last
      *         dimensional slice, and (ii) `indices`: the indices of `values` within the last axis of `input`.
      */
    def topK(k: Tensor = 1, sorted: Boolean = true): (Tensor, Tensor) = NN.topK(tensor, k, sorted)

    /** $OpDocNNInTopK
      *
      * @group NNOps
      * @param  targets [[INT32]] or [[INT64]] tensor containing the targets.
      * @param  k       Scalar [[INT32]] or [[INT64]] tensor containing the number of top elements to look at.
      * @return Result as a new tensor.
      */
    def inTopK(targets: Tensor, k: Tensor): Tensor = NN.inTopK(tensor, targets, k)

    //region Convolution Ops

    /** $OpDocConv2D
      *
      * @param  filter        4-D tensor with shape `[filterHeight, filterWidth, inChannels, outChannels]`.
      * @param  stride1       Stride of the sliding window along the second dimension of this tensor.
      * @param  stride2       Stride of the sliding window along the third dimension of this tensor.
      * @param  padding       Padding mode to use.
      * @param  dataFormat    Format of the input and output data.
      * @param  useCuDNNOnGPU Boolean value indicating whether or not to use CuDNN for the created op, if its placed on a
      *                       GPU, as opposed to the TensorFlow implementation.
      * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
      */
    def conv2D(
        filter: Tensor, stride1: Long, stride2: Long, padding: ConvPaddingMode,
        dataFormat: CNNDataFormat = CNNDataFormat.default, useCuDNNOnGPU: Boolean = true): Tensor = {
      NN.conv2D(tensor, filter, stride1, stride2, padding, dataFormat, useCuDNNOnGPU)
    }

    //endregion Convolution Ops

    //region Pooling Ops

    /** $OpDocMaxPool
      *
      * @param  windowSize The size of the pooling window for each dimension of the input tensor.
      * @param  stride1    Stride of the sliding window along the second dimension of `input`.
      * @param  stride2    Stride of the sliding window along the third dimension of `input`.
      * @param  padding    Padding mode to use.
      * @param  dataFormat Format of the input and output data.
      * @return Result as a new 4-D tensor whose dimension order depends on the value of `dataFormat`.
      */
    def maxPool(
        windowSize: Seq[Long], stride1: Long, stride2: Long, padding: ConvPaddingMode,
        dataFormat: CNNDataFormat = CNNDataFormat.default): Tensor = {
      NN.maxPool(tensor, windowSize, stride1, stride2, padding, dataFormat)
    }

    //endregion Pooling Ops
  }

  /** Creates an op that flattens the outer axes of `input` and keeps its last axis. */
  private[ops] def flattenOuterAxes(input: Tensor): Tensor = {
    val rank = Basic.rank(input)
    val lastAxisSize = Basic.slice(
      Basic.shape(input),
      Basic.expandDims(Math.subtract(rank, 1), -1),
      Tensor.fill(rank.dataType, Shape(1))(1))
    Basic.reshape(input, Basic.concatenate(Seq(Tensor.fill(rank.dataType, Shape(1))(-1), lastAxisSize), 0))
  }

  /** Creates an op that swaps the axes `axis1` and `axis2` in `input` and ignores all axes after `axis2`. */
  private[ops] def swapAxes(input: Tensor, axis1: Tensor, axis2: Tensor): Tensor = {
    Basic.transpose(
      input,
      Basic.concatenate(Seq(
        Math.range(0, axis1),
        axis2,
        Math.range(axis1 + 1, axis2),
        axis1), 0))
  }

  /** Creates an op that moves `axis` to the end. */
  private[ops] def moveAxisToEnd(input: Tensor, axis: Int, rank: Tensor): Tensor = {
    if (axis == -1) {
      input
    } else {
      val axisOutput = Tensor(rank.dataType, axis)
      Basic.transpose(
        input,
        Basic.concatenate(Seq(
          Math.range(0, axisOutput),
          Math.range(axisOutput + 1, rank),
          axisOutput), 0))
    }
  }
}


text:
require 'private_please/tracking/trace_point_processor'

module PrivatePlease
  class MethodsCallsTracker
    def self.instance
      @instance ||= new(Config.new)
    end

    def self.reset
      @instance = nil
    end

    # -----
    attr_reader :config

    def initialize(config)
      @config                 = config
      @trace_point_processor  = Tracking::TracePointProcessor.new(config)
    end
    private_class_method :new

    def start_tracking
      tracer.enable
    end

    def stop_tracking
      tracer.disable
    end

    def result
      @trace_point_processor.result
    end

    private

    def tracer
      @_tracer ||= begin
        TracePoint.new do |tp|
          @trace_point_processor.process(tp)
        end
      end
    end
  end
end


text:
'use strict'

const test = require('ava')
// const index = require('./index')

test('tests the index file', function (t) {
  // t.deepEqual(prefixer({}, 'foo'), {})
})


text:
<?php
namespace frontend\models;

use yii\base\Model;
use common\models\User;
use common\models\web_content;

/**
 * Signup form
 */
class RegisterForm extends Model
{
	public $FirstName;
	public $username;
    public $email;
    public $password;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

        	['FirstName', 'trim'],
        	['FirstName', 'required'],
        	['username', 'string', 'min' => 2, 'max' => 50],

            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function RegisterUser()
    {
        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->FirstName = $this->FirstName;
        $user->username = $this->username;
        $user->email = $this->email;
        $user->activation_code = sha1(mt_rand(10000,99999).time().$this->email, false);
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->RegistrationDateTime = date('Y-m-d H:i:s');
        $user->privacy_accepted_version = web_content::findLatestContentVersion('PRIVACY');
        $user->terms_accepted_version = web_content::findLatestContentVersion('TERMS');

        return $user->save() ? $user : null;
    }
}


text:
<?php

class sfHtml5FormDemoForm extends sfForm {

	public function configure() {

		$now = time();
		$choices = array('Mr.', 'Mrs.', 'Dr.', 'Prof.');

		$this->setWidgets(array(
			'input_color' => new sfWidgetFormInputColor(),
			'input_date' => new sfWidgetFormInputDate(),
			'input_date_limits' => new sfWidgetFormInputDate(array(
				'min' => $now,
				'max' => $now + 30*86400
			)),
			'input_date_step' => new sfWidgetFormInputDate(array(), array(
				'step' => 7
			)),
			'input_date_time' => new sfWidgetFormInputDateTime(),
			'input_date_time_limits' => new sfWidgetFormInputDateTime(array(
				'min' => $now,
				'max' => $now + 30*86400
			)),
			'input_date_time_step' => new sfWidgetFormInputDateTime(array(), array(
				'step' => 3600
			)),
			'input_date_time_local' => new sfWidgetFormInputDateTimeLocal(),
			'input_date_time_local_limits' => new sfWidgetFormInputDateTimeLocal(array(
				'min' => $now,
				'max' => $now + 30*86400
			)),
			'input_date_time_local_step' => new sfWidgetFormInputDateTimeLocal(array(), array(
				'step' => 3600
			)),
			'input_email' => new sfWidgetFormInputEmail(),
			'input_email_multiple' => new sfWidgetFormInputEmail(array(
				'multiple' => true
			)),
			'input_month' => new sfWidgetFormInputMonth(),
			'input_month_limit' => new sfWidgetFormInputMonth(array(
				'min' => $now,
				'max' => $now + 12*30*86400
			)),
			'input_month_step' => new sfWidgetFormInputMonth(array(), array(
				'step' => 12
			)),
			'input_week' => new sfWidgetFormInputWeek(),
			'input_week_limit' => new sfWidgetFormInputWeek(array(
				'min' => $now,
				'max' => $now + 12*30*86400
			)),
			'input_week_step' => new sfWidgetFormInputWeek(array(), array(
				'step' => 2
			)),
			'input_number' => new sfWidgetFormInputNumber(),
			'input_number_limit' => new sfWidgetFormInputNumber(array(
				'min' => 0,
				'max' => 100
			)),
			'input_number_step' => new sfWidgetFormInputNumber(array(), array(
				'step' => 0.01
			)),
			'input_range' => new sfWidgetFormInputRange(),
			'input_range_limit' => new sfWidgetFormInputRange(array(
				'min' => -50,
				'max' => 50
			)),
			'input_search' => new sfWidgetFormInputSearch(),
			'input_tel' => new sfWidgetFormInputTel(),
			'input_time' => new sfWidgetFormInputTime(),
			'input_time_limit' => new sfWidgetFormInputTime(array(
				'min' => 8*3600,
				'max' => 17*3600
			)),
			'input_time_step' => new sfWidgetFormInputTime(array(), array(
				'step' => 3600
			)),
			'input_url' => new sfWidgetFormInputUrl(),
//			'keygen' => new sfWidgetFormKeygen(),

			'input_datalist' => new sfWidgetFormInputDatalist(array(
				'choices' => $choices
			)),

			'input_datalist_autocomplete' => new sfWidgetFormInputDatalist(array(
				'choices_url' => ''
			)),
		));

		$this->widgetSchema->setHelps(array(
			'input_color' => '',
			'input_date' => '',
			'input_date_limits' => 'date between now and now+30 days',
			'input_date_step' => 'only select days that have todays weekday',
			'input_date_time' => '',
			'input_date_time_limits' => 'date between now and now+30 days',
			'input_date_time_step' => 'only select by hours',
			'input_date_time_local' => '',
			'input_date_time_local_limits' => 'date between now and now+30 days',
			'input_date_time_local_step' => 'only select by hours',
			'input_email' => '',
			'input_email_multiple' => 'allow multiple email addresses',
			'input_month' => '',
			'input_month_limit' => 'months between now and now+1 year',
			'input_month_step' => 'the current month in any year',
			'input_week' => '',
			'input_week_limit' => 'weeks between now and now+1 year',
			'input_week_step' => 'every second week',
			'input_number' => '',
			'input_number_limit' => 'values between 0 and 100',
			'input_number_step' => 'float values with step 0.01',
			'input_range' => '',
			'input_range_limit' => 'value between -50 and 50',
			'input_search' => '',
			'input_tel' => '',
			'input_time' => '',
			'input_time_limit' => 'time between 9am and 6pm',
			'input_time_step' => 'full hours',
			'input_url' => '',
			'input_datalist' => '',
			'input_datalist_autocomplete' => 'auto-completion through AJAX',
//			'keygen' => '',

		));

		$this->setValidators(array(
			'input_color' => new sfValidator5Color(),
			'input_date' => new sfValidator5Date(),
			'input_date_limits' => new sfValidator5Date(),
			'input_date_step' => new sfValidator5Date(),
			'input_date_time' => new sfValidator5DateTime(),
			'input_date_time_limits' => new sfValidator5DateTime(),
			'input_date_time_step' => new sfValidator5DateTime(),
			'input_date_time_local' => new sfValidator5DateTimeLocal(),
			'input_date_time_local_limits' => new sfValidator5DateTimeLocal(),
			'input_date_time_local_step' => new sfValidator5DateTimeLocal(),
			'input_email' => new sfValidator5Email(),
			'input_email_multiple' => new sfValidator5Email(),
			'input_month' => new sfValidator5Month(),
			'input_month_limit' => new sfValidator5Month(),
			'input_month_step' => new sfValidator5Month(),
			'input_week' => new sfValidatorPass(),
			'input_week_limit' => new sfValidatorPass(),
			'input_week_step' => new sfValidatorPass(),
			'input_number' => new sfValidatorNumber(),
			'input_number_limit' => new sfValidatorNumber(),
			'input_number_step' => new sfValidatorNumber(),
			'input_range' => new sfValidatorNumber(),
			'input_range_limit' => new sfValidatorNumber(),
			'input_search' => new sfValidatorString(),
			'input_tel' => new sfValidatorString(),
			'input_time' => new sfValidator5Time(),
			'input_time_limit' => new sfValidator5Time(),
			'input_time_step' => new sfValidator5Time(),
			'input_url' => new sfValidatorUrl(),
			'input_datalist' => new sfValidatorString(),
			'input_datalist_autocomplete' => new sfValidatorString(),
//			'keygen' => new sfValidatorPass(), //TODO: we need a validator
		));

		foreach($this->validatorSchema->getFields() as $validator) {
			$validator->setOption('required', false);
		}

		$this->widgetSchema->setNameFormat('sf_html5_form_demo[%s]');
		$this->widgetSchema->setFormFormatterName('table');

	}
}


text:
package com.google.iot.m2m.local.rpn;

public class RPNStackUnderflowException extends RPNException {
    RPNStackUnderflowException() {}
    RPNStackUnderflowException(Throwable t) { super(t); }
    RPNStackUnderflowException(String d) { super(d); }
    RPNStackUnderflowException(String d, Throwable t) { super(d,t); }
}


text:
Final
===

![1953 – Queen Elizabeth II launches the Royal Yacht HMY Britannia.](http://upload.wikimedia.org/wikipedia/commons/e/e2/HMY_Britannia.jpg "1953 – Queen Elizabeth II launches the Royal Yacht HMY Britannia.")

This test is intended to draw your attention to some of the more customer related aspects of this course. It is open everything. The [test is here](tests/prog3030final2.htm). Good luck!


text:
require('file-loader?emit=false&name=[name].[ext]!./images/portal.png');

const translate = require('./translate');

class Portal {
	constructor(portal, view) {
		this.div = document.createElement('div');
		this.nametag = document.createElement('div');
		this.rootElement = document.createElement('div');

		this.portal = portal;

		const { div, nametag, rootElement } = this;

		rootElement.className = 'container';
		rootElement.style.transform = translate(portal.pos);

		div.className = 'portal'
		div.style.backgroundImage = 'url(/images/portal.png)';

		nametag.className = 'nametag';
		nametag.textContent = portal.getParent().name.valueOf();;

		rootElement.appendChild(div);
		rootElement.appendChild(nametag);

		view.appendChild(rootElement);

		portal.once('destroy', this.destroy.bind(this));

		setTimeout(function () {
			rootElement.style.opacity = 1;
		}, 0);
	}

	update() {
		const { portal, rootElement } = this;

		rootElement.style.transform = translate(portal.pos);
	}

	destroy() {
		const { rootElement } = this;

		rootElement.addEventListener('transitionend', (e) => {
			if (e.propertyName === 'opacity') {
				rootElement.parentNode.removeChild(rootElement);

				e.stopPropagation();
			}
		});

		rootElement.style.opacity = 0;
	}
}

module.exports = Portal;


text:
//============================================================================
//
// Copyright (C) 2006-2022 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
//============================================================================

package org.talend.components.netsuite;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

import org.talend.components.netsuite.test.NetSuitePortTypeMockAdapterImpl;

import com.netsuite.webservices.test.platform.NetSuitePortType;
import com.netsuite.webservices.test.platform.messages.LoginRequest;
import com.netsuite.webservices.test.platform.messages.LoginResponse;
import com.netsuite.webservices.test.platform.messages.SessionResponse;

/**
 *
 */
public class NetSuiteComponentMockTestFixture
        extends AbstractNetSuiteComponentMockTestFixture<NetSuitePortType> {

    public NetSuiteComponentMockTestFixture(
            NetSuiteWebServiceMockTestFixture<NetSuitePortType, ?> webServiceMockTestFixture) {
        super(webServiceMockTestFixture);
    }

    @Override
    protected void mockLoginResponse(NetSuitePortType port) throws Exception {
        SessionResponse sessionResponse = new SessionResponse();
        sessionResponse.setStatus(NetSuitePortTypeMockAdapterImpl.createSuccessStatus());
        LoginResponse response = new LoginResponse();
        response.setSessionResponse(sessionResponse);

        when(port.login(any())).thenReturn(response);
    }

}


text:
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.pentaho.kettle.plugins</groupId>
    <artifactId>aggregate-rows</artifactId>
    <version>8.0-SNAPSHOT</version>
  </parent>
  <artifactId>aggregate-rows-assemblies</artifactId>
  <version>8.0-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>Aggregate Rows Assemblies</name>
  <description>Packages Aggregate Rows artifacts</description>
  <url>http://www.pentaho.com</url>
  <modules>
    <module>aggregate-rows-plugin</module>
  </modules>
</project>


text:
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;

use builder::{Builder, TokenString, add_node_dependency};
use node;
use super::pinmap;

pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
  node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
  for port_node in node.subnodes().iter() {
    port_node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
    add_node_dependency(&node, port_node);
    for pin_node in port_node.subnodes().iter() {
      pin_node.materializer.set(Some(build_pin as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>)));
      add_node_dependency(port_node, pin_node);
      super::add_node_dependency_on_clock(builder, pin_node);
    }
  }
}

pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
  node.expect_no_attributes(cx);
}

fn build_pin(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) {
  let port_node = node.parent.clone().unwrap().upgrade().unwrap();
  let ref port_path = port_node.path;
  let port_str = format!("Port{}", match port_path.as_slice().parse::<usize>().unwrap() {
    0...4 => port_path,
    other => {
      cx.parse_sess().span_diagnostic.span_err(port_node.path_span,
          format!("unknown port `{}`, allowed values: 0...4",
              other).as_slice());
      return;
    }
  });
  let port = TokenString(port_str);

  if node.name.is_none() {
    cx.parse_sess().span_diagnostic.span_err(node.name_span,
        "pin node must have a name");
    return;
  }

  let direction_str = if node.get_string_attr("function").is_some() {
    "core::option::Option::None"
  } else {
    match node.get_string_attr("direction").unwrap().as_slice() {
      "out" => "core::option::Option::Some(zinc::hal::pin::Out)",
      "in"  => "core::option::Option::Some(zinc::hal::pin::In)",
      other => {
        let attr = node.get_attr("direction");
        cx.parse_sess().span_diagnostic.span_err(attr.value_span,
            format!("unknown direction `{}`, allowed values: `in`, `out`",
                other).as_slice());
        return;
      }
    }
  };
  let direction = TokenString(direction_str.to_string());

  let pin_str = match node.path.as_slice().parse::<usize>().unwrap() {
    0...31 => &node.path,
    other  => {
      cx.parse_sess().span_diagnostic.span_err(node.path_span,
          format!("unknown pin `{}`, allowed values: 0...31",
              other).as_slice());
      return;
    }
  };

  let port_def = pinmap::port_def();
  let function_str = match node.get_string_attr("function") {
    None => "Gpio".to_string(),
    Some(fun) => {
      let pins = &port_def[*port_path];
      let maybe_pin_index: usize = node.path.as_slice().parse().unwrap();
      let maybe_pin: &Option<pinmap::PinDef> = pins.get(maybe_pin_index).unwrap();
      match maybe_pin {
        &None => {
          cx.parse_sess().span_diagnostic.span_err(
              node.get_attr("function").value_span,
              format!("unknown pin function `{}`, only GPIO avaliable on this pin",
                  fun).as_slice());
          return;
        }
        &Some(ref pin_funcs) => {
          let maybe_func = pin_funcs.get(&fun);
          match maybe_func {
            None => {
              let avaliable: Vec<String> = pin_funcs.keys().map(|k|{k.to_string()}).collect();
              cx.parse_sess().span_diagnostic.span_err(
                  node.get_attr("function").value_span,
                  format!("unknown pin function `{}`, allowed functions: {}",
                      fun, avaliable.connect(", ")).as_slice());
              return;
            },
            Some(func_idx) => {
              format!("AltFunction{}", func_idx)
            }
          }
        }
      }
    }
  };

  let function = TokenString(function_str);
  let pin = TokenString(format!("{}u8", pin_str));
  let pin_name = TokenString(node.name.clone().unwrap());

  node.set_type_name("zinc::hal::lpc17xx::pin::Pin".to_string());

  let st = quote_stmt!(&*cx,
      let $pin_name = zinc::hal::lpc17xx::pin::Pin::new(
          zinc::hal::lpc17xx::pin::Port::$port,
          $pin,
          zinc::hal::lpc17xx::pin::Function::$function,
          $direction);
  );
  builder.add_main_statement(st);
}

#[cfg(test)]
mod test {
  use std::ops::Deref;
  use builder::Builder;
  use test_helpers::{assert_equal_source, with_parsed};

  #[test]
  fn builds_input_gpio() {
    with_parsed("
      gpio {
        0 {
          p1@1 { direction = \"in\"; }
        }
      }", |cx, failed, pt| {
      let mut builder = Builder::new(pt.clone(), cx);
      super::build_pin(&mut builder, cx, pt.get_by_name("p1").unwrap());
      assert!(unsafe{*failed} == false);
      assert!(builder.main_stmts().len() == 1);

      assert_equal_source(builder.main_stmts()[0].deref(),
          "let p1 = zinc::hal::lpc17xx::pin::Pin::new(
               zinc::hal::lpc17xx::pin::Port::Port0,
               1u8,
               zinc::hal::lpc17xx::pin::Function::Gpio,
               core::option::Option::Some(zinc::hal::pin::In));");
    });
  }

  #[test]
  fn builds_output_gpio() {
    with_parsed("
      gpio {
        0 {
          p2@2 { direction = \"out\"; }
        }
      }", |cx, failed, pt| {
      let mut builder = Builder::new(pt.clone(), cx);
      super::build_pin(&mut builder, cx, pt.get_by_name("p2").unwrap());
      assert!(unsafe{*failed} == false);
      assert!(builder.main_stmts().len() == 1);

      assert_equal_source(builder.main_stmts()[0].deref(),
          "let p2 = zinc::hal::lpc17xx::pin::Pin::new(
               zinc::hal::lpc17xx::pin::Port::Port0,
               2u8,
               zinc::hal::lpc17xx::pin::Function::Gpio,
               core::option::Option::Some(zinc::hal::pin::Out));");
    });
  }

  #[test]
  fn builds_altfn_gpio() {
    with_parsed("
      gpio {
        0 {
          p3@3 { direction = \"out\"; function = \"ad0_6\"; }
        }
      }", |cx, failed, pt| {
      let mut builder = Builder::new(pt.clone(), cx);
      super::build_pin(&mut builder, cx, pt.get_by_name("p3").unwrap());
      assert!(unsafe{*failed} == false);
      assert!(builder.main_stmts().len() == 1);

      assert_equal_source(builder.main_stmts()[0].deref(),
          "let p3 = zinc::hal::lpc17xx::pin::Pin::new(
               zinc::hal::lpc17xx::pin::Port::Port0,
               3u8,
               zinc::hal::lpc17xx::pin::Function::AltFunction2,
               core::option::Option::None);");
    });
  }
}


text:
require_relative 'abstract'

require_relative 'prince_xml_service/command'
require_relative 'prince_xml_service/query'

module DocGenerationWrapper
  module Adapter
    class PrinceXmlAdapter < Abstract

      def create! options, &respond_callback
        PrinceXmlService::Command.new.create! options, &respond_callback
      end

      def status status_id
        PrinceXmlService::Query.new.status status_id
      end

    end
  end
end


text:
package mxgo

import (
	"github.com/howeyc/fsnotify"
	"path"
	"strings"
)

func WatchDoTask(callback func(filePath string, event *fsnotify.FileEvent), filePaths ...string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		mxLog.Error(err)
	}

	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				if !strings.HasPrefix(path.Base(ev.Name), ".") {
					callback(ev.Name, ev)
				}
			case <-watcher.Error:
				continue
			}
		}
	}()
	for i := range filePaths {
		err = watcher.Watch(filePaths[i])
		if err != nil {
			mxLog.Error(err)
		}
	}

}


text:
//  @flow

/**
 * @description An MVC-component's builder module.
 * @module core/app/connection
 * @license MIT
 * @author Aleksandr Yackovlev <aleksandryackovlev@yandex.ru>
 */

/**
 * @description Interface for classes that represent a db-connector.
 *
 * @interface
 */
export interface ConnectorInterface {
    /**
     * @description Connects to a database.
     * @param {string} name - A name of a new cdb-connection.
     * @param {string} url - An url to connect to.
     * @param {Object} options - An options object for a new connetion.
     * @returns {Promise} - A promise that resolves to a new connection.
     * @access public
     */
    connect(name: string, url: string, options: {
        [key: string]: any,
    }): Promise<any>;
}