text:
<?php
namespace Acme\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="post")
*/
class Post {

    /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="posts")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    public $user;

    /**
    * @ORM\Column(type="string", length=255)
    */
    protected $title;

    /**
    * @ORM\Column(type="text")
    */
    protected $body;

    /**
    * @ORM\Column(type="datetime")
    */
    protected $created_date;

    /**
    * @ORM\Column(type="datetime")
    */
    protected $updated_date;

    public function __construct()
    {
        $this->created_date = new \DateTime('now');
        $this->updated_date = new \DateTime('now');
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Post
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set body
     *
     * @param string $body
     * @return Post
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Set created_date
     *
     * @param \DateTime $createdDate
     * @return Post
     */
    public function setCreatedDate($createdDate)
    {
        $this->created_date = $createdDate;

        return $this;
    }

    /**
     * Get created_date
     *
     * @return \DateTime
     */
    public function getCreatedDate()
    {
        return $this->created_date;
    }

    /**
     * Set updated_date
     *
     * @param \DateTime $updatedDate
     * @return Post
     */
    public function setUpdatedDate($updatedDate)
    {
        $this->updated_date = $updatedDate;

        return $this;
    }

    /**
     * Get updated_date
     *
     * @return \DateTime
     */
    public function getUpdatedDate()
    {
        return $this->updated_date;
    }
}


text:
'use strict';var e2e_util_1 = require('angular2/src/testing/e2e_util');
function waitForElement(selector) {
    var EC = protractor.ExpectedConditions;
    // Waits for the element with id 'abc' to be present on the dom.
    browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('reuse example app', function () {
    afterEach(e2e_util_1.verifyNoBrowserErrors);
    var URL = 'angular2/examples/router/ts/can_activate/';
    it('should navigate to user 1', function () {
        browser.get(URL);
        waitForElement('home-cmp');
        element(by.css('#user-1-link')).click();
        waitForElement('control-panel-cmp');
        expect(browser.getCurrentUrl()).toMatch(/\/user-settings\/1$/);
        expect(element(by.css('control-panel-cmp')).getText()).toContain('Settings');
    });
    it('should not navigate to user 2', function () {
        browser.get(URL);
        waitForElement('home-cmp');
        element(by.css('#user-2-link')).click();
        waitForElement('home-cmp');
        expect(element(by.css('home-cmp')).getText()).toContain('Welcome Home!');
    });
});
//# sourceMappingURL=can_activate_spec.js.map

redpajama_set_name: RedPajamaGithub


text:
module CC
  module Kafka
    module OffsetStorage
      module Minidoc
        def self.included(base)
          base.extend ClassMethods
          base.attribute :topic, String
          base.attribute :partition, Integer
          base.attribute :current, Integer
        end

        module ClassMethods
          def find_or_create!(attributes)
            find_one(attributes) || create!(attributes)
          end
        end
      end
    end
  end
end


text:
/**
 * --- Day 1: Not Quite Lisp ---

Santa was hoping for a white Christmas,
but his weather machine's "snow" function
is powered by stars, and he's fresh out!
To save Christmas,
he needs you to collect fifty stars by December 25th.

Collect stars by helping Santa solve puzzles.
Two puzzles will be made available on each day in the advent calendar;
the second puzzle is unlocked when you complete the first.
Each puzzle grants one star. Good luck!

Here's an easy puzzle to warm you up.

Santa is trying to deliver presents in a large apartment building,
but he can't find the right floor -
the directions he got are a little confusing.
He starts on the ground floor (floor 0) and
then follows the instructions one character at a time.

An opening parenthesis, (, means he should go up one floor,
and a closing parenthesis, ), means he should go down one floor.

The apartment building is very tall, and the basement is very deep;
he will never find the top or bottom floors.

For example:

(()) and ()() both result in floor 0.
((( and (()(()( both result in floor 3.
))((((( also results in floor 3.
()) and ))( both result in floor -1 (the first basement level).
))) and )())()) both result in floor -3.
To what floor do the instructions take Santa?

--- Part Two ---

Now, given the same instructions, find the position of the
first character that causes him to enter the basement (floor -1).
The first character in the instructions has position 1,
the second character has position 2, and so on.

For example:

) causes him to enter the basement at character position 1.
()()) causes him to enter the basement at character position 5.
What is the position of the character
that causes Santa to first enter the basement?*/

#include <stdio.h>

int main(int args, char **argv)
{
    FILE *fp;
    // Initial floor is the GROUND FLOOR
    int floors = 0;
    int i = 0;
    long basement_position = 0;
    char input = 'a';

    // Open file for reading
    fp = fopen("./input.txt", "r");
    // Read one character from file until EOF
    for(i=1; input!=EOF; i++) {
    // while((input=fgetc(fp)) != EOF) {
        input = fgetc(fp);
        // If (, go one floor up
        // If ), go one floor down
        // Else, ignore
        if (input == '(') {
            floors += 1;
        } else if (input == ')') {
            floors -= 1;
        } else {

        }

        // If the basement position has not been set,
        // check if the current floor is the basement
        // and save it if it is.
        // The index in enumeration starts from 0,
        // so we add 1 since the starting character position is 1.
        if (!basement_position) {
            if (floors == -1) {
                basement_position = i;
            }
        }
    }

    // Close the file
    fclose(fp);

    printf("Santa is at floor %d.", floors);
    printf("\nSanta reaches the basement at character %ld.", basement_position);

    return 0;
}


text:
[![Build Status](https://secure.travis-ci.org/julio/compactor.png)](http://travis-ci.org/julio/compactor) [![Gem Version](https://badge.fury.io/rb/compactor.png)](http://badge.fury.io/rb/compactor) [![Coverage Status](https://coveralls.io/repos/julio/compactor/badge.png?branch=master)](https://coveralls.io/r/julio/compactor)

Scrape Amazon Seller Central

## Installation

Add this line to your application's Gemfile:

    gem 'compactor'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install compactor

## Usage

```
rake test:coverage
```

```ruby
def scrape(email, password, from, to)
  scraper = Compactor::Amazon::ReportScraper.new(:email => email, :password => password)
  marketplaces = scraper.marketplaces

  original_from = from
  original_to   = to

  marketplaces.each do |marketplace|
    scraper.select_marketplace marketplace[1]

    from = original_from
    to   = original_to

    puts "Marketplace: #{marketplace[1]}"
    while from < to
      begin
        reports_by_type = scraper.reports(from, to)
        puts "There are #{reports_by_type.size} reports between #{from.to_date} and #{to.to_date}"
      rescue Exception => e
        puts "ERROR: #{e.message} - USER: #{email}"
      end
      from += 1.week
    end
  end
end

scrape "me@there.com", "secret", DateTime.parse("1/1/2012"), DateTime.now
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## Contributors

* Trae Robrock ( https://github.com/trobrock )
* Julio Santos ( https://github.com/julio )

## To-do

- Refactor
- 100% coverage


text:
package org.apache.commons.exec;

import java.util.Enumeration;
import java.util.Vector;

/**
 * Destroys all registered {@code Process}es when the VM exits.
 *
 * @version $Id$
 */
public class ShutdownHookProcessDestroyer implements ProcessDestroyer, Runnable {

    /** the list of currently running processes */
    private final Vector<Process> processes = new Vector<Process>();

    /** The thread registered at the JVM to execute the shutdown handler */
    private ProcessDestroyerImpl destroyProcessThread = null;

    /** Whether or not this ProcessDestroyer has been registered as a shutdown hook */
    private boolean added = false;

    /**
     * Whether or not this ProcessDestroyer is currently running as shutdown hook
     */
    private volatile boolean running = false;

    private class ProcessDestroyerImpl extends Thread {

        private boolean shouldDestroy = true;

        public ProcessDestroyerImpl() {
            super("ProcessDestroyer Shutdown Hook");
        }

        @Override
        public void run() {
            if (shouldDestroy) {
                ShutdownHookProcessDestroyer.this.run();
            }
        }

        public void setShouldDestroy(final boolean shouldDestroy) {
            this.shouldDestroy = shouldDestroy;
        }
    }

    /**
     * Constructs a {@code ProcessDestroyer} and obtains
     * {@code Runtime.addShutdownHook()} and
     * {@code Runtime.removeShutdownHook()} through reflection. The
     * ProcessDestroyer manages a list of processes to be destroyed when the VM
     * exits. If a process is added when the list is empty, this
     * {@code ProcessDestroyer} is registered as a shutdown hook. If
     * removing a process results in an empty list, the
     * {@code ProcessDestroyer} is removed as a shutdown hook.
     */
    public ShutdownHookProcessDestroyer() {
    }

    /**
     * Registers this {@code ProcessDestroyer} as a shutdown hook, uses
     * reflection to ensure pre-JDK 1.3 compatibility.
     */
    private void addShutdownHook() {
        if (!running) {
            destroyProcessThread = new ProcessDestroyerImpl();
            Runtime.getRuntime().addShutdownHook(destroyProcessThread);
            added = true;
        }
    }

    /**
     * Removes this {@code ProcessDestroyer} as a shutdown hook, uses
     * reflection to ensure pre-JDK 1.3 compatibility
     */
    private void removeShutdownHook() {
        if (added && !running) {
            final boolean removed = Runtime.getRuntime().removeShutdownHook(
                    destroyProcessThread);
            if (!removed) {
                System.err.println("Could not remove shutdown hook");
            }
            /*
             * start the hook thread, a unstarted thread may not be eligible for
             * garbage collection Cf.: http://developer.java.sun.com/developer/
             * bugParade/bugs/4533087.html
             */

            destroyProcessThread.setShouldDestroy(false);
            destroyProcessThread.start();
            // this should return quickly, since it basically is a NO-OP.
            try {
                destroyProcessThread.join(20000);
            } catch (final InterruptedException ie) {
                // the thread didn't die in time
                // it should not kill any processes unexpectedly
            }
            destroyProcessThread = null;
            added = false;
        }
    }

    /**
     * Returns whether or not the ProcessDestroyer is registered as as shutdown
     * hook
     *
     * @return true if this is currently added as shutdown hook
     */
    public boolean isAddedAsShutdownHook() {
        return added;
    }

    /**
     * Returns {@code true} if the specified {@code Process} was
     * successfully added to the list of processes to destroy upon VM exit.
     *
     * @param process
     *            the process to add
     * @return {@code true} if the specified {@code Process} was
     *         successfully added
     */
    public boolean add(final Process process) {
        synchronized (processes) {
            // if this list is empty, register the shutdown hook
            if (processes.size() == 0) {
                addShutdownHook();
            }
            processes.addElement(process);
            return processes.contains(process);
        }
    }

    /**
     * Returns {@code true} if the specified {@code Process} was
     * successfully removed from the list of processes to destroy upon VM exit.
     *
     * @param process
     *            the process to remove
     * @return {@code true} if the specified {@code Process} was
     *         successfully removed
     */
    public boolean remove(final Process process) {
        synchronized (processes) {
            final boolean processRemoved = processes.removeElement(process);
            if (processRemoved && processes.size() == 0) {
                removeShutdownHook();
            }
            return processRemoved;
        }
    }

  /**
   * Returns the number of registered processes.
   *
   * @return the number of register process
   */
  public int size() {
    return processes.size();
  }

  /**
     * Invoked by the VM when it is exiting.
     */
  public void run() {
      synchronized (processes) {
          running = true;
          final Enumeration<Process> e = processes.elements();
          while (e.hasMoreElements()) {
              final Process process = e.nextElement();
              try {
                  process.destroy();
              }
              catch (final Throwable t) {
                  System.err.println("Unable to terminate process during process shutdown");
              }
          }
      }
  }
}


text:
from experiment_construction.index_construction.indexes.lazy_indexer import LazyIndexer

class FreebaseRelationIndexer:

    inner_indexer = None

    def __init__(self, vocabulary_shape, cutoff_count):
        self.inner_indexer = LazyIndexer(vocabulary_shape)
        self.load_file(cutoff_count)

    def load_file(self, cutoff_count):
        file = "/home/mschlic1/GCNQA/data/webquestions/filtered_edge_count.txt"

        for line in open(file):
            line = line.strip()
            if line:
                parts = line.split("\t")
                relation_name = parts[0]
                count = int(parts[1])

                if count > cutoff_count:
                    self.index_single_element(relation_name)

        self.inner_indexer.freeze()

    def index_single_element(self, element):
        return self.inner_indexer.index_single_element(element)

    def get_dimension(self):
        return self.inner_indexer.get_dimension()

    def retrieve_vector(self, index):
        return self.inner_indexer.retrieve_vector(index)

    def get_all_vectors(self):
        return self.inner_indexer.get_all_vectors()

    def index(self, elements):
        return self.inner_indexer.index(elements)


text:
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [("course_catalog", "0001_initial")]

    operations = [
        migrations.CreateModel(
            name="CourseInstructor",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("first_name", models.CharField(max_length=128)),
                ("last_name", models.CharField(max_length=128)),
            ],
        ),
        migrations.CreateModel(
            name="CoursePrice",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("price", models.DecimalField(decimal_places=2, max_digits=5)),
                ("mode", models.CharField(max_length=128)),
                ("upgrade_deadline", models.DateTimeField(null=True)),
            ],
        ),
        migrations.CreateModel(
            name="CourseTopic",
            fields=[
                (
                    "id",
                    models.AutoField(
                        auto_created=True,
                        primary_key=True,
                        serialize=False,
                        verbose_name="ID",
                    ),
                ),
                ("name", models.CharField(max_length=128, unique=True)),
            ],
        ),
        migrations.RemoveField(model_name="course", name="image"),
        migrations.AddField(
            model_name="course",
            name="image_description",
            field=models.CharField(max_length=1024, null=True),
        ),
        migrations.AddField(
            model_name="course", name="image_src", field=models.URLField(null=True)
        ),
        migrations.AddField(
            model_name="course",
            name="instructors",
            field=models.ManyToManyField(to="course_catalog.CourseInstructor"),
        ),
        migrations.AddField(
            model_name="course",
            name="prices",
            field=models.ManyToManyField(to="course_catalog.CoursePrice"),
        ),
        migrations.AddField(
            model_name="course",
            name="topics",
            field=models.ManyToManyField(to="course_catalog.CourseTopic"),
        ),
    ]


text:
// +build wireinject

package main

import (
	"context"

	"github.com/google/knative-gcp/pkg/pubsub/adapter"
	"github.com/google/knative-gcp/pkg/utils/clients"

	"github.com/google/wire"
)

func InitializeAdapter(
	ctx context.Context,
	maxConnsPerHost clients.MaxConnsPerHost,
	projectID clients.ProjectID,
	subscriptionID adapter.SubscriptionID,
	namespace adapter.Namespace,
	name adapter.Name,
	resourceGroup adapter.ResourceGroup,
	args *adapter.AdapterArgs) (*adapter.Adapter, error) {
	panic(wire.Build(
		adapter.AdapterSet,
	))
}


text:
from game.ai.defence.yaku_analyzer.chinitsu import ChinitsuAnalyzer
from game.ai.defence.yaku_analyzer.honitsu_analyzer_base import HonitsuAnalyzerBase
from game.ai.helpers.defence import TileDanger
from mahjong.tile import TilesConverter
from mahjong.utils import count_tiles_by_suits, is_honor

class HonitsuAnalyzer(HonitsuAnalyzerBase):
    id = "honitsu"

    MIN_DISCARD = 6
    MAX_MELDS = 3
    EARLY_DISCARD_DIVISOR = 4
    LESS_SUIT_PERCENTAGE_BORDER = 20
    HONORS_PERCENTAGE_BORDER = 30

    def is_yaku_active(self):
        # TODO: in some distant future we may want to analyze menhon as well
        if not self.enemy.melds:
            return False

        total_melds = len(self.enemy.melds)
        total_discards = len(self.enemy.discards)

        # let's check if there is too little info to analyze
        if total_discards < HonitsuAnalyzer.MIN_DISCARD and total_melds < HonitsuAnalyzer.MAX_MELDS:
            return False

        # first of all - check melds, they must be all from one suit or honors
        current_suit = None
        for meld in self.enemy.melds:
            tile = meld.tiles[0]
            tile_34 = tile // 4

            if is_honor(tile_34):
                continue

            suit = ChinitsuAnalyzer._get_tile_suit(tile)
            if not current_suit:
                current_suit = suit
            elif suit["name"] != current_suit["name"]:
                return False

        # let's check discards
        discards = [x.value for x in self.enemy.discards]
        discards_34 = TilesConverter.to_34_array(discards)
        result = count_tiles_by_suits(discards_34)

        honors = [x for x in result if x["name"] == "honor"][0]
        suits = [x for x in result if x["name"] != "honor"]
        suits = sorted(suits, key=lambda x: x["count"], reverse=False)

        less_suit = suits[0]
        less_suit_tiles = less_suit["count"]
        percentage_of_less_suit = (less_suit_tiles / total_discards) * 100
        percentage_of_honor_tiles = (honors["count"] / total_discards) * 100

        # there is not too much one suit + honor tiles in the discard
        # so we can tell that user trying to collect honitsu
        if (
            percentage_of_less_suit <= HonitsuAnalyzer.LESS_SUIT_PERCENTAGE_BORDER
            and percentage_of_honor_tiles <= HonitsuAnalyzer.HONORS_PERCENTAGE_BORDER
        ):
            if not current_suit:
                current_suit = less_suit
            elif current_suit != less_suit:
                return False

        # still cannot determine the suit - this is probably not honitsu
        if not current_suit:
            return False

        if not self._check_discard_order(current_suit, int(total_discards / HonitsuAnalyzer.EARLY_DISCARD_DIVISOR)):
            return False

        # all checks have passed - assume this is honitsu
        self.chosen_suit = current_suit["function"]
        return True

    def melds_han(self):
        return self.enemy.is_open_hand and 2 or 3

    def get_safe_tiles_34(self):
        if not self.chosen_suit:
            return []

        safe_tiles = []
        for x in range(0, 34):
            if not self.chosen_suit(x) and not is_honor(x):
                safe_tiles.append(x)

        return safe_tiles

    def get_bonus_danger(self, tile_136, number_of_revealed_tiles):
        tile_34 = tile_136 // 4

        if is_honor(tile_34):
            if number_of_revealed_tiles == 4:
                return []
            elif number_of_revealed_tiles == 3:
                return [TileDanger.HONITSU_THIRD_HONOR_BONUS_DANGER]
            elif number_of_revealed_tiles == 2:
                return [TileDanger.HONITSU_SECOND_HONOR_BONUS_DANGER]
            else:
                return [TileDanger.HONITSU_SHONPAI_HONOR_BONUS_DANGER]

        return []

    def is_absorbed(self, possible_yaku, tile_34=None):
        return self._is_absorbed_by(possible_yaku, ChinitsuAnalyzer.id, tile_34)


text:
Courses
========

This repository holds the application code for IEEE AlexSB Courses website
which will contain all courses organized and instructed by IEEE AlexSB.

Dependencies
-------------

This application requires:

- [Ruby](https://www.ruby-lang.org/en/documentation/installation/) 2.2.x
- [Rails](http://railsapps.github.io/installing-rails.html) 5.0.0.1
- Gems:
    - [Devise](https://github.com/plataformatec/devise)
    - [Active Admin](https://github.com/activeadmin/activeadmin)
    - [Will paginate](https://github.com/mislav/will_paginate)
    - Other gems can be found in the [Gemfile](https://github.com/alexsb-software/Courses/blob/master/Gemfile)

Contributing
------------
Open source contribution is currently unavailable.

Credits
-------
IEEE AlexSB Software Development Committee

License
-------
[MIT license](https://github.com/alexsb-software/Courses/blob/master/LICENSE)


text:
@interface KYSwitchFreelyVC : KYBaseViewController

@end


text:
About

EcoSML is part of the EcoSIS Toolkit,
        which is funded by NASA's Earth Science Technology Office ESTO)
        through the Advanced Information Systems Technology (AIST) Program (Grant Number: 80NSSC17K0244).

The EcoSIS Toolkit is an extension of EcoSIS.org,
        which is online open-source database of ecologically
        oriented spectral measurements and associated metadata such as leaf or plant morphological and chemical
        measurements. EcoSIS is a repository to store your spectral data for distribution to the larger scientific
        community, as required by granting agencies and journals. EcoSIS enables data discovery and integration
        across datasets through a web-based search or an API. EcoSIS provides contributors with a DOI to enable
        long-term archiving and accessibility.

EcoSML.org is part of the EcoSIS Toolkit. EcoSML stand for the EcoSIS Spectral Model Library. One of the
        major uses of spectral data such as you might find in EcoSIS is the development of spectral models to
        predict vegetation traits such as leaf mass per area, chlorophyll content, water content or nitrogen
        concentration.  EcoSML is meant to be a repository for the spectral models that people use to
        predict variables of interest from spectral data (spectral data can include image, canopy  (proximal)
        or leaf level data). EcoSML provides both coefficients (e.g., for models built using partial least-squares
        regression, PLSR) and code needed by users to apply a spectral model to their data.

Researchers provide details and resources to create model packages that include coefficients, error parameters,
        demonstration data, and code. Users will be able to browse models, explore example code, and test outputs. Model
        packages will be installable via common package managers like Python's PyPI/pip, as well as R's CRAN.

          EcoSML accommodates any model forms that can be imbedded in code. At present this includes PLSR and Gaussian
          Process Models, and will be expanded to accept other model formats.

EcoSML's primary objectives:

Serve as a widely-accessible online repository where researchers can offer spectroscopy-derived models to
          the science community

Provide a robust API that allows direct links with EcoSIS.org, and various open-source software or
          desktop softwares users may have.

Personnel:

PI Philip Townsend

Project Manager Erin Wagner

Lead Developer Justin Merz


text:
    <input
    ms-widget="datepicker, $, $fromConfig"
    ms-duplex="MS_OPTION_FROMDUPLEX"/>

-

    <input
    ms-widget="datepicker, $, $toConfig"
    ms-duplex="MS_OPTION_TODUPLEX"/>

MS_OPTION_TEMPLATE
<input
    ms-widget="datepicker, $, $fromConfig"
    ms-duplex="MS_OPTION_FROMDUPLEX"/>
<input
    ms-widget="datepicker, $, $toConfig"
    ms-duplex="MS_OPTION_TODUPLEX"/>


text:
namespace xzero {

TcpConnection::TcpConnection(TcpEndPoint* endpoint,
                             Executor* executor)
    : endpoint_(endpoint),
      executor_(executor) {
}

TcpConnection::~TcpConnection() {
}

void TcpConnection::onOpen(bool dataReady) {
}

void TcpConnection::close() {
  if (endpoint_) {
    endpoint_->close();
  }
}

void TcpConnection::wantRead() {
  endpoint()->wantRead();
}

void TcpConnection::wantWrite() {
  endpoint()->wantWrite();
}

void TcpConnection::onReadable() {
}

void TcpConnection::onWriteable() {
}

void TcpConnection::onInterestFailure(const std::exception& error) {
  close();
}

bool TcpConnection::onReadTimeout() {
  // inform caller to close the endpoint
  return true;
}

}  // namespace xzero


text:
namespace Urho3D
{

/// 2D pulley constraint component.
class URHO3D_API ConstraintPulley2D : public Constraint2D
{
    URHO3D_OBJECT(ConstraintPulley2D, Constraint2D);

public:
    /// Construct.
    explicit ConstraintPulley2D(Context* context);
    /// Destruct.
    ~ConstraintPulley2D() override;
    /// Register object factory.
    static void RegisterObject(Context* context);

    /// Set other body ground anchor point.
    void SetOwnerBodyGroundAnchor(const Vector2& groundAnchor);
    /// Set other body ground anchor point.
    void SetOtherBodyGroundAnchor(const Vector2& groundAnchor);
    /// Set owner body anchor point.
    void SetOwnerBodyAnchor(const Vector2& anchor);
    /// Set other body anchor point.
    void SetOtherBodyAnchor(const Vector2& anchor);
    /// Set ratio.
    void SetRatio(float ratio);

    /// Return owner body ground anchor.
    const Vector2& GetOwnerBodyGroundAnchor() const { return ownerBodyGroundAnchor_; }

    /// return other body ground anchor.
    const Vector2& GetOtherBodyGroundAnchor() const { return otherBodyGroundAnchor_; }

    /// Return owner body anchor.
    const Vector2& GetOwnerBodyAnchor() const { return ownerBodyAnchor_; }

    /// Return other body anchor.
    const Vector2& GetOtherBodyAnchor() const { return otherBodyAnchor_; }

    /// Return ratio.
    float GetRatio() const { return jointDef_.ratio; }

private:
    /// Return Joint def.
    b2JointDef* GetJointDef() override;

    /// Box2D joint def.
    b2PulleyJointDef jointDef_;
    /// Owner body ground anchor.
    Vector2 ownerBodyGroundAnchor_;
    /// Other body ground anchor.
    Vector2 otherBodyGroundAnchor_;
    /// Owner body anchor.
    Vector2 ownerBodyAnchor_;
    /// Other body anchor.
    Vector2 otherBodyAnchor_;
};

}


text:
import uuid

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('taxonomy', '0010_auto_20181130_0829'),
    ]

    operations = [
        migrations.AddField(
            model_name='community',
            name='source',
            field=models.PositiveIntegerField(choices=[(0, 'Direct entry'), (1, 'Manual entry from paper datasheet'), (2, 'Digital data capture (ODK)'), (10, 'Threatened Fauna'), (11, 'Threatened Flora'), (12, 'Threatened Communities'), (13, 'Threatened Communities Boundaries'), (14, 'Threatened Communities Buffers'), (15, 'Threatened Communities Sites'), (20, 'Turtle Tagging Database WAMTRAM2'), (21, 'Ningaloo Turtle Program'), (22, 'Broome Turtle Program'), (23, 'Pt Hedland Turtle Program'), (24, 'Gnaraloo Turtle Program'), (25, 'Eco Beach Turtle Program'), (30, 'Cetacean Strandings Database'), (31, 'Pinniped Strandings Database')], default=0, help_text='Where was this record captured initially?', verbose_name='Data Source'),
        ),
        migrations.AddField(
            model_name='community',
            name='source_id',
            field=models.CharField(default=uuid.UUID('f14f768e-f7b4-11e8-a86f-40f02f6195e0'), help_text='The ID of the record in the original source, if available.', max_length=1000, verbose_name='Source ID'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='class_name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Class'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='division_name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Division'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='family_name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Family Name'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='kingdom_name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Kingdom'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='order_name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Order Name'),
        ),
        migrations.AlterField(
            model_name='hbvfamily',
            name='supra_code',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='HBV Suprafamily Group Code'),
        ),
        migrations.AlterField(
            model_name='hbvgroup',
            name='class_id',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='HBV Suprafamily Group Code'),
        ),
        migrations.AlterField(
            model_name='hbvparent',
            name='class_id',
            field=models.CharField(blank=True, help_text='', max_length=100, null=True, verbose_name='WACensus ClassID'),
        ),
        migrations.AlterField(
            model_name='hbvspecies',
            name='consv_code',
            field=models.CharField(blank=True, help_text='', max_length=100, null=True, verbose_name='Conservation Code'),
        ),
        migrations.AlterField(
            model_name='hbvspecies',
            name='naturalised',
            field=models.CharField(blank=True, help_text='', max_length=100, null=True, verbose_name='Naturalised'),
        ),
        migrations.AlterField(
            model_name='hbvspecies',
            name='ranking',
            field=models.CharField(blank=True, help_text='', max_length=100, null=True, verbose_name='Ranking'),
        ),
        migrations.AlterField(
            model_name='hbvvernacular',
            name='name',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Name'),
        ),
        migrations.AlterField(
            model_name='hbvvernacular',
            name='vernacular',
            field=models.CharField(blank=True, help_text='', max_length=1000, null=True, verbose_name='Vernacular Name'),
        ),
    ]


text:
using Frapid.DataAccess.Models;

namespace Frapid.DataAccess
{
    public interface IPolicy
    {
        string ObjectNamespace { get; set; }
        string ObjectName { get; set; }
        AccessTypeEnum AccessType { get; set; }
        bool HasAccess { get; }
        long LoginId { get; set; }
        string Database { get; set; }
        void Validate();
    }
}


text:
using System;

using NQuery.Runtime;

namespace NQuery.Compilation
{
	internal sealed class MetaInfo
	{
		private ColumnRefBinding[] _columnDependencies;
		private TableRefBinding[] _tableDependencies;
		private bool _containsSingleRowSubselects;
		private bool _containsExistenceSubselects;

		public MetaInfo(ColumnRefBinding[] columnDependencies,
		                TableRefBinding[] tableDependencies,
		                bool containsSingleRowSubselects,
		                bool containsExistenceSubselects)
		{
			_columnDependencies = columnDependencies;
			_tableDependencies = tableDependencies;
			_containsSingleRowSubselects = containsSingleRowSubselects;
			_containsExistenceSubselects = containsExistenceSubselects;
		}

		public ColumnRefBinding[] ColumnDependencies
		{
			get { return _columnDependencies; }
		}

		public TableRefBinding[] TableDependencies
		{
			get { return _tableDependencies; }
		}

		public bool ContainsSingleRowSubselects
		{
			get { return _containsSingleRowSubselects; }
			set { _containsSingleRowSubselects = value; }
		}

		public bool ContainsExistenceSubselects
		{
			get { return _containsExistenceSubselects; }
			set { _containsExistenceSubselects = value; }
		}
	}
}


text:
/* */
"format cjs";
import { bindActionCreators } from 'redux'

function wrapActionCreators(actionCreators) {
  return dispatch => bindActionCreators(actionCreators, dispatch)
}

module.exports = wrapActionCreators


text:
namespace Logging {

FileLogger::FileLogger(Level level) : StreamLogger(level) {
}

void FileLogger::init(const std::string& fileName) {
  fileStream.open(fileName, std::ios::app);
  StreamLogger::attachToStream(fileStream);
}

}


text:
using System;
using System.Diagnostics;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

namespace ExtraLayers.LZ4
{
    /// <summary>
    /// Static LZ4 Compression and Decompression. This is threadsafe because it creates new instances of the
    /// compression/decompression classes for each method call.
    /// It is recommended to use LZ4Compressor and LZ4Decompressor for repeated compressing/decompressing for speed and less memory allocations.
    /// </summary>
    public static unsafe class LZ4
    {
        public static byte[] Compress(byte[] source)
        {
            return LZ4CompressorFactory.CreateNew().Compress(source);
        }

        /// <summary>
        /// Calculate the max compressed byte[] size given the size of the uncompressed byte[]
        /// </summary>
        /// <param name="uncompressedLength">Length of the uncompressed data</param>
        /// <returns>The maximum required size in bytes of the compressed data</returns>
        public static int CalculateMaxCompressedLength(int uncompressedLength)
        {
            return LZ4CompressorFactory.CreateNew().CalculateMaxCompressedLength(uncompressedLength);
        }

        /// <summary>
        /// Compress source into dest returning compressed length
        /// </summary>
        /// <param name="source">uncompressed data</param>
        /// <param name="dest">array into which source will be compressed</param>
        /// <returns>compressed length</returns>
        public static int Compress(byte[] source, byte[] dest)
        {
            return LZ4CompressorFactory.CreateNew().Compress(source, dest);
        }

        /// <summary>
        /// Compress source into dest returning compressed length
        /// </summary>
        /// <param name="source">uncompressed data</param>
        /// <param name="srcOffset">offset in source array where reading will start</param>
        /// <param name="count">count of bytes in source array to compress</param>
        /// <param name="dest">array into which source will be compressed</param>
        /// <param name="dstOffset">start index in dest array where writing will start</param>
        /// <returns>compressed length</returns>
        public static int Compress(byte[] source, int srcOffset, int count, byte[] dest, int dstOffset)
        {
            return LZ4CompressorFactory.CreateNew().Compress(source, srcOffset, count, dest, dstOffset);
        }

        public static void DecompressKnownSize(byte[] compressed, byte[] decompressed)
        {
            LZ4DecompressorFactory.CreateNew().DecompressKnownSize(compressed, decompressed);
        }

        public static int DecompressKnownSize(byte[] compressed, byte[] decompressedBuffer, int decompressedSize)
        {
            return LZ4DecompressorFactory.CreateNew().DecompressKnownSize(compressed, decompressedBuffer, decompressedSize);
        }

        public static int DecompressKnownSize(byte* compressed, byte* decompressedBuffer, int decompressedSize)
        {
            return LZ4DecompressorFactory.CreateNew().DecompressKnownSize(compressed, decompressedBuffer, decompressedSize);
        }

        public static byte[] Decompress(byte[] compressed)
        {
            return LZ4DecompressorFactory.CreateNew().Decompress(compressed);
        }

        public static int Decompress(byte[] compressed, byte[] decompressedBuffer)
        {
            return LZ4DecompressorFactory.CreateNew().Decompress(compressed, decompressedBuffer);
        }

        public static int Decompress(byte[] compressedBuffer, byte[] decompressedBuffer, int compressedSize)
        {
            return LZ4DecompressorFactory.CreateNew().Decompress(compressedBuffer, decompressedBuffer, compressedSize);
        }

        public static int Decompress(
            byte* compressedBuffer,
            byte* decompressedBuffer,
            int compressedSize,
            int maxDecompressedSize)
        {
            return LZ4DecompressorFactory.CreateNew().Decompress(compressedBuffer, decompressedBuffer, compressedSize, maxDecompressedSize);
        }
    }

}


text:
<?php

require __DIR__ . '/../vendor/autoload.php';

use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use React\Promise\Deferred;

$loop = Factory::create();

/** @async() */
function readUserInput() {
    /** @await($loop) */
    $stream = fopen('php://stdin', 'r');

    throw new \Exception('error');

    echo $str . "\n";
}

/** @async() */
function main(LoopInterface $loop = null) {
    echo "start\n";

    try {
        /** @await($loop) */
        readUserInput();
        echo "end\n";
    } catch (\Exception $e) {
        echo "Exception: " . $e;
        return;
    }

}

main($loop);

$loop->run();


text:
from st2common.models.db.notification import NotificationSchema, NotificationSubSchema

NotificationSubSchemaAPI = {
    "type": "object",
    "properties": {
        "message": {
            "type": "string",
            "description": "Message to use for notification"
        },
        "data": {
            "type": "object",
            "description": "Data to be sent as part of notification"
        },
        "channels": {
            "type": "array",
            "description": "Channels to post notifications to."
        },
    },
    "additionalProperties": False
}

class NotificationsHelper(object):

    @staticmethod
    def to_model(notify_api_object):
        if notify_api_object.get('on-success', None):
            on_success = NotificationsHelper._to_model_sub_schema(notify_api_object['on-success'])
        else:
            on_success = None

        if notify_api_object.get('on-complete', None):
            on_complete = NotificationsHelper._to_model_sub_schema(
                notify_api_object['on-complete'])
        else:
            on_complete = None

        if notify_api_object.get('on-failure', None):
            on_failure = NotificationsHelper._to_model_sub_schema(notify_api_object['on-failure'])
        else:
            on_failure = None

        model = NotificationSchema(on_success=on_success, on_failure=on_failure,
                                   on_complete=on_complete)
        return model

    @staticmethod
    def _to_model_sub_schema(notification_settings_json):
        message = notification_settings_json.get('message' or None)
        data = notification_settings_json.get('data' or {})
        channels = notification_settings_json.get('channels' or [])

        model = NotificationSubSchema(message=message, data=data, channels=channels)
        return model

    @staticmethod
    def from_model(notify_model):
        notify = {}
        if getattr(notify_model, 'on_complete', None):
            notify['on-complete'] = NotificationsHelper._from_model_sub_schema(
                notify_model.on_complete)
        if getattr(notify_model, 'on_success', None):
            notify['on-success'] = NotificationsHelper._from_model_sub_schema(
                notify_model.on_success)
        if getattr(notify_model, 'on_failure', None):
            notify['on-failure'] = NotificationsHelper._from_model_sub_schema(
                notify_model.on_failure)
        return notify

    @staticmethod
    def _from_model_sub_schema(notify_sub_schema_model):
        notify_sub_schema = {}

        if getattr(notify_sub_schema_model, 'message', None):
            notify_sub_schema['message'] = notify_sub_schema_model.message
        if getattr(notify_sub_schema_model, 'message', None):
            notify_sub_schema['data'] = notify_sub_schema_model.data
        if getattr(notify_sub_schema_model, 'channels', None):
            notify_sub_schema['channels'] = notify_sub_schema_model.channels

        return notify_sub_schema


text:
import Component from 'react-pure-render/component';
import Helmet from 'react-helmet';
import React from 'react';
import linksMessages from '../../common/app/linksMessages';
import { FormattedHTMLMessage, defineMessages, injectIntl, intlShape } from 'react-intl';

const messages = defineMessages({
  intro: {
    defaultMessage: `

        Ahoy, this is the
        Este dev stack.

    `,
    id: 'home.intro'
  }
});

class HomePage extends Component {

  static propTypes = {
    intl: intlShape.isRequired
  };

  render() {
    const { intl } = this.props;
    const title = intl.formatMessage(linksMessages.home);

    return (

        <Helmet title={title} />
        <FormattedHTMLMessage {...messages.intro} />
        {/* Use require for assets. It's super useful for CDN. */}

    );
  }

}

export default injectIntl(HomePage);


text:
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace CInovonics.Domain.Helpers
{
    public static class Parsers
    {
        public static T ParseXML<T>(this XmlReader reader) where T: class
        {
            return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
        }

        public static T ParseXML<T>(this string xml) where T : class
        {
            return new XmlSerializer(typeof(T)).Deserialize(new StringReader(xml)) as T;
        }
    }
}


text:
package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.validator.StorageDomainValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.MoveOrCopyImageGroupParameters;
import org.ovirt.engine.core.common.action.MoveOrCopyParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.CopyVolumeType;
import org.ovirt.engine.core.common.businessentities.DiskImage;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.VmTemplate;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.VdcBllMessages;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;

public class ExportVmTemplateCommand<T extends MoveOrCopyParameters> extends MoveOrCopyTemplateCommand<T> {
    public ExportVmTemplateCommand(T parameters) {
        super(parameters);
        setVmTemplateId(parameters.getContainerId());
        setStoragePoolId(getVmTemplate().getstorage_pool_id());
    }

    protected ExportVmTemplateCommand(Guid commandId) {
        super(commandId);
    }

    @Override
    protected void MoveOrCopyAllImageGroups(final Guid containerID, final Iterable<DiskImage> disks) {
        TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {

            @Override
            public Void runInTransaction() {
                for (DiskImage disk : disks) {
                    // we force export template image to COW+Sparse but we don't update
                    // the ovf so the import
                    // will set the original format
                    MoveOrCopyImageGroupParameters tempVar = new MoveOrCopyImageGroupParameters(containerID, disk
                            .getimage_group_id().getValue(), disk.getId(), getParameters().getStorageDomainId(),
                            getMoveOrCopyImageOperation());
                    tempVar.setParentCommand(getActionType());
                    tempVar.setParentParemeters(getParameters());
                    tempVar.setEntityId(getParameters().getEntityId());
                    tempVar.setUseCopyCollapse(true);
                    tempVar.setCopyVolumeType(CopyVolumeType.SharedVol);
                    tempVar.setVolumeFormat(disk.getvolume_format());
                    tempVar.setVolumeType(disk.getvolume_type());
                    tempVar.setPostZero(disk.getwipe_after_delete());
                    tempVar.setForceOverride(getParameters().getForceOverride());
                    MoveOrCopyImageGroupParameters p = tempVar;
                    if (getSourceDomain() != null) {
                        p.setSourceDomainId(getSourceDomain().getId());
                    }
                    VdcReturnValueBase vdcRetValue = Backend.getInstance().runInternalAction(
                                    VdcActionType.MoveOrCopyImageGroup,
                                    p,
                                    ExecutionHandler.createDefaultContexForTasks(getExecutionContext()));
                    getParameters().getImagesParameters().add(p);

                    if (!vdcRetValue.getSucceeded()) {
                        throw new VdcBLLException(vdcRetValue.getFault().getError(), vdcRetValue.getFault()
                                .getMessage());
                    }

                    getReturnValue().getTaskIdList().addAll(vdcRetValue.getInternalTaskIdList());
                }
                return null;
            }
        });
    }

    @Override
    protected boolean canDoAction() {
        if (getVmTemplate() != null) {
            setDescription(getVmTemplateName());
        }
        StorageDomainValidator storageDomainValidator = new StorageDomainValidator(getStorageDomain());
        boolean retVal = storageDomainValidator.isDomainExistAndActive(getReturnValue().getCanDoActionMessages());

        if (retVal) {
            // export must be to export domain
            if (getStorageDomain().getstorage_domain_type() != StorageDomainType.ImportExport) {
                addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_SPECIFY_DOMAIN_IS_NOT_EXPORT_DOMAIN);
                retVal = false;
            }
        }

        retVal = retVal && super.canDoAction();

        if (retVal) {
            // check that we have at least one disk
            if (getParameters().getDiskInfoList() != null) {
                if (getParameters().getDiskInfoList().size() > 0) {
                    addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL);
                    retVal = false;
                }
            }
        }

        // check if template (with no override option)
        if (retVal && !getParameters().getForceOverride()) {
            retVal = !ExportVmCommand.CheckTemplateInStorageDomain(getVmTemplate().getstorage_pool_id().getValue(),
                    getParameters().getStorageDomainId(), getVmTemplateId());
            if (!retVal) {
                addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_TEMPLATE_NAME_ALREADY_EXISTS);
            }
        }

        // set source storage
        if (retVal) {
            DiskImage image = getTemplateDisks().get(0);
            if (image == null) {
                addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_VM_HAS_NO_DISKS);
                retVal = false;
            }
            if (retVal) {
                if (getSourceDomain() == null) {
                    addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST);
                    retVal = false;
                }
            }
        }
        // check that source domain is leagal
        if (retVal) {
            retVal = IsDomainActive(getSourceDomain().getId(), getVmTemplate().getstorage_pool_id());
        }
        // check that source domain is not ISO or Export domain
        if (retVal) {
            if (getSourceDomain().getstorage_domain_type() == StorageDomainType.ISO
                    || getSourceDomain().getstorage_domain_type() == StorageDomainType.ImportExport) {
                addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_TYPE_ILLEGAL);
                retVal = false;
            }
        }
        if (!retVal) {
            addCanDoActionMessage(VdcBllMessages.VAR__ACTION__EXPORT);
            addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM);
        }
        return retVal;
    }

    @Override
    public AuditLogType getAuditLogTypeValue() {
        switch (getActionState()) {
        case EXECUTE:
            return getSucceeded() ? AuditLogType.IMPORTEXPORT_STARTING_EXPORT_TEMPLATE
                    : AuditLogType.IMPORTEXPORT_EXPORT_TEMPLATE_FAILED;

        case END_SUCCESS:
            return getSucceeded() ? AuditLogType.IMPORTEXPORT_EXPORT_TEMPLATE
                    : AuditLogType.IMPORTEXPORT_EXPORT_TEMPLATE_FAILED;
        }
        return super.getAuditLogTypeValue();
    }

    @Override
    protected void UpdateTemplateInSpm() {
        // update the target (export) domain
        VmTemplateCommand.UpdateTemplateInSpm(getVmTemplate().getstorage_pool_id().getValue(),
                new java.util.ArrayList<VmTemplate>(java.util.Arrays.asList(new VmTemplate[] { getVmTemplate() })),
                getParameters().getStorageDomainId(), null);
    }
}


text:
package Nodes.Frames;

import Nodes.StatisticalDistributions.TruncatedGaussian;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 *
 * @author Administrator
 */
public class TruncGaussDistPanel extends javax.swing.JPanel {

    /**
     * Creates new form TruncGaussDistPanel
     */
    private TruncatedGaussian distribution;
    public TruncGaussDistPanel(TruncatedGaussian dist) {
        initComponents();
        this.distribution = dist;
        jTextFieldLowerLimit.setText(Double.toString(distribution.GetLowerLimit()));
        jTextFieldUpperLimit.setText(Double.toString(distribution.GetUpperLimit()));
        jTextFieldMean.setText(Double.toString(distribution.GetMean()));
        jTextFieldStd.setText(Double.toString(distribution.GetStd()));
        AddChangeListeners();
    }
    private void AddChangeListeners()
     {
         AddChangeListener(jTextFieldUpperLimit);
         AddChangeListener(jTextFieldLowerLimit);
         AddChangeListener(jTextFieldMean);
         AddChangeListener(jTextFieldStd);
     }
     private void AddChangeListener(JTextField field)
    {
         //ModelParameterNodeWindow f = (ModelParameterNodeWindow)javax.swing.SwingUtilities.getWindowAncestor(this);
//        //VERY VERY VERY BAD PROGRAMMING PRACTICE
 field.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
           ModelParameterNodeWindow p = (ModelParameterNodeWindow) getParent().getParent();
           p.UpdateButtonChangeState(true);
           // parent.UpdateButtonChangeState(true);
            // text was changed
        }
        @Override
        public void removeUpdate(DocumentEvent e) {

            ModelParameterNodeWindow p = (ModelParameterNodeWindow) getParent().getParent();
           p.UpdateButtonChangeState(true);

           // parent.UpdateButtonChangeState(true);
            // text was deleted
        }
       @Override
        public void insertUpdate(DocumentEvent e) {
          ModelParameterNodeWindow p = (ModelParameterNodeWindow) getParent().getParent();
           p.UpdateButtonChangeState(true);
            ///parent.UpdateButtonChangeState(true);
            // text was inserted
       }

    });
         }
     private boolean isNumeric(String str)
    {
        try
        {
            double d = Double.parseDouble(str);
        }
        catch(NumberFormatException nfe)
        {
            return false;
        }
        return true;
    }
     private void SetDistribution()
     {
         distribution.SetLowerLimit(Double.parseDouble(jTextFieldLowerLimit.getText()));
         distribution.SetUpperLimit(Double.parseDouble(jTextFieldUpperLimit.getText()));
         distribution.SetMean(Double.parseDouble(jTextFieldMean.getText()));
         distribution.SetStd(Double.parseDouble(jTextFieldStd.getText()));
     }

     public boolean Validate()
     {

         boolean retVal = false;

         if (!isEverythingNumeric())
         {

              JOptionPane.showMessageDialog(this, "Incorrect Input:\n "
                    + "Please Enter numeric values only",
                   "Error", JOptionPane.ERROR_MESSAGE);
                retVal = false;
         }
         else
         {
             double lowerLimit = Double.parseDouble(jTextFieldLowerLimit.getText());
             double upperLimit = Double.parseDouble(jTextFieldUpperLimit.getText());
             double mean = Double.parseDouble(jTextFieldMean.getText());

             if (upperLimit < lowerLimit)
             {
                   JOptionPane.showMessageDialog(this, "Incorrect Input:\n "
                    + "Upper Limit can not be less than the lower limit",
                   "Error", JOptionPane.ERROR_MESSAGE);
                retVal = false;

             }
             else if(mean > upperLimit)
             {
                 JOptionPane.showMessageDialog(this, "Incorrect Input:\n "
                    + "Mean can not be greater than the upper limit",
                   "Error", JOptionPane.ERROR_MESSAGE);
                retVal = false;

             }
             else if (mean < lowerLimit)
             {
                 JOptionPane.showMessageDialog(this, "Incorrect Input:\n "
                    + "Mean can not be less than the lower limit",
                   "Error", JOptionPane.ERROR_MESSAGE);
                retVal = false;
             }
             else
             {
                 SetDistribution();
                 retVal = true;
             }
         }
         return retVal;
     }
     private boolean isEverythingNumeric()
     {
        if (isNumeric(jTextFieldLowerLimit.getText())
                && isNumeric(jTextFieldUpperLimit.getText())
                && isNumeric(jTextFieldMean.getText())
                && isNumeric(jTextFieldStd.getText()))
                {
                    return true;
                }

        else
        {
                return false;
        }
     }
    public TruncatedGaussian GetDistribution()
    {
        return distribution;

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextFieldUpperLimit = new javax.swing.JTextField();
        jTextFieldLowerLimit = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldMean = new javax.swing.JTextField();
        jTextFieldStd = new javax.swing.JTextField();

        setPreferredSize(new java.awt.Dimension(547, 100));

        jTextFieldUpperLimit.setText("jTextField1");

        jTextFieldLowerLimit.setText("jTextField2");

        jLabel1.setText("Upper Limit:");

        jLabel2.setText("Lower Limit:");

        jLabel3.setLabelFor(jTextFieldMean);
        jLabel3.setText("Mean:");

        jLabel4.setLabelFor(jTextFieldStd);
        jLabel4.setText("Std. Dev:");

        jTextFieldMean.setText("jTextField1");

        jTextFieldStd.setText("jTextField2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(112, 112, 112)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldUpperLimit, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextFieldLowerLimit, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextFieldMean, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                    .addComponent(jTextFieldStd))
                .addContainerGap(68, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldUpperLimit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldMean, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldLowerLimit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldStd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(30, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextFieldLowerLimit;
    private javax.swing.JTextField jTextFieldMean;
    private javax.swing.JTextField jTextFieldStd;
    private javax.swing.JTextField jTextFieldUpperLimit;
    // End of variables declaration//GEN-END:variables
}


text:
var app = angular.module("MyApp", []).
  config(function($routeProvider, $locationProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.
      when("/persons", { templateUrl: "partials/index.html" }).
      when("/persons/:id", { templateUrl: "partials/show.html", controller: "ShowCtrl" }).
      when("/login", { templateUrl: "partials/login.html", controller: "LoginCtrl" }).
      when("/help", { templateUrl: "partials/help.html" }).
      otherwise( { redirectTo: "/persons" });
  }).
  run(function($rootScope, $location) {

    $rootScope.$on( "$routeChangeStart", function(event, next, current) {
      if ($rootScope.loggedInUser == null) {
        // no logged user, redirect to /login
        if ( next.templateUrl === "partials/login.html") {
        } else {
          $location.path("/login");
        }
      }
    });
  });

app.factory("Person", function() {

  var persons = [
    { name: "Peter", age: 25, id: 1 },
    { name: "Stefan", age: 35, id: 2 },
    { name: "Agnes", age: 22, id: 3 }
  ];

  return {
    all: function() {
      return persons;
    },
    get: function(id) {
      var result = null;
      angular.forEach(persons, function(p) {
        if (p.id == id) result = p;
      });
      return result;
    }
  };
});

app.controller("IndexCtrl", function($scope, Person) {
  $scope.persons = Person.all();
});

app.controller("ShowCtrl", function($scope, $routeParams, Person) {
  $scope.person = Person.get($routeParams.id);
});

app.controller("MainCtrl", function($scope, $location) {
  $scope.menuClass = function(page) {
    var current = $location.path().substring(1);
    return page === current ? "active" : "";
  };
});

app.controller("LoginCtrl", function($scope, $location, $rootScope) {
  $scope.login = function() {
    $rootScope.loggedInUser = $scope.username;
    $location.path("/persons");
  };
});


text:
OCAMLINCLUDES += $(DYP_LIB) ../ $(GETOPT_DIR)

OCAMLFLAGS = $(filter-out -dtypes, $(OCAMLFLAGS))

newParser.ml newParser.mli: newParser.dyp $(DYPGEN)
	$(DYPGEN)  newParser.dyp

typeAnnotParser.ml typeAnnotParser.mli: typeAnnotParser.mly
  ocamlyacc -v typeAnnotParser.mly

FILES[] +=
   parser/typeAnnotParser
   parser/typeAnnotLexer
   parser/newParser
   parser/newLexer
   parser/rubyLexerState
   parser/parse_helper
   parser/ast
   parser/ast_printer
   parser/annotation

TEST[] =
   rat_test

OCAML_OTHER_LIBS += nums str unix getopt
OCAML_LIBS = $(DYP_LIB)/dyp ../druby

RAT_TEST = $(OCamlProgram rat_test, $(TEST))

.DEFAULT: $(RAT_TEST)


text:
package org.adligo.tests4j_v1_tests.gwt_refs.v2_6.lang;

/** autogenerated by org.adligo.tests4j.gen.dependency_groups.ClassUseGen*/
public class NoSuchFieldError_2_6_MockUse {

	public NoSuchFieldError obj = null;
	public NoSuchFieldError_2_6_MockUse() {
	  obj = new NoSuchFieldError();
		obj = new NoSuchFieldError(
			"string");
		callObjectMethods();
		callThrowableMethods();
	}

	/**
	 * this needs to be generated each
	 * time so the instance getting methods called
	 * on it is the correct type.
	 */
	public void callObjectMethods() {
		obj.equals(null);
		obj.getClass();
		obj.hashCode();
		obj.toString();
	}
	/**
	 * this needs to be generated each
	 * time so the instance getting methods called
	 * on it is the correct type.
	 */
	public void callThrowableMethods() {
		obj = new NoSuchFieldError();
		obj.initCause(new Throwable("hmm"));
		obj = new NoSuchFieldError();
		obj.addSuppressed(new Throwable());

		obj.getStackTrace();
		obj.getSuppressed();
		obj.getLocalizedMessage();
		obj.getMessage();
		obj.toString();
		obj.fillInStackTrace();
		obj.getCause();

		obj.printStackTrace();
		obj.printStackTrace(System.out);
		obj.setStackTrace(new StackTraceElement[] {});
	}
}


text:
package macaca.client.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import macaca.client.model.JsonWireStatus;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
public class Utils {
//    private final Log log = LogFactory.getLog(getClass());

    private HttpGet httpget = null;
    //Use static variables to ensure that the same connection pool is used when
    // multiple macacaClient instances are initialized in the application.
    private static CloseableHttpClient httpclient;
    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        //max size conect per host route
        connectionManager.setDefaultMaxPerRoute(500);
        //max size connect
        connectionManager.setMaxTotal(1000);
        HttpClientBuilder builder = HttpClientBuilder.create();

        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(
                CookieSpecs.STANDARD);
        //set timeout config
        RequestConfig requestConfig = requestConfigBuilder.setConnectTimeout(50000)
                .setSocketTimeout(50000).build();

        builder.setConnectionManager(connectionManager).setDefaultHeaders(Arrays.asList(
                new BasicHeader("Accept", "*/*"),
                new BasicHeader("Connection", "keep-alive")));
        builder.setDefaultRequestConfig(requestConfig);
        httpclient = builder.build();
    }

    private CloseableHttpResponse response = null;
    private HttpEntity entity = null;
    private JSONObject jsonResponse = null;
    private String stringResponse = "";
    private MacacaDriver driver;

    private static Callback<Exception, Boolean> exceptionCallback;

    public Utils(MacacaDriver driver) {
        this.driver = driver;
    }

    // you can set Exception Callback for request macaca server error process.
    public static void setExceptionCallback(Callback<Exception, Boolean> callback) {
        exceptionCallback = callback;
    }

    private static SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式

    private void printResponse(String stringResponse) throws Exception {
        if (stringResponse.length() > 800) {
            System.out.println(sDateFormat.format(new java.util.Date()) + " Response:" + stringResponse.substring(0, 800) + "...more response is ignored..");
        } else {
            System.out.println(sDateFormat.format(new java.util.Date()) + " Response:" + stringResponse);
        }
    }

    private void printRequest(String stringRequest) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式
        System.out.println(df.format(new java.util.Date()) + " Request:" + stringRequest);
    }

    private void executeRequest(HttpRequestBase request) throws Exception {
        // avoid entity is null
        jsonResponse = null;
        try {
            response = httpclient.execute(request);
            entity = response.getEntity();
            //System.out.println(response.getStatusLine().getStatusCode());
            if (entity != null) {
                stringResponse = EntityUtils.toString(entity);
                printResponse(stringResponse);
                jsonResponse = JSON.parseObject(stringResponse);
                handleStatus(jsonResponse.getInteger("status"));
            }
        } finally {
            if (response != null) {
                //Release the resources occupied by the connection after use
                response.close();
            }
        }

    }

    private Object getRequest(String method, JSONObject jsonBody) throws Exception {
        for (String key : jsonBody.keySet()) {
            String value = jsonBody.get(key).toString();
            method = method.replace(":" + key, value);
        }

        String url = Constants.SUFFIX.replace("${host}", driver.getHost()).replace("${port}", driver.getPort()) + method;
        printRequest(url);
        httpget = new HttpGet(url);
        executeRequest(httpget);
        if (jsonResponse != null) {
            return jsonResponse.get("value");
        }
        return null;
    }

    private Object postRequest(String method, JSONObject jsonBody) throws Exception {
        JSONObject tempObj = new JSONObject();
        for (String key : jsonBody.keySet()) {
            String value;
            if (jsonBody.get(key) == null) {
                value = null;
            } else {
                value = jsonBody.get(key).toString();
            }
            if (method.contains(":" + key)) {
                if (value != null) {
                    method = method.replace(":" + key, value);
                }
            } else {
                tempObj.put(key, jsonBody.get(key));
            }
        }

        String url = Constants.SUFFIX.replace("${host}", driver.getHost()).replace("${port}", driver.getPort()) + method;

        HttpPost httppost = new HttpPost(url);
        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(tempObj, SerializerFeature.WriteMapNullValue), "utf-8");
        stringEntity.setContentEncoding("utf-8");
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        printRequest(url + ":" + JSONObject.toJSONString(tempObj,
                SerializerFeature.WriteMapNullValue));
        executeRequest(httppost);
        return jsonResponse;
    }

    public Object deleteRequest(String method, JSONObject jsonBody) throws Exception {
        for (String key : jsonBody.keySet()) {
            String value = jsonBody.get(key).toString();
            method = method.replace(":" + key, value);
        }

        String url = Constants.SUFFIX.replace("${host}", driver.getHost()).replace("${port}", driver.getPort()) + method;
        HttpDelete httpdelete = new HttpDelete(url);
        executeRequest(httpdelete);
        return jsonResponse;
    }

    public Object request(String method, String url, JSONObject jsonObj) throws Exception {
        try {
            if ("GET".equals(method.toUpperCase())) {
                return getRequest(url, jsonObj);
            } else if ("POST".equals(method.toUpperCase())) {
                return postRequest(url, jsonObj);
            } else if ("DELETE".equals(method.toUpperCase())) {
                return deleteRequest(url, jsonObj);
            }
        } catch (Exception e) {
            // if exceptionCallback return Boolean.TRUE, throw exception again
            if (exceptionCallback != null) {
                Boolean needThrow = exceptionCallback.call(e);
                if (needThrow != null && needThrow.booleanValue()) {
                    throw e;
                }
            } else {
                throw e;
            }
        }

        return null;
    }

    void handleStatus(int statusCode) throws Exception {
        JsonWireStatus status = JsonWireStatus.findByStatus(statusCode);
        if (status != JsonWireStatus.Success && status != JsonWireStatus.Default && status != JsonWireStatus.NoAlertOpenError) {
            throw new Exception(status.message());
        }
    }

    public String getStatus(String method) throws Exception {
        try {
            String url = Constants.SUFFIX.replace("${host}", driver.getHost()).replace("${port}", driver.getPort()) + method;
            httpget = new HttpGet(url);
            response = httpclient.execute(httpget);
            entity = response.getEntity();
            return String.valueOf(response.getStatusLine().getStatusCode());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
        return "get server status error";
    }
}


text:
from neutron.common import rpc as n_rpc
from neutron import manager

# TODO(amotoki): Move security group RPC API and agent callback
# from securitygroups_rpc.py.

class SecurityGroupServerRpcCallback(n_rpc.RpcCallback):
    """Callback for SecurityGroup agent RPC in plugin implementations.

    Subclass which inherits this class must implement get_port_from_device().
    """

    # API version history:
    #   1.1 - Initial version
    #   1.2 - security_group_info_for_devices introduced as an optimization

    # NOTE: RPC_API_VERSION must not be overridden in subclasses
    # to keep RPC API version consistent across plugins.
    RPC_API_VERSION = '1.2'

    @property
    def plugin(self):
        return manager.NeutronManager.get_plugin()

    def _get_devices_info(self, devices):
        devices_info = {}
        for device in devices:
            port = self.plugin.get_port_from_device(device)
            if not port:
                continue
            if port['device_owner'].startswith('network:'):
                continue
            devices_info[port['id']] = port
        return devices_info

    def security_group_rules_for_devices(self, context, **kwargs):
        """Callback method to return security group rules for each port.

        also convert remote_group_id rule
        to source_ip_prefix and dest_ip_prefix rule

        :params devices: list of devices
        :returns: port correspond to the devices with security group rules
        """
        devices_info = kwargs.get('devices')
        ports = self._get_devices_info(devices_info)
        return self.plugin.security_group_rules_for_ports(context, ports)

    def security_group_info_for_devices(self, context, **kwargs):
        """Return security group information for requested devices.

        :params devices: list of devices
        :returns:
        sg_info{
          'security_groups': {sg_id: [rule1, rule2]}
          'sg_member_ips': {sg_id: {'IPv4': [], 'IPv6': []}}
          'devices': {device_id: {device_info}}
        }
        """
        devices_info = kwargs.get('devices')
        ports = self._get_devices_info(devices_info)
        return self.plugin.security_group_info_for_ports(context, ports)


text:
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

namespace VideoWidgetDemo
{
	[Register ("ViewController")]
	partial class ViewController
	{
		[Outlet]
		[GeneratedCode ("iOS Designer", "1.0")]
		UITextView attributionTextView { get; set; }

		[Outlet]
		[GeneratedCode ("iOS Designer", "1.0")]
		Google.VR.GVRVideoView videoView { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (attributionTextView != null) {
				attributionTextView.Dispose ();
				attributionTextView = null;
			}
			if (videoView != null) {
				videoView.Dispose ();
				videoView = null;
			}
		}
	}
}


text:
from setuptools import setup, find_packages

with open('requirements.txt') as f_in:
    lines = (l.strip() for l in f_in.readlines())
    install_requires = [l for l in lines if l and not l.startswith('--')]

with open('README.md') as f_in:
    long_description = f_in.read()

setup(
    name='fangorn',
    version='0.0.1',
    description='Slackbot for personal use',
    long_description=long_description,
    url='https://github.com/lwbrooke/slackbot',
    license='Apache',
    author='Logan Brooke',
    packages=find_packages(),
    package_data={
        'fangorn': ['config_files/*.yaml']
    },
    entry_points={
        'console_scripts': [
            'fangorn = fangorn.__main__:main'
        ]
    },
    install_requires=install_requires,
    setup_requires=[
        'wheel'
    ]
)


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.apache.commons.collections4.splitmap (Apache Commons Collections 4.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

org.apache.commons.collections4.splitmap

Classes

AbstractIterableGetMapDecorator

TransformedSplitMap


text:
package apiv1

import (
	"net/http"
	"os"
	"strings"
	"testing"

	"github.com/jamiefdhurst/journal/internal/app"
	"github.com/jamiefdhurst/journal/test/mocks/controller"
	"github.com/jamiefdhurst/journal/test/mocks/database"
)

func TestUpdate_Run(t *testing.T) {
	db := &database.MockSqlite{}
	container := &app.Container{Configuration: app.DefaultConfiguration(), Db: db}
	response := &controller.MockResponse{}
	response.Reset()
	controller := &Update{}
	os.Chdir(os.Getenv("GOPATH") + "/src/github.com/jamiefdhurst/journal")

	// Test forbidden
	controller.Init(container, []string{"", "0"})
	container.Configuration.EnableEdit = false
	request, _ := http.NewRequest("POST", "/slug/edit", strings.NewReader("{\"not\":\"valid\":\"json\"}"))
	request.Header.Add("Content-Type", "application/json")
	controller.Run(response, request)
	if response.StatusCode != 403 {
		t.Error("Expected 403 error when creation is disabled")
	}

	// Test not found/error with GET/POST
	controller.Init(container, []string{"", "0"})
	container.Configuration.EnableEdit = true
	db.Rows = &database.MockRowsEmpty{}
	request = &http.Request{Method: "POST"}
	controller.Run(response, request)
	if response.StatusCode != 404 {
		t.Error("Expected 404 error when journal not found")
	}

	// Test for bad request on invalid JSON
	response.Reset()
	request, _ = http.NewRequest("POST", "/slug/edit", strings.NewReader("{\"not\":\"valid\":\"json\"}"))
	request.Header.Add("Content-Type", "application/json")
	db.Rows = &database.MockJournal_SingleRow{}
	controller.Run(response, request)
	if response.StatusCode != 400 {
		t.Error("Expected 400 error when invalid JSON provided")
	}

	// Test Journal is retrieved on save
	response.Reset()
	request, _ = http.NewRequest("POST", "/slug/edit", strings.NewReader("{\"title\":\"Something New\",\"date\":\"2018-01-01\",\"content\":\"New\"}"))
	request.Header.Add("Content-Type", "application/json")
	db.Rows = &database.MockJournal_SingleRow{}
	controller.Run(response, request)
	if response.StatusCode != 200 || !strings.Contains(response.Content, "Something New") {
		t.Error("Expected new title to be within content")
	}
}


text:
package com.onion.view

import com.onion.model.Meeting
import com.onion.mongo.DB._
import com.onion.view.ViewObject.ResponseCode.{ERROR400, ERROR500, OK200}
import com.onion.view.ViewObject._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Promise, Future}
import scala.util.{Failure, Success}
import com.onion.util.OptionUtil._
import com.onion.util.FutureUtil._

/**
 * Created by jincao on 1/30/15.
 */
object ViewController {

  def getMeetingsFromDB(cityId: String, pageNum: Int): Future[ViewObject.MeetingAbsResponse] = {
    MeetingAbsResponse.fromModels(MeetingDao.findByCityId(cityId, pageNum))
  }

  def getMeetingDetailFromDB(id: String) = {
    MeetingResponse.fromModels(MeetingDao.findById(id))
  }

  def addMeetingToDB(meeting: Option[MeetingDetail]): Future[PostResponse] = {
    val postResponse = Promise[PostResponse]()
    meeting match {
      case Some(meetingDetail) => MeetingDao.add(meetingDetail.toMeeting).onComplete {
        case Success(_) => postResponse success PostResponse(OK200, "success")
        case Failure(t) => postResponse success PostResponse(ERROR500, t.getMessage)
      }
      case None => postResponse success PostResponse(ERROR400, "request body empty")
    }
    postResponse.future
  }

  def updateMeetingToDB(meeting: Option[Meeting]): Future[PostResponse] = {
    MeetingDao.findById(meeting.id)
      .to(orginMeeting => {
      val postResponse = Promise[PostResponse]()
      val _meeting = meeting.map {
        (m: Meeting) =>
          val _selection = m.selection.getOrElse(List()).map(_.copy(id = newGuid))
          orginMeeting.copy(
            cityId = m.cityId,
            subject = m.subject,
            target = m.target,
            description = m.description,
            price = m.price,
            selection = _selection,
            updateTime = System.currentTimeMillis
          )
      }
      _meeting match {
        case Some(m: Meeting) => MeetingDao.update(m).onComplete {
          case Success(_) => postResponse success PostResponse(OK200, "success")
          case Failure(t) =>
            postResponse success PostResponse(ERROR500, t.getMessage)
            println(t)
        }
        case None => postResponse success PostResponse(ERROR400, "request body empty")
      }
      postResponse.future
    }).get(PostResponse(ERROR400, "can't find meeting by id"))

  }

  def deleteMeetingToDB(id: String) : Future[PostResponse] = {
    MeetingDao.findById(id)
      .to(orginMeeting => {
      val postResponse = Promise[PostResponse]()
      val _meeting = orginMeeting.copy(updateTime = System.currentTimeMillis(), isDeleted = true)
      MeetingDao.update(_meeting).onComplete {
        case Success(_) => postResponse success PostResponse(OK200, "success")
        case Failure(t) => postResponse success PostResponse(ERROR500, t.getMessage)
          println(t)
      }
      postResponse.future
    }).get(PostResponse(ERROR400,"can't find meeting by id"))
  }

  def putBookToDB(putBook: PutBook) = {

  }
}


text:
require_relative '../_client' # Gives access to @client

# Example: Create/Update/Delete logical enclosure
# NOTE: This will create a logical enclosure named 'OneViewSDK Test Logical Enclosure', update it and then delete it.
# To run this test with Synergy you must have an enclosureGroup with enclosure count = 3.
#

# Supported Variants:
# - C7000 and Synergy for all API versions

# Resource Class used in this sample
logical_enclosure_class = OneviewSDK.resource_named('LogicalEnclosure', @client.api_version, 'Synergy')

# Scope class used in this sample
encl_group_class = OneviewSDK.resource_named('EnclosureGroup', @client.api_version, 'Synergy')
enclosure_class = OneviewSDK.resource_named('Enclosure', @client.api_version, 'Synergy')

variant = 'Synergy'

scope_class = OneviewSDK.resource_named('Scope', @client.api_version)
scope_1 = scope_class.new(@client, name: 'Scope_for_LE')
scope_1.create

if variant == 'Synergy'
  options = {
    name: 'LE',
    forceInstallFirmware: false,
    firmwareBaselineUri: nil,
    initialScopeUris: [scope_1['uri']]
  }

  puts "\nCreating a logical enclosure with the name = '#{options[:name]}'."
  item = logical_enclosure_class.new(@client, options)
  # set an enclosure group with enclosure count = 3
  enclosure_group = encl_group_class.find_by(@client, enclosureCount: 3).first
  item.set_enclosure_group(enclosure_group)

  # set the enclosures
  enclosure1 = enclosure_class.find_by(@client, name: '0000A66101').first
  enclosure2 = enclosure_class.find_by(@client, name: '0000A66102').first
  enclosure3 = enclosure_class.find_by(@client, name: '0000A66103').first
  item.set_enclosures([enclosure1, enclosure2, enclosure3])

  item.create
  sleep(10)
  puts "\nCreated a logical enclosure '#{item[:name]}' successfully.\n  uri = '#{item[:uri]}'"
end

puts "\nListing all logical enclosures:"
items = logical_enclosure_class.get_all(@client)
items.each do |i|
  puts i['name']
end

log_encl_name = items.first['name']
log_encl_uri = items.first['uri']

# retrieve a logical enclosure
item2 = logical_enclosure_class.new(@client, name: log_encl_name)
puts "\nRetrieves a logical enclosure by name: '#{log_encl_name}'"
item2.retrieve!
puts "\nFound by name: '#{item2[:name]}'.\n  uri = '#{item2[:uri]}'"

# Gets a logical enclosure by uri
puts "\nGets a logical enclosure with uri '#{log_encl_uri}'"
item3 = logical_enclosure_class.find_by(@client, uri: log_encl_uri).first
puts "Found logical enclosure '#{item3[:uri]}'."

if @client.api_version >= 600
  # Gets a logical enclosure by scopeUris
  query = {
    scopeUris: scope_1['uri']
  }
  puts "\nGets a logical enclosure with scope '#{query[:scopeUris]}'"
  item4 = logical_enclosure_class.get_all_with_query(@client, query)
  puts "Found logical enclosure '#{item4}'."
end

puts "\nUpdating a logical enclosure with the name = '#{item3['name']}'."
old_name = item3['name']
item3.update(name: "#{item3['name']}_Updated")
item3.retrieve!
puts "\nlogical enclosure updated successfully and new name = '#{item3['name']}'."
puts "\nUpdating to original name."
item3.update(name: old_name)
item3.retrieve!
puts "\nlogical enclosure updated successfully and returned to original name = '#{item3['name']}'."

# Reconfigure script
puts "\nReconfiguring a logical enclosure"
item3.reconfigure
puts "\nOperation performed successfully."

orig_script = nil

# Get configuration script
puts "\nGetting a logical enclosure script"
begin
  orig_script = item3.get_script
  puts "\nRetrieved logical enclosure '#{item3['name']}' script\n  Content = '#{orig_script}'"
rescue OneviewSDK::MethodUnavailable => e
  puts "\n#{e}. Available only for C7000."
end

# Set configuration script
puts "\nSetting a logical enclosure script"
if variant == 'C7000'
  begin
    item3.set_script(orig_script)
    puts "\nOperation performed successfully."
  rescue OneviewSDK::MethodUnavailable => e
    puts "\n#{e}. Available only for C7000."
  end
end

# Update from Group
puts "\nUpdate from Group"
item3.update_from_group
puts "\nlogical enclosure updated successfully."

item3.retrieve!
# Performs a patch
puts "Updating the firmware of the logical enclosure #{item3['name']}"
begin
  value = {
    firmwareUpdateOn: 'SharedInfrastructureOnly',
    forceInstallFirmware: false,
    updateFirmwareOnUnmanagedInterconnect: true
  }

  item3.update_firmware(value)
  sleep(10)
  puts "Firmware updated successfully on logical enclosure #{item3['name']}"
rescue NoMethodError
  puts "\nThe method #update_firmware is available from API 300 onwards.."
end

# Generate dump
dump = {
  errorCode: 'test',
  excludeApplianceDump: true
}
puts 'Generate support dump'
item3.support_dump(dump)
puts "\nGenerated dump for logical enclosure '#{item3['name']}'."

# Skipping delete LE since the system will goto bad state after LE delete
# if variant == 'Synergy'
#   puts "\nRemoving the logical enclosure"
#   item3.delete
#   puts "\nRemoved logical enclosure '#{item3['name']}'."
# end